Merge main into feat/plugin-importers

This commit is contained in:
dotCooCoo committed 2026-11-07 23:49:11 -08:00
commit a3c37ea1f4
287 files changed
+24708 -1142

No files matched your search

Generated
+12 -2
View File
@@ -2978,8 +2978,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a25df1b0c5432893f41bba817150e323703ee5f6d974f3a6808ac7fd7f046d18"
source = "git+https://github.com/storytold/craft-libs?rev=481f66d287b2a06845f3667a19daf35f0fe958ed#481f66d287b2a06845f3667a19daf35f0fe958ed"
dependencies = [
"arrayvec",
"kurbo 0.13.1",
@@ -6265,6 +6264,7 @@ dependencies = [
"vectorcraft-eps",
"vectorcraft-format",
"vectorcraft-geom",
"vectorcraft-js",
"vectorcraft-metafile",
"vectorcraft-pathops",
"vectorcraft-pdf",
@@ -6283,6 +6283,7 @@ dependencies = [
name = "vectorcraft-eps"
version = "0.21.0"
dependencies = [
"craft-pdf",
"fax",
"flate2",
"hayro-ccitt",
@@ -6332,6 +6333,14 @@ dependencies = [
"vectorcraft-testkit",
]
[[package]]
name = "vectorcraft-js"
version = "0.21.0"
dependencies = [
"proptest",
"unicode-general-category",
]
[[package]]
name = "vectorcraft-mcp"
version = "0.21.0"
@@ -6413,6 +6422,7 @@ dependencies = [
name = "vectorcraft-plugins"
version = "0.21.0"
dependencies = [
"log",
"serde",
"serde_json",
"sha2",
+2
View File
@@ -53,6 +53,7 @@ vectorcraft-metafile = { path = "crates/metafile" }
vectorcraft-plugins = { path = "crates/plugins" }
vectorcraft-affinity = { path = "crates/affinity" }
vectorcraft-scriptcheck = { path = "crates/scriptcheck" }
vectorcraft-js = { path = "crates/js" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
@@ -153,6 +154,7 @@ hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "9be9a637
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "481f66d287b2a06845f3667a19daf35f0fe958ed" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+6 -1
View File
@@ -20,10 +20,15 @@ list (author, source, license) is in ASSETS.md.
(Ubuntu Font Licence 1.0), Hack (MIT), Noto Emoji (SIL Open Font License 1.1) and emoji-icon-font
(MIT). Their license texts ship with that crate.
Rust dependencies (vello_cpu, kurbo, peniko, skrifa, harfrust, usvg, linesweeper, egui, eframe, …) are
Rust dependencies (vello_cpu, kurbo, peniko, skrifa, harfrust, usvg, egui, eframe, …) are
fetched through crates.io under their own permissive licenses (mostly MIT and/or Apache-2.0; also
BSD, ISC, Zlib, BSL-1.0 and Unicode-3.0).
linesweeper 0.5.0 (MIT OR Apache-2.0) is fetched from https://github.com/storytold/craft-libs at
revision 481f66d287b2a06845f3667a19daf35f0fe958ed. The copy in craft-libs' vendor/linesweeper is
the crates.io package with no file changed, and it keeps the package's LICENSE-MIT and
LICENSE-APACHE.
JPEG export uses the jpeg-encoder crate (MIT OR Apache-2.0, and the IJG License): this software is
based in part on the work of the Independent JPEG Group.
+1 -1
View File
@@ -253,7 +253,7 @@ The scores are self-assessed from our code against public documentation;
[target-app-parity.md](docs/target-app-parity.md#how-this-was-measured-2026-10-10) explains how far to trust them.
**What's missing:**
- reliable exchange of .ai files (layer structure in real files; the editing copy a save writes leaves out live effects and writes symbols and live objects as their art);
- reliable exchange of .ai files (layer structure in real files; the editing copy a save writes keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), leaves out other objects' effects other than geometry effects, and writes live objects as their art);
- an interaction-fidelity pass covering every tool's modifiers and small behaviours;
- 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials);
- filter thumbnails and a preview area inside the Effect Gallery (the gallery itself and all 57 Photoshop-style raster filters, approximated, are in);
+1 -1
View File
@@ -24,7 +24,7 @@ and the work list in [`docs/gaps.md`](docs/gaps.md).
**Why alpha:** the core workflows exist end to end (drawing and path editing, Pathfinder, paint and appearance,
type, SVG/PDF/EPS, print, export) and feature depth is ~75%, but a professional can't yet switch: Illustrator's
own `.ai` files open with a wrong layer structure in real cases and are saved back with an editing copy that
leaves out live effects and writes symbols and live objects as their art, the interaction details have never been checked side by side, and some machines fail to start the
keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), and writes live objects as their art, the interaction details have never been checked side by side, and some machines fail to start the
app. Beta needs those closed (the beta list in [gaps.md](docs/gaps.md)). It passes the core-workflow
gate: all six core workflows (path drawing and editing, paint and style, type, layers/artboards/export, print
production, file exchange) work end to end on macOS with save and reopen, and only the last is partial, without
+4
View File
@@ -475,6 +475,10 @@ pub struct PatternBrush {
pub side_frame: Option<Rect>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub side_swatch: Option<String>,
/// Art for the corners where the path turns towards the side tile's top (`-y`); `inner_corner`
/// is the art for the corners where it turns the other way. Both are drawn as the corner that
/// joins a side tile on its right to one below it, and each corner tile is turned so that
/// those two arms meet the sides.
#[serde(skip_serializing_if = "Option::is_none")]
pub outer_corner: Option<Node>,
#[serde(default, skip_serializing_if = "Option::is_none")]
+96 -1
View File
@@ -1,6 +1,6 @@
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, StrokeLayer};
use vectorcraft_geom::{Affine, BezPath, Point, Rect, shapes};
use vectorcraft_geom::{Affine, BezPath, Point, Rect, Vec2, shapes};
use super::*;
@@ -299,6 +299,101 @@ fn pattern_places_corner_tiles() {
}
}
/// A pattern brush whose corner tiles have a 4 × 4 pt frame and, as art, a 2 × 2 pt square in the
/// top-left quarter of the frame. Corner art joins a side tile on its right to one below it, so
/// that quarter is on the outside of the turn. `inner` and `outer` say which kinds of corner have
/// art; `flips` are the brush's Flip Along and Flip Across.
fn marked_corner_brush(inner: bool, outer: bool, (flip_along, flip_across): (bool, bool)) -> Brush {
let marker =
Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, -2.0, 2.0, 0.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
let mut b = pattern_brush(PatternFit::Stretch, false);
if let BrushKind::Pattern(p) = &mut b.kind {
let frame = Some(Rect::new(0.0, -2.0, 4.0, 2.0));
if inner {
(p.inner_corner, p.inner_corner_frame) = (Some(marker.clone()), frame);
}
if outer {
(p.outer_corner, p.outer_corner_frame) = (Some(marker), frame);
}
(p.flip_along, p.flip_across) = (flip_along, flip_across);
}
b
}
/// Each combination of corner art (both kinds, inner only, outer only) and of the two flips.
fn marked_corner_brushes() -> Vec<(String, Brush)> {
let mut v = vec![];
for (inner, outer) in [(true, true), (true, false), (false, true)] {
for flips in [(false, false), (true, false), (false, true), (true, true)] {
v.push((format!("inner {inner}, outer {outer}, flips {flips:?}"), marked_corner_brush(inner, outer, flips)));
}
}
v
}
/// The bounds of the 2 × 2 pt corner markers among `out`, turned or not.
fn marker_bounds(out: &[Node]) -> Vec<Rect> {
out.iter().filter_map(Node::geometric_bounds).filter(|r| r.width() < 3.0 && r.height() < 3.0).collect()
}
/// Corner tiles are square to the sides at a right angle and turn 90° with each turn of the path:
/// on a square drawn either way round, each corner's marker fills the quarter of the band's corner
/// outside the turn, with the brush flipped or not and with art for one kind of corner only
/// (#6110).
#[test]
fn pattern_corner_tiles_are_square_to_the_sides() {
let doc = Document::new(1.0, 1.0);
let sq = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)).to_bezpath();
let mut reversed = BezPath::new();
reversed.move_to((0.0, 0.0));
for (x, y) in [(0.0, 100.0), (100.0, 100.0), (100.0, 0.0)] {
reversed.line_to((x, y));
}
reversed.close_path();
// The square turns the same way at all four corners, and the reversed square the other way,
// so one draws only inner corner tiles and the other only outer ones.
for (name, brush) in marked_corner_brushes() {
for path in [&sq, &reversed] {
let out = stroke_pieces(&doc, &brush, path, &stroke(1.0));
let marks = marker_bounds(&out);
assert_eq!(marks.len(), 4, "{name}: one marker a corner");
for (corner, outside) in SQUARE_CORNERS {
let want = Rect::from_points(corner, outside);
assert!(
marks
.iter()
.any(|r| near(r.x0, want.x0, 1e-6) && near(r.y0, want.y0, 1e-6) && near(r.x1, want.x1, 1e-6) && near(r.y1, want.y1, 1e-6)),
"{name}: the marker at {corner:?} fills {want:?}: {marks:?}"
);
}
}
}
}
/// At a corner that is not a right angle, a corner tile splits the difference between the two
/// sides: its marker lies on the line that halves the angle, outside the turn, for sharp and
/// shallow turns either way. Near a hairpin the marker moves smoothly towards the line the path
/// arrives on.
#[test]
fn pattern_corner_tiles_sit_on_the_corners_diagonal() {
let doc = Document::new(1.0, 1.0);
for (name, brush) in marked_corner_brushes() {
for turn in [-179.9_f64, -170.0, -135.0, -60.0, -45.0, 45.0, 60.0, 135.0, 170.0, 179.9] {
let (a, b) = (Vec2::new(1.0, 0.0), Vec2::new(turn.to_radians().cos(), turn.to_radians().sin()));
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
bp.line_to((50.0, 0.0));
bp.line_to(Point::new(50.0, 0.0) + b * 50.0);
let out = stroke_pieces(&doc, &brush, &bp, &stroke(1.0));
let marks = marker_bounds(&out);
assert_eq!(marks.len(), 1, "{name}, {turn}°: one corner marker");
let away = a - b;
let want = Point::new(50.0, 0.0) + away / away.hypot() * 2.0_f64.sqrt();
assert!(marks[0].center().distance(want) < 1e-6, "{name}, {turn}°: the marker is at {:?}, not {want:?}", marks[0].center());
}
}
}
/// The 10 × 4 pt side tile of [`pattern_brush`] with the given corner sources and no corner art.
fn auto_corner_brush(outer: Option<CornerSource>, inner: Option<CornerSource>) -> Brush {
let mut b = pattern_brush(PatternFit::Stretch, false);
+10 -6
View File
@@ -879,12 +879,16 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
};
trims.push(None);
corner_half = corner_half.max(bb.width() * k / 2.0);
let bis = a + b;
let bis = if bis.hypot() < 1e-9 { a } else { bis / bis.hypot() };
let xf = Affine::translate(t.verts[i].to_vec2())
* Affine::rotate(bis.y.atan2(bis.x))
* Affine::scale(k)
* Affine::translate(-bb.center().to_vec2());
// Inner and outer corner art is the corner that joins a side tile on its right to one
// below it, so its arms point along +x and +y (as the flips leave them). The tile is
// turned so that the line halving its arms lies on the line halving the sides at the
// corner, back along the incoming side and on along the outgoing one: at a right angle
// the arms meet the side tiles, and at other angles the difference is split between
// the two sides (#6110).
let arms = Vec2::new(if pb.flip_along { -1.0 } else { 1.0 }, if pb.flip_across { -1.0 } else { 1.0 });
let sides = b - a;
let angle = sides.y.atan2(sides.x) - arms.y.atan2(arms.x);
let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(k) * Affine::translate(-bb.center().to_vec2());
let mut n = art.clone();
n.transform(xf, true);
out.take(Some(n));
+15
View File
@@ -231,6 +231,21 @@ impl GenericCmyk {
}
g[p] = -(0..3).map(|i| j[i][p] * r[i]).sum::<f32>();
}
// An ink at a bound whose descent direction points out of the box stays where it is; the step moves the other inks.
for p in 0..3 {
if (x[p] <= 0.0 && g[p] < 0.0) || (x[p] >= 1.0 && g[p] > 0.0) {
a[p] = [0.0; 3];
for row in &mut a {
row[p] = 0.0;
}
a[p][p] = 1.0;
g[p] = 0.0;
}
}
// Every ink is held at a bound, or the gradient is zero: no step can lower the error.
if g == [0.0; 3] {
break;
}
let mut improved = false;
for _ in 0..8 {
let mut al = a;
+40
View File
@@ -259,6 +259,46 @@ fn generic_cmyk_black_round_trips_with_bpc() {
assert!(raw.iter().all(|v| *v > 0.05), "{raw:?}");
}
/// A color whose solve holds cyan at 0 separates to the same inks when its values change by a few
/// float steps: hex ed1e79 with its red stepped one `f32` at a time over 4,001 values (about 0.00024
/// in all) stays within 0.001 on every ink.
#[test]
fn generic_cmyk_separates_nearby_colors_at_the_gamut_edge_alike() {
let c = cms();
let pink = [237.0f32 / 255.0, 30.0 / 255.0, 121.0 / 255.0];
let (mut lo, mut hi) = ([f32::MAX; 4], [f32::MIN; 4]);
for step in -2000i32..=2000 {
let mut rgb = pink;
rgb[0] = f32::from_bits(pink[0].to_bits().wrapping_add_signed(step));
let ink = c.srgb_to_cmyk(rgb, Intent::RelativeColorimetric);
for i in 0..4 {
lo[i] = lo[i].min(ink[i]);
hi[i] = hi[i].max(ink[i]);
}
}
assert!((0..4).all(|i| hi[i] - lo[i] < 1e-3), "{lo:?} to {hi:?}");
assert_eq!(lo[0], 0.0, "{lo:?}");
}
/// A color whose solve holds cyan and magenta at 1 separates to the same inks when its values change
/// by a few float steps: sRGB (0, 0, 0.25) with its blue stepped one `f32` at a time over 121 values
/// stays within 0.001 on every ink.
#[test]
fn generic_cmyk_separates_nearby_colors_with_inks_at_full_alike() {
let c = cms();
let (mut lo, mut hi) = ([f32::MAX; 4], [f32::MIN; 4]);
for step in -60i32..=60 {
let blue = f32::from_bits(0.25f32.to_bits().wrapping_add_signed(step));
let ink = c.srgb_to_cmyk([0.0, 0.0, blue], Intent::RelativeColorimetric);
for i in 0..4 {
lo[i] = lo[i].min(ink[i]);
hi[i] = hi[i].max(ink[i]);
}
}
assert!((0..4).all(|i| hi[i] - lo[i] < 1e-3), "{lo:?} to {hi:?}");
assert_eq!((lo[0], lo[1]), (1.0, 1.0), "{lo:?}");
}
#[test]
fn lab_colours_round_trip_through_the_cms() {
let c = cms_no_bpc();
+337 -61
View File
@@ -699,6 +699,34 @@ fn compound(path: PathData, rule: FillRule, counts: &[usize], total: usize) -> N
/// Interpolate text `x` → `y` into `o` (a copy of the nearer): the transform by its parts, an
/// area frame anchor by anchor, and each run's colours, stroke weight and size from the runs at
/// the same place (by character) of both.
/// The run of `of` at fraction `u` of its characters.
fn run_at(of: &TextObject, u: f64) -> Option<&crate::text::TextRun> {
let total: usize = of.runs.iter().map(|r| r.text.chars().count()).sum();
let target = (u * total as f64) as usize;
let mut seen = 0;
for r in &of.runs {
seen += r.text.chars().count();
if seen > target {
return Some(r);
}
}
of.runs.last()
}
/// The fraction of the characters of `runs` at the middle of each run.
fn run_middles(runs: &[crate::text::TextRun]) -> Vec<f64> {
let total: usize = runs.iter().map(|r| r.text.chars().count()).sum::<usize>().max(1);
let mut start = 0usize;
runs.iter()
.map(|r| {
let len = r.text.chars().count();
let u = (start as f64 + len as f64 / 2.0) / total as f64;
start += len;
u
})
.collect()
}
fn lerp_text(o: &mut TextObject, x: &TextObject, y: &TextObject, t: f64, tc: f64) {
o.xf = lerp_affine(x.xf, y.xf, t);
if let (crate::text::TextKind::Area { frame: f }, crate::text::TextKind::Area { frame: fx }, crate::text::TextKind::Area { frame: fy }) =
@@ -706,27 +734,10 @@ fn lerp_text(o: &mut TextObject, x: &TextObject, y: &TextObject, t: f64, tc: f64
{
*f = lerp_path(fx, fy, t);
}
// The run of `of` at fraction `u` of its characters.
fn run_at(of: &TextObject, u: f64) -> Option<&crate::text::TextRun> {
let total: usize = of.runs.iter().map(|r| r.text.chars().count()).sum();
let target = (u * total as f64) as usize;
let mut seen = 0;
for r in &of.runs {
seen += r.text.chars().count();
if seen > target {
return Some(r);
}
}
of.runs.last()
}
let total: usize = o.runs.iter().map(|r| r.text.chars().count()).sum::<usize>().max(1);
let mut start = 0usize;
let tf = tc as f32;
let mut resized = false;
for r in &mut o.runs {
let len = r.text.chars().count();
let u = (start as f64 + len as f64 / 2.0) / total as f64;
start += len;
let middles = run_middles(&o.runs);
for (r, u) in o.runs.iter_mut().zip(middles) {
let (Some(rx), Some(ry)) = (run_at(x, u), run_at(y, u)) else { continue };
let (sx, sy) = (&rx.style, &ry.style);
r.style.fill = lerp_paint(&sx.fill, &sy.fill, tf);
@@ -752,33 +763,115 @@ pub fn lerp_node(a: &Node, b: &Node, t: f64) -> Node {
// Step counts
// =====================================================================================
/// Largest channel difference (0..1) between the solid colours of two objects' top fill and stroke.
fn color_distance(a: &Node, b: &Node) -> f32 {
let mut d = 0.0f32;
let mut cmp = |x: &Paint, y: &Paint| {
let cols = |p: &Paint| -> Vec<Color> {
match p {
Paint::Solid { color, .. } => vec![*color],
Paint::Gradient(g) => g.gradient.stops.iter().map(|s| s.color).collect(),
_ => vec![],
}
};
let (cx, cy) = (cols(x), cols(y));
for (i, c) in cx.iter().enumerate() {
if let Some(o) = cy.get(i).or(cy.first()) {
let (p, q) = (c.to_rgb(), o.to_rgb());
for k in 0..3 {
d = d.max((p[k] - q[k]).abs());
}
}
}
/// Largest channel difference between two solid colors, as a fraction of the channel's range: two
/// tints of the same swatch by their tints, RGB by its 0 to 255 values over 256, CMYK and gray by
/// their percentages, and colors in different spaces (or Lab) by the difference of their RGB
/// values over 255. A solid paint against no paint, or anything that isn't solid, differs by 0:
/// [`lerp_paint`] switches such paints halfway rather than mixing them.
fn paint_difference(x: &Paint, y: &Paint) -> f64 {
let (Paint::Solid { color: p, swatch: sp, tint: tp }, Paint::Solid { color: q, swatch: sq, tint: tq }) = (x, y) else {
return 0.0;
};
cmp(&a.appearance.fill_paint(), &b.appearance.fill_paint());
cmp(&a.appearance.stroke_paint(), &b.appearance.stroke_paint());
d
if sp.is_some() && sp == sq && tp != tq {
return f64::from((tp - tq).abs());
}
let most = |a: &[f32], b: &[f32]| a.iter().zip(b).fold(0.0f64, |m, (u, v)| m.max(f64::from((u - v).abs())));
match (p, q) {
(Color::Rgb { r, g, b }, Color::Rgb { r: r2, g: g2, b: b2 }) => most(&[*r, *g, *b], &[*r2, *g2, *b2]) * 255.0 / 256.0,
(Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) => most(&[*c, *m, *y, *k], &[*c2, *m2, *y2, *k2]),
(Color::Gray { k }, Color::Gray { k: k2 }) => most(&[*k], &[*k2]),
_ => most(&p.to_rgb(), &q.to_rgb()),
}
}
/// Number of intermediate steps between two keys `len` apart (along the spine).
/// Largest difference (see [`paint_difference`]) between pairs of fills and strokes, or `None`
/// when any of them is a gradient or a pattern.
fn paints_difference(pairs: &[(&Paint, &Paint)]) -> Option<f64> {
let mut d = 0.0f64;
for (x, y) in pairs {
if [x, y].iter().any(|p| matches!(p, Paint::Gradient(_) | Paint::Pattern { .. })) {
return None;
}
d = d.max(paint_difference(x, y));
}
Some(d)
}
/// Largest channel difference (0..1, see [`paint_difference`]) between the solid colors of two
/// keys: their top fill and stroke, the runs of two text objects paired as [`lerp_text`] pairs
/// them, and the members of two groups paired as [`Lerp::new`] pairs them. `None` when any of
/// these holds a gradient or a pattern, whose steps Smooth Color counts by distance.
fn color_distance(a: &Node, b: &Node) -> Option<f64> {
let mut d =
paints_difference(&[(&a.appearance.fill_paint(), &b.appearance.fill_paint()), (&a.appearance.stroke_paint(), &b.appearance.stroke_paint())])?;
match (&a.kind, &b.kind) {
(NodeKind::Group { children: ca, clip: k1 }, NodeKind::Group { children: cb, clip: k2 }) if k1 == k2 && !(*k1 && ca.len() != cb.len()) => {
for (x, y) in ca.iter().zip(cb) {
d = d.max(color_distance(x, y)?);
}
}
(NodeKind::Text(x), NodeKind::Text(y)) => {
// The runs `lerp_text` pairs: those of `x` and of `y` at the middle of each run of either.
for u in run_middles(&x.runs).into_iter().chain(run_middles(&y.runs)) {
let (Some(rx), Some(ry)) = (run_at(x, u), run_at(y, u)) else { continue };
d = d.max(paints_difference(&[(&rx.style.fill, &ry.style.fill), (&rx.style.stroke, &ry.style.stroke)])?);
}
}
_ => {}
}
d.is_finite().then_some(d)
}
/// Smooth Color's steps between two keys by distance: the largest distance between their
/// corresponding visible bounding-box edges, in mean key widths (left and right edges) or heights
/// (top and bottom), rounded, less one, from 1 to 1000. Keys with no width are measured in their
/// mean height across as well, keys with no height in their mean width, and keys with neither in
/// points.
fn spatial_steps(ba: Rect, bb: Rect) -> usize {
let (w, h) = ((ba.width() + bb.width()) / 2.0, (ba.height() + bb.height()) / 2.0);
let size = |s: f64, other: f64| {
if s > 1e-9 {
s
} else if other > 1e-9 {
other
} else {
1.0
}
};
let (w, h) = (size(w, h), size(h, w));
let q = ((ba.x0 - bb.x0).abs().max((ba.x1 - bb.x1).abs()) / w).max((ba.y0 - bb.y0).abs().max((ba.y1 - bb.y1).abs()) / h);
if !q.is_finite() {
return 1;
}
((q + 0.5).floor() - 1.0).clamp(1.0, 1000.0) as usize
}
/// `255 × d` steps for a color difference `d` (see [`color_distance`]), a half step rounding down,
/// from 1 to 254.
fn level_steps(d: f64) -> f64 {
// The tolerance keeps a difference that lands on a half step (128 of 256 RGB values gives
// 127.5), stored as an `f32`, from rounding up.
(255.0 * d - 0.5 - 1e-4).ceil().clamp(1.0, 254.0)
}
/// Smooth Color's steps between two keys whose colors differ by `d` (see [`color_distance`]):
/// [`level_steps`], and at most eight per point of the largest of the keys' widths and heights
/// and the distance between their centers along either axis.
fn color_steps(d: f64, ba: Rect, bb: Rect) -> usize {
let by_color = level_steps(d);
let (ca, cb) = (ba.center(), bb.center());
let reach = [(ca.x - cb.x).abs(), (ca.y - cb.y).abs(), ba.width(), ba.height(), bb.width(), bb.height()].into_iter().fold(0.0f64, f64::max);
let by_density = (8.0 * reach + 0.5).floor().clamp(1.0, 254.0);
if !by_density.is_finite() {
return by_color as usize;
}
by_color.min(by_density) as usize
}
/// Number of intermediate steps between two keys. Specified Distance counts along the spine, `len`
/// long between them. Smooth Color counts from the keys' colors and visible bounds, whatever the
/// spine: keys whose colors differ make [`color_steps`] ([`level_steps`] when either key has no
/// bounds), and others make [`spatial_steps`] (1 when either key has no bounds).
pub fn blend_step_count(a: &Node, b: &Node, spacing: BlendSpacing, len: f64) -> usize {
match spacing {
BlendSpacing::Steps(n) => n.clamp(1, 1000) as usize,
@@ -787,17 +880,14 @@ pub fn blend_step_count(a: &Node, b: &Node, spacing: BlendSpacing, len: f64) ->
((len / d).round() as i64 - 1).clamp(0, 1000) as usize
}
BlendSpacing::SmoothColor => {
let cd = color_distance(a, b);
if cd > 1.0 / 255.0 {
((cd * 255.0 / 2.0).ceil() as usize).clamp(1, 256)
} else {
// Same colours: base the count on the distance between the objects.
let (ba, bb) = (a.geometric_bounds(), b.geometric_bounds());
let dist = match (ba, bb) {
(Some(x), Some(y)) => (x.x0 - y.x0).abs().max((x.x1 - y.x1).abs()).max((x.y0 - y.y0).abs()).max((x.y1 - y.y1).abs()),
_ => len,
};
((dist / 2.0).ceil() as usize).clamp(1, 256)
let bounds = a.visual_bounds().zip(b.visual_bounds());
match (color_distance(a, b), bounds) {
// Colors that differ by less than a thousandth of a step count as the same.
(Some(d), Some((ba, bb))) if d * 255.0 > 1e-3 => color_steps(d, ba, bb),
(Some(d), None) if d * 255.0 > 1e-3 => level_steps(d) as usize,
// Same colors, gradients and patterns: the distance between the objects.
(_, Some((ba, bb))) => spatial_steps(ba, bb),
(_, None) => 1,
}
}
}
@@ -1148,13 +1238,19 @@ fn requested_steps(keys: &[Arc<Node>], spec: &BlendSpec, rail: Option<&Rail>) ->
.collect()
}
/// Most steps `spacing` makes between two keys, whatever their size and distance
/// ([`blend_step_count`]'s clamps).
fn most_steps(spacing: BlendSpacing) -> usize {
/// Most steps `spacing` makes between keys `a` and `b`, whatever their size and distance
/// ([`blend_step_count`]'s clamps). A copy of a blend is moved and scaled, never recolored
/// ([`Shape::Other`]), so Smooth Color between colors that differ makes no more than their color
/// change asks for, whatever the copy's scale or rotation. By distance, a copy turned by Align to
/// Path can measure its edges differently, so it counts as up to 1000.
fn most_steps(a: &Node, b: &Node, spacing: BlendSpacing) -> usize {
match spacing {
BlendSpacing::Steps(n) => n.clamp(1, 1000) as usize,
BlendSpacing::Distance(_) => 1000,
BlendSpacing::SmoothColor => 256,
BlendSpacing::SmoothColor => match color_distance(a, b) {
Some(d) if d * 255.0 > 1e-3 => level_steps(d) as usize,
_ => 1000,
},
}
}
@@ -1182,8 +1278,8 @@ struct StepCount {
impl StepCount {
/// Steps the blends in `n` make in all when drawn, each keeping to [`MAX_BLEND_STEPS`].
/// `copy`: `n` is part of a blend's step, a copy moved and scaled into place. A blend spaced
/// by distance (or by distance where the colours match) makes more steps scaled up, so a
/// copy counts the most its spacing can make between each pair, an upper bound for any scale.
/// by distance, or by Smooth Color, can make more steps scaled up, so a copy counts the most
/// its spacing can make between each pair ([`most_steps`]), an upper bound for any scale.
fn node(&mut self, n: &Node, copy: bool) -> usize {
let at = (std::ptr::from_ref(n) as usize, copy);
if let Some(&known) = self.known.get(&at) {
@@ -1249,7 +1345,11 @@ impl StepCount {
fn most(&mut self, keys: &[Arc<Node>], spec: &BlendSpec) -> usize {
let inside = self.nodes(keys, true);
let each = self.steps(keys);
let demand = each.iter().map(|&c| c.saturating_mul(most_steps(spec.spacing))).fold(0, usize::saturating_add);
let most = keys.windows(2).map(|w| match w {
[a, b] => most_steps(a, b, spec.spacing),
_ => 0,
});
let demand = each.iter().zip(most).map(|(&c, m)| c.saturating_mul(m)).fold(0, usize::saturating_add);
inside.saturating_add(demand.min(MAX_BLEND_STEPS.saturating_sub(inside)))
}
}
@@ -1634,4 +1734,180 @@ mod tests {
assert_eq!(blend_steps(&keys[..50], &spec), vec![1000; 49]);
assert_eq!(fit_steps(&[10, 20], &[1, 1], MAX_BLEND_STEPS), vec![0, 0]);
}
/// A key for the Smooth Color tests: a rectangle of `size` (width, height) centered on `c`,
/// with `fill`, and `stroke` at `width`.
fn smooth_key(c: (f64, f64), size: (f64, f64), fill: Paint, stroke: Paint, width: f64) -> Node {
let ((cx, cy), (w, h)) = (c, size);
let rect = Rect::new(cx - w / 2.0, cy - h / 2.0, cx + w / 2.0, cy + h / 2.0);
Node::path(NodeId(1), shapes::rectangle(rect), Appearance::basic(fill, stroke, width))
}
/// Smooth Color's steps between two filled `size` rectangles centered on `a` and `b`.
fn smooth(a: (f64, f64), b: (f64, f64), size: (f64, f64), fill_a: Color, fill_b: Color) -> usize {
let key = |c, fill| smooth_key(c, size, Paint::solid(fill), Paint::None, 0.0);
blend_step_count(&key(a, fill_a), &key(b, fill_b), BlendSpacing::SmoothColor, a.0.max(b.0) - a.0.min(b.0))
}
/// Smooth Color counts 255 steps for a full change of the channel that changes most, a half
/// step rounding down: RGB values over 256, CMYK and gray in percent, a spot color by its
/// tint, colors in different spaces by their RGB values over 255, a fill or a stroke,
/// whichever changes more.
#[test]
fn smooth_color_counts_a_step_per_level_of_color_change() {
let (a, b, size) = ((50.0, 150.0), (250.0, 150.0), (20.0, 20.0));
let black = Color::rgb8(0, 0, 0);
for (level, steps) in [(1, 1), (2, 2), (5, 5), (64, 64), (127, 127), (128, 127), (129, 128), (200, 199), (254, 253), (255, 254)] {
assert_eq!(smooth(a, b, size, black, Color::rgb8(level, 0, 0)), steps, "black to red {level}");
assert_eq!(smooth(a, b, size, black, Color::rgb8(level, level, level)), steps, "black to gray {level}");
}
assert_eq!(smooth(a, b, size, Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255)), 254);
assert_eq!(smooth(a, b, size, black, Color::rgb8(64, 128, 0)), 127, "the channel that changes most");
assert_eq!(smooth(a, b, size, Color::rgb8(17, 42, 93), Color::rgb8(91, 147, 220)), 127);
for (percent, steps) in [(0.2, 1), (1.0, 3), (5.0, 13), (10.0, 25), (25.0, 64), (50.0, 127), (100.0, 254)] {
let p = percent / 100.0;
assert_eq!(smooth(a, b, size, Color::cmyk(0.0, 0.0, 0.0, 0.0), Color::cmyk(p, 0.0, 0.0, 0.0)), steps, "cyan {percent}%");
assert_eq!(smooth(a, b, size, Color::gray(0.0), Color::gray(p)), steps, "gray {percent}%");
}
let spot = |tint: f32| Paint::Solid { color: Color::rgb8(255, 0, 0).tinted(tint), swatch: Some("Spot".into()), tint };
let key = |c, fill| smooth_key(c, size, fill, Paint::None, 0.0);
assert_eq!(blend_step_count(&key(a, spot(1.0)), &key(b, spot(0.5)), BlendSpacing::SmoothColor, 200.0), 127, "a tint of 50%");
let stroked = |c, fill: Color, stroke: Color| smooth_key(c, size, Paint::solid(fill), Paint::solid(stroke), 1.0);
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
assert_eq!(blend_step_count(&stroked(a, red, black), &stroked(b, red, blue), BlendSpacing::SmoothColor, 200.0), 254, "the stroke changes");
let outline = |c, stroke: Color| smooth_key(c, size, Paint::None, Paint::solid(stroke), 1.0);
assert_eq!(blend_step_count(&outline(a, red), &outline(b, blue), BlendSpacing::SmoothColor, 200.0), 254, "strokes alone");
assert_eq!(smooth(a, b, size, Color::rgb8(255, 255, 127), Color::cmyk(0.0, 0.0, 0.0, 0.0)), 128, "RGB against CMYK white");
assert_eq!(smooth(a, b, size, Color::rgb8(255, 255, 127), Color::rgb8(255, 255, 255)), 127, "RGB against RGB white");
}
/// Smooth Color reads the colors of group members paired in order and of text runs, and
/// counts a solid paint against no paint by distance, since such a paint switches halfway
/// instead of mixing.
#[test]
fn smooth_color_reads_the_colors_inside_groups_and_text() {
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
let square = |x: f64, c: Color| Arc::new(smooth_key((x, 150.0), (20.0, 20.0), Paint::solid(c), Paint::None, 0.0));
let group = |x: f64, top: Color| Node::new(NodeId(1), NodeKind::Group { children: vec![square(x, red), square(x, top)], clip: false });
let steps = |a: &Node, b: &Node| blend_step_count(a, b, BlendSpacing::SmoothColor, 200.0);
assert_eq!(steps(&group(50.0, red), &group(250.0, blue)), 254, "groups whose members change color");
assert_eq!(steps(&group(50.0, red), &group(250.0, red)), 9, "groups of the same colors");
let text = |x: f64, c: Color| {
let style = crate::CharStyle { fill: Paint::solid(c), ..Default::default() };
Node::new(NodeId(1), NodeKind::Text(Box::new(crate::TextObject::point(Point::new(x, 150.0), "Hi", style))))
};
assert_eq!(steps(&text(50.0, red), &text(250.0, blue)), 254, "text whose runs change color");
let mut two_runs = text(250.0, red);
if let NodeKind::Text(t) = &mut two_runs.kind {
let style = crate::CharStyle { fill: Paint::solid(blue), ..t.runs[0].style.clone() };
t.runs.push(crate::text::TextRun::new("Hi", style));
}
assert_eq!(steps(&text(50.0, red), &two_runs), 254, "a run that turns blue against one red run");
let empty = |x: f64| smooth_key((x, 150.0), (20.0, 20.0), Paint::None, Paint::None, 0.0);
assert_eq!(steps(&smooth_key((50.0, 150.0), (20.0, 20.0), Paint::solid(red), Paint::None, 0.0), &empty(250.0)), 9, "a fill against none");
let nothing = |c: Color| Node::path(NodeId(1), PathData::new(vec![]), Appearance::basic(Paint::solid(c), Paint::None, 0.0));
assert_eq!(steps(&nothing(red), &nothing(blue)), 254, "keys without bounds whose colors differ");
assert_eq!(steps(&nothing(red), &nothing(red)), 1, "keys without bounds of the same color");
}
/// Smooth Color makes at most eight steps per point of the largest of the keys' widths and
/// heights and the distance between their centers along either axis.
#[test]
fn smooth_color_makes_at_most_eight_steps_a_point() {
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
for (dx, steps) in [(0.0, 160), (20.0, 160), (20.1, 161), (25.0, 200), (31.5, 252), (40.0, 254)] {
assert_eq!(smooth((50.0, 150.0), (50.0 + dx, 150.0), (20.0, 20.0), red, blue), steps, "{dx} pt apart");
}
assert_eq!(smooth((100.0, 150.0), (100.0, 175.0), (20.0, 20.0), red, blue), 200, "25 pt apart vertically");
assert_eq!(smooth((100.0, 150.0), (100.0, 150.0), (5.0, 5.0), red, blue), 40, "5 pt squares on each other");
assert_eq!(smooth((100.0, 150.0), (100.0, 150.0), (25.0, 5.0), red, blue), 200, "the longer side counts");
assert_eq!(smooth((100.0, 150.0), (100.0, 150.0), (1.0, 1.0), red, blue), 8);
}
/// Smooth Color between keys of the same colors counts the largest distance between their
/// corresponding visible edges in mean key widths or heights, rounded, less one; so do keys
/// with gradients, whatever their colors.
#[test]
fn smooth_color_between_the_same_colors_counts_by_distance() {
let red = Color::rgb8(255, 0, 0);
let same = |a, b, size| smooth(a, b, size, red, red);
for (dx, steps) in [(25.0, 1), (50.0, 2), (100.0, 4), (200.0, 9), (400.0, 19), (800.0, 39)] {
assert_eq!(same((50.0, 150.0), (50.0 + dx, 150.0), (20.0, 20.0)), steps, "20 pt squares {dx} pt apart");
}
for (side, steps) in [(5.0, 39), (10.0, 19), (40.0, 4), (80.0, 2)] {
assert_eq!(same((50.0, 150.0), (250.0, 150.0), (side, side)), steps, "{side} pt squares");
}
assert_eq!(same((50.0, 150.0), (250.0, 150.0), (80.0, 10.0)), 2, "wide");
assert_eq!(same((50.0, 150.0), (250.0, 150.0), (10.0, 80.0)), 19, "tall");
assert_eq!(same((50.0, 250.0), (250.0, 50.0), (20.0, 20.0)), 9, "diagonal");
assert_eq!(same((50.0, 250.0), (250.0, 50.0), (80.0, 10.0)), 19, "wide and diagonal");
assert_eq!(same((50.0, 150.0), (1050.0, 150.0), (1.0, 1.0)), 999);
assert_eq!(same((50.0, 150.0), (1052.0, 150.0), (1.0, 1.0)), 1000, "at most 1000");
assert_eq!(same((50.0, 150.0), (50.0, 150.0), (20.0, 20.0)), 1, "at least one");
assert_eq!(same((50.0, 150.0), (250.0, 150.0), (0.0, 20.0)), 9, "vertical lines, measured in their height");
assert_eq!(same((50.0, 150.0), (50.0, 350.0), (20.0, 0.0)), 9, "horizontal lines, measured in their width");
assert_eq!(same((50.0, 150.0), (60.0, 150.0), (0.0, 0.0)), 9, "points, measured in points");
let key = |c, size, stroke: f64| smooth_key(c, size, Paint::solid(red), Paint::solid(Color::BLACK), stroke);
let wide =
blend_step_count(&key((50.0, 150.0), (10.0, 20.0), 0.0), &key((250.0, 150.0), (80.0, 20.0), 0.0), BlendSpacing::SmoothColor, 200.0);
assert_eq!(wide, 4, "keys of different widths");
let strokes =
blend_step_count(&key((50.0, 150.0), (20.0, 20.0), 1.0), &key((250.0, 150.0), (20.0, 20.0), 10.0), BlendSpacing::SmoothColor, 200.0);
assert_eq!(strokes, 7, "strokes widen the visible edges");
let gradient = |a: Color, b: Color| {
Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
Default::default(),
vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)],
))))
};
let shaded = |c, fill| smooth_key(c, (20.0, 20.0), fill, Paint::None, 0.0);
let blue = Color::rgb8(0, 0, 255);
for (from, to) in [(gradient(red, blue), gradient(red, blue)), (gradient(red, blue), gradient(blue, red))] {
assert_eq!(blend_step_count(&shaded((50.0, 150.0), from), &shaded((250.0, 150.0), to), BlendSpacing::SmoothColor, 200.0), 9);
}
}
/// A Smooth Color blend counts each pair of keys on its own.
#[test]
fn smooth_color_counts_each_pair_of_keys() {
let key = |x: f64, c: Color| Arc::new(smooth_key((x, 150.0), (20.0, 20.0), Paint::solid(c), Paint::None, 0.0));
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
let spec = BlendSpec::default();
assert_eq!(blend_steps(&[key(50.0, red), key(150.0, red), key(250.0, blue)], &spec), vec![4, 254]);
assert_eq!(blend_steps(&[key(50.0, red), key(150.0, blue), key(250.0, red)], &spec), vec![254, 254]);
}
/// A Smooth Color blend between different colors inside another blend's keys counts as the
/// steps its colors ask for, so the outer blend keeps the steps it asks for within
/// [`MAX_BLEND_STEPS`]: 200 steps, each a copy making 254 more. The copies keep their keys'
/// colors, also halfway between a red-to-blue and a blue-to-red blend.
#[test]
fn a_smooth_color_blend_in_a_key_counts_its_color_steps() {
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
let key = |x: f64, c: Color| smooth_key((x, 150.0), (20.0, 20.0), Paint::solid(c), Paint::None, 0.0);
let inner = |x: f64, from: Color, to: Color| blend_of(key(x, from), key(x + 100.0, to), BlendSpacing::SmoothColor);
let outer = blend_of(inner(0.0, red, blue), inner(500.0, red, blue), BlendSpacing::Steps(200));
let (keys, spec) = blend_parts(&outer).unwrap();
assert_eq!(blend_steps(keys, spec), vec![200]);
let crossed = blend_of(inner(0.0, red, blue), inner(500.0, blue, red), BlendSpacing::Steps(199));
let (keys, spec) = blend_parts(&crossed).unwrap();
assert_eq!(blend_steps(keys, spec), vec![199]);
let drawn = blend_expand(keys, spec);
let Some(NodeKind::Blend { children, .. }) = drawn.get(100).map(|n| &n.kind) else { panic!("a copy of a blend halfway") };
let fills: Vec<_> = children.iter().map(|k| k.appearance.fill_paint().color()).collect();
assert!(fills == [Some(red), Some(blue)] || fills == [Some(blue), Some(red)], "{fills:?}");
}
/// A Smooth Color blend between the same colors inside another blend's keys counts as up to
/// 1000 steps, which a copy turned to a path can ask for: 200 steps of copies of it come
/// down to 99.
#[test]
fn a_smooth_color_blend_of_the_same_colors_in_a_key_counts_up_to_1000_steps() {
let red = Color::rgb8(255, 0, 0);
let key = |x: f64| smooth_key((x, 150.0), (20.0, 20.0), Paint::solid(red), Paint::None, 0.0);
let inner = |x: f64| blend_of(key(x), key(x + 100.0), BlendSpacing::SmoothColor);
let outer = blend_of(inner(0.0), inner(500.0), BlendSpacing::Steps(200));
let (keys, spec) = blend_parts(&outer).unwrap();
assert_eq!(blend_steps(keys, spec), vec![99]);
}
}
+96
View File
@@ -415,6 +415,68 @@ impl Document {
}
}
/// [`Self::update_links`] for the links `pick` holds for only, in one pass; only the nodes on the
/// way to one are copied.
pub fn update_links_where(&mut self, pick: impl Fn(&LinkInfo) -> bool, mut f: impl FnMut(&mut LinkInfo)) {
fn link_of(n: &Node) -> Option<&LinkInfo> {
match &n.kind {
NodeKind::Image(image) => image.link.as_ref(),
NodeKind::PlacedDocument(placed) => Some(&placed.link),
_ => None,
}
}
/// `n` updated in place, a copy of it when shared; left as it is when it holds no picked link.
fn update(n: &mut Arc<Node>, pick: &dyn Fn(&LinkInfo) -> bool, f: &mut dyn FnMut(&mut LinkInfo)) {
// Each child is updated through a second handle, so an updated child is a new node and a new
// pointer marks a change.
let mask = n.extras().mask.as_ref().and_then(|m| {
let mut art = Arc::clone(&m.art);
update(&mut art, pick, f);
(!Arc::ptr_eq(&art, &m.art)).then_some(art)
});
let mut children = vec![];
for (i, c) in n.children().into_iter().flatten().enumerate() {
let mut new = Arc::clone(c);
update(&mut new, pick, f);
if !Arc::ptr_eq(&new, c) {
children.push((i, new));
}
}
let own = link_of(n).is_some_and(pick);
if !own && mask.is_none() && children.is_empty() {
return;
}
let n = Arc::make_mut(n);
let link = match &mut n.kind {
NodeKind::Image(image) => image.link.as_mut(),
NodeKind::PlacedDocument(placed) => Some(&mut placed.link),
_ => None,
};
if let Some(link) = link.filter(|_| own) {
f(link);
}
if let (Some(art), Some(m)) = (mask, n.extras_if_any().and_then(|e| e.mask.as_mut())) {
m.art = art;
}
if let Some(slots) = n.children_mut() {
for (i, c) in children {
if let Some(slot) = slots.get_mut(i) {
*slot = c;
}
}
}
}
let roots = self
.layers
.iter_mut()
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| &mut p.art));
for root in roots {
update(root, &pick, &mut f);
}
}
/// Change every image object (in the layers, symbol definitions and pattern swatches, opacity-mask
/// art included) for which `pick` holds; only the subtrees holding one are copied.
pub fn update_images(&mut self, pick: impl Fn(&ImageObject) -> bool, mut f: impl FnMut(&mut ImageObject)) {
@@ -486,6 +548,40 @@ mod tests {
.unwrap()
}
/// `update_links_where` changes only the picked links, in a copy of the nodes on the way to them;
/// the other nodes stay shared with the document it was cloned from.
#[test]
fn update_links_where_copies_only_the_nodes_it_changes() {
let mut d = Document::new(10.0, 10.0);
image(&mut d, "a", Some(LinkInfo::new("/art/a.png")));
image(&mut d, "b", Some(LinkInfo::new("/art/b.png")));
image(&mut d, "c", None);
let mut copy = d.clone();
let mut calls = 0;
copy.update_links_where(
|l| l.path == "/art/a.png",
|l| {
calls += 1;
l.relative = Some("art/a.png".into());
},
);
assert_eq!(calls, 1);
let node = |d: &Document, key: &str| {
d.layers[0].children().unwrap().iter().find(|n| matches!(&n.kind, NodeKind::Image(im) if im.key == key)).unwrap().clone()
};
let relative = |n: &Node| match &n.kind {
NodeKind::Image(im) => im.link.as_ref().and_then(|l| l.relative.clone()),
_ => None,
};
assert_eq!((relative(&node(&copy, "a")), relative(&node(&d, "a"))), (Some("art/a.png".into()), None));
assert!(Arc::ptr_eq(&node(&copy, "b"), &node(&d, "b")) && Arc::ptr_eq(&node(&copy, "c"), &node(&d, "c")));
assert!(!Arc::ptr_eq(&copy.layers[0], &d.layers[0]));
// Nothing picked: nothing is copied.
let mut same = d.clone();
same.update_links_where(|_| false, |_| {});
assert!(Arc::ptr_eq(&same.layers[0], &d.layers[0]));
}
#[test]
fn the_placeholder_is_a_png() {
let png = missing_placeholder().unwrap();
+3 -2
View File
@@ -53,8 +53,9 @@ pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation,
#[cfg(test)]
use blend_spec::{blend_color_shift, blend_ramp};
pub use envelope::{
EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, envelope_bounds, envelope_content_boxes,
envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of, envelope_overlay, envelope_stroke_margin, smooth_handles,
EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, TypeInk, envelope_bounds, envelope_content_bounds,
envelope_content_boxes, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of, envelope_overlay, envelope_stroke_margin,
set_type_ink, smooth_handles,
};
pub(crate) use expand::max_outset;
pub use expand::{
+394 -17
View File
@@ -1,6 +1,7 @@
use super::expand::{Hooks, Outliner, Warper, map_node};
use super::mesh::{GradientMesh, MeshPoint, grid_len, grid_points, nodes_bounds, surface_of};
use super::mesh::{GradientMesh, MeshPoint, grid_len, grid_points, surface_of};
use super::{Affine, Arc, Color, Deserialize, Node, NodeId, NodeKind, PathData, Point, Rect, Serialize, Vec2, yes};
use vectorcraft_geom::Homography;
/// How an envelope distorts its content.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -127,19 +128,293 @@ impl EnvelopeOptions {
}
}
/// The bounds of `content` in the axes of `frame`, with its strokes and geometric. Strokes scale
/// with the frame as [`Node::transform`] scales them.
/// The bounds of `content` in the axes of `frame`, with its strokes and geometric, type measured by
/// its glyph outlines (see [`envelope_content_bounds`]). Strokes scale with the frame as
/// [`Node::transform`] scales them.
pub fn envelope_content_boxes(content: &[Arc<Node>], frame: Affine) -> Option<(Rect, Rect)> {
let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY };
let to_frame = frame.inverse();
let (stroked, plain) = content.iter().fold((None, None), |(stroked, plain), c| {
let mut m = (**c).clone();
m.transform(to_frame, true);
(vectorcraft_geom::union_opt(stroked, m.visual_bounds()), vectorcraft_geom::union_opt(plain, m.geometric_bounds()))
(vectorcraft_geom::union_opt(stroked, content_box(c, true, to_frame)), vectorcraft_geom::union_opt(plain, content_box(c, false, to_frame)))
});
Some((stroked?, plain?))
}
/// The geometric bounds an envelope around `content` on the page axes maps from: type, alone or
/// in groups and layers, is measured by its glyph outlines, underlines and strikethroughs instead
/// of its laid-out box. Type keeps its laid-out box while nothing is registered with
/// [`set_type_ink`], and when it draws nothing.
pub fn envelope_content_bounds(content: &[Arc<Node>]) -> Option<Rect> {
content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, false, Affine::IDENTITY)))
}
/// The box of type's glyph outlines, underlines and strikethroughs with its text space mapped by
/// the given transform (outlines mapped point by point) and, for type in perspective, then drawn
/// through its projection and mapped by the second transform. `None` when it draws nothing. Type is
/// laid out above this crate, so the text crate registers one with [`set_type_ink`].
pub type TypeInk = fn(&crate::TextObject, Affine, Option<(Homography, Affine)>) -> Option<Rect>;
/// What [`TypeInk`] maps type's text space by: a transform, and a projection with the transform
/// after it.
type TypeMap = (Affine, Option<(Homography, Affine)>);
static TYPE_INK: std::sync::OnceLock<(TypeInk, crate::hit::LiveInputs)> = std::sync::OnceLock::new();
/// Register how envelopes measure type, and a number that changes whenever what it reads besides
/// the type changes, such as the installed fonts (the first registration stays).
pub fn set_type_ink(f: TypeInk, inputs: crate::hit::LiveInputs) {
// Already set: the same measure, registered by another session, an import or a renderer.
let _ = TYPE_INK.set((f, inputs));
}
/// How many entries each table of [`TypeInks`] holds before it is emptied.
const TYPE_INK_KEPT: usize = 1024;
/// `map`, bit for bit, for a table key.
fn map_bits(map: &TypeMap) -> [u64; 21] {
let mut bits = [0; 21];
let (m, projection) = map;
for (b, v) in bits.iter_mut().zip(m.as_coeffs()) {
*b = v.to_bits();
}
if let Some((h, after)) = projection {
for (b, v) in bits[6..].iter_mut().zip(h.to_array().into_iter().chain(after.as_coeffs())) {
*b = v.to_bits();
}
}
bits
}
/// A key of [`TypeInks::nodes`]: the object's address, the map its outlines are measured in (an
/// affine map without its move) and the inputs number registered with [`set_type_ink`].
type NodeKey = (usize, [u64; 21], u64);
/// A key of [`TypeInks::content`]: two 64-bit hashes of the type without its transform's move and
/// its layout caches ([`content_hash`]), the map its outlines are measured in, and the inputs number.
type ContentKey = ([u64; 2], [u64; 21], u64);
/// Type measured by [`type_ink`] on one thread, by the map it is measured in and the inputs
/// number: by the object (an unchanged object is found without being read),
/// and by its content (a moved or copied object is found without laying it out again). Neither
/// table keeps a copy of the type.
#[derive(Default)]
struct TypeInks {
/// By the object's address, with a weak pointer that keeps the address from being reused.
nodes: std::collections::HashMap<NodeKey, (std::sync::Weak<Node>, Option<Rect>)>,
/// By the type's content.
content: std::collections::HashMap<ContentKey, Option<Rect>>,
}
/// Where [`TypeInks::find`] did not find type: its keys in both tables (no content key for type
/// that could not be hashed whole).
struct Missing {
by_node: NodeKey,
content: Option<ContentKey>,
}
impl TypeInks {
/// The kept box of type node `n` (holding `t`) mapped by `map`, or the keys to keep it under
/// once it is measured.
fn find(&mut self, n: &Arc<Node>, t: &crate::TextObject, map: &TypeMap, inputs: u64) -> Result<Option<Rect>, Box<Missing>> {
// While the table holds a weak pointer to `n`'s allocation, no other object can be at that
// address, and `n` can't be changed in place (`Arc::get_mut` refuses it and `Arc::make_mut`
// moves it).
let by_node = (Arc::as_ptr(n) as usize, map_bits(map), inputs);
if let Some((_, ink)) = self.nodes.get(&by_node) {
return Ok(*ink);
}
// Shrink Text to Fit lays type out by its size on the page, so only a move keeps its layout.
let [a, b, c, d, _, _] = t.xf.as_coeffs();
let mut text = t.clone();
text.xf = Affine::new([a, b, c, d, 0.0, 0.0]);
text.cached_bounds = None;
text.cached_baselines.clear();
let content = content_hash(&text).map(|hash| (hash, by_node.1, inputs));
match content.and_then(|key| self.content.get(&key)) {
Some(ink) => {
let ink = *ink;
self.keep_node(n, by_node, ink);
Ok(ink)
}
None => Err(Box::new(Missing { by_node, content })),
}
}
/// Keep the box `ink` measured for type node `n` under the keys `missing`.
fn keep(&mut self, n: &Arc<Node>, missing: Missing, ink: Option<Rect>) {
if let Some(key) = missing.content {
if self.content.len() >= TYPE_INK_KEPT {
self.content.clear();
}
self.content.insert(key, ink);
}
self.keep_node(n, missing.by_node, ink);
}
fn keep_node(&mut self, n: &Arc<Node>, by_node: NodeKey, ink: Option<Rect>) {
if self.nodes.len() >= TYPE_INK_KEPT {
self.nodes.retain(|_, (weak, _)| weak.strong_count() > 0);
if self.nodes.len() >= TYPE_INK_KEPT {
self.nodes.clear();
}
}
self.nodes.insert(by_node, (Arc::downgrade(n), ink));
}
}
/// Two independent 64-bit hashes of `text` as saved (the layout caches are not saved), with what
/// layout reads that is not saved: whether its first paragraph continues a thread and the bounds
/// of its inline graphics. `None` when it can't be written whole.
fn content_hash(text: &crate::TextObject) -> Option<[u64; 2]> {
use std::hash::Hasher;
/// Feeds what is written to two hashers.
struct Feed([std::collections::hash_map::DefaultHasher; 2]);
impl std::io::Write for Feed {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
for h in &mut self.0 {
h.write(buf);
}
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let mut feed = Feed(Default::default());
// The second hasher starts from another state.
feed.0[1].write_u8(1);
serde_json::to_writer(&mut feed, text).ok()?;
let inline_bounds = text.runs.iter().filter_map(|r| r.inline.as_ref()).map(|i| i.bounds.map(|b| [b.x0, b.y0, b.x1, b.y1].map(f64::to_bits)));
for h in &mut feed.0 {
h.write_u8(u8::from(text.first_para_continues));
for b in inline_bounds.clone() {
match b {
None => h.write_u8(0),
Some(bits) => {
h.write_u8(1);
bits.into_iter().for_each(|v| h.write_u64(v));
}
}
}
}
let [a, b] = feed.0;
Some([a.finish(), b.finish()])
}
std::thread_local! {
/// The type [`type_ink`] measured on this thread.
static TYPE_INKS: std::cell::RefCell<TypeInks> = std::cell::RefCell::new(TypeInks::default());
}
/// The box of the glyph outlines of type node `n` (holding `t`) with its text space mapped by `m`
/// ([`set_type_ink`]) and, for type in perspective, drawn through `projection` and mapped by its
/// second transform; measured again when `t`, the maps (without a move of `m` when there is no
/// projection) or the registered inputs number change. `None` while nothing is registered.
fn type_ink(n: &Arc<Node>, t: &crate::TextObject, m: Affine, projection: Option<(Homography, Affine)>) -> Option<Option<Rect>> {
let (f, inputs) = TYPE_INK.get()?;
let inputs = inputs();
// Without a projection the type is measured without the move, which is added to the box.
let [a, b, c, d, e, g] = m.as_coeffs();
let (map, offset) = match projection {
None => ((Affine::new([a, b, c, d, 0.0, 0.0]), None), Vec2::new(e, g)),
Some(p) => ((m, Some(p)), Vec2::ZERO),
};
let ink = match TYPE_INKS.with_borrow_mut(|kept| kept.find(n, t, &map, inputs)) {
Ok(ink) => ink,
Err(missing) => {
// Measured outside the borrow: laying type out may measure other type.
let ink = f(t, map.0, map.1);
TYPE_INKS.with_borrow_mut(|kept| kept.keep(n, *missing, ink));
ink
}
};
Some(ink.map(|r| r + offset))
}
/// Add to `typed` the address of `n` and of each group and layer in it that holds type, which
/// [`content_box`] measures by its glyphs; is there type in `n`? One walk of the tree.
fn find_type(n: &Node, typed: &mut std::collections::HashSet<usize>) -> bool {
let holds = match &n.kind {
NodeKind::Text(_) => true,
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().fold(false, |holds, c| find_type(c, typed) | holds),
_ => false,
};
if holds {
typed.insert(n as *const Node as usize);
}
holds
}
/// The box of `n` an envelope maps from, in the axes `to` takes the page to: its geometric bounds,
/// or with `stroked` its visual bounds (strokes scaled by `to` as [`Node::transform`] scales them),
/// with type measured by its glyph outlines ([`type_ink`]) instead of its laid-out box, in groups
/// and layers too. Type is laid out as it is on the page, and its outlines are then taken into
/// those axes. A character's strokes reach as far past its glyphs as past the laid-out box.
fn content_box(n: &Arc<Node>, stroked: bool, to: Affine) -> Option<Rect> {
let mut typed = std::collections::HashSet::new();
find_type(n, &mut typed);
content_box_in(n, stroked, to, &typed)
}
/// [`content_box`], with the addresses of the objects in `n` that hold type ([`find_type`]).
fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collections::HashSet<usize>) -> Option<Rect> {
// `n` in the axes of `to`.
let moved = || {
if to == Affine::IDENTITY {
return std::borrow::Cow::Borrowed(&**n);
}
let mut m = (**n).clone();
m.transform(to, true);
std::borrow::Cow::Owned(m)
};
let own = |m: &Node| if stroked { m.visual_bounds() } else { m.geometric_bounds() };
if !typed.contains(&(Arc::as_ptr(n) as usize)) {
return own(&moved());
}
match &n.kind {
NodeKind::Text(t) => {
// Type in perspective: its outlines as its projection draws them.
let ink = match n.projection() {
None => type_ink(n, t, to * t.xf, None),
Some(h) => type_ink(n, t, t.xf, Some((h, to))),
}
.flatten();
let m = moved();
let Some(ink) = ink else { return own(&m) };
if !stroked {
return Some(ink);
}
let (Some(v), Some(g)) = (m.visual_bounds(), m.geometric_bounds()) else { return Some(ink) };
Some(Rect::new(
ink.x0 - (g.x0 - v.x0).max(0.0),
ink.y0 - (g.y0 - v.y0).max(0.0),
ink.x1 + (v.x1 - g.x1).max(0.0),
ink.y1 + (v.y1 - g.y1).max(0.0),
))
}
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
// A clipping path that paints strokes over the clip edge, as in `Node::visual_bounds`.
let clip = children.first()?;
content_box_in(clip, stroked && matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)), to, typed)
}
NodeKind::Layer { .. } | NodeKind::Group { .. } => {
let layer = matches!(n.kind, NodeKind::Layer { .. });
let members = n.editing_children().iter();
if stroked {
// The container's own strokes, scaled by `to` as `Node::transform` scales them,
// without copying its members.
let mut own_strokes = Node::new(n.id, NodeKind::Group { children: Vec::new(), clip: false });
own_strokes.appearance = n.appearance.clone();
own_strokes.transform(to, true);
own_strokes.visual_of_members(members.map(|c| content_box_in(c, true, to, typed)))
} else {
members.filter(|c| c.visible || !layer).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box_in(c, false, to, typed)))
}
}
_ => own(&moved()),
}
}
/// The [`EnvelopeOptions::bounds_margin`] of content with bounds `stroked` and `plain`. `None` for
/// content with no width or no height, or for margins an `f32` can't hold.
pub fn envelope_stroke_margin(stroked: Rect, plain: Rect) -> Option<[f32; 4]> {
@@ -265,20 +540,13 @@ pub struct EnvelopeMap<'a> {
}
impl<'a> EnvelopeMap<'a> {
/// The map of an envelope of `kind` around `content` with `frame` and `options`. `None` when
/// the content has no bounds.
/// The map of an envelope of `kind` around `content` with `frame` and `options`, from the
/// content's bounds with type measured by its glyph outlines ([`envelope_content_bounds`]).
/// `None` when the content has no bounds.
pub fn new(content: &[Arc<Node>], kind: &'a EnvelopeKind, frame: Affine, options: EnvelopeOptions) -> Option<Self> {
let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY };
let to_frame = frame.inverse();
let src = if frame == Affine::IDENTITY {
nodes_bounds(content)?
} else {
content.iter().try_fold(None, |acc, c| {
let mut m = (**c).clone();
m.transform(to_frame, false);
Some(vectorcraft_geom::union_opt(acc, m.geometric_bounds()))
})??
};
let src = content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, false, to_frame)))?;
let src = options.source_box(src);
Some(Self { src, frame, to_frame, surface: surface_of(kind, src, frame) })
}
@@ -378,3 +646,112 @@ pub fn envelope_bounds(content: &[Arc<Node>], kind: &EnvelopeKind, frame: Affine
EnvelopeKind::Warp { .. } => EnvelopeMap::new(content, kind, frame, options)?.bounds(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{CharStyle, TextObject};
/// Look `n` up in `kept`, measuring it (and counting the measures) when it isn't there.
fn look_up(kept: &mut TypeInks, n: &Arc<Node>, linear: Affine, measured: &mut usize) -> Option<Rect> {
let NodeKind::Text(t) = &n.kind else { panic!("type") };
match kept.find(n, t, &(linear, None), 0) {
Ok(ink) => ink,
Err(missing) => {
*measured += 1;
let ink = Some(Rect::new(0.0, 0.0, *measured as f64, 1.0));
kept.keep(n, *missing, ink);
ink
}
}
}
fn type_node(i: usize, text: &str) -> Arc<Node> {
let t = TextObject::point(Point::new(i as f64 * 10.0, 0.0), text, CharStyle::default());
Arc::new(Node::new(NodeId(i as u64), NodeKind::Text(Box::new(t))))
}
/// Many type objects are each measured once however often they are looked up; a moved or copied
/// object is found by its content, and a changed one or another transform is measured again.
#[test]
fn measured_type_is_kept_for_many_objects() {
let mut kept = TypeInks::default();
let mut measured = 0;
let nodes: Vec<_> = (0..200).map(|i| type_node(i, &format!("Type {i}"))).collect();
for _ in 0..5 {
for n in &nodes {
look_up(&mut kept, n, Affine::IDENTITY, &mut measured);
}
}
assert_eq!(measured, 200);
let mut moved = (*nodes[7]).clone();
moved.transform(Affine::translate((300.0, 40.0)), true);
let moved = Arc::new(moved);
assert_eq!(look_up(&mut kept, &moved, Affine::IDENTITY, &mut measured), look_up(&mut kept, &nodes[7], Affine::IDENTITY, &mut measured));
assert_eq!(measured, 200, "a moved object is found by its content");
let changed = type_node(7, "Changed");
look_up(&mut kept, &changed, Affine::IDENTITY, &mut measured);
assert_eq!(measured, 201, "a changed object is measured again");
look_up(&mut kept, &nodes[7], Affine::rotate(0.5), &mut measured);
assert_eq!(measured, 202, "another transform is measured again");
}
/// Type that differs only in what layout reads but files don't save (a first paragraph that
/// continues a thread, the resolved bounds of an inline graphic) is measured again.
#[test]
fn type_that_differs_in_what_is_not_saved_is_measured_again() {
let mut kept = TypeInks::default();
let mut measured = 0;
let mut t = TextObject::point(Point::ZERO, "Type", CharStyle::default());
t.runs.push(crate::TextRun::new("", CharStyle::default()));
t.runs[1].inline = Some(crate::InlineArt { symbol: "S".into(), scale: 1.0, baseline_shift: 0.0, bounds: None });
let node = |t: &TextObject| Arc::new(Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone()))));
look_up(&mut kept, &node(&t), Affine::IDENTITY, &mut measured);
look_up(&mut kept, &node(&t), Affine::IDENTITY, &mut measured);
assert_eq!(measured, 1, "a copy is found by its content");
t.first_para_continues = true;
look_up(&mut kept, &node(&t), Affine::IDENTITY, &mut measured);
assert_eq!(measured, 2, "a first paragraph that continues a thread");
if let Some(inline) = &mut t.runs[1].inline {
inline.bounds = Some(Rect::new(0.0, 0.0, 10.0, 20.0));
}
look_up(&mut kept, &node(&t), Affine::IDENTITY, &mut measured);
assert_eq!(measured, 3, "an inline graphic's bounds");
}
/// A stroked group of type in a scaled frame reaches past its members by its own strokes scaled
/// with the frame, as the group moved into the frame does; deeply nested groups are measured in
/// one walk each.
#[test]
fn a_stroked_group_of_type_is_measured_with_its_strokes_in_the_frame() {
let text = type_node(1, "Group");
let mut group = Node::group(NodeId(2), vec![text.clone()]);
group.appearance = crate::Appearance::basic(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 4.0).into();
let group = Arc::new(group);
let to = Affine::scale(2.0);
let mut moved = (*group).clone();
moved.transform(to, true);
let want = moved.visual_of_members(std::iter::once(content_box(&text, true, to)));
assert!(want.is_some());
assert_eq!(content_box(&group, true, to), want);
let mut nested = group;
for i in 0..300 {
nested = Arc::new(Node::group(NodeId(10 + i), vec![nested]));
}
assert!(content_box(&nested, false, Affine::IDENTITY).is_some());
}
/// A table that fills up is emptied instead of growing, and what is looked up after that is
/// measured again.
#[test]
fn the_tables_stay_bounded() {
let mut kept = TypeInks::default();
let mut measured = 0;
let nodes: Vec<_> = (0..TYPE_INK_KEPT + 10).map(|i| type_node(i, &format!("Type {i}"))).collect();
for n in &nodes {
look_up(&mut kept, n, Affine::IDENTITY, &mut measured);
}
assert!(kept.content.len() <= TYPE_INK_KEPT && kept.nodes.len() <= TYPE_INK_KEPT, "{} {}", kept.content.len(), kept.nodes.len());
assert_eq!(measured, TYPE_INK_KEPT + 10);
}
}
+103
View File
@@ -7,6 +7,7 @@
//! those links (and colours) wherever art and swatches hold them, copying only the nodes that
//! change.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use vectorcraft_color::swatch::REGISTRATION;
@@ -85,6 +86,12 @@ impl Document {
fn numbered_swatch_name(&self, base: &str, from: usize) -> String {
(from..).map(|i| format!("{base} {i}")).find(|n| !self.swatch_name_taken(n)).unwrap_or_else(|| base.to_string())
}
/// Names for several new swatches: [`FreeSwatchNames::take`] gives what
/// [`Document::free_swatch_name`] gives once the swatches named before it are added.
pub fn free_swatch_names(&self) -> FreeSwatchNames {
let taken = self.swatches_iter().map(|s| s.name.clone()).chain(self.swatch_groups.iter().map(|g| g.name.clone()));
FreeSwatchNames { taken: taken.chain([REGISTRATION.to_string()]).collect(), next: HashMap::new() }
}
/// The name a new swatch of `paint` gets by default, unused in the document: a colour's values
/// ([`color_name`], made free like [`Document::free_swatch_name`]), or "New Gradient Swatch 1",
/// "New Pattern Swatch 1"…
@@ -200,6 +207,52 @@ pub fn color_name(c: Color) -> String {
}
}
/// The swatch and color group names of a document ([`Document::free_swatch_names`]) and the names
/// handed out since, for naming many new swatches without searching the document for each name.
#[derive(Clone, Debug)]
pub struct FreeSwatchNames {
taken: HashSet<String>,
/// For each base and first number already numbered, the number its next numbered name is
/// looked for from: names are only ever added, so the numbers below it stay taken.
next: HashMap<(String, usize), usize>,
}
impl FreeSwatchNames {
/// `base`, or the first of "base 2", "base 3"… not taken, as [`Document::free_swatch_name`]
/// gives it; the name is taken from then on.
pub fn take(&mut self, base: &str) -> String {
let name = if self.taken.contains(base) { self.numbered(base, 2) } else { base.to_string() };
self.taken.insert(name.clone());
name
}
/// The name [`Document::new_swatch_name`] gives a new swatch of `paint`; the name is taken
/// from then on.
pub fn take_new(&mut self, paint: &Paint) -> String {
let base = match paint {
Paint::Solid { swatch: Some(n), tint, .. } if *tint < 1.0 => return self.take(&format!("{n} {}%", tint_percent(*tint))),
Paint::Solid { color, .. } => return self.take(&color_name(*color)),
Paint::Gradient(_) => "New Gradient Swatch",
_ => "New Pattern Swatch",
};
let name = self.numbered(base, 1);
self.taken.insert(name.clone());
name
}
/// Count `name` as taken (a swatch or color group added another way).
pub fn insert(&mut self, name: &str) {
self.taken.insert(name.to_string());
}
/// The first of "base `from`", "base `from + 1`"… not taken.
fn numbered(&mut self, base: &str, from: usize) -> String {
let key = (base.to_string(), from);
let start = self.next.get(&key).copied().unwrap_or(from);
let (i, name) =
(start..).map(|i| (i, format!("{base} {i}"))).find(|(_, n)| !self.taken.contains(n)).unwrap_or_else(|| (start, base.to_string()));
self.next.insert(key, i + 1);
name
}
}
/// What [`Document::map_solid_paints`] applies to each linkable colour: `(colour, link, tint)`,
/// true when it changed them.
pub type LinkFn<'a> = dyn FnMut(&mut Color, &mut Option<String>, &mut f32) -> bool + 'a;
@@ -419,6 +472,56 @@ mod tests {
assert_eq!(d.new_swatch_name(&Paint::solid(Color::rgb(1.0, 0.0, 0.0))), "R=255 G=0 B=0");
}
#[test]
fn free_swatch_names_match_naming_each_swatch_as_it_is_added() {
let (mut d, _, _) = doc();
let mut names = d.free_swatch_names();
for base in ["Brand", "Brand", "Mine", "Fresh", "Fresh", "Brand 2", "Brand", REGISTRATION, "Fresh 3", "Fresh", "Mine 2"] {
let want = d.free_swatch_name(base);
assert_eq!(names.take(base), want, "{base}");
d.swatches.push(Swatch { name: want, paint: Paint::solid(Color::BLACK), global: false, spot: false });
}
let added: Vec<&str> = d.swatches.iter().rev().take(11).rev().map(|w| w.name.as_str()).collect();
assert_eq!(
added,
["Brand 2", "Brand 3", "Mine 2", "Fresh", "Fresh 2", "Brand 2 2", "Brand 4", "[Registration] 2", "Fresh 3", "Fresh 4", "Mine 2 2"]
);
}
#[test]
fn free_swatch_names_match_new_swatch_names_as_swatches_are_added() {
let (mut d, _, _) = doc();
let red = Color::rgb(1.0, 0.0, 0.0);
d.swatches.push(Swatch { name: "New Gradient Swatch 2".into(), paint: Paint::solid(red), global: false, spot: false });
let mut names = d.free_swatch_names();
// A name taken another way (a group made alongside) counts for both.
names.insert("R=255 G=0 B=0 3");
d.swatch_groups.push(SwatchGroup { name: "R=255 G=0 B=0 3".into(), swatches: vec![] });
let tint = Paint::Solid { color: red, swatch: Some("Brand".into()), tint: 0.4 };
let gradient = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(Default::default())));
let paints = [Paint::solid(red), Paint::solid(red), gradient.clone(), tint.clone(), Paint::solid(red), gradient.clone(), tint, gradient];
let mut added = vec![];
for paint in paints {
let want = d.new_swatch_name(&paint);
assert_eq!(names.take_new(&paint), want);
d.swatches.push(Swatch { name: want.clone(), paint, global: false, spot: false });
added.push(want);
}
assert_eq!(
added,
[
"R=255 G=0 B=0",
"R=255 G=0 B=0 2",
"New Gradient Swatch 1",
"Brand 40%",
"R=255 G=0 B=0 4",
"New Gradient Swatch 3",
"Brand 40% 2",
"New Gradient Swatch 4"
]
);
}
#[test]
fn mapping_copies_only_changed_nodes() {
let (mut d, a, b) = doc();
+2 -1
View File
@@ -228,7 +228,8 @@ pub struct ParaStyle {
pub leading_model: LeadingModel,
/// Hanging punctuation (Paragraph panel menu › Burasagari): a comma or full stop ending a line
/// may stand outside the frame. New type takes [`Burasagari::Standard`]; documents from before
/// it and imported text keep [`Burasagari::None`].
/// it and imported text keep [`Burasagari::None`], except legacy `.ai` type with binding
/// punctuation on, which opens with [`Burasagari::Forced`].
pub burasagari: Burasagari,
/// Kinsoku (Paragraph panel › Kinsoku Set): which Japanese characters may not start or end a
/// line.
+2 -2
View File
@@ -84,8 +84,8 @@ pub use reshape::{
};
pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_revolve};
pub use solids::{
EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SOLIDS, extrude_options, has_solid, inflate_options, is_three_d, solid_art, validate_solid,
validate_three_d, view_options,
EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SOLIDS, THREE_D_TYPES, extrude_options, has_solid, inflate_options, is_three_d, solid_art,
three_d_params_as, validate_solid, validate_three_d, view_options,
};
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
pub use trap::TRAP;
+2
View File
@@ -39,6 +39,8 @@ pub fn outline_object(doc: Option<&Document>, n: &Node) -> Option<Node> {
/// Run `f` with the hooks live evaluation needs; symbols and patterns come from `doc` (without a
/// document, symbol instances and pattern tiles stay as they are).
fn with_hooks<R>(doc: Option<&Document>, f: impl FnOnce(Hooks) -> R) -> R {
// Envelopes map type from its glyphs here too, without an engine session.
vectorcraft_text::register_envelope_ink();
let outline = |n: &Node| outline_object(doc, n);
let tiles = |name: &str, xf: Affine, region: Rect| Some(doc?.pattern(name)?.instances_in(xf, region));
f(Hooks { outline: Some(&outline), appearance: Some(&bake_appearance), pattern: Some(&tiles), symbols: doc })
+26
View File
@@ -25,6 +25,32 @@ pub fn is_three_d(id: &str) -> bool {
id == crate::REVOLVE || SOLIDS.contains(&id)
}
/// The 3D and Materials panel's object types and the effect that draws each: (type, effect id).
/// Plane keeps the art flat, which is what Rotate draws.
pub const THREE_D_TYPES: [(&str, &str); 4] = [("plane", ROTATE), ("extrude", EXTRUDE), ("revolve", crate::REVOLVE), ("inflate", INFLATE)];
/// The parameters of 3D effect `to` for an effect `from` with `params`, as switching the object
/// type keeps them: every setting `to` takes keeps its value from `params` (the defaults of `from`
/// under them), each rotation angle wrapped into -180° to 180° when `to` is not Revolve, and the
/// settings only `to` takes start at their defaults. Settings `to` does not take are dropped.
pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value {
let current = crate::merged_params(from, params);
let mut out = crate::default_params(to).and_then(|v| v.as_object().cloned()).unwrap_or_default();
for (key, value) in out.iter_mut() {
if let Some(v) = current.get(key) {
value.clone_from(v);
}
}
if to != crate::REVOLVE {
for key in ["rotationX", "rotationY", "rotationZ"] {
if let Some(a) = out.get(key).and_then(Value::as_f64).filter(|a| !(-180.0..=180.0).contains(a)) {
out.insert(key.into(), serde_json::json!((a + 180.0).rem_euclid(360.0) - 180.0));
}
}
}
Value::Object(out)
}
fn solid(fx: &[Effect]) -> Option<(usize, &Effect)> {
fx.iter().enumerate().find(|(_, e)| e.visible && SOLIDS.contains(&e.id.as_str()))
}
+29
View File
@@ -0,0 +1,29 @@
//! Live evaluation without an engine session makes envelopes measure type by its glyph outlines.
//! One test in its own process, so nothing else has registered the measure before the evaluation.
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::sync::Arc;
use vectorcraft_doc::{CharStyle, Node, NodeId, NodeKind, TextObject};
use vectorcraft_geom::{Point, Rect};
/// The largest distance between the edges of `a` and `b`.
fn off(a: Rect, b: Rect) -> f64 {
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().fold(0.0f64, |m, v| m.max(v.abs()))
}
#[test]
fn live_evaluation_measures_type_in_envelopes_by_its_glyphs() {
let t = TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { size: 48.0, ..Default::default() });
let n = Arc::new(Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone()))));
let laid = n.geometric_bounds().unwrap();
let ink = t.xf.transform_rect_bbox(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).ink_bounds().unwrap());
assert!(laid.height() - ink.height() > 1.0, "the laid-out box {laid:?} reaches past the glyphs {ink:?}");
let before = vectorcraft_doc::live::envelope_content_bounds(std::slice::from_ref(&n)).unwrap();
assert!(off(before, laid) < 1e-6, "with nothing registered, type keeps its laid-out box: {before:?} vs {laid:?}");
let _ = vectorcraft_effects::expand_live(None, &n);
let after = vectorcraft_doc::live::envelope_content_bounds(&[n]).unwrap();
assert!(off(after, ink) < 1e-6, "after live evaluation, type is measured by its glyphs: {after:?} vs {ink:?}");
}
+2
View File
@@ -66,3 +66,5 @@ vectorcraft-pdf = { workspace = true, features = ["read-count"] }
wat = { workspace = true }
# Zstandard streams for the Illustrator editing data fuzz tests.
ruzstd = { workspace = true }
# The JavaScript parser's lexer, compared with the script checker's on the same scripts.
vectorcraft-js = { workspace = true }
+23 -14
View File
@@ -575,21 +575,26 @@ pub(crate) fn named_id(p: &Value) -> Result<Option<NodeId>> {
}
}
/// Objects a command targets: explicit `ids` param or the selection.
pub(crate) fn targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
// Objects given are used as given: a value that isn't an object id fails rather than the
// command acting on the selection instead (#785).
match p.get("ids").filter(|v| !v.is_null()) {
Some(Value::Array(a)) => return a.iter().map(object_id).collect(),
Some(v) => return Err(EngineError::Other(format!("`ids` must be an array of object ids, not {v}"))),
None => {}
/// The object `p` gives as `key`, for a command that acts on the selection (or makes something new)
/// without it: `None` when `p` leaves it out or gives null. Any other value that isn't an object id
/// (`"abc"`, `"5"`, `true`, `{}`, `-1`, `2.5`) is an error under `cmd` that names `key`, never the
/// selection. The id is not looked up in the document.
pub(crate) fn object_param(p: &Value, key: &str, cmd: &str) -> Result<Option<NodeId>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(r)) if key == "id" && r.starts_with('$') => {
Err(bad(cmd, format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve")))
}
Some(v) => v.as_u64().map(|id| Some(NodeId(id))).ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number"))),
}
match p.get("id").filter(|v| !v.is_null()) {
Some(v @ Value::Number(_)) => Ok(vec![object_id(v)?]),
// A step reference a batch couldn't resolve (other strings are other ids, such as an
// effect's).
Some(Value::String(r)) if r.starts_with('$') => Err(unresolved_reference(r)),
_ => Ok(s.doc()?.selection.objects.clone()),
}
/// Objects a command targets: its `ids`, else its `id` as `ids` of one ([`named_ids`]), else the
/// selection. An `ids` or `id` that isn't an object id is an error, never the selection.
pub(crate) fn targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
match named_ids(p)? {
Some(ids) => Ok(ids),
None => Ok(s.doc()?.selection.objects.clone()),
}
}
@@ -722,6 +727,10 @@ pub use pathops::shape_count;
/// The gaps View › Show Live Paint Gaps shows on a Live Paint group.
pub use buildcmds::live_paint_gaps;
/// Whether Reset Transformation changes a symbol instance (the Symbols panel menu and the
/// Control bar enable it when it changes one).
pub use brushsym::reset_transformation_changes;
/// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`.
/// They run as before but the command palette leaves them out (it lists the command once).
pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")];
+15 -3
View File
@@ -24,6 +24,9 @@ use super::{
};
use crate::EngineError;
/// Whether Reset Transformation changes a symbol instance.
pub use symbols::reset_transformation_changes;
mod brushes;
mod dynamic;
mod symbols;
@@ -40,8 +43,8 @@ pub(crate) use symbols::{
stored_natural_size,
};
use symbols::{
symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_list, symbol_new, symbol_options, symbol_place, symbol_replace,
symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update,
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,
};
const SIZES_KEY: &str = vectorcraft_doc::SYMBOL_SIZES;
@@ -140,7 +143,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Brush Options…",
[],
None,
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
has_doc,
brush_options
),
@@ -272,6 +275,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
symbol_instance_reset
),
cmd!(
"symbol.instance.resetTransform",
"Reset Transformation",
[],
None,
"{ids?|id?} give the selected symbol instances (in groups too) their symbol's own scale, without rotation, shear or reflection, keeping the center of each one's bounding box in place, as one undo step; other objects, instances in perspective and instances already at their symbol's scale are left as they are, and no undo step is added when nothing changes; an id naming no object, or no symbol instance among the objects, is an error → {ids: the instances changed}",
has_selection,
symbol_instance_reset_transform
),
cmd!(
"symbol.setCurrent",
"Current Symbol",
+56
View File
@@ -696,6 +696,62 @@ pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "ids": ids_json(&ids) }))
}
/// How far a transform coefficient may be from Reset Transformation's for the instance to count as
/// already reset.
const RESET_TOLERANCE: f64 = 1e-9;
/// The transform Reset Transformation gives instance `n` of the document of `boxes`: its symbol's
/// own scale, without rotation, shear or reflection, with the center of its art's bounding box
/// where it is. `None` when [`reset_transformation_changes`] is false for `n`.
fn reset_transformation(boxes: &vectorcraft_doc::SymbolBoxes, n: &Node) -> Option<Affine> {
let d = boxes.document();
if !reset_transformation_changes(d, n) {
return None;
}
let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return None };
let scale = d.symbol_natural_xf(symbol);
// The art's box in symbol space (the ±HALF square when the art cannot be measured): its
// center keeps its place on the page.
let art = boxes.art_bounds(symbol).unwrap_or_else(|| vectorcraft_geom::Rect::new(-HALF, -HALF, HALF, HALF));
let center = xf.transform_rect_bbox(art).center();
Some(Affine::translate(center - scale * art.center()) * scale)
}
/// Does Reset Transformation change `n`? True for an instance of a symbol `d` holds, not in
/// perspective, whose scale, rotation, shear or reflection differs from the symbol's own scale
/// (its stored natural size, or the art unscaled when that size is not positive and finite).
/// It does not measure the art.
pub fn reset_transformation_changes(d: &Document, n: &Node) -> bool {
let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return false };
if n.extras().perspective.is_some() || !d.symbols.iter().any(|s| s.name == *symbol) {
return false;
}
let natural = d.symbol_natural_xf(symbol).as_coeffs();
xf.as_coeffs()[..4].iter().zip(&natural[..4]).any(|(a, b)| (a - b).abs() > RESET_TOLERANCE)
}
pub(super) fn symbol_instance_reset_transform(s: &mut Session, p: &Value) -> Result<Value> {
let ids = selected_instances(s, p)?;
if ids.is_empty() {
return Err(EngineError::Other("no symbol instances selected".into()));
}
let d = &s.doc()?.doc;
let boxes = d.symbol_boxes();
let changes: Vec<(NodeId, Affine)> = ids.iter().filter_map(|id| Some((*id, reset_transformation(&boxes, d.node(*id)?)?))).collect();
if !changes.is_empty() {
s.edit("Reset Transformation", |d, _| {
for (id, new) in &changes {
if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(*id).map(|n| &mut n.kind) {
*xf = *new;
}
}
Ok(())
})?;
}
let changed: Vec<NodeId> = changes.iter().map(|(id, _)| *id).collect();
Ok(json!({ "ids": ids_json(&changed) }))
}
pub(super) fn symbol_set_current(s: &mut Session, p: &Value) -> Result<Value> {
let name = resolve_symbol(&s.doc()?.doc, p, "symbol.setCurrent")?;
set_unknown(s, CURRENT_SYMBOL, Some(json!(name)))?;
+434 -54
View File
@@ -241,9 +241,29 @@ pub(super) struct Used {
impl Used {
fn of<'a>(defs: &Defs<'a>, nodes: impl IntoIterator<Item = &'a Node>) -> Self {
let mut used = Used::default();
let mut todo: Vec<Source<'a>> = nodes.into_iter().map(Source::Node).collect();
used.follow(defs, nodes.into_iter().map(Source::Node).collect());
used
}
/// Every character style of `defs` (with `chars`) and every paragraph style (with `paras`), and
/// the resources they use, styles of the other kind included.
fn of_text_styles(defs: &Defs<'_>, chars: bool, paras: bool) -> Self {
let mut used = Used::default();
let mut todo = vec![];
for s in defs.char_styles.iter().filter(|_| chars) {
used.note(defs, Ref::Name(Res::CharStyle, &s.name), &mut todo);
}
for s in defs.para_styles.iter().filter(|_| paras) {
used.note(defs, Ref::Name(Res::ParaStyle, &s.name), &mut todo);
}
used.follow(defs, todo);
used
}
/// Note the references of `todo`'s sources and of the definitions they lead to.
fn follow<'a>(&mut self, defs: &Defs<'a>, mut todo: Vec<Source<'a>>) {
while let Some(src) = todo.pop() {
let mut found = |r: Ref<'_>| used.note(defs, r, &mut todo);
let mut found = |r: Ref<'_>| self.note(defs, r, &mut todo);
match src {
Source::Node(n) => node_refs(n, &mut found),
Source::Appearance(a) => appearance_refs(a, &mut found),
@@ -251,7 +271,6 @@ impl Used {
Source::Paint(p) => paint_refs(p, &mut found),
}
}
used
}
/// Note `r`; a definition seen for the first time joins `todo`.
@@ -505,7 +524,7 @@ impl SwatchChoices {
}
/// How pasted art is relinked to the document's resources.
#[derive(Debug, Default)]
#[derive(Clone, Debug, Default)]
struct Relink {
renames: BTreeMap<Res, BTreeMap<String, String>>,
/// Graphic style id on the clipboard → its id in the document. Links to other ids are dropped.
@@ -665,6 +684,227 @@ impl SymbolOptions {
}
}
/// A character or paragraph style, symbol (with the Symbol Options copied with it), pattern or
/// brush (placed with the others only when they are placed in use order) to place
/// ([`Clipboard::import_used`]).
#[derive(Clone, Copy)]
enum Def<'c> {
Style(Res, &'c TextStyleDef),
Symbol(&'c Symbol, Option<&'c SymbolOptions>),
Pattern(&'c PatternDef),
Brush(&'c Brush),
}
impl<'c> Def<'c> {
fn key(&self) -> (Res, &'c str) {
match self {
Def::Style(r, s) => (*r, &s.name),
Def::Symbol(s, _) => (Res::Symbol, &s.name),
Def::Pattern(p) => (Res::Pattern, &p.name),
Def::Brush(b) => (Res::Brush, &b.name),
}
}
/// Call `f` with each resource it refers to by name.
fn each_use(&self, f: &mut dyn FnMut(Res, &str)) {
let mut g = |r: Ref<'_>| {
if let Ref::Name(res, n) = r {
f(res, n);
}
};
match self {
Def::Style(_, s) => attrs_refs(&s.attrs, &mut g),
Def::Symbol(s, _) => node_refs(&s.art, &mut g),
Def::Pattern(p) => p.art.iter().for_each(|a| node_refs(a, &mut g)),
Def::Brush(b) => b.art().into_iter().for_each(|a| node_refs(a, &mut g)),
}
}
/// Is it the definition `d` has under `name`, once relinked by `r`? (`brushes`: the brush
/// library of `d`.)
fn same_in(&self, d: &Document, brushes: &Brushes<'_>, name: &str, r: &Relink) -> bool {
match self {
Def::Style(res, s) => {
let theirs = if *res == Res::CharStyle { &d.char_styles } else { &d.para_styles };
let mut attrs = s.attrs.clone();
r.attrs(&mut attrs);
theirs.iter().any(|x| x.name == name && x.attrs == attrs)
}
Def::Symbol(s, options) => d.symbols.iter().any(|x| {
x.name == name
&& options.is_none_or(|o| SymbolOptions::of(d, name) == *o)
&& same_art(r, std::slice::from_ref(&x.art), std::slice::from_ref(&s.art))
}),
Def::Pattern(p) => {
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
d.pattern(name).is_some_and(|x| bare(x) == bare(p) && same_art(r, &x.art, &p.art))
}
Def::Brush(b) => brushes.get().iter().any(|x| x.name == name && same_brush(r, x, b)),
}
}
/// The names of its kind in `d` (`brushes`: its brush library) that are its name or a numbered
/// copy of it.
fn names_in(&self, d: &Document, brushes: &Brushes<'_>) -> Vec<String> {
let (res, name) = self.key();
let names: Vec<String> = match res {
Res::CharStyle => d.char_styles.iter().map(|s| s.name.clone()).collect(),
Res::ParaStyle => d.para_styles.iter().map(|s| s.name.clone()).collect(),
Res::Symbol => d.symbols.iter().map(|s| s.name.clone()).collect(),
Res::Brush => brushes.get().iter().map(|b| b.name.clone()).collect(),
_ => d.patterns.iter().map(|p| p.name.clone()).collect(),
};
names.into_iter().filter(|n| copy_of(name, n)).collect()
}
}
/// `defs` in rounds: each round takes those that use none of the others left, in their order.
/// → (those, the rest, which use each other in a loop or use one that does, in their order)
fn use_order(defs: Vec<Def<'_>>) -> (Vec<Def<'_>>, Vec<Def<'_>>) {
let uses = uses_of(&defs);
// The round of each definition; `None` for one in a loop or one that uses such a definition.
let mut round: Vec<Option<usize>> = vec![None; defs.len()];
// A group outside a loop holds one definition, and comes after the groups it uses.
for (group, looped) in components(&uses) {
for v in group.into_iter().filter(|_| !looped) {
let r = uses[v].iter().try_fold(0, |r, &w| round.get(w).copied().flatten().map(|k| r.max(k + 1)));
round[v] = r;
}
}
let mut ready: Vec<(usize, usize)> = round.iter().enumerate().filter_map(|(i, r)| r.map(|r| (r, i))).collect();
ready.sort_unstable();
let order = ready.into_iter().filter_map(|(_, i)| defs.get(i).copied()).collect();
let rest = defs.iter().zip(&round).filter(|(_, r)| r.is_none()).map(|(def, _)| *def).collect();
(order, rest)
}
/// The positions in `defs` of the definitions each one uses, itself included.
fn uses_of(defs: &[Def<'_>]) -> Vec<Vec<usize>> {
let mut at: BTreeMap<(Res, &str), Vec<usize>> = BTreeMap::new();
for (i, def) in defs.iter().enumerate() {
at.entry(def.key()).or_default().push(i);
}
defs.iter()
.map(|def| {
let mut to = vec![];
def.each_use(&mut |res, n| to.extend(at.get(&(res, n)).into_iter().flatten()));
to.sort_unstable();
to.dedup();
to
})
.collect()
}
/// `rest` ([`use_order`]'s definitions that use each other in a loop or use one that does) split
/// into its loops and the definitions outside a loop, each group after the groups it uses:
/// (positions in `rest`, in their order; true for a loop, definitions that use each other or one
/// that uses itself).
fn loop_groups(rest: &[Def<'_>]) -> Vec<(Vec<usize>, bool)> {
components(&uses_of(rest))
}
/// The strongly connected components of the graph `uses` (each node's successors), each after
/// those it reaches: (nodes, in their order; true for a loop, two or more nodes or one that uses
/// itself).
fn components(uses: &[Vec<usize>]) -> Vec<(Vec<usize>, bool)> {
// Tarjan's algorithm, with an explicit stack of calls.
const NONE: usize = usize::MAX;
let (mut index, mut low, mut on) = (vec![NONE; uses.len()], vec![0; uses.len()], vec![false; uses.len()]);
let (mut stack, mut next, mut groups) = (vec![], 0, vec![]);
for root in 0..uses.len() {
if index[root] != NONE {
continue;
}
let mut calls: Vec<(usize, usize)> = vec![(root, 0)];
(index[root], low[root], on[root]) = (next, next, true);
next += 1;
stack.push(root);
while let Some(&(v, k)) = calls.last() {
if let Some(&w) = uses[v].get(k) {
if let Some(top) = calls.last_mut() {
top.1 += 1;
}
if index[w] == NONE {
(index[w], low[w], on[w]) = (next, next, true);
next += 1;
stack.push(w);
calls.push((w, 0));
} else if on[w] {
low[v] = low[v].min(index[w]);
}
continue;
}
calls.pop();
if let Some(&(u, _)) = calls.last() {
low[u] = low[u].min(low[v]);
}
if low[v] == index[v] {
let mut group = vec![];
while let Some(w) = stack.pop() {
on[w] = false;
group.push(w);
if w == v {
break;
}
}
group.sort_unstable();
let looped = group.len() > 1 || uses[v].contains(&v);
groups.push((group, looped));
}
}
}
groups
}
/// The names in `d` that `looped` (a loop of definitions that use each other, [`loop_groups`])
/// all have at once, each the same once relinked by `r` with those names: each one's name or a
/// numbered copy of it. The names are picked one definition at a time, in order, and each
/// definition is compared as soon as the names of those it uses are picked, so a pick that does
/// not fit is dropped with every combination that follows from it; at most 65,536 comparisons are
/// made. `None` when no combination fits, or none was found within that many comparisons. The brush
/// library of `d` is read once, the first time a brush is compared.
fn names_of_loop(d: &Document, looped: &[Def<'_>], r: &Relink) -> Option<Vec<String>> {
let library = OnceCell::new();
let brushes = Brushes::Lazy(d, &library);
let names: Vec<Vec<String>> = looped.iter().map(|def| def.names_in(d, &brushes)).collect();
if names.is_empty() || names.iter().any(Vec::is_empty) {
return None;
}
// The definitions compared once the name at each position is picked.
let mut compare_at: Vec<Vec<usize>> = vec![vec![]; looped.len()];
for (i, uses) in uses_of(looped).iter().enumerate() {
compare_at[uses.iter().copied().fold(i, usize::max)].push(i);
}
let (mut pick, mut guess, mut budget, mut k) = (vec![0usize; looped.len()], r.clone(), 1usize << 16, 0);
loop {
let (res, own) = looped[k].key();
guess.renames.entry(res).or_default().insert(own.to_string(), names[k][pick[k]].clone());
let fits = compare_at[k].iter().all(|&i| {
budget = budget.saturating_sub(1);
looped[i].same_in(d, &brushes, &names[i][pick[i]], &guess)
});
if fits && k + 1 == looped.len() {
return Some(names.iter().zip(&pick).map(|(l, &p)| l[p].clone()).collect());
}
if budget == 0 {
return None;
}
if fits {
k += 1;
pick[k] = 0;
continue;
}
// The next name at this position, or back to the position before.
loop {
pick[k] += 1;
if pick[k] < names[k].len() {
break;
}
k = k.checked_sub(1)?;
}
}
}
/// What pasting did to the document's resources (part of the paste result).
#[derive(Debug, Default)]
pub(crate) struct Imported {
@@ -704,6 +944,12 @@ impl Clipboard {
pub(crate) fn gather(src: &Document, nodes: Vec<Node>) -> Self {
let library = OnceCell::new();
let used = Used::of(&Defs::of(src, &library), &nodes);
Self::with_used(src, &used, &library, nodes)
}
/// `nodes` and the resources of `src` that `used` names (`library`: the brush library of `src`,
/// read when a brush was used).
fn with_used(src: &Document, used: &Used, library: &OnceCell<Vec<Brush>>, nodes: Vec<Node>) -> Self {
let pick = |r: Res, list: &[TextStyleDef]| list.iter().filter(|s| used.has(r, &s.name)).cloned().collect::<Vec<_>>();
// Read when a brush was used.
let brushes = match (used.names.get(&Res::Brush), library.get()) {
@@ -757,61 +1003,158 @@ impl Clipboard {
/// Add the resources the objects use to `d` (inside the paste's undo step) and work out how
/// pasted copies relink to them.
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Imported {
let used = self.used();
self.import_used(d, &self.used(), choices, same_doc, false)
}
/// [`Self::import_into`] for the resources `used` names. The character and paragraph styles
/// come before the symbols and patterns, whose art may set type in them; with `in_use_order`,
/// each style, symbol, pattern and brush comes after the styles, symbols, patterns and brushes it uses
/// ([`use_order`]), so that it is compared and relinked with their names here, and each loop
/// of definitions that use each other is matched on its own ([`loop_groups`]).
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, in_use_order: bool) -> Imported {
let mut out = Imported::default();
self.import_images(d, &used, same_doc, &mut out);
self.import_swatches(d, &used, choices, same_doc, &mut out);
self.import_images(d, used, same_doc, &mut out);
self.import_swatches(d, used, choices, same_doc, &mut out);
// Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art
// they may brush; the others once those are in.
let mut added_brushes: HashSet<String> = self.import_brushes(d, &used, same_doc, false, &mut out).into_iter().collect();
// Character and paragraph styles (their colours relinked first).
for (r, mine, theirs) in [(Res::CharStyle, &self.char_styles, &mut d.char_styles), (Res::ParaStyle, &self.para_styles, &mut d.para_styles)] {
for def in mine.iter().filter(|s| used.has(r, &s.name)) {
let mut s = def.clone();
// they may brush; the others once those are in. With `in_use_order`, the brushes are
// placed in use order with the others.
let mut added_brushes: HashSet<String> =
if in_use_order { HashSet::new() } else { self.import_brushes(d, used, same_doc, false, &mut out).into_iter().collect() };
let mut defs: Vec<Def<'_>> = vec![];
for (r, list) in [(Res::CharStyle, &self.char_styles), (Res::ParaStyle, &self.para_styles)] {
defs.extend(list.iter().filter(|s| used.has(r, &s.name)).map(|s| Def::Style(r, s)));
}
defs.extend(self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)).map(|s| Def::Symbol(s, self.symbol_options.get(&s.name))));
defs.extend(self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)).map(Def::Pattern));
if in_use_order {
defs.extend(self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).map(Def::Brush));
}
// Groups to place in order; true for a loop of definitions that use each other.
let groups: Vec<(Vec<Def<'_>>, bool)> = if in_use_order {
let (order, rest) = use_order(defs);
let loops = loop_groups(&rest).into_iter().map(|(at, looped)| (at.into_iter().filter_map(|i| rest.get(i).copied()).collect(), looped));
std::iter::once((order, false)).chain(loops).collect()
} else {
vec![(defs, false)]
};
// Styles (their colors relinked first), symbols and patterns (compared once relinked,
// symbols with their options too). The symbols and patterns added are relinked at the end,
// when every new name and graphic style id is known; with `in_use_order`, so are the
// styles added, which a loop of uses may place before a pattern they paint with.
let (mut added_symbols, mut added_patterns, mut added_styles) = (HashSet::new(), HashSet::new(), vec![]);
// Each definition, whether it is in a loop, and the loop it starts.
let steps = groups
.iter()
.flat_map(|(group, looped)| group.iter().enumerate().map(move |(i, def)| (*def, *looped, (*looped && i == 0).then_some(group))));
// In a loop the document does not have all at once, every definition uses one that is
// added under a free name, so each one is added too.
let mut fresh = false;
// The names in the document of the loop being placed, when it has them all at once.
let mut matched: BTreeMap<(Res, String), String> = BTreeMap::new();
// The document's brush library, read the first time a brush is placed in use order and
// stored again after each brush added; nothing else in the loop changes it.
let mut library: Option<Vec<Brush>> = None;
for (def, looped, starts) in steps {
fresh &= looped;
if !looped {
matched.clear();
}
// A loop of uses that the document has all at once is known under those names before
// its definitions are compared.
if let Some(group) = starts {
matched.clear();
match names_of_loop(d, group, &out.relink) {
Some(names) => {
for (def, name) in group.iter().zip(names) {
let (res, own) = def.key();
if own != name {
out.relink.renames.entry(res).or_default().insert(own.to_string(), name.clone());
}
matched.insert((res, own.to_string()), name);
}
fresh = false;
}
None => fresh = true,
}
}
// A definition of such a loop is the document's under the name found for it.
let (res, own) = def.key();
if let Some(name) = matched.get(&(res, own.to_string())) {
let p = if name == own { Placed::Existing } else { Placed::Reused(name.clone()) };
out.placed(res, own, &p);
continue;
}
match def {
Def::Style(r, def) => {
let mut s = def.clone();
out.relink.attrs(&mut s.attrs);
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
let p = place(theirs, &s, same_doc, |a, b| !fresh && a == b);
if in_use_order && let Some(name) = p.new_name(&def.name) {
added_styles.push((r, name, def));
}
out.placed(r, &def.name, &p);
}
Def::Symbol(def, options) => {
let theirs: HashMap<String, SymbolOptions> = match options {
Some(_) => d
.symbols
.iter()
.filter(|s| copy_of(&def.name, &s.name))
.map(|s| (s.name.clone(), SymbolOptions::of(d, &s.name)))
.collect(),
None => HashMap::new(),
};
let r = &out.relink;
let p = place(&mut d.symbols, def, same_doc, |a, b| {
!fresh
&& options.is_none_or(|o| theirs.get(&a.name) == Some(o))
&& same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))
});
if let Some(name) = p.new_name(&def.name) {
if let Some(o) = options {
o.give(d, &name);
}
added_symbols.insert(name);
}
out.placed(Res::Symbol, &def.name, &p);
}
Def::Pattern(def) => {
// Tile options alike, and the art once relinked.
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
let same = |n: &str| !fresh && d.pattern(n).is_some_and(|x| bare(x) == bare(def) && same_art(&out.relink, &x.art, &def.art));
let p = existing(&def.name, d.patterns.iter().map(|p| p.name.as_str()), same_doc, same).unwrap_or_else(|| {
// Its swatch comes along under the same name.
let name = unique_name(&def.name, |n| d.pattern(n).is_some() || d.swatch_name_taken(n));
add_pattern(d, PatternDef { name: name.clone(), ..def.clone() });
Placed::added(&def.name, name)
});
added_patterns.extend(p.new_name(&def.name));
out.placed(Res::Pattern, &def.name, &p);
}
Def::Brush(b) => {
let lib = library.get_or_insert_with(|| vectorcraft_brush::library(d));
let r = &out.relink;
let p = place(lib, b, same_doc, |ours, theirs| !fresh && same_brush(r, ours, theirs));
if let Some(name) = p.new_name(&b.name) {
vectorcraft_brush::store(d, lib);
added_brushes.insert(name);
}
out.placed(Res::Brush, &b.name, &p);
}
}
}
if !in_use_order {
added_brushes.extend(self.import_brushes(d, used, same_doc, true, &mut out));
}
self.import_graphic_styles(d, used, same_doc, &mut out);
for (r, name, def) in added_styles {
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
if let Some(s) = theirs.iter_mut().find(|s| s.name == name) {
s.attrs = def.attrs.clone();
out.relink.attrs(&mut s.attrs);
let p = place(theirs, &s, same_doc, PartialEq::eq);
out.placed(r, &def.name, &p);
}
}
// Symbols and patterns, compared once relinked (symbols with their options too). Those
// added are relinked at the end, when every new name and graphic style id is known.
let mut added_symbols = HashSet::new();
for def in self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)) {
let options = self.symbol_options.get(&def.name);
let theirs: HashMap<String, SymbolOptions> = match options {
Some(_) => {
d.symbols.iter().filter(|s| copy_of(&def.name, &s.name)).map(|s| (s.name.clone(), SymbolOptions::of(d, &s.name))).collect()
}
None => HashMap::new(),
};
let r = &out.relink;
let p = place(&mut d.symbols, def, same_doc, |a, b| {
options.is_none_or(|o| theirs.get(&a.name) == Some(o)) && same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))
});
if let Some(name) = p.new_name(&def.name) {
if let Some(o) = options {
o.give(d, &name);
}
added_symbols.insert(name);
}
out.placed(Res::Symbol, &def.name, &p);
}
let mut added_patterns = HashSet::new();
for def in self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)) {
// Tile options alike, and the art once relinked.
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
let same = |n: &str| d.pattern(n).is_some_and(|x| bare(x) == bare(def) && same_art(&out.relink, &x.art, &def.art));
let p = existing(&def.name, d.patterns.iter().map(|p| p.name.as_str()), same_doc, same).unwrap_or_else(|| {
// Its swatch comes along under the same name.
let name = unique_name(&def.name, |n| d.pattern(n).is_some() || d.swatch_name_taken(n));
add_pattern(d, PatternDef { name: name.clone(), ..def.clone() });
Placed::added(&def.name, name)
});
added_patterns.extend(p.new_name(&def.name));
out.placed(Res::Pattern, &def.name, &p);
}
added_brushes.extend(self.import_brushes(d, &used, same_doc, true, &mut out));
self.import_graphic_styles(d, &used, same_doc, &mut out);
for s in d.symbols.iter_mut().filter(|s| added_symbols.contains(&s.name)) {
out.relink.node(Arc::make_mut(&mut s.art));
}
@@ -925,6 +1268,43 @@ impl Clipboard {
}
}
/// Where a loaded text style is in the document ([`import_text_styles`]).
pub(crate) struct LoadedStyle {
/// A paragraph style (else a character style).
pub para: bool,
/// Its name in the document.
pub name: String,
/// It was added (else the document's own was the same).
pub added: bool,
}
/// Add every character style of `src` (with `chars`) and every paragraph style (with `paras`) to
/// `d`, with the swatches, patterns and what their art uses (styles of the other kind included)
/// that the styles' fill and stroke lead to, as Paste adds those of pasted type
/// ([`Clipboard::import_into`]; a global or spot color whose name `d` gives another color is
/// `d`'s). Each style, symbol and pattern is placed after those it uses, so that a style follows
/// a pattern added under a free name and a pattern follows a style renamed on the way in. A style
/// `d` has under its name, or a numbered copy of it ("Body 2"), that is the same once relinked is
/// used; any other is added under a free name. → each style of `src` placed, in order, character
/// styles first.
pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, paras: bool) -> Vec<LoadedStyle> {
let library = OnceCell::new();
let used = Used::of_text_styles(&Defs::of(src, &library), chars, paras);
let clip = Clipboard::with_used(src, &used, &library, vec![]);
let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::<BTreeSet<_>>());
let out = clip.import_used(d, &used, &SwatchChoices::default(), false, true);
let mut placed: Vec<LoadedStyle> = vec![];
for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] {
for s in list {
let name = out.relink.renamed(r, &s.name);
let again = placed.iter().any(|p| p.para == para && p.name == name);
let added = !again && !before[usize::from(para)].contains(&name);
placed.push(LoadedStyle { para, name, added });
}
}
placed
}
/// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups
/// share one namespace).
fn add_swatch(d: &mut Document, w: &Swatch, same_doc: bool) -> Placed {
+47 -26
View File
@@ -19,7 +19,7 @@ use vectorcraft_render::proof;
#[cfg(not(target_arch = "wasm32"))]
use super::EngineError;
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, color_value, has_doc, str_param, targets};
use super::{CommandSpec, Result, Session, always, bad, cmd, color_value, has_doc, switch_or, targets, text_param};
/// `Document.unknown` key under which files before format v3 kept the assigned profiles (migrated
/// to `Document::color_profiles` on load).
@@ -100,7 +100,7 @@ pub fn specs() -> Vec<CommandSpec> {
proof_setup
),
cmd!(query "view.proofColors", "Proof Colors", ["View"], None, "{on?: bool (default: toggle)} → proof state", always, |s, p| {
toggle_view(s, p, |v, on| v.proof_colors = on.unwrap_or(!v.proof_colors))
toggle_view(s, p, "view.proofColors", |v, on| v.proof_colors = on.unwrap_or(!v.proof_colors))
}),
cmd!(
query "view.overprintPreview",
@@ -109,7 +109,7 @@ pub fn specs() -> Vec<CommandSpec> {
Some("Cmd+Alt+Shift+Y"),
"{on?: bool (default: toggle)} → proof state",
always,
|s, p| toggle_view(s, p, |v, on| v.overprint = on.unwrap_or(!v.overprint))
|s, p| toggle_view(s, p, "view.overprintPreview", |v, on| v.overprint = on.unwrap_or(!v.overprint))
),
cmd!(
query "view.separationsPreview",
@@ -143,12 +143,21 @@ pub fn specs() -> Vec<CommandSpec> {
}
fn intent_param(p: &Value, cmd: &str) -> Result<Option<Intent>> {
match str_param(p, "intent") {
match text_param(p, "intent", cmd)? {
None => Ok(None),
Some(i) => Intent::parse(i).map(Some).ok_or_else(|| bad(cmd, format!("unknown intent `{i}`"))),
}
}
/// The true or false `p` gives for `key`, or `None` when `p` leaves it out or gives null. Any other
/// value is an error, as [`switch_or`] reads it.
fn on_param(p: &Value, key: &str, cmd: &str) -> Result<Option<bool>> {
if p.get(key).is_none_or(Value::is_null) {
return Ok(None);
}
switch_or(p, key, false, cmd).map(Some)
}
fn settings_json(st: &ColorSettings) -> Value {
json!({
"rgb": st.rgb,
@@ -171,16 +180,16 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "edit.colorSettings";
let mut st = cms::active_settings();
let before = st.clone();
if let Some(v) = str_param(p, "rgb") {
if let Some(v) = text_param(p, "rgb", C)? {
st.rgb = cms::canonical_name(v).to_string();
}
if let Some(v) = str_param(p, "cmyk") {
if let Some(v) = text_param(p, "cmyk", C)? {
st.cmyk = cms::canonical_name(v).to_string();
}
if let Some(i) = intent_param(p, C)? {
st.intent = i;
}
st.bpc = bool_or(p, "bpc", st.bpc);
st.bpc = switch_or(p, "bpc", st.bpc, C)?;
if st != before {
cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?;
touch_all(s);
@@ -191,7 +200,7 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
#[cfg(not(target_arch = "wasm32"))]
fn load_profile(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "color.loadProfile";
let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?;
let path = text_param(p, "path", C)?.ok_or_else(|| bad(C, "missing `path`"))?;
crate::file_access::check_read(path).map_err(EngineError::Other)?;
let bytes = crate::store::read_capped(std::path::Path::new(path), crate::store::MAX_PROFILE_FILE).map_err(|e| bad(C, format!("{path}: {e}")))?;
let info = cms::register_icc(&bytes, None).map_err(|e| bad(C, e.to_string()))?;
@@ -209,7 +218,7 @@ fn load_profile(s: &mut Session, p: &Value) -> Result<Value> {
/// Forget a profile `color.loadProfile` loaded, and the copy that is kept of it.
fn remove_profile(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "color.removeProfile";
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?;
let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing `name`"))?;
let info = cms::profiles().into_iter().find(|i| i.name == name).ok_or_else(|| bad(C, format!("no profile named `{name}`")))?;
if info.builtin {
return Err(bad(C, format!("`{name}` is a built-in profile and stays")));
@@ -289,7 +298,7 @@ pub enum Grays {
impl Grays {
/// The `grays` param of `cmd`: `"profile"` (default) or `"black"`.
pub(crate) fn param(cmd: &str, p: &Value) -> Result<Self> {
match str_param(p, "grays").map(str::to_ascii_lowercase).as_deref() {
match text_param(p, "grays", cmd)?.map(str::to_ascii_lowercase).as_deref() {
None | Some("profile") => Ok(Grays::Profile),
Some("black") => Ok(Grays::Black),
Some(g) => Err(bad(cmd, format!("grays must be \"profile\" or \"black\", not `{g}`"))),
@@ -302,18 +311,18 @@ impl Grays {
/// colour through the colour settings.
pub(crate) fn convert_mode(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "file.documentColorMode";
let mode = match str_param(p, "mode").map(str::to_ascii_lowercase).as_deref() {
let mode = match p.get("mode").and_then(Value::as_str).map(str::to_ascii_lowercase).as_deref() {
Some("cmyk") => ColorMode::Cmyk,
Some("rgb") => ColorMode::Rgb,
_ => return Err(bad(C, "mode must be \"cmyk\" or \"rgb\"")),
};
let intent = intent_param(p, C)?;
let grays = Grays::param(C, p)?;
let convert = switch_or(p, "convert", true, C)?;
// Choosing the mode the document already has (the checked menu item) is not an edit.
if s.doc()?.doc.color_mode == mode {
return Ok(json!({ "changed": 0 }));
}
let convert = bool_or(p, "convert", true);
let mut changed = 0usize;
s.edit("Document Color Mode", |d, _| {
changed = set_color_mode(d, mode, convert, intent, grays);
@@ -654,7 +663,7 @@ fn convert_color(_: &mut Session, p: &Value) -> Result<Value> {
let c = cms::active();
let intent = intent_param(p, C)?.unwrap_or(c.settings().intent);
let lab = c.lab(&col);
let (model, vals) = match str_param(p, "to").unwrap_or("rgb") {
let (model, vals) = match text_param(p, "to", C)?.unwrap_or("rgb") {
"rgb" => ("rgb", values(&c.convert(&col, Model::Rgb, intent))),
"cmyk" => ("cmyk", values(&c.convert(&col, Model::Cmyk, intent))),
"gray" | "grayscale" => ("gray", values(&c.convert(&col, Model::Gray, intent))),
@@ -674,7 +683,11 @@ fn convert_color(_: &mut Session, p: &Value) -> Result<Value> {
fn gamut_check(s: &mut Session, p: &Value) -> Result<Value> {
let mut cols: Vec<Color> = vec![];
if let Some(a) = p.get("colors").and_then(Value::as_array) {
let colors = p.get("colors").filter(|v| !v.is_null());
if let Some(v) = colors.filter(|v| !v.is_array()) {
return Err(bad("color.gamutCheck", format!("`colors` must be an array of colors, not {v}")));
}
if let Some(a) = colors.and_then(Value::as_array) {
for v in a {
cols.push(color_value(v).ok_or_else(|| bad("color.gamutCheck", format!("bad color {v}")))?);
}
@@ -728,7 +741,7 @@ fn view_json(v: &proof::ProofView) -> Value {
fn proof_setup(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "view.proofSetup";
let mut v = proof::view();
if let Some(t) = str_param(p, "target") {
if let Some(t) = text_param(p, "target", C)? {
let t = ProofTarget::parse(t).ok_or_else(|| bad(C, format!("unknown proof target `{t}`")))?;
if let ProofTarget::Cmyk(name) = &t
&& !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Cmyk)
@@ -740,8 +753,8 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(i) = intent_param(p, C)? {
v.setup.intent = i;
}
v.setup.simulate_paper = bool_or(p, "simulatePaper", v.setup.simulate_paper);
if let Some(on) = p.get("proof").and_then(Value::as_bool) {
v.setup.simulate_paper = switch_or(p, "simulatePaper", v.setup.simulate_paper, C)?;
if let Some(on) = on_param(p, "proof", C)? {
v.proof_colors = on;
}
proof::set_view(v.clone());
@@ -749,9 +762,10 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result<Value> {
Ok(view_json(&v))
}
fn toggle_view(s: &mut Session, p: &Value, f: impl FnOnce(&mut proof::ProofView, Option<bool>)) -> Result<Value> {
fn toggle_view(s: &mut Session, p: &Value, cmd: &str, f: impl FnOnce(&mut proof::ProofView, Option<bool>)) -> Result<Value> {
let on = on_param(p, "on", cmd)?;
let mut v = proof::view();
f(&mut v, p.get("on").and_then(Value::as_bool));
f(&mut v, on);
proof::set_view(v.clone());
touch_all(s);
Ok(view_json(&v))
@@ -779,16 +793,23 @@ fn separations(s: &mut Session, p: &Value) -> Result<Value> {
.map(|d| proof::plates(&d.doc).into_iter().map(|p| p.name).collect())
.unwrap_or_else(|| cms::PROCESS_PLATES.iter().map(|s| s.to_string()).collect());
let check = |n: &str| if all.iter().any(|a| a == n) { Ok(n.to_string()) } else { Err(bad(C, format!("unknown plate `{n}`"))) };
if let Some(on) = p.get("on").and_then(Value::as_bool) {
if let Some(on) = on_param(p, "on", C)? {
v.separations = if on { Some(v.separations.take().unwrap_or_else(|| all.clone())) } else { None };
}
if let Some(a) = p.get("plates").and_then(Value::as_array) {
v.separations = Some(a.iter().filter_map(Value::as_str).map(check).collect::<Result<Vec<_>>>()?);
match p.get("plates") {
None | Some(Value::Null) => {}
Some(Value::Array(a)) if a.iter().all(Value::is_string) => {
v.separations = Some(a.iter().filter_map(Value::as_str).map(check).collect::<Result<Vec<_>>>()?);
}
Some(_) => {
let key = "plates";
return Err(bad(C, format!("`{key}` must be an array of these names: {}", all.join(", "))));
}
}
if let Some(n) = str_param(p, "only") {
if let Some(n) = text_param(p, "only", C)? {
v.separations = Some(vec![check(n)?]);
}
if let Some(n) = str_param(p, "toggle") {
if let Some(n) = text_param(p, "toggle", C)? {
let n = check(n)?;
let vis = v.separations.get_or_insert_with(|| all.clone());
if let Some(i) = vis.iter().position(|x| *x == n) {
@@ -804,8 +825,8 @@ fn separations(s: &mut Session, p: &Value) -> Result<Value> {
fn set_spot(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "swatch.setSpot";
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?.to_string();
let spot = bool_or(p, "spot", true);
let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing `name`"))?.to_string();
let spot = switch_or(p, "spot", true, C)?;
let sw = s.doc()?.doc.swatch(&name).ok_or_else(|| bad(C, format!("no swatch `{name}`")))?;
if !matches!(sw.paint, Paint::Solid { .. }) {
return Err(bad(C, "only solid-colour swatches can be spot colours"));
+1 -1
View File
@@ -14,7 +14,7 @@ pub(super) fn curvature(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "need at least one point"));
}
let sp = vectorcraft_tools::draw2::curvature_spline(&pts, switch_or(p, "closed", false, C)?);
if let Some(id) = id_param(p, "id") {
if let Some(id) = crate::cmd::object_param(p, "id", C)? {
s.edit("Curvature", |d, sel| {
*path_mut(d, id)? = PathData::single(sp);
sel.set([id]);
+59 -3
View File
@@ -9,9 +9,9 @@ use vectorcraft_geom::{Affine, Point, Vec2};
use super::clipboard::SwatchChoices;
use super::{
CommandSpec, Result, Session, always, bad, bool_or, can_clear_history, can_redo, can_undo, checked_ids_param, cmd, f64_or, f64_req,
finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param, index, ok,
point_param, str_param, switch_or,
CommandSpec, Result, Session, always, bad, bool_or, can_clear_history, can_redo, can_undo, checked_ids_param, clock_date, cmd, date_param,
f64_or, f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param,
index, ok, point_param, str_param, switch_or,
};
use crate::{Clipboard, EngineError, inspect};
@@ -116,6 +116,15 @@ pub fn specs() -> Vec<CommandSpec> {
can_clear_history,
clear_history
),
cmd!(
"edit.newDocumentFromState",
"New Document from State",
[],
None,
"{index?: a row of the History panel (0: the oldest state kept; default: the current state), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches)} make a new document holding the art as it was at that state, and make it the active document (the History panel's New Document from State button). The new document is named with the next Untitled-N, has nothing selected and no steps to undo or redo, is marked unsaved and links to the same files. It is out of symbol, opacity-mask and pattern editing, with the art drawn in a pattern's tile stored in the pattern as object.pattern.done stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step, as edit.undo keeps it; `index` names the row as it was listed before that. An index that names no state is an error and changes nothing → {index: the new document's, title}",
has_doc,
new_document_from_state
),
cmd!(
"edit.undoGroup.begin",
"Begin Undo Group",
@@ -606,6 +615,53 @@ fn clear_history(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "cleared": cleared }))
}
/// History panel › New Document from State: a new document with the art of a state, and without
/// the editing state that state may hold (opacity-mask or symbol editing, Puppet Warp pins, new art).
/// Its links point at the files the source finds, which may be in the source's folder away from
/// the links' paths. Later artboards in the two documents take their ids separately. A later save of the new document
/// over the file its art was read from asks first, as a save of the source does.
fn new_document_from_state(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "edit.newDocumentFromState";
let created = date_param(p, "created", C)?;
let st = s.doc()?;
// The row as the panel lists it now: keeping an edit in progress below changes the rows.
let chosen = match p.get("index") {
None | Some(Value::Null) => None,
Some(v) => {
let state = v.as_u64().and_then(|row| st.history.state(&st.doc, index(row)));
Some(state.ok_or_else(|| bad(C, format!("no history state {v}")))?.clone())
}
};
settle_interaction(s)?;
let st = s.doc()?;
let mut doc = Document::clone(chosen.as_ref().unwrap_or(&st.doc));
let (imported_from, import_losses, opened_by) = (st.imported_from.clone(), st.import_losses.clone(), st.opened_by.clone());
if let Some(path) = st.path.as_deref() {
// Files are looked for within the asking caller's roots, else within those of the caller that opened the source.
let roots = crate::file_access::current().or_else(|| opened_by.clone());
crate::file_access::confine(roots.as_ref(), || super::links::with_found_paths(&mut doc, path));
}
doc.drop_edit_modes();
if doc.pattern_edit.is_some() {
super::patterncmds::finish_edit(&mut doc, &mut vectorcraft_doc::Selection::default())?;
}
doc.puppet = None;
doc.new_art.set(Arc::default());
let retired = vectorcraft_doc::RetiredArtboardId::default();
retired.raise(doc.retired_artboard_id.get());
doc.retired_artboard_id = retired;
doc.title = s.next_untitled();
doc.metadata.created = clock_date(s, "created", created);
doc.metadata.modified = None;
let i = s.add_document(doc, None);
let st = s.doc_mut()?;
st.imported_from = imported_from;
st.import_losses = import_losses;
st.opened_by = st.opened_by.take().or(opened_by);
st.mark_unsaved();
Ok(json!({ "index": i, "title": st.title() }))
}
/// `selection` for an undo (redo) step, sharing that of `like`, the step beside it, when the same.
fn shared_selection(selection: vectorcraft_doc::Selection, like: Option<&crate::HistoryEntry>) -> Arc<vectorcraft_doc::Selection> {
match like {
+67 -8
View File
@@ -53,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Effect Options",
[],
None,
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place), visible?: bool, item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} → {ids}",
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool, item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} → {ids}",
has_doc,
set_params
),
@@ -222,6 +222,16 @@ pub(crate) const ONE_3D: &str = "An object takes one 3D effect. Edit the existin
pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "effect.apply";
let id = str_param(p, "effect").or_else(|| str_param(p, "id")).ok_or_else(|| bad(C, "missing `effect` id"))?;
// An effect given as `id` names no objects: the targets are read with that `id` as null.
let effect_as_id;
let p = if str_param(p, "effect").is_none() {
let mut q = p.clone();
q["id"] = Value::Null;
effect_as_id = q;
&effect_as_id
} else {
p
};
let mut params = p.get("params").cloned().unwrap_or(Value::Null);
if !params.is_null() && !params.is_object() {
return Err(bad(C, "`params` must be an object"));
@@ -422,10 +432,28 @@ pub(crate) fn set_params_effects(s: &Session, p: &Value) -> Vec<String> {
return vec![];
};
let Ok(targets) = effect_targets(s, p, item, index, C) else { return vec![] };
let effect = |&(id, at, index): &(NodeId, Option<usize>, usize)| Some(st.doc.node(id)?.appearance.effects_at(at)?.get(index)?.id.clone());
// A 3D effect whose type `threeDType` changes takes the new effect's parameters.
let kind = three_d_type(p, C).ok().flatten();
let effect = |&(id, at, index): &(NodeId, Option<usize>, usize)| {
let id = &st.doc.node(id)?.appearance.effects_at(at)?.get(index)?.id;
Some(kind.filter(|_| effects::is_three_d(id)).map_or_else(|| id.clone(), str::to_string))
};
targets.iter().filter_map(effect).collect()
}
/// The effect `threeDType` in `p` turns a 3D effect into ([`effects::THREE_D_TYPES`]), when given.
fn three_d_type(p: &Value, cmd: &str) -> Result<Option<&'static str>> {
let key = "threeDType";
let Some(v) = p.get(key) else { return Ok(None) };
match v.as_str().and_then(|t| effects::THREE_D_TYPES.iter().find(|(name, _)| *name == t)) {
Some((_, id)) => Ok(Some(id)),
None => {
let names: Vec<&str> = effects::THREE_D_TYPES.iter().map(|(name, _)| *name).collect();
Err(bad(cmd, format!("`{key}` must be one of {}", names.join(", "))))
}
}
}
fn lighting_preset(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "effect.lightingPreset";
let patch = str_param(p, "preset")
@@ -450,8 +478,9 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result<Value> {
}
/// `effect.setParams`: merges `params` into the effect at `index` of the targets' active item, and
/// sets its Warp style (`warpStyle`) or visibility (`visible`), as one undo step. They are checked
/// as `effect.apply` checks them, and a visible 3D effect must still fit. → `{ids}`.
/// sets its Warp style (`warpStyle`), its 3D type (`threeDType`) or visibility (`visible`), as one
/// undo step. They are checked as `effect.apply` checks them, and a visible 3D effect must still
/// fit. → `{ids}`.
fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "effect.setParams";
let index = index_param(p, "index", C)?;
@@ -459,6 +488,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
if !params.is_null() && !params.is_object() {
return Err(bad(C, "`params` must be an object"));
}
let kind = three_d_type(p, C)?;
let warp_id = p
.get("warpStyle")
.map(|v| -> Result<String> {
@@ -476,21 +506,41 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
if edited.iter().any(|e| texture_load_effect(e)) {
load_texture(&mut params, C)?;
}
for (id, target, index) in effect_targets(s, p, item, index, C)? {
let targets = effect_targets(s, p, item, index, C)?;
// The type each 3D effect already has, with nothing else to change, is no edit (and is not
// checked again).
let nothing_else = params.as_object().is_none_or(serde_json::Map::is_empty) && visible.is_none() && warp_id.is_none();
if let Some(to) = kind
&& nothing_else
{
let d = &s.doc()?.doc;
// The effects edited: a target without an effect at `index` is left as it is.
let ids: Vec<&str> =
targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index).map(|e| e.id.as_str())).collect();
if !ids.is_empty() && ids.iter().all(|id| *id == to) {
return Ok(json!({ "ids": [] }));
}
}
for &(id, target, index) in &targets {
let n = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?;
let effect = n.appearance.effects_at(target).and_then(|fx| fx.get(index));
if warp_id.is_some() && effect.is_some_and(|e| e.id.strip_prefix("warp.").and_then(effects::WarpStyle::from_id).is_none()) {
return Err(bad(C, "warpStyle can only edit an applied Warp effect"));
}
if kind.is_some() && effect.is_some_and(|e| !effects::is_three_d(&e.id)) {
return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0)));
}
if let Some(e) = effect
&& effects::is_three_d(&e.id)
&& visible != Some(false)
{
let mut prospective = effects::merged_params(&e.id, &e.params);
if let (Some(cur), Value::Object(new)) = (prospective.as_object_mut(), effects::upgrade_params(&e.id, &params)) {
let to = kind.unwrap_or(&e.id);
let mut prospective =
if to == e.id { effects::merged_params(&e.id, &e.params) } else { effects::three_d_params_as(&e.id, &e.params, to) };
if let (Some(cur), Value::Object(new)) = (prospective.as_object_mut(), effects::upgrade_params(to, &params)) {
cur.extend(new);
}
effects::validate_three_d(n, &e.id, &prospective).map_err(|e| bad(C, e))?;
effects::validate_three_d(n, to, &prospective).map_err(|e| bad(C, e))?;
}
}
let ids = edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| {
@@ -498,6 +548,12 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(id) = &warp_id {
e.id.clone_from(id);
}
if let Some(to) = kind
&& e.id != to
{
e.params = effects::three_d_params_as(&e.id, &e.params, to);
e.id = to.to_string();
}
if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, &params), &mut e.params) {
if !cur.is_object() {
*cur = effects::merged_params(&e.id, &Value::Null);
@@ -859,5 +915,8 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
#[cfg(test)]
mod lighting_presets_tests;
#[cfg(test)]
mod three_d_type_tests;
#[cfg(test)]
mod tests;
@@ -0,0 +1,144 @@
#![allow(clippy::unwrap_used, clippy::panic)]
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use crate::Session;
fn setup(effect: &str, params: Value) -> (Session, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
let id = NodeId(s.execute("path.create", &json!({"d":"M100 100L200 100L200 200L100 200Z"})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"color":"#338ad6"})).unwrap();
s.execute("effect.apply", &json!({"effect":effect,"item":null,"params":params})).unwrap();
(s, id)
}
fn effect(s: &Session, id: NodeId) -> (String, Value) {
let e = &s.doc().unwrap().doc.node(id).unwrap().appearance.effects[0];
(e.id.clone(), e.params.clone())
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
#[test]
fn three_d_type_turns_the_effect_in_place_keeping_shared_settings_in_one_undo_step() {
let types = [("plane", "threeD.rotate"), ("extrude", "threeD.extrude"), ("revolve", "threeD.revolve"), ("inflate", "threeD.inflate")];
for (from_type, from) in types {
for (to_type, to) in types {
if from == to {
continue;
}
let (mut s, id) = setup(from, json!({"rotationX": 12.0, "rotationY": -30.0, "rotationZ": 5.0, "ambient": 40.0, "lightIntensity": 55.0}));
let before = s.doc().unwrap().doc.clone();
let history = undo_len(&s);
let p = json!({"index": 0, "item": null, "threeDType": to_type});
s.check_params("effect.setParams", &p).unwrap();
s.execute("effect.setParams", &p).unwrap();
let (now, params) = effect(&s, id);
assert_eq!(now, to, "{from_type} → {to_type}");
assert_eq!(params["rotationX"], 12.0, "{from_type} → {to_type}");
assert_eq!(params["rotationY"], -30.0);
assert_eq!(params["ambient"], 40.0);
assert_eq!(params["lightIntensity"], 55.0);
// Settings only the new effect takes start at its defaults; others are dropped.
let defaults = vectorcraft_render::effects::default_params(to).unwrap();
for key in params.as_object().unwrap().keys() {
assert!(defaults.get(key).is_some(), "{from_type} → {to_type} kept `{key}`");
}
if to == "threeD.extrude" {
assert_eq!(params["bevel"], defaults["bevel"]);
}
assert_eq!(undo_len(&s), history + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, before);
}
}
}
#[test]
fn three_d_type_carries_depth_between_extrude_and_inflate_and_merges_params_after() {
let (mut s, id) = setup("threeD.extrude", json!({"depth": 80.0, "twist": 30.0, "bevel": "classic"}));
s.execute("effect.setParams", &json!({"index": 0, "threeDType": "inflate", "params": {"volume": 70.0}})).unwrap();
let (now, params) = effect(&s, id);
assert_eq!(now, "threeD.inflate");
assert_eq!(params["depth"], 80.0);
assert_eq!(params["twist"], 30.0);
assert_eq!(params["volume"], 70.0);
assert!(params.get("bevel").is_none());
}
#[test]
fn revolve_angles_outside_half_a_turn_wrap_when_the_type_leaves_revolve() {
let (mut s, id) = setup("threeD.revolve", json!({"rotationX": 270.0, "rotationY": -200.0}));
s.execute("effect.setParams", &json!({"index": 0, "threeDType": "plane"})).unwrap();
let (_, params) = effect(&s, id);
assert_eq!(params["rotationX"], -90.0);
assert_eq!(params["rotationY"], 160.0);
}
#[test]
fn the_current_type_alone_changes_nothing_and_records_no_undo_step() {
let (mut s, id) = setup("threeD.extrude", json!({"depth": 80.0}));
let before = s.doc().unwrap().doc.clone();
let history = undo_len(&s);
let r = s.execute("effect.setParams", &json!({"index": 0, "threeDType": "extrude"})).unwrap();
assert_eq!(r["ids"], json!([]));
assert_eq!(undo_len(&s), history);
assert_eq!(s.doc().unwrap().doc, before);
// With other changes the edit runs as usual.
s.execute("effect.setParams", &json!({"index": 0, "threeDType": "extrude", "params": {"depth": 90.0}})).unwrap();
assert_eq!(effect(&s, id).1["depth"], 90.0);
assert_eq!(undo_len(&s), history + 1);
}
#[test]
fn the_current_type_with_an_object_without_effects_selected_too_records_no_undo_step() {
let (mut s, a) = setup("threeD.extrude", json!({}));
let b = NodeId(s.execute("path.create", &json!({"d":"M250 100L350 100L350 200L250 200Z"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let history = undo_len(&s);
s.execute("effect.setParams", &json!({"index": 0, "item": null, "aligned": true, "threeDType": "extrude"})).unwrap();
assert_eq!(undo_len(&s), history);
assert_eq!(s.doc().unwrap().doc, before);
}
#[test]
fn three_d_type_rejects_unknown_types_and_effects_that_are_not_3d() {
let (mut s, _) = setup("threeD.extrude", json!({}));
let before = s.doc().unwrap().doc.clone();
for t in [json!("cube"), json!(""), json!(null), json!(2), json!("Plane"), json!("plane/../x")] {
let p = json!({"index": 0, "threeDType": t});
let err = s.execute("effect.setParams", &p).unwrap_err().to_string();
assert!(err.contains("must be one of plane, extrude, revolve, inflate"), "{t}: {err}");
}
assert_eq!(s.doc().unwrap().doc, before);
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "item": null})).unwrap();
let err = s.execute("effect.setParams", &json!({"index": 1, "threeDType": "plane"})).unwrap_err().to_string();
assert!(err.contains("needs a 3D effect at index 1"), "{err}");
let err = s.execute("effect.setParams", &json!({"index": 5, "threeDType": "plane"})).unwrap_err().to_string();
assert!(err.contains("no effect at index 5"), "{err}");
}
#[test]
fn three_d_type_turns_every_selected_object_in_one_undo_step() {
let (mut s, a) = setup("threeD.rotate", json!({}));
let b = NodeId(s.execute("path.create", &json!({"d":"M250 100L350 100L350 200L250 200Z"})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"color":"#d63333"})).unwrap();
s.execute("effect.apply", &json!({"effect":"threeD.rotate","item":null})).unwrap();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let history = undo_len(&s);
s.execute("effect.setParams", &json!({"index": 0, "item": null, "aligned": true, "threeDType": "extrude"})).unwrap();
assert_eq!(effect(&s, a).0, "threeD.extrude");
assert_eq!(effect(&s, b).0, "threeD.extrude");
assert_eq!(undo_len(&s), history + 1);
}
#[test]
fn params_for_the_new_type_pass_the_parameter_check() {
let (s, _) = setup("threeD.rotate", json!({}));
// `depth` is an Extrude & Bevel setting, checked against the effect the type makes.
s.check_params("effect.setParams", &json!({"index": 0, "threeDType": "extrude", "params": {"depth": 20.0}})).unwrap();
}
+1 -1
View File
@@ -109,7 +109,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[
name: "editingData",
ty: "boolean",
default: "true",
description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, compound paths, paths, fills and strokes, colors, linear and radial gradients, patterns on a grid of tiles, swatches, artboards and which one is active, the transparency of objects and layers, objects' opacity masks, clipping groups and layers clipped by a path, embedded images with their pixels, and linked images as placed files with a preview, with type, other patterns, symbols, other clipping objects and live objects as plain filled and stroked paths, freeform gradients, gradients along or across a stroke and gradients of more than 256 stops as their average color, gradients that dither or mix perceptually as classic ones, and gradient stops linked to global process colors as their colors (written only with every artboard, as Preserve Editing is)",
description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, compound paths, paths, fills and strokes, colors, linear and radial gradients, patterns on a grid of tiles, swatches, artboards and which one is active, the transparency of objects and layers, objects' opacity masks, clipping groups and layers clipped by a path, embedded images with their pixels, linked images as placed files with a preview, point type, area type and type on a path as text, and symbols and their instances, with other type, other patterns, other clipping objects, other symbol instances and live objects as plain filled and stroked paths, freeform gradients, gradients along or across a stroke and gradients of more than 256 stops as their average color, gradients that dither or mix perceptually as classic ones, and gradient stops linked to global process colors as their colors (written only with every artboard, as Preserve Editing is)",
},
FormatOption {
name: "aiVersion",
+8 -6
View File
@@ -7,7 +7,7 @@ use vectorcraft_doc::{ColorMode, Document};
use vectorcraft_pdf::{Choice, CropTo, ImportOptions, PdfError, TextAs};
use super::super::colormgmt::Grays;
use super::super::{Result, Session, bad, f64_or, parse_range, str_param};
use super::super::{Result, Session, bad, check_numbers, number_or, parse_range, text_param};
use super::{err, source};
/// The `document.open` options besides the file. The PDF ones (pages, box, password, text,
@@ -75,16 +75,17 @@ impl LoadOptions {
Some(Value::Number(n)) => Some(n.to_string()),
Some(v) => return Err(bad(cmd, format!("pages must be a range such as \"2-3\" or a page number, not {v}"))),
};
let crop = choice(cmd, "cropTo", str_param(p, "cropTo").or_else(|| str_param(p, "crop")))?;
let password = str_param(p, "password").filter(|s| !s.is_empty()).map(str::to_string);
let color_mode = match str_param(p, "colorMode").map(str::to_ascii_lowercase).as_deref() {
let (crop_to, crop_alias) = (text_param(p, "cropTo", cmd)?, text_param(p, "crop", cmd)?);
let crop = choice(cmd, "cropTo", crop_to.or(crop_alias))?;
let password = text_param(p, "password", cmd)?.filter(|s| !s.is_empty()).map(str::to_string);
let color_mode = match text_param(p, "colorMode", cmd)?.map(str::to_ascii_lowercase).as_deref() {
None => None,
Some("rgb") => Some(ColorMode::Rgb),
Some("cmyk") => Some(ColorMode::Cmyk),
Some(m) => return Err(bad(cmd, format!("colorMode must be rgb or cmyk, not `{m}`"))),
};
let grays = Grays::param(cmd, p)?;
let text_as = choice(cmd, "textAs", str_param(p, "textAs"))?;
let text_as = choice(cmd, "textAs", text_param(p, "textAs", cmd)?)?;
let layers = match p.get("layers").filter(|v| !v.is_null()) {
None => true,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "layers must be true or false"))?,
@@ -172,6 +173,7 @@ const INFO: &str = "document.pdfInfo";
pub(super) fn pdf_info(_: &mut Session, p: &Value) -> Result<Value> {
let bytes = source(p, INFO)?.bytes;
let o = LoadOptions::from_params(INFO, p)?;
check_numbers(p, &["thumbnailSize"], INFO)?;
// Programs whose header is only `%!` are PostScript too, as `clipboard.importEps` reads them.
if bytes.starts_with(b"%!") || vectorcraft_pdf::is_postscript(&bytes) {
return postscript_info(&bytes, p);
@@ -229,7 +231,7 @@ fn postscript_info(bytes: &[u8], p: &Value) -> Result<Value> {
/// A PNG of `doc`'s first artboard, `thumbnailSize` px (default 160, from 16 to 1024) on its longer
/// side, base64.
fn thumbnail(doc: &Document, p: &Value) -> Result<String> {
let size = f64_or(p, "thumbnailSize", 160.0).clamp(16.0, 1024.0);
let size = number_or(p, "thumbnailSize", 160.0, INFO)?.clamp(16.0, 1024.0);
let r = doc.artboards.first().map(|a| a.rect).ok_or_else(|| err("the page has no area"))?;
let png = super::encode(doc, "png", &json!({"scale": size / r.width().max(r.height()).max(1.0)}))?;
Ok(vectorcraft_format::base64_encode(&png))
+21 -2
View File
@@ -14,7 +14,7 @@
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use vectorcraft_doc::cancel::{self, CancelToken, ProgressSink};
@@ -26,6 +26,9 @@ pub struct Progress {
total: AtomicU64,
/// The steps are files (Export for Screens), not artboards.
files: bool,
/// The last report came from a plug-in ([`vectorcraft_plugins::host::PROGRESS_STEP`]): its
/// steps are its own, shown as a share of the work.
share: AtomicBool,
}
impl Progress {
@@ -43,6 +46,11 @@ impl Progress {
self.files
}
/// Are the steps a plug-in's own, which only a share of the work done describes?
pub fn counts_share(&self) -> bool {
self.share.load(Ordering::Relaxed)
}
/// `(steps done, steps in all)`; `total` is 0 while the export can't say (one file made in one go).
pub fn counts(&self) -> (u64, u64) {
let total = self.total.load(Ordering::Relaxed);
@@ -68,7 +76,8 @@ impl Progress {
/// Run `f` with `progress`'s token in effect on this thread and the steps reported to it.
pub fn scope<R>(progress: &Arc<Progress>, f: impl FnOnce() -> R) -> R {
let to = Arc::clone(progress);
let sink: ProgressSink = Rc::new(move |done, total, _| {
let sink: ProgressSink = Rc::new(move |done, total, what| {
to.share.store(what == vectorcraft_plugins::host::PROGRESS_STEP, Ordering::Relaxed);
to.total.store(total, Ordering::Relaxed);
to.done.store(done, Ordering::Relaxed);
});
@@ -94,4 +103,14 @@ mod tests {
assert!(matches!(r, Err(crate::EngineError::Cancelled)), "{:?}", r.err());
assert!(!cancel::is_cancelled(), "the scope ended");
}
/// A plug-in's reports count as a share of the work, not as artboards or files.
#[test]
fn a_plugin_s_reports_count_as_a_share_of_the_work() {
let p = Progress::new();
scope(&p, || cancel::progress(1, 4, "artboard"));
assert_eq!((p.counts(), p.counts_share()), ((1, 4), false));
scope(&p, || cancel::progress(3, 8, vectorcraft_plugins::host::PROGRESS_STEP));
assert_eq!((p.counts(), p.counts_share()), ((3, 8), true));
}
}
@@ -98,7 +98,9 @@ fn templates_and_libraries_cannot_silently_extract_preview_content() {
let original = s.doc().unwrap().doc.clone();
for name in ["test.af", "renamed.svg"] {
let p = json!({"name":name, "dataBase64":vectorcraft_format::base64_encode(&file(&png()))});
for cmd in ["file.newFromTemplate", "swatch.library.load", "graphicStyle.loadLibrary"] {
for cmd in
["file.newFromTemplate", "swatch.library.load", "graphicStyle.loadLibrary", "charStyle.load", "paraStyle.load", "textStyle.loadAll"]
{
let e = s.execute(cmd, &p).unwrap_err().to_string();
assert!(e.contains("File › Open"), "{cmd}: {e}");
}
@@ -488,7 +488,7 @@ fn an_ai_file_opens_from_its_vectorcraft_document_when_the_editing_copy_differs(
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [id]})).unwrap();
s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [id]})).unwrap();
let r = s.execute("document.export", &json!({"format": "ai"})).unwrap();
assert!(r["warnings"].to_string().contains("live effects"), "{r}");
let bytes = b64(&r);
@@ -147,6 +147,76 @@ fn load_options_read_pages_crop_and_password() {
assert_eq!(LoadOptions::from_params("x", &Value::Null).unwrap(), LoadOptions::default());
}
/// `cropTo` (and `crop`), `password`, `colorMode` and `textAs` given as anything but a string are an
/// error naming the param: `document.open` opens nothing and `file.place` places nothing and records
/// no undo step. Null is the same as leaving the param out.
#[test]
fn pdf_options_of_the_wrong_type_are_refused() {
let bytes = three_pages();
let wrong = [
("cropTo", json!(5)),
("crop", json!(true)),
("password", json!(123)),
("colorMode", json!(5)),
("textAs", json!(true)),
("textAs", json!(["outlines"])),
];
let one = |key: &str, v: &Value| {
let mut p = json!({});
p[key] = v.clone();
p
};
let mut s = Session::new();
for (key, v) in &wrong {
let e = open(&mut s, &bytes, one(key, v)).unwrap_err().to_string();
assert!(e.contains(&format!("`{key}` must be a string")), "{key}: {e}");
assert!(s.active().is_none(), "{key}: nothing opened");
}
// A wrong `cropTo` is refused even when `crop` is a box, and a wrong `crop` when `cropTo` is.
let e = open(&mut s, &bytes, json!({"cropTo": 2, "crop": "art"})).unwrap_err().to_string();
assert!(e.contains("`cropTo` must be a string"), "{e}");
let e = open(&mut s, &bytes, json!({"cropTo": "art", "crop": 2})).unwrap_err().to_string();
assert!(e.contains("`crop` must be a string"), "{e}");
assert!(s.active().is_none(), "nothing opened");
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let undo = s.doc().unwrap().history.undo.len();
let nodes = s.doc().unwrap().doc.node_count();
for (key, v) in &wrong {
let mut p = json!({"name": "pages.pdf", "dataBase64": b64(&bytes)});
p[*key] = v.clone();
let e = s.execute("file.place", &p).unwrap_err().to_string();
assert!(e.contains(&format!("`{key}` must be a string")), "{key}: {e}");
assert_eq!((s.doc().unwrap().history.undo.len(), s.doc().unwrap().doc.node_count()), (undo, nodes), "{key}: nothing placed");
}
// Null is left out; valid strings read as before.
let nulls = json!({"cropTo": null, "crop": null, "password": null, "colorMode": null, "textAs": null});
assert_eq!(LoadOptions::from_params("x", &nulls).unwrap(), LoadOptions::default());
let o = LoadOptions::from_params("x", &json!({"cropTo": null, "crop": "Bleed", "colorMode": "CMYK", "textAs": "outlines"})).unwrap();
assert_eq!(
(o.crop, o.color_mode, o.text_as),
(vectorcraft_pdf::CropTo::Bleed, Some(vectorcraft_doc::ColorMode::Cmyk), vectorcraft_pdf::TextAs::Outlines)
);
}
/// `document.pdfInfo`'s `thumbnailSize` given as anything but a number is an error, with or without
/// a `thumbnail`; null is 160 px.
#[test]
fn pdf_info_refuses_a_thumbnail_size_that_is_not_a_number() {
let bytes = three_pages();
let mut s = Session::new();
for v in [json!("100"), json!(true)] {
for p in [json!({"dataBase64": b64(&bytes), "thumbnail": 1, "thumbnailSize": v}), json!({"dataBase64": b64(&bytes), "thumbnailSize": v})] {
let e = s.execute("document.pdfInfo", &p).unwrap_err().to_string();
assert!(e.contains("`thumbnailSize` must be a number"), "{v}: {e}");
}
}
let e = s.execute("document.pdfInfo", &json!({"dataBase64": b64(&bytes), "colorMode": 1})).unwrap_err().to_string();
assert!(e.contains("`colorMode` must be a string"), "{e}");
let v = s.execute("document.pdfInfo", &json!({"dataBase64": b64(&bytes), "thumbnail": 1, "thumbnailSize": null})).unwrap();
let png = vectorcraft_format::base64_decode(v["thumbnail"].as_str().unwrap()).unwrap();
assert_eq!(image::load_from_memory(&png).unwrap().width(), 160);
}
#[test]
fn a_postscript_ai_file_says_it_cannot_be_opened_yet() {
// PostScript opens through the EPS reader now (tests_epsimport.rs): a program it can't read,
+2
View File
@@ -49,6 +49,8 @@ mod presets;
mod report;
pub(crate) use analysis::{outlined_text, see_through_images};
#[cfg(test)]
pub(crate) use apply::with_every_region;
pub(crate) use apply::{expand_transparent_tile_images, flatten_document, flatten_expanded, has_transparent_tile_images};
pub use commands::specs;
pub use options::FlattenOptions;
+34 -2
View File
@@ -150,9 +150,15 @@ fn flatten_group(plain: &[&Node], o: &FlattenOptions, cmyk: bool) -> Option<(Reg
}
// An unclipped full raster needs no regions.
let whole = o.balance <= 0.0 && !o.clip_complex_regions;
let regions = if whole { vec![] } else { po::regions(&b.shapes) };
// Nor does one that splits into more regions than the balance allows: the build stops at the
// first region past the limit.
let (regions, over) = match o.region_limit().filter(|_| !every_region()) {
_ if whole => (vec![], false),
Some(limit) => po::regions_within(&b.shapes, limit).map_or((vec![], true), |r| (r, false)),
None => (po::regions(&b.shapes), false),
};
// An arrangement that failed (degenerate geometry) leaves only rasterizing.
let all = regions.is_empty() || o.rasterize_all(regions.len());
let all = over || regions.is_empty() || o.rasterize_all(regions.len());
let mut vector: Vec<(usize, RegionFill)> = vec![];
let mut complex: Vec<usize> = vec![];
let mut gradients_only = !all;
@@ -195,6 +201,32 @@ fn flatten_group(plain: &[&Node], o: &FlattenOptions, cmyk: bool) -> Option<(Reg
Some((vector, area))
}
#[cfg(test)]
thread_local! {
/// Groups flattened on this thread build all of their regions ([`with_every_region`]).
static EVERY_REGION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Whether groups build all of their regions, past the balance's limit too.
#[cfg(test)]
fn every_region() -> bool {
EVERY_REGION.with(std::cell::Cell::get)
}
#[cfg(not(test))]
fn every_region() -> bool {
false
}
/// `f` with every group it flattens building all of its regions, past the balance's limit too.
#[cfg(test)]
pub(crate) fn with_every_region<T>(f: impl FnOnce() -> T) -> T {
EVERY_REGION.with(|e| e.set(true));
let out = f();
EVERY_REGION.with(|e| e.set(false));
out
}
/// The flat colour of a region covered by `sources` (CMYK in a `cmyk` document); `None` where
/// nothing paints it.
fn region_fill(elems: &[Elem], sources: &[usize], o: &FlattenOptions, cmyk: bool) -> Option<RegionFill> {
+8 -1
View File
@@ -169,9 +169,16 @@ impl FlattenOptions {
}
/// Whether a group that splits into `regions` atomic regions is rasterized whole.
pub(super) fn rasterize_all(&self, regions: usize) -> bool {
pub(crate) fn rasterize_all(&self, regions: usize) -> bool {
self.balance <= 0.0 || (self.balance < 100.0 && regions as f64 > 10f64.powf(self.balance / 20.0))
}
/// The most atomic regions a group can split into without being rasterized whole, when a group
/// with more needs none of its regions: `None` at a balance of 0 or 100, and with Clip Complex
/// Regions (a group rasterized whole is clipped to all of its regions).
pub(crate) fn region_limit(&self) -> Option<usize> {
(!self.clip_complex_regions && self.balance > 0.0 && self.balance < 100.0).then(|| 10f64.powf(self.balance / 20.0).floor() as usize)
}
}
pub(super) fn flatten(s: &mut Session, p: &Value) -> Result<Value> {
+4 -3
View File
@@ -10,7 +10,7 @@ use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use super::layer::{NewLayers, row_roots, rows_param};
use super::{CommandSpec, Result, Session, bad, checked_id, cmd, has_doc, id_param, ok, switch_or};
use super::{CommandSpec, Result, Session, bad, checked_id, cmd, has_doc, object_param, ok, switch_or};
use crate::EngineError;
pub fn specs() -> Vec<CommandSpec> {
@@ -336,7 +336,7 @@ fn release(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "layer.releaseToLayers";
let build = switch_or(p, "build", false, C)?;
let st = s.doc()?;
let id = match id_param(p, "id") {
let id = match object_param(p, "id", C)? {
Some(id) => id,
None => match st.highlighted_rows().as_slice() {
[id] => *id,
@@ -434,8 +434,9 @@ fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
}
fn locate(s: &mut Session, p: &Value) -> Result<Value> {
let id = object_param(p, "id", "layer.locate")?;
let st = s.doc_mut()?;
let id = id_param(p, "id").or_else(|| st.selection.objects.last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?;
let id = id.or_else(|| st.selection.objects.last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?;
let ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?;
st.layer_rows = vec![id];
st.revision += 1;
+443 -79
View File
@@ -24,14 +24,15 @@
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path};
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::links::{Align, Preserve, hash_bytes};
use vectorcraft_doc::{Appearance, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions};
use vectorcraft_geom::{Affine, Rect, shapes};
use vectorcraft_geom::{Affine, PathData, Rect, shapes};
use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file};
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, id_param, ids_param, str_param};
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -49,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Update Links",
[],
None,
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. One undo step → {updated: [ids], missing: [ids]}",
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. The images and placed documents inside symbols, graph designs, patterns and opacity masks that show the same content are read again too (by default also those only that art shows); they have no ids to list. One undo step → {updated: [ids], missing: [ids]}",
has_doc,
update
),
@@ -67,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Relink",
[],
None,
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, copy?: false (with path, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy)}",
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object in the layers linked to the same file as one of them) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy)}",
has_doc,
relink
),
@@ -483,23 +484,183 @@ fn read_for(f: &mut Found, g: &Group, cmd: &str) -> Result<Read> {
Ok(Read::Document(f.link(&bytes, &g.link), src))
}
/// Objects `ids` show what was read (see [`install`], [`install_document`]).
fn install_read(d: &mut Document, ids: &[NodeId], read: Read, force: Option<Preserve>) -> Result<()> {
/// Objects `ids` show what was read (see [`install`], [`install_document`]), and with `also`, the
/// objects outside the layer tree that show group `also`'s content.
fn install_read(d: &mut Document, ids: &[NodeId], read: Read, force: Option<Preserve>, also: Option<&Group>) -> Result<()> {
let also = also.map(|g| (g.link.path.as_str(), g.key.as_str()));
match read {
Read::Image(r) => install(d, ids, r, force),
Read::Document(link, src) => install_document(d, ids, &link, &src, force),
Read::Image(r) => install(d, ids, r, force, also),
Read::Document(link, src) => install_document(d, ids, &link, &src, force, also),
}
}
/// Is `n` a linked image (or, with `document`, a placed document) of the file at `path` showing
/// content `key`?
fn shows(n: &Node, (path, key): (&str, &str), document: bool) -> bool {
match &n.kind {
NodeKind::Image(im) => !document && im.key == key && im.link.as_ref().is_some_and(|l| l.path == path),
NodeKind::PlacedDocument(p) => document && p.key == key && p.link.path == path,
_ => false,
}
}
/// The clipping path of `clip`: its room as a rectangle in its frame.
fn clip_shape((frame, room): Clip) -> PathData {
shapes::rectangle(Rect::new(0.0, 0.0, room.0, room.1)).transformed(frame)
}
/// Remakes the linked objects outside the layer tree (in symbols, graph designs, patterns and
/// opacity masks, where [`Document::node`] finds no ids) that `pick` holds for.
struct Nested<'a> {
pick: &'a dyn Fn(&Node) -> bool,
/// The object an object becomes, and the clip it takes ([`placed_xf`]).
make: &'a mut dyn FnMut(&Node) -> (Node, Option<Clip>),
/// The next node id for a clip group (taken from the document after the walk).
next: u64,
}
impl Nested<'_> {
/// Every root of `d`: the layers (whose own objects are left alone), then the art of symbols,
/// graph designs and patterns.
fn run(mut self, d: &mut Document) {
let first = d.peek_next_id();
self.next = first;
for l in d.layers.iter_mut() {
self.update(l, false);
}
for root in d.symbols.iter_mut().map(|s| &mut s.art).chain(d.graph_designs.iter_mut().map(|g| &mut g.art)) {
self.root(root);
}
for root in d.patterns.iter_mut().flat_map(|p| &mut p.art) {
self.root(root);
}
for _ in first..self.next {
d.alloc_id();
}
}
/// The art at a root outside the layer tree (a symbol's, graph design's or pattern's art, or
/// mask art).
fn root(&mut self, n: &mut Arc<Node>) {
if !(self.pick)(n) {
return self.update(n, true);
}
let (new, clip) = (self.make)(n);
let mut new = Arc::new(new);
self.update(&mut new, true);
*n = match clip {
Some(clip) => Arc::new(self.clip_group(new, clip)),
None => new,
};
}
/// `n` (outside the layer tree when `nested`) with the picked objects under it remade; it stays
/// the same node when none is there, and only the nodes on the way to one are copied.
fn update(&mut self, n: &mut Arc<Node>, nested: bool) {
let mask = n.extras().mask.as_ref().and_then(|m| {
let mut art = Arc::clone(&m.art);
self.root(&mut art);
(!Arc::ptr_eq(&art, &m.art)).then_some(art)
});
let mut slots: Vec<(usize, Arc<Node>)> = vec![];
if let Some(children) = n.children() {
// A clip group holding just the object: its clipping path changes.
let clip_path = match (&n.kind, &children[..]) {
(NodeKind::Group { clip: true, .. }, [c, _]) if matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some(c),
_ => None,
};
for (i, c) in children.iter().enumerate() {
if !(nested && (self.pick)(c)) {
let mut new = Arc::clone(c);
self.update(&mut new, nested);
if !Arc::ptr_eq(&new, c) {
slots.push((i, new));
}
continue;
}
let (new, clip) = (self.make)(c);
let mut new = Arc::new(new);
self.update(&mut new, true);
match (clip, clip_path) {
(None, _) => slots.push((i, new)),
(Some(clip), Some(path)) if i == 1 => {
let mut path = Node::clone(path);
if let NodeKind::Path { path: p, .. } = &mut path.kind {
*p = clip_shape(clip);
}
slots.extend([(0, Arc::new(path)), (1, new)]);
}
(Some(clip), _) => {
let group = self.clip_group(new, clip);
slots.push((i, Arc::new(group)));
}
}
}
}
if mask.is_none() && slots.is_empty() {
return;
}
let n = Arc::make_mut(n);
if let (Some(art), Some(m)) = (mask, n.extras_if_any().and_then(|e| e.mask.as_mut())) {
m.art = art;
}
if let Some(children) = n.children_mut() {
for (i, c) in slots {
if let Some(slot) = children.get_mut(i) {
*slot = c;
}
}
}
}
/// A clip group of `object` clipped to `clip`, as [`clip_image`] makes one in the layers.
fn clip_group(&mut self, object: Arc<Node>, clip: Clip) -> Node {
let (path_id, group_id) = (NodeId(self.next), NodeId(self.next + 1));
self.next += 2;
let none = vectorcraft_color::Paint::None;
let mut path = Node::path(path_id, clip_shape(clip), Appearance::basic(none.clone(), none, 0.0));
if let NodeKind::Path { clipping, .. } = &mut path.kind {
*clipping = true;
}
Node::new(group_id, NodeKind::Group { children: vec![Arc::new(path), object], clip: true })
}
}
/// Placed documents `ids` show `src`, read from the file `link` points at, each placed as its
/// Placement Options say (`force`: as that Preserve choice says, whatever they say).
fn install_document(d: &mut Document, ids: &[NodeId], link: &LinkInfo, src: &super::place::document::Source, force: Option<Preserve>) -> Result<()> {
/// Placement Options say (`force`: as that Preserve choice says, whatever they say); with `also`
/// (a file's path and the content shown), so do the placed documents outside the layer tree that
/// show that content.
fn install_document(
d: &mut Document,
ids: &[NodeId],
link: &LinkInfo,
src: &super::place::document::Source,
force: Option<Preserve>,
also: Option<(&str, &str)>,
) -> Result<()> {
let mut clips = vec![];
let (w, h) = (src.frame.width(), src.frame.height());
let placed = |p: &PlacedDocument| {
let o = PlacementOptions { preserve: force.unwrap_or(p.placement.preserve), ..p.placement };
placed_xf(p.xf, (p.width, p.height), (1.0, 1.0), (w, h), (1.0, 1.0), o)
};
if let Some(also) = also {
let pick = |n: &Node| shows(n, also, true);
let mut make = |n: &Node| {
let mut n = n.clone();
let mut clip = None;
if let NodeKind::PlacedDocument(p) = &mut n.kind {
let (xf, c) = placed(p);
(p.key, p.width, p.height, p.xf, p.link) = (src.key.clone(), w, h, xf, link.clone());
clip = c;
}
(n, clip)
};
Nested { pick: &pick, make: &mut make, next: 0 }.run(d);
}
for id in ids {
let Some(NodeKind::PlacedDocument(p)) = d.node(*id).map(|n| &n.kind) else { continue };
let o = PlacementOptions { preserve: force.unwrap_or(p.placement.preserve), ..p.placement };
let (xf, clip) = placed_xf(p.xf, (p.width, p.height), (1.0, 1.0), (w, h), (1.0, 1.0), o);
let (xf, clip) = placed(p);
if let Some(n) = d.node_mut(*id)
&& let NodeKind::PlacedDocument(p) = &mut n.kind
{
@@ -565,8 +726,8 @@ fn placed_xf(xf: Affine, old: (f64, f64), old_pt: (f64, f64), new: (f64, f64), n
/// Clip image `id` of `d` to `room` in `frame`: the clipping path of the clip group holding just
/// it changes, else the image goes into a new clip group.
fn clip_image(d: &mut Document, id: NodeId, (frame, room): Clip) -> Result<()> {
let path = shapes::rectangle(Rect::new(0.0, 0.0, room.0, room.1)).transformed(frame);
fn clip_image(d: &mut Document, id: NodeId, clip: Clip) -> Result<()> {
let path = clip_shape(clip);
let clip_path = d.parent_of(id).and_then(|p| match &d.node(p)?.kind {
NodeKind::Group { children, clip: true } => match &children[..] {
[c, im] if im.id == id && matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some(c.id),
@@ -602,14 +763,33 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
let path = fileio::document_path(path, doc_path).map_err(|r| EngineError::Other(format!("the image `{path}` isn't followed: {r}")))?;
let bytes = read_file(&path)?;
let read = (link_info(&path, &bytes), linked_image(&bytes)?);
install(d, &[id], read, Some(Preserve::Bounds))
install(d, &[id], read, Some(Preserve::Bounds), None)
}
/// Image objects `ids` show the file read for `link` (`img`), each placed as its Placement
/// Options say (`force`: as that Preserve choice says, whatever they say).
fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option<Preserve>) -> Result<()> {
/// Options say (`force`: as that Preserve choice says, whatever they say); with `also` (a file's
/// path and the content shown), so do the images outside the layer tree that show that content.
fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
let new_pt = super::place::pt_per_px(img.ppi);
let mut clips = vec![];
if let Some(also) = also {
// Every image picked shows content `also.1`, so one resolution serves them all.
let old_pt = file_pt(d, also.1);
let pick = |n: &Node| shows(n, also, false);
let mut make = |n: &Node| {
let mut n = n.clone();
let mut clip = None;
if let NodeKind::Image(im) = &mut n.kind {
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
let size = |w: u32, h: u32| (w as f64, h as f64);
let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o);
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone()));
clip = c;
}
(n, clip)
};
Nested { pick: &pick, make: &mut make, next: 0 }.run(d);
}
for id in ids {
let Some(NodeKind::Image(im)) = d.node(*id).map(|n| &n.kind) else { continue };
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
@@ -678,6 +858,9 @@ pub fn resolve(d: &mut Document, doc_path: Option<&str>, update: bool, low_res_p
// of other keys linking to the same file share them, rather than each reading, decoding and
// keeping a copy of its own.
let mut read_images: BTreeMap<String, (ImageBlob, String)> = BTreeMap::new();
// (the path as it was, the content shown, a placed document?, the link now) of each file found
// away from its path or read again.
let mut moved: Vec<(String, String, bool, LinkInfo)> = vec![];
for g in groups(d, None) {
let row = rows(std::iter::once(&g), doc_path);
let unread = g.document.is_none() && g.link.hash.is_none() && g.link.size.is_none() && previewing(d, &g.key);
@@ -685,7 +868,8 @@ pub fn resolve(d: &mut Document, doc_path: Option<&str>, update: bool, low_res_p
match probe(&g, doc_path) {
(Status::Missing, _) => out.missing.extend(row),
(Status::Modified, Some(mut f)) if update || unread => {
match read_for(&mut f, &g, "document.open").and_then(|read| install_read(d, &g.ids, read, unread.then_some(Preserve::Bounds))) {
let force = unread.then_some(Preserve::Bounds);
match read_for(&mut f, &g, "document.open").and_then(|read| install_read(d, &g.ids, read, force, Some(&g))) {
Ok(()) if unread => {}
Ok(()) => out.updated.extend(row),
Err(_) => out.missing.extend(row),
@@ -697,7 +881,7 @@ pub fn resolve(d: &mut Document, doc_path: Option<&str>, update: bool, low_res_p
let read = if stale(d, &g) { Some(read_for(&mut f, &g, "document.open")) } else { None };
match read {
Some(Ok(read)) => {
if install_read(d, &g.ids, read, Some(Preserve::Bounds)).is_err() {
if install_read(d, &g.ids, read, Some(Preserve::Bounds), Some(&g)).is_err() {
out.missing.extend(row);
}
}
@@ -709,6 +893,7 @@ pub fn resolve(d: &mut Document, doc_path: Option<&str>, update: bool, low_res_p
};
if link != g.link {
set_links(d, &g.ids, &link);
moved.push((g.link.path.clone(), g.key.clone(), true, link));
}
}
}
@@ -720,6 +905,7 @@ pub fn resolve(d: &mut Document, doc_path: Option<&str>, update: bool, low_res_p
let link = f.link_hashed(hash, &g.link);
if link != g.link {
set_links(d, &g.ids, &link);
moved.push((g.link.path.clone(), g.key.clone(), false, link));
}
continue;
}
@@ -745,11 +931,34 @@ pub fn resolve(d: &mut Document, doc_path: Option<&str>, update: bool, low_res_p
};
if link != g.link {
set_links(d, &g.ids, &link);
moved.push((g.link.path.clone(), g.key.clone(), false, link));
}
}
(Status::Ok, None) => {}
}
}
// The objects in symbols, graph designs, patterns and opacity masks that show the same file and
// content, which have no ids here, whatever else their links hold.
if !moved.is_empty() {
let mut by_path: BTreeMap<String, Vec<(String, bool, LinkInfo)>> = BTreeMap::new();
for (path, key, document, new) in moved {
by_path.entry(path).or_default().push((key, document, new));
}
let new = |n: &Node| {
let (l, key, document) = linked(n)?;
let m = by_path.get(&l.path)?;
m.iter().find(|(k, doc, _)| k == key && *doc == document.is_some()).map(|(_, _, new)| new)
};
let pick = |n: &Node| new(n).is_some();
let mut make = |n: &Node| {
let mut out = n.clone();
if let (Some(link), Some(l)) = (new(n), link_mut(&mut out)) {
*l = link.clone();
}
(out, None)
};
Nested { pick: &pick, make: &mut make, next: 0 }.run(d);
}
out
}
@@ -772,35 +981,31 @@ fn set_links(d: &mut Document, ids: &[NodeId], link: &LinkInfo) {
}
/// Placed documents of the document saved at `path` (document `saved` of `s`) in the other open
/// documents: read again from the new file, each as one Update Links step of its document.
/// documents, in the layers, symbols, graph designs, patterns and opacity masks: read again from
/// the new file, each as one Update Links step of its document.
pub(crate) fn refresh_placed(s: &mut Session, saved: u64, path: &str) {
let path = absolute_path(path);
let targets: Vec<(usize, Vec<u64>)> = s
let targets: Vec<usize> = s
.documents()
.iter()
.enumerate()
.filter(|(_, st)| st.uid != saved)
.filter_map(|(i, st)| {
let mut ids = vec![];
st.doc.walk(|n| {
if let NodeKind::PlacedDocument(p) = &n.kind
&& p.link.path == path
{
ids.push(n.id.0);
}
});
(!ids.is_empty()).then_some((i, ids))
.filter(|(_, st)| {
let mut placed = false;
st.doc.visit_placed(|_, p| placed |= p.link.path == path);
placed
})
.map(|(i, _)| i)
.collect();
if targets.is_empty() {
return;
}
// Each document is updated as the active one, without switching tools.
let back = s.active;
for (i, ids) in targets {
for i in targets {
s.active = Some(i);
// A file that can't be read leaves what its objects show: links.check reports it.
let _ = update(s, &json!({ "ids": ids }));
let _ = update_where(s, None, Some(&path));
}
s.active = back;
}
@@ -826,31 +1031,45 @@ fn relative_path(target: &Path, base: &Path) -> Option<String> {
}
/// `d` as saved to `dest`: the links' paths relative to its folder written in; `None` when they
/// are already.
/// are already. Links in the layers, symbols, graph designs, patterns and opacity masks are all set.
pub fn with_relative_paths(d: &Document, dest: &str) -> Option<Document> {
let dest = absolute_path(dest);
let dir = Path::new(&dest).parent()?;
let mut changes = vec![];
d.walk(|n| {
if let Some((l, _, _)) = linked(n) {
let r = relative_path(Path::new(&l.path), dir);
if r != l.relative {
changes.push((n.id, r));
}
}
});
if changes.is_empty() {
let relative = |l: &LinkInfo| relative_path(Path::new(&l.path), dir);
let outdated = |l: &LinkInfo| relative(l) != l.relative;
let mut changed = false;
d.visit_images(|_, im| changed |= im.link.as_ref().is_some_and(outdated));
d.visit_placed(|_, p| changed |= outdated(&p.link));
if !changed {
return None;
}
let mut d = d.clone();
for (id, r) in changes {
if let Some(l) = d.node_mut(id).and_then(link_mut) {
l.relative = r;
}
}
d.update_links_where(outdated, |l| l.relative = relative(l));
Some(d)
}
/// Sets each link of `d`, a copy of the document saved at `doc_path` that has no file of its own,
/// to the path where that document finds its file, so the copy finds the same files.
/// Links in the layers, symbols, graph designs, patterns and opacity masks are all set.
pub(crate) fn with_found_paths(d: &mut Document, doc_path: &str) {
// The new path of each link by what `locate` reads of it: its path, relative path and name.
let mut found: BTreeMap<(String, Option<String>), Option<String>> = BTreeMap::new();
let mut look = |l: &LinkInfo| {
found.entry((l.path.clone(), l.relative.clone())).or_insert_with(|| locate(l, Some(doc_path)).map(|f| f.path));
};
d.visit_images(|_, im| im.link.iter().for_each(&mut look));
d.visit_placed(|_, p| look(&p.link));
found.retain(|(path, _), f| f.as_ref().is_some_and(|f| f != path));
if found.is_empty() {
return;
}
d.update_links(|l| {
if let Some(Some(f)) = found.get(&(l.path.clone(), l.relative.clone())) {
l.path = f.clone();
}
});
}
// ---------- commands ----------
fn check(s: &mut Session, p: &Value) -> Result<Value> {
@@ -876,28 +1095,92 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
}
fn update(s: &mut Session, p: &Value) -> Result<Value> {
update_where(s, ids_param(p, "ids"), None)
}
/// Update Links in the active document of `s` for objects `ids` (default: the linked files that
/// changed or show their preview), or with `path`, for the placed documents of the file at `path`
/// whatever their status. The objects in symbols, graph designs, patterns and opacity masks that
/// show the same content are read again too, and have no ids to report.
fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) -> Result<Value> {
let st = s.doc()?;
let ids = ids_param(p, "ids");
let (mut reads, mut missing) = (vec![], vec![]);
for g in groups(&st.doc, ids.as_deref()).into_iter().filter(|g| !g.ids.is_empty()) {
let asked = ids.is_some() || path.is_some();
for g in groups(&st.doc, ids.as_deref()).into_iter().filter(|g| path.is_none_or(|p| g.document.is_some() && g.link.path == p)) {
match probe(&g, st.path.as_deref()) {
(Status::Missing, _) | (_, None) => missing.extend(ids_json(&g.ids)),
// Unchanged and showing the file: nothing to read unless asked for by id.
(Status::Ok, Some(_)) if ids.is_none() && !stale(&st.doc, &g) => {}
// Unchanged and showing the file: nothing to read unless asked for.
(Status::Ok, Some(_)) if !asked && !stale(&st.doc, &g) => {}
// Unreadable as an image (or a document) counts as missing.
(_, Some(mut f)) => match read_for(&mut f, &g, "links.update") {
Ok(read) => reads.push((g.ids, read)),
Ok(read) => reads.push((g, read)),
Err(_) => missing.extend(ids_json(&g.ids)),
},
}
}
let updated: Vec<u64> = reads.iter().flat_map(|(ids, _)| ids_json(ids)).collect();
let updated: Vec<u64> = reads.iter().flat_map(|(g, _)| ids_json(&g.ids)).collect();
if !reads.is_empty() {
s.edit("Update Links", |d, _| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, None)))?;
s.edit("Update Links", |d, _| reads.into_iter().try_for_each(|(g, read)| install_read(d, &g.ids, read, None, Some(&g))))?;
}
Ok(json!({ "updated": updated, "missing": missing }))
}
/// Which links `links.relink` points at the new file (the Replace choice of Relink).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Scope {
/// Each link its own file (`paths`).
Each,
/// The objects given or selected.
Selected,
/// Every object in the layers linked to the same file as one given or selected.
All,
/// The objects given or selected, then every other missing link whose file name is in the new
/// file's folder.
MissingInFolder,
}
impl Scope {
fn from_id(id: &str) -> Option<Self> {
match id {
"each" => Some(Scope::Each),
"selected" => Some(Scope::Selected),
"all" => Some(Scope::All),
"missingInFolder" => Some(Scope::MissingInFolder),
_ => None,
}
}
}
/// The error for `scope` and `paths` given one without the other, or `paths` beside ids, path or
/// folder.
fn each_mismatch(cmd: &str) -> EngineError {
bad(cmd, "scope each and paths go together: paths lists entries of ids and path, in place of ids, path and folder")
}
/// `links.relink {scope: "each", paths}`: each entry's ids with its absolute file, entries naming
/// one file merged. A malformed entry, an id in two entries or an empty list is an error.
fn each_paths(p: &Value, cmd: &str) -> Result<Vec<(Vec<NodeId>, String)>> {
let entries = p.get("paths").and_then(Value::as_array).filter(|a| !a.is_empty()).ok_or_else(|| each_mismatch(cmd))?;
let mut seen = BTreeSet::new();
let mut out: Vec<(Vec<NodeId>, String)> = vec![];
for (i, e) in entries.iter().enumerate() {
let malformed = || bad(cmd, format!("paths entry {i} needs path and ids (object ids no other entry has)"));
let path = e.get("path").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or_else(malformed)?;
let ids = e.get("ids").and_then(Value::as_array).filter(|a| !a.is_empty()).ok_or_else(malformed)?;
let mut these = vec![];
for v in ids {
let id = v.as_u64().map(NodeId).filter(|id| seen.insert(*id)).ok_or_else(malformed)?;
these.push(id);
}
let path = absolute_path(path);
match out.iter_mut().find(|(_, p)| *p == path) {
Some((ids, _)) => ids.extend(these),
None => out.push((these, path)),
}
}
Ok(out)
}
fn relink(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "links.relink";
// How the new file takes the image's place this time (default: its Placement Options).
@@ -905,13 +1188,26 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
None => None,
Some(v) => Some(Preserve::from_id(v).ok_or_else(|| bad(C, format!("preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill")))?),
};
let scope = match p.get("scope").filter(|v| !v.is_null()) {
None => Scope::Selected,
Some(v) => v.as_str().and_then(Scope::from_id).ok_or_else(|| bad(C, format!("scope {v} is not each|selected|all|missingInFolder")))?,
};
let st = s.doc()?;
let folder_param = str_param(p, "folder");
match scope {
Scope::Each if p.get("path").is_some() || folder_param.is_some() || p.get("ids").is_some() => return Err(each_mismatch(C)),
Scope::Selected | Scope::All | Scope::MissingInFolder if p.get("paths").is_some() => return Err(each_mismatch(C)),
Scope::MissingInFolder if folder_param.is_some() => {
return Err(bad(C, "scope missingInFolder takes path: the folder of that file is searched for the other missing links"));
}
_ => {}
}
let each = if scope == Scope::Each { Some(each_paths(p, C)?) } else { None };
// With copy: the saved document's folder, which the file is copied into.
let copy_to = match (bool_or(p, "copy", false), str_param(p, "path")) {
let copy_to = match (bool_or(p, "copy", false), str_param(p, "path").is_some() || each.is_some()) {
(false, _) => None,
(true, None) => return Err(bad(C, "copy needs path: the file to copy into the document's folder")),
(true, Some(_)) => {
(true, false) => return Err(bad(C, "copy needs path: the file to copy into the document's folder")),
(true, true) => {
let doc = st.path.as_deref().map(absolute_path).ok_or_else(|| bad(C, "save the document first: copy puts the file in its folder"))?;
Some(Path::new(&doc).parent().map(Path::to_path_buf).ok_or_else(|| bad(C, format!("{doc} has no folder")))?)
}
@@ -924,9 +1220,10 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
_ => None,
})
};
let ids: Vec<NodeId> = match ids_param(p, "ids") {
Some(ids) => ids,
None => {
let mut ids: Vec<NodeId> = match (&each, ids_param(p, "ids")) {
(Some(each), _) => each.iter().flat_map(|(ids, _)| ids.iter().copied()).collect(),
(None, Some(ids)) => ids,
(None, None) => {
let selected: Vec<NodeId> = st.selection.objects.iter().copied().filter(|id| image(id).is_some()).collect();
match folder_param {
Some(_) if selected.is_empty() => {
@@ -942,15 +1239,37 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
if ids.is_empty() {
return Err(bad(C, "select the images to relink, or pass ids"));
}
// All Instances: the other objects in the layers linked to the same files.
if scope == Scope::All {
let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect();
let given: BTreeSet<NodeId> = ids.iter().copied().collect();
let mut more = vec![];
st.doc.walk(|n| {
if let Some((l, _, _)) = linked(n)
&& paths.contains(l.path.as_str())
&& !given.contains(&n.id)
{
more.push(n.id);
}
});
ids.extend(more);
}
if copy_to.is_some() && ids.iter().any(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) {
return Err(bad(C, "copy takes images only: relink placed documents where their files are"));
}
// (ids, the file) per file to read.
let mut files: Vec<(Vec<NodeId>, String)> = vec![];
let mut not_found = vec![];
match (str_param(p, "path"), folder_param) {
(Some(path), _) => files.push((ids, absolute_path(path))),
(None, Some(dir)) => {
match (each, str_param(p, "path"), folder_param) {
(Some(each), _, _) => files = each,
(None, Some(path), _) if scope == Scope::MissingInFolder => {
let path = absolute_path(path);
let given: BTreeSet<NodeId> = ids.iter().copied().collect();
files.push((ids, path));
missing_in_folder(st, &given, copy_to.is_some(), &mut files, &mut not_found);
}
(None, Some(path), _) => files.push((ids, absolute_path(path))),
(None, None, Some(dir)) => {
for id in ids {
let Some(link) = image(&id).flatten() else { continue };
let path = absolute_path(&Path::new(dir).join(link.name()).to_string_lossy());
@@ -961,10 +1280,10 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
(None, None) => return Err(bad(C, "give path (a file) or folder")),
(None, None, None) => return Err(bad(C, "give path (a file) or folder")),
}
let mut reads = vec![];
let (mut copied, mut kept) = (vec![], vec![]);
// Every file is read and checked before any is copied.
let mut checked = vec![];
for (ids, path) in files {
let bytes = read_file(&path)?;
// Images show the file; placed documents each show their artboard or page of it.
@@ -988,20 +1307,28 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
for ((page, bounding, page_box), ids) in documents {
sources.push((page, ids, super::place::document::source(&path, &bytes, Some(&path), page, bounding, page_box, C)?));
}
let to = match &copy_to {
Some(dir) => {
let (to, new) = copy_into_folder(&path, &bytes, dir)?;
// The bytes are kept only to be copied, the file as it was checked.
let link = link_info(&path, &bytes);
let bytes = copy_to.is_some().then_some(bytes);
checked.push((path, link, bytes, images, img, sources));
}
let mut reads = vec![];
let (mut copied, mut kept): (Vec<Value>, Vec<Value>) = (vec![], vec![]);
for (path, link, bytes, images, img, sources) in checked {
let link = match (&copy_to, bytes) {
(Some(dir), Some(bytes)) => {
let (to, new) = copy_or_remove(&path, &bytes, dir, &copied)?;
let link = link_info(&to, &bytes);
let pair = json!({ "from": path, "to": to });
if new {
copied.push(pair)
} else {
kept.push(pair)
}
to
link
}
None => path,
_ => link,
};
let link = link_info(&to, &bytes);
if let Some(img) = img {
reads.push((images, Read::Image((link.clone(), img))));
}
@@ -1011,7 +1338,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
}
let relinked: Vec<u64> = reads.iter().flat_map(|(ids, _)| ids_json(ids)).collect();
if !reads.is_empty() {
s.edit("Relink", |d, _| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve)))?;
s.edit("Relink", |d, _| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve, None)))?;
}
not_found.sort();
not_found.dedup();
@@ -1023,6 +1350,41 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// `links.relink {scope: "missingInFolder"}`: the other missing links of `st` (not `given`; only
/// images when `images_only`, as copy takes), each added to `files` with the file of its name in
/// the folder of the first file there; names not there go to `not_found`.
fn missing_in_folder(
st: &crate::DocState,
given: &BTreeSet<NodeId>,
images_only: bool,
files: &mut Vec<(Vec<NodeId>, String)>,
not_found: &mut Vec<String>,
) {
let Some(dir) = files.first().and_then(|(_, p)| Path::new(p).parent()).map(Path::to_path_buf) else { return };
for g in groups(&st.doc, None).into_iter().filter(|g| !(images_only && g.document.is_some())) {
let rest: Vec<NodeId> = g.ids.iter().copied().filter(|id| !given.contains(id)).collect();
if rest.is_empty() || probe(&g, st.path.as_deref()).0 != Status::Missing {
continue;
}
let found = absolute_path(&dir.join(g.link.name()).to_string_lossy());
match files.iter_mut().find(|(_, p)| *p == found) {
Some((ids, _)) => ids.extend(rest),
None if file_stamp(&found).is_some() => files.push((rest, found)),
None => not_found.push(g.link.name().to_string()),
}
}
}
/// [`copy_into_folder`]; when it fails, the copies `copied` (`{from, to}`) the same call made
/// before are removed, since nothing is relinked.
fn copy_or_remove(from: &str, bytes: &[u8], dir: &Path, copied: &[Value]) -> Result<(String, bool)> {
copy_into_folder(from, bytes, dir).inspect_err(|_| {
for to in copied.iter().filter_map(|pair| pair.get("to").and_then(Value::as_str)) {
let _ = std::fs::remove_file(to);
}
})
}
/// `links.relink {copy}`: put the file at `from` (`bytes`, as just read) into the folder `dir`,
/// never replacing a file there ([`fileio::copy_new`]) → where it is now, and whether it was
/// copied (`false`: a file there with the same contents, of its name or a numbered one, is used).
@@ -1071,7 +1433,9 @@ fn selected_images(st: &crate::DocState, keep: impl Fn(&ImageObject) -> bool) ->
/// `id`, else the first selected image.
fn image_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
let id = id_param(p, "id").or_else(|| selected_images(st, |_| true).first().copied()).ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
let id = object_param(p, "id", cmd)?
.or_else(|| selected_images(st, |_| true).first().copied())
.ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
match image_of(&st.doc, id) {
Some(_) => Ok(id),
None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)),
@@ -1100,7 +1464,7 @@ fn placement_of(d: &Document, id: NodeId) -> Option<PlacementOptions> {
/// `id`, else the first selected image or placed document.
fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
let first = || st.selection.objects.iter().copied().find(|id| placement_of(&st.doc, *id).is_some());
let id = id_param(p, "id").or_else(first).ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
let id = object_param(p, "id", cmd)?.or_else(first).ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
match placement_of(&st.doc, id) {
Some(_) => Ok(id),
None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)),
@@ -1270,7 +1634,7 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> {
if !done.is_empty() || !documents.is_empty() {
s.edit("Embed", |d, _| {
for (ids, read) in reads {
install(d, &ids, read, Some(Preserve::Bounds))?;
install(d, &ids, read, Some(Preserve::Bounds), None)?;
}
for id in &done {
if let Some(Node { kind: NodeKind::Image(im), .. }) = d.node_mut(*id) {
@@ -1327,7 +1691,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
let img = linked_image(&bytes)?;
write_file(&path, &bytes)?;
let read = (link_info(&path, &bytes), img);
s.edit("Unembed", |d, _| install(d, &[id], read, Some(Preserve::Bounds)))?;
s.edit("Unembed", |d, _| install(d, &[id], read, Some(Preserve::Bounds), None))?;
Ok(json!({ "id": id.0, "path": path }))
}
+2 -2
View File
@@ -20,8 +20,8 @@ use super::edit::selected_roots;
use super::expand::gradient_sampler;
use super::pathops::Beside;
use super::{
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, check_switches, cmd, color_param, f64_or, f64_req, finite_numbers,
has_doc, has_multi, has_selection, id_param, named_ids, number_or, ok, str_param, switch_or,
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_param, f64_or, f64_req, finite_numbers, has_doc, has_multi,
has_selection, id_param, named_ids, number_or, ok, str_param, switch_or, text_param,
};
mod blend;
+2 -2
View File
@@ -7,7 +7,7 @@ use super::common::{
use super::mesh::index_param;
use super::{
Affine, Anchor, Appearance, Arc, Beside, BlendDefaults, BlendOrientation, BlendSpacing, BlendSpec, Document, EngineError, Node, NodeId, NodeKind,
Paint, PathData, Point, Result, Session, Spine, Value, Vec2, bad, f64_req, id_param, json, live, number_or, ok, str_param, switch_or,
Paint, PathData, Point, Result, Session, Spine, Value, Vec2, bad, f64_req, json, live, number_or, ok, str_param, switch_or,
};
/// The first blend among `roots`.
@@ -160,7 +160,7 @@ fn edit_spine<T>(
label: &str,
f: impl FnOnce(&mut vectorcraft_geom::SubPath, &mut Vec<usize>, &mut [Arc<Node>]) -> Result<T>,
) -> Result<T> {
let id = match id_param(p, "id") {
let id = match crate::cmd::object_param(p, "id", cmd)? {
Some(id) => id,
None => *selected_of(s, is_blend).first().ok_or_else(|| bad(cmd, "select a blend or give `id`"))?,
};
+4 -4
View File
@@ -136,7 +136,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make with Warp…",
["Object", "Envelope Distort"],
Some("Cmd+Alt+Shift+W"),
"{ids?, style?: arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist (arc), bend?: % -100..100 (50), h?: horizontal distortion % -100..100 (0), v?: vertical distortion % (0), horizontal?: bool (true) | orientation?: horizontal|vertical, horizontalDistortion?: as h, verticalDistortion?: as v} envelope the selected objects with a warp (Envelope Options from object.envelope.options with nothing selected) → {id}",
"{ids?, style?: arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist (arc), bend?: % -100..100 (50), h?: horizontal distortion % -100..100 (0), v?: vertical distortion % (0), horizontal?: bool (true) | orientation?: horizontal|vertical, horizontalDistortion?: as h, verticalDistortion?: as v} envelope the selected objects with a warp (Envelope Options from object.envelope.options with nothing selected; type maps from its glyph outline bounds) → {id}",
has_selection,
env_make_warp
),
@@ -145,7 +145,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make with Mesh…",
["Object", "Envelope Distort"],
Some("Cmd+Alt+M"),
"{ids?, rows?: 1..50 (4), cols?: 1..50 (4), columns?: as cols} envelope the selected objects with a mesh of rows × cols patches → {id}",
"{ids?, rows?: 1..50 (4), cols?: 1..50 (4), columns?: as cols} envelope the selected objects with a mesh of rows × cols patches over their bounds (type measured by its glyph outlines) → {id}",
has_selection,
env_make_mesh
),
@@ -154,7 +154,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make with Top Object",
["Object", "Envelope Distort"],
Some("Cmd+Alt+C"),
"{ids?} the topmost selected path becomes the envelope of the others → {id}",
"{ids?} the topmost selected path becomes the envelope of the others (type maps from its glyph outline bounds) → {id}",
has_multi,
env_make_top
),
@@ -172,7 +172,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reset with Mesh…",
["Object", "Envelope Distort"],
None,
"{rows?: 1..50, cols?: 1..50 (unset: a mesh envelope's own, else 4), maintainShape?: bool (true: the mesh follows the current envelope shape; false: a flat grid over the content), columns?: as cols} make the selected envelopes mesh envelopes, keeping their content",
"{rows?: 1..50, cols?: 1..50 (unset: a mesh envelope's own, else 4), maintainShape?: bool (true: the mesh follows the current envelope shape; false: a flat grid over the content, type measured by its glyph outlines), columns?: as cols} make the selected envelopes mesh envelopes, keeping their content",
has_envelope,
env_reset_mesh
),
+10 -11
View File
@@ -1,9 +1,9 @@
use super::super::object::choice;
use super::common::{fix_ids, ids_json, is_envelope, roots_param, selected_of, wrap};
use super::mesh::{handle_param, index_param, whole};
use super::{
Affine, Appearance, Arc, Beside, Color, Document, EngineError, EnvelopeKind, EnvelopeMap, EnvelopeOptions, Node, NodeId, NodeKind, Paint,
PathData, Point, PreserveShape, Result, Session, Value, bad, check_numbers, check_switches, f64_or, f64_req, id_param, json, live, ok, str_param,
switch_or,
PathData, Point, PreserveShape, Result, Session, Value, bad, check_numbers, f64_or, f64_req, id_param, json, live, ok, switch_or, text_param,
};
// ---------- Envelope ----------
@@ -17,7 +17,7 @@ fn warp_kind(p: &Value, cmd: &str, cur: Option<&EnvelopeKind>) -> Result<Envelop
if let Some(EnvelopeKind::Warp { style: s0, bend: b0, h: h0, v: v0, horizontal: z0 }) = cur {
(style, bend, h, v, horizontal) = (s0.clone(), *b0, *h0, *v0, *z0);
}
if let Some(s) = str_param(p, "style") {
if let Some(s) = text_param(p, "style", cmd)? {
let s = s.strip_prefix("warp.").unwrap_or(s);
if live::WarpStyle::from_id(s).is_none() {
return Err(bad(cmd, format!("unknown warp style `{s}`")));
@@ -28,10 +28,9 @@ fn warp_kind(p: &Value, cmd: &str, cur: Option<&EnvelopeKind>) -> Result<Envelop
h = f64_or(p, "h", f64_or(p, "horizontalDistortion", h)).clamp(-100.0, 100.0);
v = f64_or(p, "v", f64_or(p, "verticalDistortion", v)).clamp(-100.0, 100.0);
let given = switch_or(p, "horizontal", horizontal, cmd)?;
horizontal = match str_param(p, "orientation") {
Some("vertical") => false,
Some("horizontal") => true,
_ => given,
horizontal = match choice(p, cmd, "orientation", &["horizontal", "vertical"])? {
Some(o) => o == "horizontal",
None => given,
};
Ok(EnvelopeKind::Warp { style, bend, h, v, horizontal })
}
@@ -85,7 +84,7 @@ pub(super) fn env_make_mesh(s: &mut Session, p: &Value) -> Result<Value> {
let roots = roots_param(s, p)?;
let st = s.doc()?;
let nodes: Vec<Arc<Node>> = roots.iter().filter_map(|id| st.doc.node(*id).cloned()).map(Arc::new).collect();
let src = live::nodes_bounds(&nodes).ok_or_else(|| bad(C, "selection has no bounds"))?;
let src = live::envelope_content_bounds(&nodes).ok_or_else(|| bad(C, "selection has no bounds"))?;
let kind = EnvelopeKind::Mesh { rows, cols, points: live::grid_points(src, rows, cols), handles: vec![] };
let defaults = envelope_defaults(s);
let id = s.edit("Make Envelope", |d, sel| wrap(d, sel, &roots, |id, content| envelope(id, content, kind, defaults)))?;
@@ -185,7 +184,7 @@ fn envelope_options_json(mut v: Value, o: &EnvelopeOptions, fidelity: f64) -> Va
/// `cur` with the options `p` sets.
fn options_param(p: &Value, cmd: &str, cur: EnvelopeOptions) -> Result<EnvelopeOptions> {
let preserve_shape = match str_param(p, "preserveShape") {
let preserve_shape = match text_param(p, "preserveShape", cmd)? {
Some(v) => PreserveShape::parse(v).ok_or_else(|| bad(cmd, "preserveShape must be clippingMask|transparency"))?,
None => cur.preserve_shape,
};
@@ -289,8 +288,8 @@ pub(super) fn env_release(s: &mut Session, _: &Value) -> Result<Value> {
pub(super) fn env_options(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.envelope.options";
check_numbers(p, &["fidelity"], C)?;
check_numbers(p, WARP_NUMBERS, C)?;
check_switches(p, &["horizontal"], C)?;
// The warp keys are checked whatever is selected: with nothing or only mesh envelopes, too.
warp_kind(p, C, None)?;
let fid = p.get("fidelity").and_then(Value::as_f64);
if fid.is_some_and(|f| !(0.0..=100.0).contains(&f)) {
return Err(bad(C, "fidelity must be 0..100"));
+4 -3
View File
@@ -14,7 +14,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, MaskEdit, Node, NodeId, NodeKind, Selection};
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_doc, id_param, switch_or};
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_doc, object_param, switch_or};
/// Name of the temporary mask-editing layer.
pub const MASK_EDIT_LAYER: &str = "Opacity Mask Editing";
@@ -117,7 +117,7 @@ fn enter(s: &mut Session, p: &Value) -> Result<Value> {
if st.doc.mask_edit.is_some() {
return Err(bad(C, "already editing an opacity mask"));
}
let id = id_param(p, "id").or_else(|| first_masked(st)).ok_or_else(|| bad(C, "select an object with an opacity mask"))?;
let id = object_param(p, "id", C)?.or_else(|| first_masked(st)).ok_or_else(|| bad(C, "select an object with an opacity mask"))?;
let layer = start(s, id)?;
Ok(json!({ "layer": layer.0 }))
}
@@ -136,6 +136,7 @@ fn start(s: &mut Session, id: NodeId) -> Result<NodeId> {
fn view_mask(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "transparency.viewOpacityMask";
let given = object_param(p, "id", C)?;
let st = s.doc()?;
let editing = st.doc.mask_edit.map(|m| m.object);
if !switch_or(p, "on", st.shown_mask().is_none(), C)? {
@@ -144,7 +145,7 @@ fn view_mask(s: &mut Session, p: &Value) -> Result<Value> {
st.revision += 1;
return Ok(json!({ "on": false, "id": id.map(|i| i.0) }));
}
let id = id_param(p, "id").or(editing).or_else(|| first_masked(st)).ok_or_else(|| bad(C, "select an object with an opacity mask"))?;
let id = given.or(editing).or_else(|| first_masked(st)).ok_or_else(|| bad(C, "select an object with an opacity mask"))?;
match editing {
Some(e) if e != id => return Err(bad(C, "already editing another object's opacity mask")),
Some(_) => {}
+49 -7
View File
@@ -106,7 +106,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reset Bounding Box",
["Object", "Transform"],
None,
"{} square the bounding box of the selected objects to the page again after a rotation (their geometry stays; one undo step, none when no box is rotated) → {changed: objects reset}",
"{} square the bounding box of the selected objects, and of every object inside them (the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks), to the page again after a rotation (their geometry stays; one undo step, none when no box is rotated) → {changed: objects reset, the objects inside included}",
has_selection,
reset_bounding_box
),
@@ -223,21 +223,63 @@ pub(crate) fn squash(s: &mut Session, from: usize, label: &str) {
// ---------- Reset Bounding Box ----------
/// Squares each selected object and every object inside it: the children of groups, compound paths,
/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks.
fn reset_bounding_box(s: &mut Session, _: &Value) -> Result<Value> {
let ids = selected_roots(s)?;
let d = &s.doc()?.doc;
let turned: Vec<NodeId> = ids.into_iter().filter(|id| d.node(*id).is_some_and(|n| n.bbox_angle != 0.0)).collect();
if !turned.is_empty() {
let mut changed = 0;
let squared: Vec<(NodeId, Node)> = ids
.into_iter()
.filter_map(|id| {
let (n, count) = squared(d.node(id)?);
changed += count;
Some((id, n?))
})
.collect();
if !squared.is_empty() {
s.edit("Reset Bounding Box", |d, _| {
for id in &turned {
if let Some(n) = d.node_mut(*id) {
n.bbox_angle = 0.0;
for (id, n) in squared {
if let Some(slot) = d.node_mut(id) {
*slot = n;
}
}
Ok(())
})?;
}
Ok(json!({ "changed": turned.len() }))
Ok(json!({ "changed": changed }))
}
/// A copy of `n` with the angle of every object in its subtree set to 0, or `None` when no box in
/// it stands at an angle, and the number of objects squared. The subtree takes in children and the
/// art of linked opacity masks (an unlinked mask's art turns on its own); layers have no box. Only
/// the nodes on the way to a turned object are copied.
fn squared(n: &Node) -> (Option<Node>, usize) {
let mut out = (!n.is_layer() && n.bbox_angle != 0.0).then(|| {
let mut c = n.clone();
c.bbox_angle = 0.0;
c
});
let mut count = usize::from(out.is_some());
for (i, c) in n.children().into_iter().flatten().enumerate() {
let (child, k) = squared(c);
count += k;
if let Some(child) = child
&& let Some(slot) = out.get_or_insert_with(|| n.clone()).children_mut().and_then(|ch| ch.get_mut(i))
{
*slot = Arc::new(child);
}
}
if let Some(m) = n.extras().mask.as_ref().filter(|m| m.linked) {
let (art, k) = squared(&m.art);
count += k;
if let Some(art) = art
&& let Some(m) = out.get_or_insert_with(|| n.clone()).extras_if_any().and_then(|e| e.mask.as_mut())
{
m.art = Arc::new(art);
}
}
(out, count)
}
// ---------- Lock / Hide ----------
+1 -1
View File
@@ -16,7 +16,7 @@ use super::edit::{duplicate_in, outermost, selected_roots, selected_roots_to_tra
use super::opacitymask::percent;
use super::{
CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, f64_or, f64_req, has_doc, has_multi, has_selection,
has_selection_or_guides, id_param, ids_param, matrix_param, ok, point_param, str_param, targets,
has_selection_or_guides, ids_param, matrix_param, object_param, ok, point_param, str_param, targets,
};
use crate::{EngineError, LastTransform};
+1 -1
View File
@@ -66,7 +66,7 @@ fn measure(s: &Session, p: &Value, cmd: &str) -> Result<Measure> {
Ok(Measure { preview, point: s.prefs.align_glyph_bounds_point, area: s.prefs.align_glyph_bounds_area })
}
/// Param `key` of the Align commands, Shear, Unlock All, Show All and `text.setFormat`'s lists: one
/// Param `key` of the Align commands, Shear, Unlock All, Show All, a warp's `orientation` and `text.setFormat`'s lists: one
/// of `values`, or `None` when it is missing or null. Any other value is an error that lists `values`.
pub(crate) fn choice<'a>(p: &'a Value, cmd: &str, key: &str, values: &[&str]) -> Result<Option<&'a str>> {
let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(None) };
+2 -2
View File
@@ -1,5 +1,5 @@
use super::align::choice;
use super::{Document, EngineError, Node, NodeId, NodeKind, Result, Session, Value, bad, id_param, json, ok, selected_roots};
use super::{Document, EngineError, Node, NodeId, NodeKind, Result, Session, Value, bad, json, object_param, ok, selected_roots};
pub(super) enum Arrange {
Front,
@@ -293,7 +293,7 @@ pub(super) fn show_all(s: &mut Session, p: &Value) -> Result<Value> {
}
pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> {
let id = id_param(p, "id")
let id = object_param(p, "id", "object.isolate")?
.or_else(|| s.active().and_then(|d| d.selection.objects.first().copied()))
.ok_or_else(|| bad("object.isolate", "missing id"))?;
let guides_locked = s.menu.guides_locked;
+4 -3
View File
@@ -128,7 +128,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Recent Colors",
[],
None,
"{} → {colors: [{hex, color}] newest first (fed by every paint command and the eyedropper), lastColor: {hex, color}, lastGradient: gradient paint}",
"{} → {colors: [{hex, color}] newest first, at most 30, each once, kept across documents for the session (fed by every paint command and the eyedropper), lastColor: {hex, color}, lastGradient: gradient paint}",
always,
|s, _| {
let c = |c: &Color| json!({"hex": c.to_hex(), "color": c});
@@ -152,8 +152,9 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
}
impl Session {
/// How many colours the Recent Colors rows keep.
pub const RECENT_MAX: usize = 10;
/// How many colors Recent Colors keeps. The Session holds the list, so it stays the same when
/// another document is opened or made active.
pub const RECENT_MAX: usize = 30;
/// Remember an applied paint: a solid colour becomes the last colour and the newest recent
/// colour, a gradient the last gradient. During a live preview this waits for the commit.
+14 -10
View File
@@ -377,20 +377,24 @@ pub(crate) fn pattern_done(s: &mut Session, _: &Value) -> Result<Value> {
if editing(s).is_some() {
s.end_text_edit();
}
let name = s.edit("Done Editing Pattern", |d, sel| {
let (pe, art) = leave_edit(d, sel)?;
if let Some(def) = d.pattern_mut(&pe.pattern) {
def.art = art;
if def.size_tile_to_art {
def.fit_tile_to_art();
}
}
Ok(pe.pattern)
})?;
let name = s.edit("Done Editing Pattern", finish_edit)?;
after_edit_mode(s, None)?;
Ok(json!({ "name": name }))
}
/// Leave pattern editing mode in `d`, storing the editing layer's art as the pattern's tile art
/// (resizing the tile to the art when the pattern does so) → the pattern's name.
pub(crate) fn finish_edit(d: &mut Document, sel: &mut Selection) -> Result<String> {
let (pe, art) = leave_edit(d, sel)?;
if let Some(def) = d.pattern_mut(&pe.pattern) {
def.art = art;
if def.size_tile_to_art {
def.fit_tile_to_art();
}
}
Ok(pe.pattern)
}
fn pattern_cancel(s: &mut Session, _: &Value) -> Result<Value> {
s.edit("Cancel Pattern Editing", |d, sel| {
let (pe, _) = leave_edit(d, sel)?;
+2 -2
View File
@@ -47,7 +47,7 @@ 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, id_param, str_param, unique_name};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, finite_numbers, has_doc, object_param, str_param, unique_name};
use crate::{EngineError, MAX_COORD};
const PLACE: &str = "file.place";
@@ -866,7 +866,7 @@ pub fn read_info(p: &Value) -> Result<Value> {
pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "image.info";
let st = s.doc()?;
let id = match (id_param(p, "id"), &st.selection.objects[..]) {
let id = match (object_param(p, "id", C)?, &st.selection.objects[..]) {
(Some(id), _) => id,
(None, [id]) => *id,
_ => return Err(bad(C, "select one image or pass id")),
+8 -2
View File
@@ -20,6 +20,12 @@
//! a filter does only what they allow: without `doc.read` it is given no objects, without
//! `doc.write` an output that changes the document is refused, and without `state` it neither
//! reads nor writes the data it keeps with the document.
//!
//! A plug-in of API level 2 that lists `progress` may import the host's `vc_progress`,
//! `vc_cancelled` and `vc_log` ([`vectorcraft_plugins::host`]): run inside a
//! [`vectorcraft_doc::cancel::scope`] (the app's heavy filters and background exports), its
//! progress goes to the scope's sink and it sees the scope's Cancel; its log lines go to the log
//! under its id.
use std::sync::{Arc, Mutex};
@@ -46,7 +52,7 @@ pub fn describe(p: &Plugin) -> Value {
"id": m.id, "name": m.name, "version": m.version, "kind": m.kind.name(), "author": m.author, "description": m.description,
"params": m.params_doc(), "paramsSchema": serde_json::to_value(m).ok().and_then(|v| v.get("params").cloned()),
"size": p.size(), "source": p.source(),
"permissions": permissions::names(&m.permissions()), "hash": p.hash(),
"permissions": permissions::names(&m.permissions()), "hash": p.hash(), "api": m.api,
});
match m.kind {
Kind::Effect => v["effect"] = json!(effect::effect_id(&m.id)),
@@ -505,7 +511,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List Plug-ins",
[],
None,
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies), hash (the module's SHA-256)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null}",
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null}",
always,
list
),
+5
View File
@@ -152,6 +152,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("zoomWithMouseWheel", "General", "Options", "Zoom with Mouse Wheel", bool),
p!("scrubNumericFields", "General", "Options", "Scrub Numeric Fields by Dragging", bool),
p!("trackpadRotateView", "General", "Options", "Trackpad Gesture to Rotate View", bool),
p!("holdToolKeys", "General", "Options", "Hold a Tool Shortcut to Use the Tool Temporarily", bool),
// Selection & Anchor Display
p!("selectionTolerance", "Selection & Anchor Display", "Selection", "Tolerance", num(1.0, 8.0, "px")),
p!("objectSelectionByPathOnly", "Selection & Anchor Display", "Selection", "Object Selection by Path Only", bool),
@@ -247,6 +248,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("measurementLabels", "Smart Guides", "Display Options", "Measurement Labels", bool),
p!("spacingGuides", "Smart Guides", "Display Options", "Spacing Guides", bool),
p!("distanceGuides", "Smart Guides", "Display Options", "Invoke Distance Guides", bool),
p!("snapToLastLocation", "Smart Guides", "Display Options", "Snap to Last Location", bool),
p!("snappingTolerance", "Smart Guides", "", "Snapping Tolerance", num(0.0, 40.0, "pt")),
p!("snapTangent", "Smart Guides", "Geometric Guides", "Snap to Tangent", bool),
p!("snapPerpendicular", "Smart Guides", "Geometric Guides", "Snap to Perpendicular", bool),
@@ -422,6 +424,9 @@ pub const PREF_SPECS: &[PrefSpec] = &[
// The Align panel menu's Align to Glyph Bounds: Align and Distribute measure type by its glyphs' ink.
p!("alignGlyphBoundsPoint", "Type", "Align to Glyph Bounds", "Point Text", bool),
p!("alignGlyphBoundsArea", "Type", "Align to Glyph Bounds", "Area Text", bool),
// Artboard Options › Global: the canvas darkens the area outside the artboards while the Artboard tool is active.
p!("fadeRegionOutsideArtboard", "General", "Artboard Options", "Fade Region Outside Artboard", bool),
p!("artboardUpdateWhileDragging", "General", "Artboard Options", "Update While Dragging", bool),
];
pub fn spec(key: &str) -> Option<&'static PrefSpec> {
+7 -7
View File
@@ -2,7 +2,7 @@
//! art retained underneath. Recipes select topology regions; source edits re-evaluate them in
//! the same undo transaction. Rendering and exporters only see ordinary groups and paths.
use super::pathops::Beside;
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, has_doc, id_param, point_param};
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, has_doc, id_param, object_param, point_param};
use serde_json::{Value, json};
use std::{
collections::{BTreeMap, HashMap},
@@ -785,15 +785,15 @@ fn end_isolation(s: &mut Session) -> Result<()> {
st.isolation = editing_layer(&st.doc);
Ok(())
}
fn target(s: &Session, p: &Value) -> Result<NodeId> {
let id = id_param(p, "id")
fn target(s: &Session, p: &Value, cmd: &str) -> Result<NodeId> {
let id = object_param(p, "id", cmd)?
.or_else(|| s.active().and_then(|d| d.selection.objects.first().copied()))
.ok_or_else(|| bad("shaper.release", "select a Shaper group"))?;
s.doc()?.doc.node(id).filter(|n| n.extras().shaper.is_some()).ok_or_else(|| bad("shaper.release", "select a Shaper group"))?;
.ok_or_else(|| bad(cmd, "select a Shaper group"))?;
s.doc()?.doc.node(id).filter(|n| n.extras().shaper.is_some()).ok_or_else(|| bad(cmd, "select a Shaper group"))?;
Ok(id)
}
fn release(s: &mut Session, p: &Value) -> Result<Value> {
let id = target(s, p)?;
let id = target(s, p, "shaper.release")?;
let ids = s.edit("Release Shaper Group", |d, sel| {
let original = d.node(id).map(sources).ok_or(EngineError::NoNode(id))?;
let (parent, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
@@ -809,7 +809,7 @@ fn release(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))
}
fn expand(s: &mut Session, p: &Value) -> Result<Value> {
let id = target(s, p)?;
let id = target(s, p, "shaper.expand")?;
s.edit("Expand Shaper Group", |d, sel| {
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
n.extras_mut().shaper = None;
+2 -2
View File
@@ -20,7 +20,7 @@ use vectorcraft_color::Paint;
use vectorcraft_doc::{Appearance, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, Node, NodeId, NodeKind};
use vectorcraft_geom::Rect;
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, id_param, index, ok, str_param, unique_name};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, index, object_param, ok, str_param, unique_name};
use crate::EngineError;
pub fn specs() -> Vec<CommandSpec> {
@@ -290,7 +290,7 @@ fn style_index(d: &Document, name: &str) -> Result<usize> {
/// The object a style is made from: `id`, else the first selected object.
fn source<'a>(s: &'a Session, p: &Value, cmd: &str) -> Result<(NodeId, &'a Node)> {
let id = match id_param(p, "id") {
let id = match object_param(p, "id", cmd)? {
Some(id) => id,
None => super::edit::selected_roots(s)?.first().copied().ok_or_else(|| bad(cmd, "select an object (or pass `id`)"))?,
};
+122 -27
View File
@@ -1,16 +1,15 @@
//! The Swatches panel: new, delete and duplicate swatches, colour groups and sorting.
use std::collections::{HashMap, HashSet};
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint, Swatch, SwatchGroup, tint_percent};
use vectorcraft_color::{Color, Gradient, GradientKind, GradientMethod, GradientStop, Paint, Swatch, SwatchGroup, tint_percent};
use vectorcraft_doc::pattern::pattern_paint;
use vectorcraft_doc::swatches::{LinkFn, color_name, map_node_solid_paints, node_colors};
use vectorcraft_doc::{Document, NodeId};
use super::paint::paint_from;
use super::{
CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, index, ok, str_param, switch_or,
unique_name,
};
use super::{CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, index, ok, str_param, switch_or};
use crate::EngineError;
pub fn specs() -> Vec<CommandSpec> {
@@ -195,10 +194,11 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> {
let requested = name_param(p, "name").filter(|_| paints.len() == 1);
let names = s.edit("New Swatch", |d, _| {
let mut names = vec![];
let mut free = d.free_swatch_names();
for paint in paints {
let name = match &requested {
Some(n) => d.free_swatch_name(n),
None => d.new_swatch_name(&paint),
Some(n) => free.take(n),
None => free.take_new(&paint),
};
// A tint swatch's kind is its base's.
let tint = matches!(paint, Paint::Solid { swatch: Some(_), .. });
@@ -271,36 +271,116 @@ fn swatch_delete(s: &mut Session, p: &Value) -> Result<Value> {
/// each). A tint (a linked colour that differs from its swatch's) brings its swatch, and with
/// `tints` its own colour too. Links to missing swatches count as unlinked.
fn artwork_colors(d: &Document, ids: &[NodeId], tints: bool, swatches: &mut Vec<String>, colors: &mut Vec<Color>) {
let by_name = swatches_by_name(d);
let mut seen_swatches: HashSet<String> = swatches.iter().cloned().collect();
let mut seen_colors: HashSet<ColorKey> = colors.iter().filter_map(color_key).collect();
for n in ids.iter().filter_map(|id| d.node(*id)) {
node_colors(n, &mut |c, link| {
let sw = link.and_then(|l| d.swatch(l)).filter(|w| w.paint.color().is_some());
let sw = link.and_then(|l| by_name.get(l).copied()).filter(|w| w.paint.color().is_some());
if let Some(w) = sw
&& !swatches.contains(&w.name)
&& !seen_swatches.contains(&w.name)
{
seen_swatches.insert(w.name.clone());
swatches.push(w.name.clone());
}
let own = sw.is_none_or(|w| tints && w.paint.color() != Some(*c));
if own && !colors.contains(c) {
// A color with a NaN component equals no color, so it is never already listed.
if own && color_key(c).is_none_or(|k| seen_colors.insert(k)) {
colors.push(*c);
}
});
}
}
/// Link the solid paints in the subtrees of `ids` whose colour is one of `links`' to that swatch,
/// unless they already link to an existing swatch. Returns the number of paints linked.
/// Every swatch by name, as [`Document::swatch`] finds it: the first swatch of each name, and the
/// built-in Registration swatch when no swatch has its name.
fn swatches_by_name(d: &Document) -> HashMap<&str, &Swatch> {
let mut by_name = HashMap::new();
for w in d.swatches_iter().chain([vectorcraft_color::swatch::registration()]) {
by_name.entry(w.name.as_str()).or_insert(w);
}
by_name
}
/// A color's model and the bits of its components, with -0.0 read as 0.0: two keys are equal
/// exactly when the colors are equal (`==`). `None` for a color with a NaN component, which
/// equals no color.
type ColorKey = (u8, [u32; 4]);
fn color_key(c: &Color) -> Option<ColorKey> {
let (model, v) = match *c {
Color::Rgb { r, g, b } => (0, [r, g, b, 0.0]),
Color::Cmyk { c, m, y, k } => (1, [c, m, y, k]),
Color::Gray { k } => (2, [k, 0.0, 0.0, 0.0]),
Color::Lab { l, a, b } => (3, [l, a, b, 0.0]),
};
Some((model, [float_key(v[0])?, float_key(v[1])?, float_key(v[2])?, float_key(v[3])?]))
}
/// The bits of `v`, with -0.0 read as 0.0, so keys are equal exactly when the values are; `None`
/// for NaN.
fn float_key(v: f32) -> Option<u32> {
if v.is_nan() {
None
} else if v == 0.0 {
Some(0)
} else {
Some(v.to_bits())
}
}
/// A gradient stop's offset, color, opacity, midpoint, swatch link, tint and process plates, as
/// keys.
type StopKey<'a> = (u32, ColorKey, u32, u32, Option<&'a str>, u32, Option<[u32; 4]>);
/// A gradient's kind, method, dither and stops, as keys.
type GradientKey<'a> = (u8, u8, bool, Vec<StopKey<'a>>);
/// A key that is equal for two gradients exactly when the gradients are equal (`==`); `None` when
/// any of its numbers is NaN, so the gradient equals no gradient.
fn gradient_key(g: &Gradient) -> Option<GradientKey<'_>> {
let kind = match g.kind {
GradientKind::Linear => 0,
GradientKind::Radial => 1,
GradientKind::Freeform => 2,
};
let method = match g.method {
GradientMethod::Classic => 0,
GradientMethod::Perceptual => 1,
};
Some((kind, method, g.dither, g.stops.iter().map(stop_key).collect::<Option<_>>()?))
}
/// A stop's key for [`gradient_key`]; `None` when any of its numbers is NaN.
fn stop_key(s: &GradientStop) -> Option<StopKey<'_>> {
let plates = match s.plates {
Some(p) => Some([float_key(p[0])?, float_key(p[1])?, float_key(p[2])?, float_key(p[3])?]),
None => None,
};
Some((float_key(s.offset)?, color_key(&s.color)?, float_key(s.opacity)?, float_key(s.midpoint)?, s.swatch.as_deref(), float_key(s.tint)?, plates))
}
/// Link the solid paints in the subtrees of `ids` whose color is one of `links`' to that swatch
/// (the first one listed for the color), unless they already link to an existing swatch or to the
/// built-in Registration swatch. Returns the number of paints linked.
fn link_colors(d: &mut Document, ids: &[NodeId], links: &[(Color, String)]) -> usize {
if links.is_empty() {
return 0;
}
let live: Vec<String> = d.swatches_iter().map(|w| w.name.clone()).collect();
let live: HashSet<String> = d.swatches_iter().chain([vectorcraft_color::swatch::registration()]).map(|w| w.name.clone()).collect();
let mut by_color: HashMap<ColorKey, &String> = HashMap::new();
for (c, n) in links {
if let Some(k) = color_key(c) {
by_color.entry(k).or_insert(n);
}
}
d.map_solid_paints_in(ids, &mut |c, link, _| {
if link.as_ref().is_some_and(|l| live.contains(l)) {
return false;
}
match links.iter().find(|(lc, _)| lc == c) {
Some((_, n)) => {
*link = Some(n.clone());
match color_key(c).and_then(|k| by_color.get(&k)) {
Some(n) => {
*link = Some((*n).clone());
true
}
None => false,
@@ -346,8 +426,11 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
}
// The global swatches made from the art's colours, which its unlinked paints link to.
let mut links: Vec<(Color, String)> = vec![];
let mut free = d.free_swatch_names();
free.insert(&name);
group.swatches.iter().for_each(|sw| free.insert(&sw.name));
for (c, global) in new {
let nm = unique_name(&color_name(c), |n| n == name || d.swatch_name_taken(n) || group.swatches.iter().any(|sw| sw.name == n));
let nm = free.take(&color_name(c));
if global {
links.push((c, nm.clone()));
}
@@ -798,10 +881,12 @@ fn swatch_add_used(s: &mut Session, p: &Value) -> Result<Value> {
let (mut linked_to, mut colors) = (vec![], vec![]);
artwork_colors(d, &ids, false, &mut linked_to, &mut colors);
// Colours a solid swatch already has are skipped.
colors.retain(|c| !d.swatches_iter().any(|w| w.paint.color() == Some(*c)));
let have: HashSet<ColorKey> = d.swatches_iter().filter_map(|w| w.paint.color()).filter_map(|c| color_key(&c)).collect();
colors.retain(|c| color_key(c).is_none_or(|k| !have.contains(&k)));
let mut free = d.free_swatch_names();
let mut links = vec![];
for c in colors {
let name = d.free_swatch_name(&color_name(c));
let name = free.take(&color_name(c));
d.swatches.push(Swatch { name: name.clone(), paint: Paint::solid(c), global, spot: false });
links.push((c, name));
}
@@ -813,10 +898,11 @@ fn swatch_add_used(s: &mut Session, p: &Value) -> Result<Value> {
fn swatch_unused(s: &mut Session, _: &Value) -> Result<Value> {
let d = &s.doc()?.doc;
let by_name = swatches_by_name(d);
// Links with their tints, so a tint swatch is used where its tint of its base is.
let (mut links, mut colors, mut gradients, mut patterns, mut gradient_links) = (vec![], vec![], vec![], vec![], vec![]);
let mut color = |c: &Color, link: Option<&String>, tint: f32| match link {
Some(l) if d.swatch(l).is_some() => links.push((l.clone(), tint)),
Some(l) if by_name.contains_key(l.as_str()) => links.push((l.clone(), tint)),
_ => colors.push(*c),
};
let mut paint = |p: &Paint| match p {
@@ -838,16 +924,22 @@ fn swatch_unused(s: &mut Session, _: &Value) -> Result<Value> {
}
}
}
let gradient_links: HashSet<&String> = gradient_links.iter().collect();
let link_names: HashSet<&str> = links.iter().map(|(l, _)| l.as_str()).collect();
let link_tints: HashSet<(&str, u32)> = links.iter().filter_map(|(l, t)| Some((l.as_str(), float_key(*t)?))).collect();
let colors: HashSet<ColorKey> = colors.iter().filter_map(color_key).collect();
let patterns: HashSet<&String> = patterns.iter().collect();
let gradients: HashSet<GradientKey> = gradients.iter().filter_map(gradient_key).collect();
let used = |w: &Swatch| {
gradient_links.contains(&w.name)
|| links.iter().any(|(l, t)| match w.tint_of() {
Some((base, tint)) => l == base && *t == tint,
None => *l == w.name,
})
|| match w.tint_of() {
Some((base, tint)) => float_key(tint).is_some_and(|t| link_tints.contains(&(base, t))),
None => link_names.contains(w.name.as_str()),
}
|| match &w.paint {
Paint::None => true,
Paint::Solid { color, .. } => colors.contains(color),
Paint::Gradient(g) => gradients.contains(&g.gradient),
Paint::Solid { color, .. } => color_key(color).is_some_and(|k| colors.contains(&k)),
Paint::Gradient(g) => gradient_key(&g.gradient).is_some_and(|k| gradients.contains(&k)),
Paint::Pattern { pattern, .. } => patterns.contains(pattern),
}
};
@@ -1017,8 +1109,11 @@ pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Color], ren
}
}
}
let mut free = d.free_swatch_names();
free.insert(&name);
swatches.iter().for_each(|w| free.insert(&w.name));
for c in colors.iter().skip(swatches.len()) {
let nm = unique_name(&color_name(*c), |n| n == name || d.swatch_name_taken(n) || swatches.iter().any(|w| w.name == n));
let nm = free.take(&color_name(*c));
swatches.push(Swatch { name: nm, paint: Paint::solid(*c), global: false, spot: false });
}
let g = &mut d.swatch_groups[gi];
+2 -2
View File
@@ -20,7 +20,7 @@ use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection, SymbolEdit, S
use vectorcraft_geom::{Affine, Point};
use super::brushsym::{natural_size, place_xf};
use super::{EngineError, Result, Session, bad, id_param, number_or, ok, str_param};
use super::{EngineError, Result, Session, bad, number_or, object_param, ok, str_param};
/// The name of the undo step that enters symbol editing mode.
const ENTER: &str = "Edit Symbol";
@@ -65,7 +65,7 @@ pub(crate) fn enter(s: &mut Session, p: &Value) -> Result<Value> {
if st.doc.pattern_edit.is_some() {
return Err(bad(C, "finish editing the pattern first"));
}
let given = id_param(p, "id").map(|i| vec![i]).or_else(|| super::ids_param(p, "ids").filter(|v| !v.is_empty()));
let given = object_param(p, "id", C)?.map(|i| vec![i]).or_else(|| super::ids_param(p, "ids").filter(|v| !v.is_empty()));
let (name, xf, instance) = match given {
Some(ids) => {
let symbols = ids.iter().map(|id| instance_of(&st.doc, *id)).collect::<Option<Vec<_>>>();
+1 -1
View File
@@ -1676,7 +1676,7 @@ pub(crate) fn type_ranges(
at_caret: impl Fn(&str, usize) -> Option<(usize, usize)>,
) -> Result<Vec<(NodeId, usize, usize, bool)>> {
// (text, its range; None: all of it).
let targets: Vec<(NodeId, Option<(usize, usize)>)> = match id_param(p, "id") {
let targets: Vec<(NodeId, Option<(usize, usize)>)> = match super::object_param(p, "id", c)? {
// An object that isn't type is refused as `ids` of it is.
Some(id) if s.doc()?.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Text(_))) => {
return Err(bad(c, "no text objects selected"));
+109 -10
View File
@@ -10,8 +10,9 @@ use serde::de::DeserializeOwned;
use serde_json::{Map, Value, json};
use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind, ParaStyle, TextStyleDef};
use super::clipboard::resources::import_text_styles;
use super::typecmd::{refresh_bounds, text_targets};
use super::{CommandSpec, Result, Run, Session, bad, bool_or, has_doc, id_param, index, ok, str_param};
use super::{CommandSpec, Result, Run, Session, bad, bool_or, has_doc, index, object_param, ok, str_param};
pub const NORMAL_CHAR: &str = "[Normal Character Style]";
pub const NORMAL_PARA: &str = "[Normal Paragraph Style]";
@@ -111,10 +112,21 @@ macro_rules! style_cmds {
|s, _| unused(s, $kind),
false,
),
spec(
concat!($p, ".load"),
concat!("Load ", $what, " Styles…"),
&["Window", "Type", $menu],
LOAD_PARAMS,
|s, p| load(s, p, &[$kind]),
true,
),
]
};
}
/// The params of `charStyle.load`, `paraStyle.load` and `textStyle.loadAll`.
const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind";
pub fn specs() -> Vec<CommandSpec> {
let mut v = style_cmds!(
Kind::Char,
@@ -132,6 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
true,
));
v.extend(style_cmds!(Kind::Para, "paraStyle", "Paragraph Styles", "Paragraph", ""));
v.push(spec("textStyle.loadAll", "Load All Styles…", &["Window", "Type"], LOAD_PARAMS, |s, p| load(s, p, &[Kind::Char, Kind::Para]), true));
v
}
@@ -426,10 +439,11 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Valu
/// The selected text's attributes: the first selected character for a nonempty range,
/// the insertion style at a lone `start`, or the first selected text object's first run.
/// Paragraph capture always samples the paragraph at `start`.
fn selection_attrs(s: &Session, p: &Value, kind: Kind) -> Result<Option<Map<String, Value>>> {
/// Paragraph capture always samples the paragraph at `start`. An `id` that isn't an object id is
/// an error under the `verb` command of `kind`.
fn selection_attrs(s: &Session, p: &Value, kind: Kind, verb: &str) -> Result<Option<Map<String, Value>>> {
let d = &s.doc()?.doc;
let id = match id_param(p, "id") {
let id = match object_param(p, "id", &kind.cmd(verb))? {
Some(id) => Some(id),
None => text_targets(s, &json!({}), "").ok().and_then(|v| v.first().copied()),
};
@@ -451,14 +465,14 @@ fn selection_attrs(s: &Session, p: &Value, kind: Kind) -> Result<Option<Map<Stri
/// The selected text's character (`para`: paragraph) attributes, every one of them: what a
/// library keeps of a text style. `None` without text selected.
pub(crate) fn selected_style_attrs(s: &Session, para: bool) -> Result<Option<Map<String, Value>>> {
selection_attrs(s, &json!({}), if para { Kind::Para } else { Kind::Char })
selection_attrs(s, &json!({}), if para { Kind::Para } else { Kind::Char }, "new")
}
/// The attributes `charStyle.new` (`para`: `paraStyle.new`) would give a style made now from
/// `target` (its `id`, `start` and `end`; empty for the selected objects). `None` without text
/// there.
pub fn target_style_attrs(s: &Session, target: &Value, para: bool) -> Option<Map<String, Value>> {
selection_attrs(s, target, if para { Kind::Para } else { Kind::Char }).ok().flatten()
selection_attrs(s, target, if para { Kind::Para } else { Kind::Char }, "new").ok().flatten()
}
/// The attributes a new character or paragraph style receives when no text is selected.
@@ -631,7 +645,7 @@ fn new(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
/// (`charStyle.duplicate`), which `attrs` keeps as [`attrs_param`] keeps the target text's.
fn new_from(s: &mut Session, p: &Value, kind: Kind, copied: Option<&Map<String, Value>>) -> Result<Value> {
let c = kind.cmd("new");
let target = selection_attrs(s, p, kind)?;
let target = selection_attrs(s, p, kind, "new")?;
let attrs = match attrs_param(&s.doc()?.doc, p, kind, "new", copied.or(target.as_ref()))? {
Some(a) => a,
None => match target {
@@ -672,8 +686,9 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
let style_name = (name != kind.normal()).then(|| name.clone());
// A Type tool range or whole text objects.
let text_range = super::typecmd::TextRange::parse(p, &c)?;
let range = id_param(p, "id").filter(|_| text_range.is_some());
let ids = match range.or_else(|| id_param(p, "id")) {
let given = object_param(p, "id", &c)?;
let range = given.filter(|_| text_range.is_some());
let ids = match given {
Some(id) => vec![id],
None => text_targets(s, p, &c)?,
};
@@ -754,7 +769,7 @@ fn redefine_to(s: &mut Session, kind: Kind, name: &str, new_attrs: Map<String, V
fn redefine(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
let name = name_param(p, kind, "redefine")?.to_string();
let attrs = selection_attrs(s, p, kind)?.ok_or_else(|| bad(&kind.cmd("redefine"), "select text to redefine the style from"))?;
let attrs = selection_attrs(s, p, kind, "redefine")?.ok_or_else(|| bad(&kind.cmd("redefine"), "select text to redefine the style from"))?;
redefine_to(s, kind, &name, attrs, "redefine")
}
@@ -899,5 +914,89 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> {
Ok(json!({ "names": names }))
}
/// The styles of `kind` in `src` that load, with their source names so that art in the file keeps
/// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes,
/// scales, leading, shifts or stroke width are out of the range `charStyle.new` takes, or whose name
/// is empty, which are skipped. → (the styles, the names in `src` of those skipped)
fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
const RANGED: [&str; 8] = ["size", "h_scale", "v_scale", "leading", "baseline_shift", "tcyUpDown", "tcyLeftRight", "stroke_width"];
let (mut defs, mut skipped) = (vec![], vec![]);
for def in kind.defs(src) {
let name = def.name.as_str();
if name.trim() == kind.normal() {
continue;
}
// Paints, features and language are taken as the file stores them; the ranged values are checked.
let mut kept = def.attrs.clone();
kept.retain(|k, _| !RANGED.contains(&k.as_str()));
match attrs_param(src, &json!({ "attrs": def.attrs }), kind, "load", Some(&kept)).ok().flatten().filter(|_| !name.trim().is_empty()) {
Some(attrs) => defs.push(TextStyleDef { name: name.to_string(), attrs }),
None => skipped.push(def.name.clone()),
}
}
(defs, skipped)
}
/// Load Character Styles, Load Paragraph Styles and Load All Styles: the `kinds` of style of the
/// document `p` gives (`path`, `data` or `dataBase64`) added to the active one with the swatches and
/// patterns they paint with, as Paste adds those of pasted type ([`import_text_styles`]).
fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result<Value> {
let label = match kinds {
[Kind::Char] => "Load Character Styles",
[Kind::Para] => "Load Paragraph Styles",
_ => "Load All Styles",
};
let c = &match kinds {
[kind] => kind.cmd("load"),
_ => "textStyle.loadAll".to_string(),
};
let path = str_param(p, "path");
let bytes = match (path, str_param(p, "data"), str_param(p, "dataBase64")) {
(Some(path), ..) => super::fileio::read_file(path)?,
(None, Some(text), _) => text.as_bytes().to_vec(),
(None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?,
_ => return Err(bad(c, "give `path`, `data` or `dataBase64`")),
};
let file = str_param(p, "name").or(path).unwrap_or("Styles");
let src = super::fileio::load(file, &bytes).map_err(|e| bad(c, e.to_string()))?;
if src.preview_only {
return Err(bad(c, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning"));
}
// The source with only the styles that load. Those of a kind not loaded still come along when
// a pattern or symbol that a loaded style paints with sets type in them.
let mut src = src.doc;
let mut skipped = [vec![], vec![]];
for kind in [Kind::Char, Kind::Para] {
let (defs, names) = loadable(&src, kind);
*kind.defs_mut(&mut src) = defs;
if kinds.contains(&kind) {
skipped[usize::from(kind == Kind::Para)] = names;
}
}
let (chars, paras) = (kinds.contains(&Kind::Char), kinds.contains(&Kind::Para));
let mut trial = (*s.doc()?.doc).clone();
let mut placed = import_text_styles(&src, &mut trial, chars, paras);
// An undo step only when the document changes. The step takes the document the import made,
// unless the edit first ends a typing session, which can change the document it starts from.
if trial != *s.doc()?.doc {
if super::typing_in_progress(s) {
placed = s.edit(label, |d, _| Ok(import_text_styles(&src, d, chars, paras)))?;
} else {
s.edit(label, |d, _| {
*d = trial;
Ok(())
})?;
}
}
let reply = |para: bool| {
let names = |added: bool| placed.iter().filter(|p| p.para == para && p.added == added).map(|p| p.name.as_str()).collect::<Vec<_>>();
json!({ "added": names(true), "existing": names(false), "skipped": skipped[usize::from(para)] })
};
Ok(match kinds {
[kind] => reply(*kind == Kind::Para),
_ => json!({ "charStyles": reply(false), "paraStyles": reply(true) }),
})
}
#[cfg(test)]
mod tests;
+474
View File
@@ -733,6 +733,480 @@ fn several_styles_are_deleted_in_one_step() {
assert_eq!(s.execute("edit.undo", &json!({})).unwrap()["undone"], "Delete Style");
}
/// A saved document whose character and paragraph styles are `char` and `para` (name, attrs),
/// stored as they are, as `charStyle.load`'s `dataBase64`.
fn styles_file(char: &[(&str, Value)], para: &[(&str, Value)]) -> String {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let mut d = (*s.doc().unwrap().doc).clone();
let defs = |v: &[(&str, Value)]| {
v.iter().map(|(n, a)| TextStyleDef { name: n.to_string(), attrs: a.as_object().cloned().unwrap_or_default() }).collect::<Vec<_>>()
};
d.char_styles = defs(char).into();
d.para_styles = defs(para).into();
vectorcraft_format::base64_encode(&vectorcraft_format::save(&d, false))
}
/// Load Character Styles and Load Paragraph Styles copy the other document's styles of their kind
/// after the document's own, in one undo step. A style with the same attributes as the style here
/// of its name, or of its name with a number, is not added again; any other gets the first free of
/// those names, and the style here and the type using it keep their attributes. The file's Normal
/// style is not loaded, and a style whose attributes do not read, or whose name is empty, is
/// skipped.
#[test]
fn styles_load_from_another_document_in_one_step() {
for p in ["charStyle", "paraStyle"] {
let (mut s, id) = session_with_text("Title");
let normal = if p == "charStyle" { NORMAL_CHAR } else { NORMAL_PARA };
let key = if p == "charStyle" { "size" } else { "space_after" };
let size = |v: f64| Value::Object(Map::from_iter([(key.to_string(), json!(v))]));
for (n, v) in [("Body", 12.0), ("Accent", 9.0), ("Accent 2", 1.0)] {
s.execute(&format!("{p}.new"), &json!({"name": n, "attrs": size(v)})).unwrap();
}
s.execute(&format!("{p}.apply"), &json!({"name": "Accent", "id": id})).unwrap();
let file =
[("Body", size(12.0)), ("Accent", size(20.0)), ("Fresh", size(5.0)), (normal, size(30.0)), ("Bad", json!({"nope": 1})), (" ", size(2.0))];
let data = styles_file(&file, &file);
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let r = s.execute(&format!("{p}.load"), &json!({"dataBase64": data, "name": "Other.vectorcraft"})).unwrap();
assert_eq!(r, json!({"added": ["Accent 3", "Fresh"], "existing": ["Body"], "skipped": ["Bad", " "]}), "{p}");
assert_eq!(listed(&mut s, p), [normal, "Body", "Accent", "Accent 2", "Accent 3", "Fresh"], "{p}");
let d = s.doc().unwrap().doc.clone();
let attrs = |name: &str| super::style_attrs(&d, p == "paraStyle", name).map(Value::Object);
assert_eq!((attrs("Accent"), attrs("Accent 3"), attrs(normal)), (Some(size(9.0)), Some(size(20.0)), Some(json!({}))), "{p}");
// The other kind and the type are as they were.
let (other, mine) = if p == "charStyle" { (&d.para_styles, &d.char_styles) } else { (&d.char_styles, &d.para_styles) };
let (other_before, mine_before) =
if p == "charStyle" { (&before.para_styles, &before.char_styles) } else { (&before.char_styles, &before.para_styles) };
assert_eq!((other, &mine[..mine_before.len()]), (other_before, &mine_before[..]), "{p}");
assert_eq!(d.node(NodeId(id)), before.node(NodeId(id)), "{p}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{p}");
// Loading the same file again adds nothing and makes no undo step.
let again = s.execute(&format!("{p}.load"), &json!({"dataBase64": data, "name": "Other.vectorcraft"})).unwrap();
assert_eq!(again["added"], json!([]), "{p}");
assert_eq!(again["existing"], json!(["Body", "Accent 3", "Fresh"]), "{p}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{p}");
let undone = s.execute("edit.undo", &json!({})).unwrap()["undone"].clone();
assert_eq!(undone, if p == "charStyle" { "Load Character Styles" } else { "Load Paragraph Styles" });
assert_eq!(s.doc().unwrap().doc, before, "{p}");
}
}
/// Load All Styles loads both kinds in one undo step, from a path too; a file that does not open,
/// or no file, loads nothing.
#[test]
fn load_all_styles_loads_both_kinds_in_one_step() {
let (mut s, _) = session_with_text("Title");
let data = styles_file(&[("Lead", json!({"size": 30.0}))], &[("Centered", json!({"justify": "Center"}))]);
let dir = std::env::temp_dir().join(format!("vc-load-styles-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("Other.vectorcraft");
std::fs::write(&path, vectorcraft_format::base64_decode(&data).unwrap()).unwrap();
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
for bad in [json!({}), json!({"data": "not a document", "name": "x.vectorcraft"}), json!({"dataBase64": "!"})] {
assert!(s.execute("textStyle.loadAll", &bad).is_err(), "{bad}");
}
let r = s.execute("textStyle.loadAll", &json!({"path": path.to_string_lossy()})).unwrap();
std::fs::remove_dir_all(&dir).ok();
let one = |name: &str| json!({"added": [name], "existing": [], "skipped": []});
assert_eq!(r, json!({"charStyles": one("Lead"), "paraStyles": one("Centered")}));
assert_eq!(listed(&mut s, "charStyle"), [NORMAL_CHAR, "Lead"]);
assert_eq!(listed(&mut s, "paraStyle"), [NORMAL_PARA, "Centered"]);
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
assert_eq!(s.execute("edit.undo", &json!({})).unwrap()["undone"], "Load All Styles");
assert_eq!(s.doc().unwrap().doc, before);
}
/// A loaded character style whose size, scale, leading, shift or stroke width is out of the range
/// `charStyle.new` takes is skipped.
#[test]
fn loaded_styles_out_of_range_are_skipped() {
let (mut s, _) = session_with_text("Title");
let file = [
("Huge", json!({"size": 2000.0})),
("Flat", json!({"h_scale": 0.5})),
("Shifted", json!({"baseline_shift": 5000.0})),
("Thick", json!({"stroke_width": -2.0})),
("Fine", json!({"size": 12.0, "h_scale": 50.0})),
];
let data = styles_file(&file, &[]);
let r = s.execute("charStyle.load", &json!({"dataBase64": data, "name": "Other.vectorcraft"})).unwrap();
assert_eq!(r, json!({"added": ["Fine"], "existing": [], "skipped": ["Huge", "Flat", "Shifted", "Thick"]}));
assert_eq!(listed(&mut s, "charStyle"), [NORMAL_CHAR, "Fine"]);
}
/// A loaded style brings the pattern it paints with, renamed when the document has another pattern
/// of that name, as Paste brings it; a global color whose name the document gives another color
/// is the document's.
#[test]
fn loaded_styles_bring_the_patterns_and_swatches_they_paint_with() {
// A pattern "Dots" made from a `size` square, a global "Ink", and type painted with each.
let painted = |size: f64, ink: &str| {
let (mut s, id) = session_with_text("Dots");
let square = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": size, "height": size})).unwrap()["id"].clone();
s.execute("object.pattern.make", &json!({"name": "Dots", "edit": false, "ids": [square]})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": ink, "global": true})).unwrap();
(s, id)
};
let (mut src, id) = painted(10.0, "#3366cc");
src.execute("select.set", &json!({"ids": [id]})).unwrap();
src.execute("paint.setFill", &json!({"swatch": "Dots", "ids": [id]})).unwrap();
src.execute("charStyle.new", &json!({"name": "Patterned", "id": id})).unwrap();
src.execute("paint.setFill", &json!({"swatch": "Ink", "ids": [id]})).unwrap();
src.execute("charStyle.new", &json!({"name": "Inked", "id": id})).unwrap();
let data = vectorcraft_format::base64_encode(&vectorcraft_format::save(&src.doc().unwrap().doc, false));
let (mut s, id) = painted(30.0, "#ff0000");
let r = s.execute("charStyle.load", &json!({"dataBase64": data, "name": "Other.vectorcraft"})).unwrap();
assert_eq!(r["added"], json!(["Patterned", "Inked"]));
let d = s.doc().unwrap().doc.clone();
let fill = |name: &str| super::style_attrs(&d, false, name).unwrap()["fill"].to_string();
assert!(d.pattern("Dots 2").is_some() && fill("Patterned").contains("\"Dots 2\""), "{}", fill("Patterned"));
assert!(fill("Inked").contains("\"Ink\"") && d.swatch("Ink 2").is_none(), "{}", fill("Inked"));
s.execute("charStyle.apply", &json!({"name": "Patterned", "id": id})).unwrap();
assert!(matches!(&runs(&s, id)[0].style.fill, vectorcraft_color::Paint::Pattern { pattern, .. } if pattern == "Dots 2"));
}
/// A pattern whose type is set in a loaded style that was renamed on the way in ("Accent 2") is
/// the same pattern when the file is loaded again, and so is the style that paints with it, also
/// when "Accent" itself paints with another pattern.
#[test]
fn reloaded_patterns_follow_the_renamed_styles_their_type_uses() {
for patterned in [false, true] {
let (mut src, id) = session_with_text("Tile");
if patterned {
let square = src.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 10, "height": 10})).unwrap()["id"].clone();
src.execute("object.pattern.make", &json!({"name": "Dots", "edit": false, "ids": [square]})).unwrap();
src.execute("paint.setFill", &json!({"swatch": "Dots", "ids": [id]})).unwrap();
}
src.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 4, "kerning": 40})).unwrap();
src.execute("charStyle.new", &json!({"name": "Accent", "id": id})).unwrap();
src.execute("charStyle.apply", &json!({"name": "Accent", "id": id})).unwrap();
if patterned {
// A solid fill over the style's, so the tile's type itself paints with no pattern.
src.execute("paint.setFill", &json!({"color": "#000000", "ids": [id]})).unwrap();
}
src.execute("object.pattern.make", &json!({"name": "Tiles", "edit": false, "ids": [id]})).unwrap();
let other = src.execute("text.create", &json!({"x": 10, "y": 90, "text": "B"})).unwrap()["id"].as_u64().unwrap();
src.execute("paint.setFill", &json!({"swatch": "Tiles", "ids": [other]})).unwrap();
src.execute("charStyle.new", &json!({"name": "Tiled", "id": other})).unwrap();
let data = vectorcraft_format::base64_encode(&vectorcraft_format::save(&src.doc().unwrap().doc, false));
let (mut s, _) = session_with_text("X");
s.execute("charStyle.new", &json!({"name": "Accent", "attrs": {"kerning": 10}})).unwrap();
let load = json!({"dataBase64": data, "name": "Other.vectorcraft"});
s.execute("charStyle.load", &load).unwrap();
let counts = |s: &Session| {
let d = &s.doc().unwrap().doc;
(d.patterns.len(), d.char_styles.iter().map(|c| c.name.clone()).collect::<Vec<_>>())
};
let first = counts(&s);
assert!(first.1.contains(&"Accent 2".to_string()) && first.1.contains(&"Tiled".to_string()), "{patterned}: {first:?}");
let r = s.execute("charStyle.load", &load).unwrap();
assert_eq!(r["added"], json!([]), "{patterned}: {r}");
assert_eq!(counts(&s), first, "{patterned}");
}
}
/// A loaded style that paints with a pattern whose type is set in that same style still paints
/// with the pattern when the pattern comes in under a free name ("Dots 2"). The commands refuse to
/// make that loop, so the source is a document edited directly, as a file may hold it.
#[test]
fn a_style_and_the_pattern_that_uses_it_load_together() {
let (mut src, id) = session_with_text("Tile");
src.execute("charStyle.new", &json!({"name": "Accent", "attrs": {"kerning": 40}})).unwrap();
src.execute("charStyle.apply", &json!({"name": "Accent", "id": id})).unwrap();
src.execute("object.pattern.make", &json!({"name": "Dots", "edit": false, "ids": [id]})).unwrap();
let other = src.execute("text.create", &json!({"x": 10, "y": 90, "text": "B"})).unwrap()["id"].as_u64().unwrap();
src.execute("charStyle.apply", &json!({"name": "Accent", "id": other})).unwrap();
src.execute("paint.setFill", &json!({"swatch": "Dots", "ids": [other]})).unwrap();
src.execute("charStyle.new", &json!({"name": "Painted", "id": other})).unwrap();
let mut source = (*src.doc().unwrap().doc).clone();
let painted = source.char_styles.iter().find(|s| s.name == "Painted").unwrap().attrs.clone();
source.char_styles.retain(|s| s.name != "Painted");
source.char_styles.iter_mut().find(|s| s.name == "Accent").unwrap().attrs = painted;
let data = vectorcraft_format::base64_encode(&vectorcraft_format::save(&source, false));
let fill = |s: &Session, name: &str| super::style_attrs(&s.doc().unwrap().doc, false, name).unwrap()["fill"].to_string();
let source_fill = super::style_attrs(&source, false, "Accent").unwrap()["fill"].to_string();
assert!(source_fill.contains("\"Dots\""), "{source_fill}");
let (mut s, _) = session_with_text("X");
let square = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 30, "height": 30})).unwrap()["id"].clone();
s.execute("object.pattern.make", &json!({"name": "Dots", "edit": false, "ids": [square]})).unwrap();
let load = json!({"dataBase64": data, "name": "Other.vectorcraft"});
s.execute("charStyle.load", &load).unwrap();
assert!(s.doc().unwrap().doc.pattern("Dots 2").is_some());
assert!(fill(&s, "Accent").contains("\"Dots 2\""), "{}", fill(&s, "Accent"));
// Loaded again, the two are found under those names, and nothing is added.
let (doc, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
let r = s.execute("charStyle.load", &load).unwrap();
assert_eq!(r["added"], json!([]), "{r}");
assert_eq!((s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()), (doc, undo));
}
/// A style and the pattern it paints with, whose type is set in that style, are both added when
/// the document has a style of that name and attributes but another pattern of that name: the
/// copy of the style paints with the copy of the pattern, and a second load adds nothing. A loop the
/// document has is used under the names it has together.
#[test]
fn a_style_in_a_loop_is_not_matched_to_a_style_that_paints_with_another_pattern() {
let (mut src, id) = session_with_text("Tile");
src.execute("charStyle.new", &json!({"name": "Accent", "attrs": {"kerning": 40}})).unwrap();
src.execute("charStyle.apply", &json!({"name": "Accent", "id": id})).unwrap();
src.execute("object.pattern.make", &json!({"name": "Dots", "edit": false, "ids": [id]})).unwrap();
let other = src.execute("text.create", &json!({"x": 10, "y": 90, "text": "B"})).unwrap()["id"].as_u64().unwrap();
src.execute("charStyle.apply", &json!({"name": "Accent", "id": other})).unwrap();
src.execute("paint.setFill", &json!({"swatch": "Dots", "ids": [other]})).unwrap();
src.execute("charStyle.new", &json!({"name": "Painted", "id": other})).unwrap();
let mut source = (*src.doc().unwrap().doc).clone();
let painted = source.char_styles.iter().find(|s| s.name == "Painted").unwrap().attrs.clone();
source.char_styles.retain(|s| s.name != "Painted");
source.char_styles.iter_mut().find(|s| s.name == "Accent").unwrap().attrs = painted.clone();
let data = vectorcraft_format::base64_encode(&vectorcraft_format::save(&source, false));
let (mut s, _) = session_with_text("X");
let square = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 30, "height": 30})).unwrap()["id"].clone();
s.execute("object.pattern.make", &json!({"name": "Dots", "edit": false, "ids": [square]})).unwrap();
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.char_styles.push(TextStyleDef { name: "Accent".into(), attrs: painted });
let load = json!({"dataBase64": data, "name": "Other.vectorcraft"});
let r = s.execute("charStyle.load", &load).unwrap();
assert_eq!(r["added"], json!(["Accent 2"]), "{r}");
let d = s.doc().unwrap().doc.clone();
let fill = |name: &str| super::style_attrs(&d, false, name).unwrap()["fill"].to_string();
assert!(fill("Accent").contains("\"Dots\"") && fill("Accent 2").contains("\"Dots 2\""), "{} {}", fill("Accent"), fill("Accent 2"));
let NodeKind::Text(text) = &d.pattern("Dots 2").unwrap().art[0].kind else { panic!("pattern art should be type") };
assert_eq!(text.runs[0].style.style_name.as_deref(), Some("Accent 2"));
let r = s.execute("charStyle.load", &load).unwrap();
assert_eq!(r["added"], json!([]), "{r}");
assert_eq!(s.doc().unwrap().doc, d);
// With the loop's style renamed "Accent 3" and an "Accent 2" listed before it that also paints
// with "Dots 2", the loop is still found as "Accent 3" and "Dots 2", the names it has together.
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let at = doc.char_styles.iter().position(|c| c.name == "Accent 2").unwrap();
doc.char_styles[at].name = "Accent 3".into();
let copy = TextStyleDef { name: "Accent 2".into(), attrs: doc.char_styles[at].attrs.clone() };
doc.char_styles.insert(at, copy);
let tile = doc.patterns.iter_mut().find(|p| p.name == "Dots 2").unwrap();
let NodeKind::Text(text) = &mut std::sync::Arc::make_mut(&mut tile.art[0]).kind else { panic!("pattern art should be type") };
text.runs[0].style.style_name = Some("Accent 3".into());
let d = s.doc().unwrap().doc.clone();
let r = s.execute("charStyle.load", &load).unwrap();
assert_eq!(r, json!({"added": [], "existing": ["Accent 3"], "skipped": []}));
assert_eq!(s.doc().unwrap().doc, d);
}
/// A brush in a loaded style's pattern whose art sets type in a style renamed on the way in
/// ("Accent 2") is the same brush when the file is loaded again.
#[test]
fn reloaded_brushes_follow_the_renamed_styles_their_art_uses() {
let (mut src, id) = session_with_text("Ink");
src.execute("charStyle.new", &json!({"name": "Accent", "attrs": {"kerning": 40}})).unwrap();
src.execute("charStyle.apply", &json!({"name": "Accent", "id": id})).unwrap();
src.execute("brush.new", &json!({"type": "art", "name": "Lettering", "ids": [id]})).unwrap();
let path = src.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 40, "height": 10})).unwrap()["id"].clone();
src.execute("brush.apply", &json!({"name": "Lettering", "ids": [path]})).unwrap();
src.execute("object.pattern.make", &json!({"name": "Tiles", "edit": false, "ids": [path]})).unwrap();
let other = src.execute("text.create", &json!({"x": 10, "y": 90, "text": "B"})).unwrap()["id"].as_u64().unwrap();
src.execute("paint.setFill", &json!({"swatch": "Tiles", "ids": [other]})).unwrap();
src.execute("charStyle.new", &json!({"name": "Tiled", "id": other})).unwrap();
let data = vectorcraft_format::base64_encode(&vectorcraft_format::save(&src.doc().unwrap().doc, false));
let (mut s, _) = session_with_text("X");
s.execute("charStyle.new", &json!({"name": "Accent", "attrs": {"kerning": 10}})).unwrap();
let load = json!({"dataBase64": data, "name": "Other.vectorcraft"});
let r = s.execute("charStyle.load", &load).unwrap();
assert!(r["added"].as_array().unwrap().contains(&json!("Accent 2")), "{r}");
let d = s.doc().unwrap().doc.clone();
let lib = vectorcraft_brush::library(&d);
let brush = lib.iter().find(|b| b.name == "Lettering").unwrap();
let mut styles = vec![];
for a in brush.art() {
a.walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind {
styles.extend(t.runs.iter().filter_map(|r| r.style.style_name.clone()));
}
});
}
assert_eq!(styles, ["Accent 2"]);
let r = s.execute("charStyle.load", &load).unwrap();
assert_eq!(r["added"], json!([]), "{r}");
assert_eq!(s.doc().unwrap().doc, d);
}
/// A style name from a saved document stays the name used by type in imported pattern art.
#[test]
fn loaded_style_keeps_the_name_used_by_pattern_type() {
let (mut src, id) = session_with_text("Tile");
src.execute("charStyle.new", &json!({"name": "Accent", "attrs": {"kerning": 40}})).unwrap();
src.execute("charStyle.apply", &json!({"name": "Accent", "id": id})).unwrap();
src.execute("object.pattern.make", &json!({"name": "Tiles", "edit": false, "ids": [id]})).unwrap();
let other = src.execute("text.create", &json!({"x": 10, "y": 90, "text": "B"})).unwrap()["id"].as_u64().unwrap();
src.execute("paint.setFill", &json!({"swatch": "Tiles", "ids": [other]})).unwrap();
src.execute("charStyle.new", &json!({"name": "Tiled", "id": other})).unwrap();
let mut source = (*src.doc().unwrap().doc).clone();
source.char_styles.iter_mut().find(|s| s.name == "Accent").unwrap().name = " Accent ".into();
let tile = source.patterns.iter_mut().find(|p| p.name == "Tiles").unwrap();
let art = std::sync::Arc::make_mut(&mut tile.art[0]);
let NodeKind::Text(text) = &mut art.kind else { panic!("pattern art should be type") };
text.runs[0].style.style_name = Some(" Accent ".into());
let data = vectorcraft_format::base64_encode(&vectorcraft_format::save(&source, false));
let (mut dst, _) = session_with_text("X");
let load = json!({"dataBase64": data, "name": "Other.vectorcraft"});
dst.execute("charStyle.load", &load).unwrap();
let doc = &dst.doc().unwrap().doc;
assert!(doc.char_styles.iter().any(|s| s.name == " Accent "));
let NodeKind::Text(text) = &doc.pattern("Tiles").unwrap().art[0].kind else { panic!("pattern art should be type") };
assert_eq!(text.runs[0].style.style_name.as_deref(), Some(" Accent "));
}
/// Load Character Styles brings the paragraph style that type in a loaded style's pattern is set
/// in, renamed when the document has another style of that name, without listing it in the reply.
#[test]
fn loaded_pattern_type_keeps_its_paragraph_style() {
let (mut src, id) = session_with_text("Tile");
src.execute("paraStyle.new", &json!({"name": "Centered", "attrs": {"justify": "Center"}})).unwrap();
src.execute("paraStyle.apply", &json!({"name": "Centered", "id": id})).unwrap();
src.execute("object.pattern.make", &json!({"name": "Tiles", "edit": false, "ids": [id]})).unwrap();
let other = src.execute("text.create", &json!({"x": 10, "y": 90, "text": "B"})).unwrap()["id"].as_u64().unwrap();
src.execute("paint.setFill", &json!({"swatch": "Tiles", "ids": [other]})).unwrap();
src.execute("charStyle.new", &json!({"name": "Tiled", "id": other})).unwrap();
let data = vectorcraft_format::base64_encode(&vectorcraft_format::save(&src.doc().unwrap().doc, false));
let (mut s, _) = session_with_text("X");
s.execute("paraStyle.new", &json!({"name": "Centered", "attrs": {"justify": "Right"}})).unwrap();
let load = json!({"dataBase64": data, "name": "Other.vectorcraft"});
let r = s.execute("charStyle.load", &load).unwrap();
assert_eq!(r, json!({"added": ["Tiled"], "existing": [], "skipped": []}));
let d = s.doc().unwrap().doc.clone();
assert_eq!(listed(&mut s, "paraStyle"), [NORMAL_PARA, "Centered", "Centered 2"]);
assert_eq!(super::style_attrs(&d, true, "Centered 2").map(Value::Object), Some(json!({"justify": "Center"})));
let NodeKind::Text(text) = &d.pattern("Tiles").unwrap().art[0].kind else { panic!("pattern art should be type") };
assert_eq!(text.para_styles().filter_map(|p| p.style_name.as_deref()).collect::<Vec<_>>(), ["Centered 2"]);
// Loaded again, nothing is added.
let r = s.execute("charStyle.load", &load).unwrap();
assert_eq!(r["added"], json!([]), "{r}");
assert_eq!(s.doc().unwrap().doc, d);
}
/// A pattern whose tile paints with itself is found under its renamed copy on a second load.
#[test]
fn self_referencing_pattern_is_not_added_again() {
let (mut src, id) = session_with_text("Patterned");
let square = src.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 10, "height": 10})).unwrap()["id"].clone();
src.execute("object.pattern.make", &json!({"name": "Dots", "edit": false, "ids": [square]})).unwrap();
let tile = src.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 10, "height": 10})).unwrap()["id"].clone();
src.execute("paint.setFill", &json!({"swatch": "Dots", "ids": [tile]})).unwrap();
let art = src.doc().unwrap().doc.node(NodeId(tile.as_u64().unwrap())).unwrap().clone();
assert!(art.appearance.items.iter().any(|item| matches!(item.paint(), vectorcraft_color::Paint::Pattern { pattern, .. } if pattern == "Dots")));
let mut source = (*src.doc().unwrap().doc).clone();
source.patterns.iter_mut().find(|p| p.name == "Dots").unwrap().art = vec![std::sync::Arc::new(art)];
src.execute("paint.setFill", &json!({"swatch": "Dots", "ids": [id]})).unwrap();
src.execute("charStyle.new", &json!({"name": "Patterned", "id": id})).unwrap();
source.char_styles = src.doc().unwrap().doc.char_styles.clone();
assert!(super::style_attrs(&source, false, "Patterned").unwrap()["fill"].to_string().contains("\"Dots\""));
let (mut dst, _) = session_with_text("X");
let different = dst.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 30, "height": 30})).unwrap()["id"].clone();
dst.execute("object.pattern.make", &json!({"name": "Dots", "edit": false, "ids": [different]})).unwrap();
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
super::super::clipboard::resources::import_text_styles(&source, target, true, true);
assert!(dst.doc().unwrap().doc.pattern("Dots 2").is_some());
assert!(
dst.doc().unwrap().doc.pattern("Dots 2").unwrap().art[0]
.appearance
.items
.iter()
.any(|item| matches!(item.paint(), vectorcraft_color::Paint::Pattern { pattern, .. } if pattern == "Dots 2"))
);
let before = dst.doc().unwrap().doc.clone();
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
let again = super::super::clipboard::resources::import_text_styles(&source, target, true, true);
assert!(again.iter().all(|s| !s.added));
assert_eq!(dst.doc().unwrap().doc, before);
}
/// Patterns whose tiles each paint with themselves are matched one loop at a time: nine of them,
/// each in the document under its name with other art and as the copy an earlier load added,
/// are found under those copies, and a second load adds nothing.
#[test]
fn separate_self_referencing_patterns_are_not_added_again() {
let (mut src, id) = session_with_text("Patterned");
let mut tiles = vec![];
for k in 0..9 {
let name = format!("Dots{k}");
let square = src.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 10, "height": 10})).unwrap()["id"].clone();
src.execute("object.pattern.make", &json!({"name": name, "edit": false, "ids": [square]})).unwrap();
let tile = src.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 10, "height": 10})).unwrap()["id"].clone();
src.execute("paint.setFill", &json!({"swatch": name, "ids": [tile]})).unwrap();
tiles.push((name.clone(), src.doc().unwrap().doc.node(NodeId(tile.as_u64().unwrap())).unwrap().clone()));
src.execute("paint.setFill", &json!({"swatch": name, "ids": [id]})).unwrap();
src.execute("charStyle.new", &json!({"name": format!("Patterned{k}"), "id": id})).unwrap();
}
let mut source = (*src.doc().unwrap().doc).clone();
for (name, art) in tiles {
source.patterns.iter_mut().find(|p| p.name == name).unwrap().art = vec![std::sync::Arc::new(art)];
}
let (mut dst, _) = session_with_text("X");
for k in 0..9 {
let different = dst.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 30, "height": 30})).unwrap()["id"].clone();
dst.execute("object.pattern.make", &json!({"name": format!("Dots{k}"), "edit": false, "ids": [different]})).unwrap();
}
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
super::super::clipboard::resources::import_text_styles(&source, target, true, true);
for k in 0..9 {
assert!(dst.doc().unwrap().doc.pattern(&format!("Dots{k} 2")).is_some(), "{k}");
}
let before = dst.doc().unwrap().doc.clone();
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
let again = super::super::clipboard::resources::import_text_styles(&source, target, true, true);
assert!(again.iter().all(|s| !s.added));
assert_eq!(dst.doc().unwrap().doc.patterns.len(), before.patterns.len());
assert_eq!(dst.doc().unwrap().doc, before);
// With one loop's pattern gone from the document, the others are still found.
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
target.patterns.retain(|p| !p.name.starts_with("Dots8"));
let left = target.patterns.len();
let third = super::super::clipboard::resources::import_text_styles(&source, target, true, true);
assert_eq!(dst.doc().unwrap().doc.patterns.len(), left + 1);
assert!(third.iter().filter(|s| s.name != "Patterned8" && !s.name.starts_with("Patterned8 ")).all(|s| !s.added));
}
/// Nine patterns whose tiles each paint with the next one, the last with the first, in the
/// document under their names with other art and as the copies an earlier load added, are found
/// under those copies, and a second load adds nothing.
#[test]
fn a_long_loop_of_patterns_is_not_added_again() {
let (mut src, id) = session_with_text("Patterned");
for k in 0..9 {
let square = src.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 10, "height": 10})).unwrap()["id"].clone();
src.execute("object.pattern.make", &json!({"name": format!("Dots{k}"), "edit": false, "ids": [square]})).unwrap();
}
let mut tiles = vec![];
for k in 0..9 {
let tile = src.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 10, "height": 10})).unwrap()["id"].clone();
src.execute("paint.setFill", &json!({"swatch": format!("Dots{}", (k + 1) % 9), "ids": [tile]})).unwrap();
tiles.push(src.doc().unwrap().doc.node(NodeId(tile.as_u64().unwrap())).unwrap().clone());
}
src.execute("paint.setFill", &json!({"swatch": "Dots0", "ids": [id]})).unwrap();
src.execute("charStyle.new", &json!({"name": "Patterned", "id": id})).unwrap();
let mut source = (*src.doc().unwrap().doc).clone();
for (k, art) in tiles.into_iter().enumerate() {
source.patterns.iter_mut().find(|p| p.name == format!("Dots{k}")).unwrap().art = vec![std::sync::Arc::new(art)];
}
let (mut dst, _) = session_with_text("X");
for k in 0..9 {
let different = dst.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 30, "height": 30})).unwrap()["id"].clone();
dst.execute("object.pattern.make", &json!({"name": format!("Dots{k}"), "edit": false, "ids": [different]})).unwrap();
}
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
super::super::clipboard::resources::import_text_styles(&source, target, true, true);
for k in 0..9 {
assert!(dst.doc().unwrap().doc.pattern(&format!("Dots{k} 2")).is_some(), "{k}");
}
let before = dst.doc().unwrap().doc.clone();
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
let again = super::super::clipboard::resources::import_text_styles(&source, target, true, true);
assert!(again.iter().all(|s| !s.added));
assert_eq!(dst.doc().unwrap().doc.patterns.len(), before.patterns.len());
assert_eq!(dst.doc().unwrap().doc, before);
}
/// #1001: attributes their JSON leaves out at the defaults (Auto leading and kerning, no
/// mojikumi) are still attributes a style can set, and a style captured with one applies to
/// text at the default, is duplicated and comes back out of a library.
+39 -26
View File
@@ -6,9 +6,11 @@ use serde_json::{Value, json};
use vectorcraft_doc::{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::{
CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, find_command, has_clipboard, has_doc, has_selection, ids_param, str_param, targets,
CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, number_or,
switch_or, targets, text_param,
};
pub fn specs() -> Vec<CommandSpec> {
@@ -182,7 +184,7 @@ struct CaseState {
fn change_case(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.changeCase";
let case = str_param(p, "case").ok_or_else(|| bad(C, "missing case"))?.to_ascii_lowercase();
let case = text_param(p, "case", C)?.ok_or_else(|| bad(C, "missing case"))?.to_ascii_lowercase();
if !["upper", "uppercase", "lower", "lowercase", "title", "sentence"].contains(&case.as_str()) {
return Err(bad(C, "case must be upper|lower|title|sentence"));
}
@@ -253,11 +255,14 @@ pub(crate) fn smarten(text: &str, prev: &mut Option<char>, quotes: Option<&Quote
}
fn smart_punctuation(s: &mut Session, p: &Value) -> Result<Value> {
let (d, e) = (bool_or(p, "dashes", true), bool_or(p, "ellipsis", true));
const C: &str = "type.smartPunctuation";
let (d, e) = (switch_or(p, "dashes", true, C)?, switch_or(p, "ellipsis", true, C)?);
let quotes = switch_or(p, "quotes", true, C)?;
let document = choice(p, C, "scope", &["selection", "document"])? == Some("document");
let st = s.doc()?;
// Quotes in the document's style (Document Setup → Type).
let q = bool_or(p, "quotes", true).then_some(st.doc.setup.quotes);
let ids = if str_param(p, "scope") == Some("document") || st.selection.is_empty() {
let q = quotes.then_some(st.doc.setup.quotes);
let ids = if document || st.selection.is_empty() {
let mut v = vec![];
st.doc.walk(|n| {
if matches!(n.kind, NodeKind::Text(_)) {
@@ -436,16 +441,19 @@ fn path_options(s: &mut Session, p: &Value) -> Result<Value> {
let start = fraction("start")?;
// `end: null` puts the end bracket back at the end of the path.
let end = p.get("end").map(|_| fraction("end")).transpose()?;
let flip = bool_or(p, "flip", false);
let effect = match str_param(p, "effect") {
let flip = switch_or(p, "flip", false, C)?;
let effect = match text_param(p, "effect", C)? {
Some(e) => Some(vectorcraft_doc::PathEffect::parse(e).ok_or_else(|| bad(C, format!("unknown effect `{e}`")))?),
None => None,
};
let align = match str_param(p, "alignToPath") {
let align = match text_param(p, "alignToPath", C)? {
Some(a) => Some(vectorcraft_doc::PathAlign::parse(a).ok_or_else(|| bad(C, format!("unknown alignToPath `{a}`")))?),
None => None,
};
let spacing = p.get("spacing").and_then(Value::as_f64).filter(|x| x.is_finite()).map(|x| x.clamp(-1000.0, 1000.0));
let spacing = match p.get("spacing") {
None | Some(Value::Null) => None,
Some(_) => Some(number_or(p, "spacing", 0.0, C)?.clamp(-1000.0, 1000.0)),
};
// Without a flip, when every object already has every value given, the document and its undo
// history stay as they are.
let has_values = |t: &TextObject| match &t.kind {
@@ -608,16 +616,21 @@ fn unicode_char(u: &str) -> Option<char> {
fn insert_char(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.insert";
let text = match (str_param(p, "char"), str_param(p, "text")) {
(Some(c), _) => special_char(c).ok_or_else(|| bad(C, format!("unknown character `{c}`")))?.to_string(),
(None, Some(t)) => t.to_string(),
_ => match (p.get("code"), str_param(p, "unicode")) {
(Some(code), _) => alt_code_char(code.as_u64().ok_or_else(|| bad(C, "`code` must be a whole number"))?)
.ok_or_else(|| bad(C, format!("no character has code {code}")))?
.to_string(),
(None, Some(u)) => unicode_char(u).ok_or_else(|| bad(C, format!("`{u}` is no Unicode character")))?.to_string(),
_ => return Err(bad(C, "give `char`, `text`, `code` or `unicode`")),
},
// Every source is type-checked before one is chosen, so a bad value is refused even when a
// source ahead of it is given.
let ch = text_param(p, "char", C)?;
let txt = text_param(p, "text", C)?;
let code = match p.get("code").filter(|v| !v.is_null()) {
Some(v) => Some(v.as_u64().ok_or_else(|| bad(C, "`code` must be a whole number"))?),
None => None,
};
let uni = text_param(p, "unicode", C)?;
let text = match (ch, txt, code, uni) {
(Some(c), ..) => special_char(c).ok_or_else(|| bad(C, format!("unknown character `{c}`")))?.to_string(),
(None, Some(t), ..) => t.to_string(),
(None, None, Some(code), _) => alt_code_char(code).ok_or_else(|| bad(C, format!("no character has code {code}")))?.to_string(),
(None, None, None, Some(u)) => unicode_char(u).ok_or_else(|| bad(C, format!("`{u}` is no Unicode character")))?.to_string(),
(None, None, None, None) => return Err(bad(C, "give `char`, `text`, `code` or `unicode`")),
};
let ids = texts(s, p, C)?;
// When `text` is empty and every object ends with a run of text, the document and its undo
@@ -722,11 +735,11 @@ fn all_texts(d: &Document) -> Vec<NodeId> {
fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "edit.findReplace";
let find = str_param(p, "find").filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `find`"))?.to_string();
let rep = str_param(p, "replace").unwrap_or("").to_string();
let (mc, ww) = (bool_or(p, "matchCase", false), bool_or(p, "wholeWord", false));
let ids = match ids_param(p, "ids") {
Some(v) => text_ids(&s.doc()?.doc, &v),
let find = text_param(p, "find", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `find`"))?.to_string();
let rep = text_param(p, "replace", C)?.unwrap_or("").to_string();
let (mc, ww) = (switch_or(p, "matchCase", false, C)?, switch_or(p, "wholeWord", false, C)?);
let ids = match p.get("ids").filter(|v| !v.is_null()) {
Some(_) => text_ids(&s.doc()?.doc, &checked_ids_param(s, p, "ids", C)?),
None => all_texts(&s.doc()?.doc),
};
let st = s.doc()?;
@@ -779,8 +792,8 @@ fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
fn find_next(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "edit.findNext";
let find = str_param(p, "find").filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `find`"))?.to_string();
let (mc, ww) = (bool_or(p, "matchCase", false), bool_or(p, "wholeWord", false));
let find = text_param(p, "find", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `find`"))?.to_string();
let (mc, ww) = (switch_or(p, "matchCase", false, C)?, switch_or(p, "wholeWord", false, C)?);
let st = s.doc()?;
let all = all_texts(&st.doc);
let cur = st.selection.objects.first().and_then(|id| all.iter().position(|x| x == id));
+2 -1
View File
@@ -27,8 +27,9 @@ pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitTo
/// [`ON_ACTIVE_ARTBOARD`] and [`FIT_ACTIVE_ARTBOARD`] commands and to a batch; the artboards the
/// Artboard tool had selected for its commands; the view's center the app passes to Edit Symbol);
/// an action leaves them out ([`Session::journal_for_action`]).
const REPLAY_ONLY: [(&str, &str); 21] = [
const REPLAY_ONLY: [(&str, &str); 22] = [
("file.new", "created"),
("edit.newDocumentFromState", "created"),
("document.save", "modified"),
("file.saveAs", "modified"),
("edit.pasteInPlace", "artboard"),
+11
View File
@@ -155,6 +155,17 @@ impl History {
self.undo.iter().chain(&self.redo).map(|e| e.bytes).sum()
}
/// The document at row `row` of the History panel, `now` being the document now: the rows before
/// it are the undo steps, oldest first, and the rows after it the redo steps, nearest first.
pub(crate) fn state<'a>(&'a self, now: &'a Arc<Document>, row: usize) -> Option<&'a Arc<Document>> {
let current = self.undo.len();
match row.cmp(&current) {
std::cmp::Ordering::Less => self.undo.get(row).map(|e| &e.doc),
std::cmp::Ordering::Equal => Some(now),
std::cmp::Ordering::Greater => self.redo.len().checked_sub(row - current).and_then(|i| self.redo.get(i)).map(|e| &e.doc),
}
}
/// Let the oldest steps go while over the step limit or the memory budget: undo steps first
/// (the oldest), then redo steps (the furthest ahead).
pub fn trim(&mut self) {
+14
View File
@@ -41,6 +41,12 @@ pub struct Prefs {
/// Align panel menu › Align to Glyph Bounds › Area Text: the same for area type, instead of
/// its frame.
pub align_glyph_bounds_area: bool,
/// Artboard Options › Fade Region Outside Artboard: while the Artboard tool is active, the
/// canvas draws everything outside the artboards darker, the pasteboard and the art on it.
pub fade_region_outside_artboard: bool,
/// Artboard Options › Update While Dragging: the area outside the artboards stays darker while
/// the Artboard tool moves or resizes an artboard; off, it draws as usual until the drag ends.
pub artboard_update_while_dragging: bool,
pub display_print_size: bool,
pub double_click_to_isolate: bool,
pub transform_pattern_tiles: bool,
@@ -52,6 +58,9 @@ pub struct Prefs {
pub scrub_numeric_fields: bool,
/// A two-finger rotation on a Mac trackpad turns the view about the pointer once it reaches 5°.
pub trackpad_rotate_view: bool,
/// A single-key tool shortcut held down chooses its tool until the key is let go, and then the
/// tool active before comes back; a quick press chooses the tool for good.
pub hold_tool_keys: bool,
/// Offset for Paste / duplicate (Illustrator pastes to the view centre; we offset by this).
pub paste_offset: f64,
// Selection & Anchor Display
@@ -115,6 +124,7 @@ pub struct Prefs {
pub measurement_labels: bool,
pub spacing_guides: bool,
pub distance_guides: bool,
pub snap_to_last_location: bool,
pub snapping_tolerance: f64,
pub snap_tangent: bool,
pub snap_perpendicular: bool,
@@ -349,6 +359,8 @@ impl Default for Prefs {
use_preview_bounds: false,
align_glyph_bounds_point: false,
align_glyph_bounds_area: false,
fade_region_outside_artboard: true,
artboard_update_while_dragging: true,
display_print_size: false,
double_click_to_isolate: true,
transform_pattern_tiles: false,
@@ -357,6 +369,7 @@ impl Default for Prefs {
zoom_with_mouse_wheel: false,
scrub_numeric_fields: true,
trackpad_rotate_view: true,
hold_tool_keys: true,
paste_offset: 10.0,
selection_tolerance: 3.0,
object_selection_by_path_only: false,
@@ -410,6 +423,7 @@ impl Default for Prefs {
measurement_labels: true,
spacing_guides: true,
distance_guides: true,
snap_to_last_location: false,
snapping_tolerance: 4.0,
snap_tangent: true,
snap_perpendicular: true,
+2
View File
@@ -25,6 +25,8 @@ impl Session {
vectorcraft_doc::hit::set_live_art(vectorcraft_render::effects::expand_live, || {
vectorcraft_text::FontDb::global().generation().rotate_left(32) ^ vectorcraft_render::effects::plugin_revision()
});
// Envelopes map type from the bounds of its glyph outlines, underlines and strikethroughs.
vectorcraft_text::register_envelope_ink();
// Exports bake Vector Halftone into the dots the renderer samples.
vectorcraft_render::effects::addons::halftone::set_art(vectorcraft_render::addons::halftone::art);
// OpenType SVG glyphs are drawn as the SVG importer reads their documents.
+73 -19
View File
@@ -289,21 +289,42 @@ impl Session {
}
/// Record in the store what the user granted plug-in `id` (`None`: nothing), leaving the store's
/// other grants as they are; with none left, remove the file.
/// other grants as they are; with none left, remove the file. Entries this version can't use
/// are written back as they were, except one for `id`. A grants file that is too large, can't
/// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded;
/// so is one whose new content would be larger than `MAX_GRANTS_FILE`.
pub(crate) fn store_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) {
let Some(dir) = &self.plugin_dir else { return };
let mut grants = stored_grants(dir);
let changed = match grant {
Some(g) => grants.insert(id.to_string(), g.clone()).as_ref() != Some(&g),
None => grants.remove(id).is_some(),
let mut file = match read_grants(dir) {
Ok(file) => file,
Err(e) => {
log::warn!("not updating the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display());
return;
}
};
let others = file.other.len();
file.other.retain(|entry| entry.get("id").and_then(serde_json::Value::as_str) != Some(id));
let changed = match grant {
Some(g) => file.grants.insert(id.to_string(), g.clone()).as_ref() != Some(&g),
None => file.grants.remove(id).is_some(),
} || file.other.len() != others;
if !changed {
return;
}
if grants.is_empty() {
let mut entries: Vec<serde_json::Value> = file.grants.into_values().filter_map(|g| serde_json::to_value(g).ok()).collect();
entries.extend(file.other);
if entries.is_empty() {
take(dir, GRANTS_FILE);
} else if let Ok(bytes) = serde_json::to_vec_pretty(&grants.into_values().collect::<Vec<_>>()) {
put(dir, GRANTS_FILE, &bytes);
return;
}
// The file is read back only up to its cap: written compactly when pretty-printed is larger,
// and not at all when that is too.
let fits = |bytes: &Vec<u8>| bytes.len() as u64 <= MAX_GRANTS_FILE;
match serde_json::to_vec_pretty(&entries).ok().filter(fits).or_else(|| serde_json::to_vec(&entries).ok().filter(fits)) {
Some(bytes) => {
put(dir, GRANTS_FILE, &bytes);
}
None => log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), too_large(MAX_GRANTS_FILE)),
}
}
@@ -315,20 +336,53 @@ impl Session {
}
}
/// The grants kept in the plug-in store `dir`, by plug-in id: none when there is no grants file,
/// and none, with a log record, when it is too large or doesn't parse. Grants for an invalid id are
/// left out.
fn stored_grants(dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
/// What the grants file of a plug-in store holds.
#[derive(Default)]
struct GrantsFile {
/// The grants this version can use, by plug-in id.
grants: BTreeMap<String, vectorcraft_plugins::permissions::Grant>,
/// The entries it can't use (a permission it doesn't know, an invalid id), as they were.
other: Vec<serde_json::Value>,
}
/// The grants file of the plug-in store `dir`: empty when there is none, an error when it is too
/// large, can't be read or doesn't hold a list. An entry that doesn't parse as a grant, or names an
/// invalid id, is kept in [`GrantsFile::other`] with a log record.
fn read_grants(dir: &Path) -> Result<GrantsFile, String> {
let path = dir.join(GRANTS_FILE);
if !path.is_file() {
return BTreeMap::new();
if !path.exists() {
return Ok(GrantsFile::default());
}
let grants = read_capped(&path, MAX_GRANTS_FILE)
.and_then(|bytes| serde_json::from_slice::<Vec<vectorcraft_plugins::permissions::Grant>>(&bytes).map_err(|e| e.to_string()));
match grants {
Ok(grants) => grants.into_iter().filter(|g| vectorcraft_plugins::manifest::valid_id(&g.id)).map(|g| (g.id.clone(), g)).collect(),
let entries =
read_capped(&path, MAX_GRANTS_FILE).and_then(|bytes| serde_json::from_slice::<Vec<serde_json::Value>>(&bytes).map_err(|e| e.to_string()))?;
let mut file = GrantsFile::default();
let mut first_error = None;
for entry in entries {
let why = match serde_json::from_value::<vectorcraft_plugins::permissions::Grant>(entry.clone()) {
Ok(g) if vectorcraft_plugins::manifest::valid_id(&g.id) => {
file.grants.insert(g.id.clone(), g);
continue;
}
Ok(g) => format!("invalid id `{}`", g.id.escape_debug()),
Err(e) => e.to_string(),
};
first_error.get_or_insert(why);
file.other.push(entry);
}
if let Some(why) = first_error {
log::warn!("skipping {} stored plug-in grants in {} (the first: {why})", file.other.len(), path.display());
}
Ok(file)
}
/// The grants kept in the plug-in store `dir` that this version can use, by plug-in id: none when
/// there is no grants file, and none, with a log record, when it is too large, can't be read or
/// doesn't hold a list.
fn stored_grants(dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
match read_grants(dir) {
Ok(file) => file.grants,
Err(e) => {
log::warn!("skipping the stored plug-in grants {}: {e}", path.display());
log::warn!("skipping the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display());
BTreeMap::new()
}
}
+53 -7
View File
@@ -70,6 +70,7 @@ mod gradpresets;
mod gradspan;
mod guide_clipboard;
mod halftone;
mod history_document;
mod history_mem;
mod ids_without_selection;
mod inline;
@@ -3616,16 +3617,18 @@ fn given_targets_are_used_as_given_and_range_style_takes_the_selected_type() {
}
/// #785: commands whose `ids` or `id` the shared check doesn't read (it reads `id` where it stands
/// for `ids` of one) refuse one that isn't an object id. They don't act on the selection or the
/// current layer instead, and the document and its undo history stay as they are.
/// for `ids` of one) refuse one that isn't an object id. They don't act on the selection, the
/// current layer or a new object instead, and the document, the selection and the undo history
/// stay as they are.
#[test]
fn malformed_ids_are_refused_by_commands_that_default_to_the_selection() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 80.0, 60.0);
let b = rect(&mut s, 140.0, 120.0, 80.0, 60.0);
let graph = s.execute("graph.create", &json!({"type": "column", "x": 400, "y": 300, "width": 120, "height": 80, "rows": [[1, 2]]})).unwrap();
let text = s.execute("text.create", &json!({"x": 10, "y": 60, "text": "type", "size": 30})).unwrap()["id"].clone();
let ids = [json!([a.0, "x"]), json!(3)];
let id = [json!("2"), json!("$1.id"), json!(2.5)];
let id = [json!("2"), json!("$1.id"), json!(2.5), json!("abc"), json!(true), json!({})];
let commands = [
("object.blend.make", json!({}), "ids", &ids[..], json!([a.0, b.0])),
("object.envelope.makeWithWarp", json!({}), "ids", &ids[..], json!([a.0, b.0])),
@@ -3635,6 +3638,26 @@ fn malformed_ids_are_refused_by_commands_that_default_to_the_selection() {
("perspective.editText", json!({}), "id", &id[..], json!([a.0])),
("layer.clippingMask.toggle", json!({}), "id", &id[..], json!([a.0, b.0])),
("layer.newSublayer", json!({}), "parent", &id[..], json!([a.0])),
("object.isolate", json!({}), "id", &id[..], json!([a.0])),
("graphicStyle.new", json!({"name": "From a"}), "id", &id[..], json!([a.0])),
("charStyle.new", json!({"name": "From type"}), "id", &id[..], json!([text])),
("paraStyle.new", json!({"name": "From type"}), "id", &id[..], json!([text])),
("charStyle.apply", json!({"name": "[Normal Character Style]"}), "id", &id[..], json!([text])),
("type.step", json!({"attribute": "size"}), "id", &id[..], json!([text])),
("layer.releaseToLayers", json!({"build": true}), "id", &id[..], json!([a.0])),
("layer.locate", json!({}), "id", &id[..], json!([a.0])),
("transparency.editOpacityMask", json!({}), "id", &id[..], json!([a.0])),
("transparency.viewOpacityMask", json!({}), "id", &id[..], json!([a.0])),
("links.info", json!({}), "id", &id[..], json!([a.0])),
("links.unembed", json!({}), "id", &id[..], json!([a.0])),
("links.goTo", json!({}), "id", &id[..], json!([a.0])),
("shaper.release", json!({}), "id", &id[..], json!([a.0])),
("shaper.expand", json!({}), "id", &id[..], json!([a.0])),
("image.info", json!({}), "id", &id[..], json!([a.0])),
("symbol.edit", json!({}), "id", &id[..], json!([a.0])),
("object.blend.spine.addAnchor", json!({"x": 120, "y": 110}), "id", &id[..], json!([a.0])),
("path.curvature", json!({"points": [[0, 0], [50, 40], [100, 0]]}), "id", &id[..], json!([a.0])),
("css.export", json!({"unnamed": true}), "id", &id[..], json!([a.0])),
];
let mut wrong = vec![];
for (cmd, params, key, values, selected) in commands {
@@ -3644,21 +3667,44 @@ fn malformed_ids_are_refused_by_commands_that_default_to_the_selection() {
if let Some(p) = p.as_object_mut() {
p.insert(key.into(), bad.clone());
}
let (doc, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
let (doc, selection, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().selection.clone(), s.doc().unwrap().history.undo.len());
let r = s.execute(cmd, &p);
let refused = r.as_ref().err().map(|e| e.to_string()).is_some_and(|e| e.contains("object id") || e.contains("step reference"));
let same = s.doc().unwrap().doc == doc && s.doc().unwrap().history.undo.len() == undo;
let named = |e: &str| e.contains("object id") || e.contains("step reference") || e.contains(&format!("`{key}` must be"));
let refused = r.as_ref().err().map(|e| e.to_string()).is_some_and(|e| named(&e));
let same = s.doc().unwrap().doc == doc && s.doc().unwrap().selection == selection && s.doc().unwrap().history.undo.len() == undo;
if !(refused && same) {
wrong.push(format!("{cmd} {p}: {r:?}, document unchanged: {same}"));
}
if !same {
s.execute("edit.undo", &json!({})).ok();
let st = s.doc_mut().unwrap();
(st.doc, st.selection) = (doc, selection);
st.history.undo.truncate(undo);
}
}
}
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
}
/// An omitted or null `id` still means the selection, and an object id names that object.
/// `effect.apply` with the effect given as `id` (its older key) still applies it to the selection,
/// as one undo step.
#[test]
fn an_omitted_id_still_means_the_selection_and_effect_apply_takes_an_effect_as_id() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 80.0, 60.0);
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
for p in [json!({}), json!({"id": null}), json!({"id": a.0})] {
assert_eq!(s.execute("layer.locate", &p).unwrap()["id"], a.0, "{p}");
}
for p in [json!({"unnamed": true}), json!({"id": null, "unnamed": true}), json!({"id": a.0, "unnamed": true})] {
assert_eq!(s.execute("css.export", &p).unwrap()["rules"], 1, "{p}");
}
let undo = s.doc().unwrap().history.undo.len();
let r = s.execute("effect.apply", &json!({"id": "stylize.dropShadow"})).unwrap();
assert_eq!(r["ids"], json!([a.0]));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
}
#[test]
fn malformed_anchor_selection_never_replaces_or_partially_changes_selection() {
let mut s = session();
+144 -1
View File
@@ -3,7 +3,7 @@
//! the box to the page again.
use serde_json::{Value, json};
use vectorcraft_doc::OrientedBox;
use vectorcraft_doc::{Node, OrientedBox};
use vectorcraft_geom::{Point, Rect};
use vectorcraft_tools::bbox::Handle;
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
@@ -141,6 +141,149 @@ fn reset_bounding_box_squares_the_box_in_one_step() {
assert!(near(angle(&s, a), 45.0));
}
/// The angles of every object in `n`'s subtree, opacity mask art included, layers left out.
fn subtree_angles(n: &Node, out: &mut Vec<f64>) {
if !n.is_layer() {
out.push(n.bbox_angle);
}
for c in n.children().into_iter().flatten() {
subtree_angles(c, out);
}
if let Some(m) = &n.extras().mask {
subtree_angles(&m.art, out);
}
}
/// The angles of every object in the document, opacity mask art included, layers left out.
fn object_angles(s: &Session) -> Vec<f64> {
let mut out = vec![];
for l in &s.doc().unwrap().doc.layers {
subtree_angles(l, &mut out);
}
out
}
#[test]
fn reset_bounding_box_squares_the_objects_inside_a_group() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
let b = rect(&mut s, 300.0, 100.0, 100.0, 50.0);
sel(&mut s, &[a, b]);
s.execute("object.rotate", &json!({"angle": 20})).unwrap();
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.execute("object.rotate", &json!({"angle": 10})).unwrap();
assert!(near(angle(&s, g), 10.0) && near(angle(&s, a), 30.0) && near(angle(&s, b), 30.0));
let n = undo_len(&s);
// The group and both members, in one step.
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 3);
assert_eq!(undo_len(&s), n + 1);
assert!(object_angles(&s).iter().all(|a| *a == 0.0), "{:?}", object_angles(&s));
s.execute("object.ungroup", &json!({})).unwrap();
assert_eq!(selection_box(&s).angle, 0.0);
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 0);
// Undo brings every angle back.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert!(near(angle(&s, g), 10.0) && near(angle(&s, a), 30.0) && near(angle(&s, b), 30.0));
}
#[test]
fn reset_bounding_box_squares_the_turned_members_of_a_square_group() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
let b = rect(&mut s, 300.0, 100.0, 100.0, 50.0);
sel(&mut s, &[a, b]);
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
s.execute("object.group", &json!({})).unwrap();
assert_eq!(selection_box(&s).angle, 0.0);
let n = undo_len(&s);
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 2);
assert_eq!(undo_len(&s), n + 1);
s.execute("object.ungroup", &json!({})).unwrap();
assert_eq!(selection_box(&s).angle, 0.0);
}
/// Two rectangles turned 20°, put in a container by `make`, turned 10° with it and reset, then
/// released by `release`: nothing stands at an angle before or after the release.
fn reset_then_release(make: &str, release: &str) -> Session {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
let b = rect(&mut s, 150.0, 120.0, 100.0, 50.0);
sel(&mut s, &[a, b]);
s.execute("object.rotate", &json!({"angle": 20})).unwrap();
s.execute(make, &json!({})).unwrap();
s.execute("object.rotate", &json!({"angle": 10})).unwrap();
assert!(object_angles(&s).iter().any(|a| near(*a, 30.0)), "{make}: {:?}", object_angles(&s));
s.execute("object.resetBoundingBox", &json!({})).unwrap();
assert!(object_angles(&s).iter().all(|a| *a == 0.0), "{make}: {:?}", object_angles(&s));
s.execute(release, &json!({})).unwrap();
assert!(object_angles(&s).iter().all(|a| *a == 0.0), "{release}: {:?}", object_angles(&s));
s.execute("select.all", &json!({})).unwrap();
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 0, "{release}");
s
}
#[test]
fn reset_bounding_box_then_release_clipping_mask() {
reset_then_release("object.clippingMask.make", "object.clippingMask.release");
}
#[test]
fn reset_bounding_box_then_release_compound_path() {
reset_then_release("object.compoundPath.make", "object.compoundPath.release");
}
#[test]
fn reset_bounding_box_then_expand_blend() {
reset_then_release("object.blend.make", "object.blend.expand");
}
#[test]
fn reset_bounding_box_then_release_envelope() {
reset_then_release("object.envelope.makeWithWarp", "object.envelope.release");
}
#[test]
fn reset_bounding_box_then_release_repeat() {
reset_then_release("object.repeat.grid", "object.repeat.release");
}
#[test]
fn reset_bounding_box_then_release_intertwine() {
reset_then_release("object.intertwine.make", "object.intertwine.release");
}
#[test]
fn reset_bounding_box_then_release_linked_opacity_mask() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
let b = rect(&mut s, 150.0, 120.0, 100.0, 50.0);
sel(&mut s, &[a, b]);
s.execute("object.rotate", &json!({"angle": 20})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
let mask = s.doc().unwrap().doc.node(a).unwrap().extras().mask.clone().unwrap();
assert!(mask.linked && near(mask.art.bbox_angle, 20.0));
drop(s);
reset_then_release("transparency.makeOpacityMask", "transparency.releaseOpacityMask");
}
#[test]
fn reset_bounding_box_leaves_the_art_of_an_unlinked_opacity_mask() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
let b = rect(&mut s, 150.0, 120.0, 100.0, 50.0);
sel(&mut s, &[a, b]);
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
s.execute("object.rotate", &json!({"angle": 20})).unwrap();
s.execute("transparency.unlinkOpacityMask", &json!({})).unwrap();
let mask_angle = |s: &Session| s.doc().unwrap().doc.node(a).unwrap().extras().mask.as_ref().unwrap().art.bbox_angle;
assert!(near(angle(&s, a), 20.0) && near(mask_angle(&s), 20.0));
// Only the object: its mask's art no longer turns with it.
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 1);
assert_eq!(angle(&s, a), 0.0);
assert!(near(mask_angle(&s), 20.0));
}
#[test]
fn page_flips_keep_an_upright_box_upright() {
let mut s = session();
+144
View File
@@ -1343,6 +1343,150 @@ fn delete_duplicate_and_replace_symbols() {
assert!(s.execute("symbol.delete", &json!({"name": "Small"})).is_err());
}
fn xf_of(s: &Session, id: NodeId) -> vectorcraft_geom::Affine {
match node(s, id).kind {
NodeKind::SymbolInstance { xf, .. } => xf,
_ => panic!("{id:?} is not a symbol instance"),
}
}
fn close_xf(a: vectorcraft_geom::Affine, b: vectorcraft_geom::Affine) -> bool {
a.as_coeffs().iter().zip(b.as_coeffs()).all(|(x, y)| (x - y).abs() < 1e-9)
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
/// Reset Transformation gives rotated, scaled, sheared and reflected instances (in a group too)
/// their symbol's own scale again, each keeping the center of its bounding box, as one undo step.
#[test]
fn reset_transformation_restores_the_symbols_scale_and_keeps_the_center() {
let mut s = session();
let (a, name, placed) = make_symbol(&mut s);
let b = NodeId(s.execute("symbol.place", &json!({"name": name, "x": 300, "y": 200})).unwrap()["id"].as_u64().unwrap());
let c = NodeId(s.execute("symbol.place", &json!({"name": name, "x": 100, "y": 220})).unwrap()["id"].as_u64().unwrap());
let master = xf_of(&s, b).with_translation(vectorcraft_geom::Vec2::ZERO);
select(&mut s, &[a]);
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
s.execute("object.scale", &json!({"sx": 150, "sy": 50})).unwrap();
select(&mut s, &[b]);
s.execute("object.shear", &json!({"angle": 20})).unwrap();
select(&mut s, &[c]);
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
let turned: Vec<_> = [a, b, c].iter().map(|id| xf_of(&s, *id)).collect();
let centers: Vec<_> = [a, b, c].iter().map(|id| bounds(&s, *id).center()).collect();
let plain = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
select(&mut s, &[b, c]);
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[a, group, plain]);
let plain_before = node(&s, plain);
let before = undo_len(&s);
let r = s.execute("symbol.instance.resetTransform", &json!({})).unwrap();
assert_eq!(r["ids"], json!([a.0, b.0, c.0]));
assert_eq!(undo_len(&s), before + 1, "one undo step");
for (id, center) in [a, b, c].into_iter().zip(&centers) {
let got = bounds(&s, id);
assert!((got.width() - placed.width()).abs() < 1e-9 && (got.height() - placed.height()).abs() < 1e-9, "{id:?}: {got:?}");
assert!((got.center() - *center).hypot() < 1e-9, "{id:?} keeps its center: {got:?} vs {center:?}");
let xf = xf_of(&s, id);
assert!(close_xf(xf.with_translation(vectorcraft_geom::Vec2::ZERO), master), "{id:?}: {xf:?}");
}
assert!(node(&s, plain) == plain_before, "other objects are left as they are");
s.execute("edit.undo", &json!({})).unwrap();
for (id, xf) in [a, b, c].into_iter().zip(turned) {
assert!(close_xf(xf_of(&s, id), xf), "Undo gives {id:?} its own transform back");
}
}
/// An instance of a symbol whose art lies away from the symbol's origin (as imported symbols can)
/// keeps the center of the box its art fills when Reset Transformation turns it back.
#[test]
fn reset_transformation_keeps_the_center_of_art_away_from_the_origin() {
let mut s = session();
let r = rect(&mut s, 300.0, 10.0, 20.0, 20.0);
let art = node(&s, r);
s.execute("edit.clear", &json!({"ids": [r.0]})).unwrap();
let st = s.doc_mut().unwrap();
let d = std::sync::Arc::make_mut(&mut st.doc);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Off".into(), art: std::sync::Arc::new(art) });
let layer = d.layers[0].id;
let id = d.alloc_id();
let xf = vectorcraft_geom::Affine::translate((100.0, 100.0)) * vectorcraft_geom::Affine::rotate(0.5);
d.insert(Some(layer), usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: "Off".into(), xf })).unwrap();
let measured = |s: &Session| s.doc().unwrap().doc.bounds_of(&[id], false).unwrap();
let before = measured(&s);
assert_eq!(s.execute("symbol.instance.resetTransform", &json!({"ids": [id.0]})).unwrap()["ids"], json!([id.0]));
let after = measured(&s);
assert!((after.center() - before.center()).hypot() < 1e-9, "{after:?} vs {before:?}");
assert!((after.width() - 20.0).abs() < 1e-9 && (after.height() - 20.0).abs() < 1e-9, "{after:?}");
}
/// A stored natural size that is not positive (from a damaged file: zero or negative on either
/// side) does not flatten or mirror the instance: Reset Transformation gives it the art's own
/// size, as drawing the symbol does.
#[test]
fn reset_transformation_ignores_a_stored_size_that_is_not_positive() {
for size in [json!([0.0, 20.0]), json!([-20.0, 20.0]), json!([20.0, -5.0]), json!([-20.0, -20.0])] {
let mut s = session();
let r = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let art = node(&s, r);
s.execute("edit.clear", &json!({"ids": [r.0]})).unwrap();
let st = s.doc_mut().unwrap();
let d = std::sync::Arc::make_mut(&mut st.doc);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Flat".into(), art: std::sync::Arc::new(art) });
d.unknown.insert(vectorcraft_doc::SYMBOL_SIZES.to_string(), json!({ "Flat": size }));
let layer = d.layers[0].id;
let id = d.alloc_id();
let xf = vectorcraft_geom::Affine::translate((100.0, 100.0)) * vectorcraft_geom::Affine::rotate(0.5);
d.insert(Some(layer), usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: "Flat".into(), xf })).unwrap();
assert_eq!(s.execute("symbol.instance.resetTransform", &json!({"ids": [id.0]})).unwrap()["ids"], json!([id.0]), "{size}");
let after = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap();
assert!((after.width() - 20.0).abs() < 1e-9 && (after.height() - 20.0).abs() < 1e-9, "{size}: {after:?}");
assert!(close_xf(xf_of(&s, id).with_translation(vectorcraft_geom::Vec2::ZERO), vectorcraft_geom::Affine::IDENTITY), "{size}: not mirrored");
}
}
/// Reset Transformation adds no undo step for an instance already at its symbol's scale or for
/// one in perspective, and refuses an id naming no object and objects without an instance,
/// changing nothing.
#[test]
fn reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 1000, "height": 800})).unwrap();
let (inst, name, _) = make_symbol(&mut s);
let before = undo_len(&s);
assert_eq!(s.execute("symbol.instance.resetTransform", &json!({"ids": [inst.0]})).unwrap()["ids"], json!([]));
assert_eq!(undo_len(&s), before, "nothing changed: no undo step");
let plain = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
select(&mut s, &[inst]);
s.execute("object.rotate", &json!({"angle": 45})).unwrap();
let turned = s.doc().unwrap().doc.clone();
let before = undo_len(&s);
for bad in [json!({"ids": [inst.0, 999_999]}), json!({"id": 999_999}), json!({"ids": [plain.0]}), json!({"ids": "x"})] {
assert!(s.execute("symbol.instance.resetTransform", &bad).is_err(), "{bad}");
}
assert!(*s.doc().unwrap().doc == *turned && undo_len(&s) == before, "the refusals change nothing");
// An instance in perspective is left as it is.
s.execute("perspective.grid.preset", &json!({"kind": 2})).unwrap();
let projected = NodeId(s.execute("symbol.place", &json!({"name": name, "x": 500, "y": 350})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[projected]);
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
s.execute("perspective.attach", &json!({"ids": [projected.0], "plane": "right"})).unwrap();
let xf = xf_of(&s, projected);
let before = undo_len(&s);
assert_eq!(s.execute("symbol.instance.resetTransform", &json!({"ids": [projected.0]})).unwrap()["ids"], json!([]));
assert!(undo_len(&s) == before && close_xf(xf_of(&s, projected), xf), "an instance in perspective stays as it was");
// Selected with a turned instance, the instance in perspective still stays as it was, and only
// the other one is reset and returned, in one undo step.
select(&mut s, &[inst, projected]);
assert_eq!(s.execute("symbol.instance.resetTransform", &json!({})).unwrap()["ids"], json!([inst.0]));
assert_eq!(undo_len(&s), before + 1, "one undo step");
assert!(close_xf(xf_of(&s, projected), xf), "the instance in perspective stays as it was");
let reset = xf_of(&s, inst).with_translation(vectorcraft_geom::Vec2::ZERO);
assert!(close_xf(reset, s.doc().unwrap().doc.symbol_natural_xf(&name)), "the turned instance is reset: {reset:?}");
}
/// New Symbol and Duplicate Symbol trim the name they are given, as Symbol Options trims
/// `newName`; the trimmed name is the one compared with the symbols there are.
#[test]
+109
View File
@@ -542,3 +542,112 @@ fn intents_reach_the_document_conversion() {
assert_ne!(first(&a), first(&b));
let _ = Intent::Perceptual;
}
/// The error `cmd` gives for `params`: it must name `msg`.
fn refused(s: &mut Session, cmd: &str, params: Value, msg: &str) {
let e = match s.execute(cmd, &params) {
Ok(r) => panic!("{cmd} {params} gave {r}"),
Err(e) => e.to_string(),
};
assert!(e.contains(msg), "{cmd} {params}: {e}");
}
#[test]
fn color_settings_refuse_a_param_of_the_wrong_type() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let before = cms::active_settings();
let rev = s.doc().unwrap().revision;
let c = "edit.colorSettings";
refused(&mut s, c, json!({"bpc": "no"}), "`bpc` must be true or false");
refused(&mut s, c, json!({"rgb": 5}), "`rgb` must be a string");
refused(&mut s, c, json!({"cmyk": true}), "`cmyk` must be a string");
refused(&mut s, c, json!({"intent": 2}), "`intent` must be a string");
assert_eq!(cms::active_settings(), before, "the settings are unchanged");
assert_eq!(s.doc().unwrap().revision, rev, "nothing redraws");
// Omitted and null params keep the settings.
s.execute(c, &json!({"bpc": null, "rgb": null})).unwrap();
assert_eq!(cms::active_settings(), before);
refused(&mut s, "color.convert", json!({"color": "#808080", "to": 1}), "`to` must be a string");
refused(&mut s, "color.convert", json!({"color": "#808080", "intent": ["relative"]}), "`intent` must be a string");
assert_eq!(s.execute("color.convert", &json!({"color": "#808080", "to": null})).unwrap()["model"], "rgb");
let profiles = || cms::profiles().into_iter().map(|i| i.name).collect::<Vec<_>>();
let listed = profiles();
refused(&mut s, "color.loadProfile", json!({"path": 7}), "`path` must be a string");
refused(&mut s, "color.removeProfile", json!({"name": 7}), "`name` must be a string");
assert_eq!(profiles(), listed, "no profile is loaded or removed");
assert_eq!(cms::active_settings(), before, "the settings are unchanged");
assert_eq!(s.doc().unwrap().revision, rev, "nothing redraws");
}
#[test]
fn document_color_mode_refuses_a_param_of_the_wrong_type() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!("#ff0000"));
let fill = fill_of(&s, a);
let undo = s.doc().unwrap().history.undo.len();
for c in ["file.documentColorMode", "object.convertDocumentColorMode"] {
refused(&mut s, c, json!({"mode": "cmyk", "convert": "no"}), "`convert` must be true or false");
refused(&mut s, c, json!({"mode": "rgb", "convert": 0}), "`convert` must be true or false");
refused(&mut s, c, json!({"mode": "cmyk", "grays": 1}), "`grays` must be a string");
refused(&mut s, c, json!({"mode": "cmyk", "intent": false}), "`intent` must be a string");
}
let st = s.doc().unwrap();
assert_eq!(st.doc.color_mode, ColorMode::Rgb);
assert_eq!(st.history.undo.len(), undo, "no undo step");
assert_eq!(fill_of(&s, a), fill, "the colors are unchanged");
}
#[test]
fn proof_views_refuse_a_param_of_the_wrong_type() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let view = vectorcraft_render::proof::view();
let rev = s.doc().unwrap().revision;
refused(&mut s, "view.proofSetup", json!({"simulatePaper": "yes"}), "`simulatePaper` must be true or false");
refused(&mut s, "view.proofSetup", json!({"proof": 1}), "`proof` must be true or false");
refused(&mut s, "view.proofSetup", json!({"target": 3}), "`target` must be a string");
refused(&mut s, "view.proofColors", json!({"on": "true"}), "`on` must be true or false");
refused(&mut s, "view.overprintPreview", json!({"on": 1}), "`on` must be true or false");
refused(&mut s, "view.separationsPreview", json!({"on": "false"}), "`on` must be true or false");
refused(&mut s, "view.separationsPreview", json!({"plates": "Cyan"}), "`plates` must be an array of these names: Cyan, Magenta");
refused(&mut s, "view.separationsPreview", json!({"plates": ["Cyan", 2]}), "`plates` must be an array of these names");
refused(&mut s, "view.separationsPreview", json!({"only": 0}), "`only` must be a string");
refused(&mut s, "view.separationsPreview", json!({"toggle": ["Cyan"]}), "`toggle` must be a string");
assert_eq!(vectorcraft_render::proof::view(), view, "the proof view is unchanged");
assert_eq!(s.doc().unwrap().revision, rev, "nothing redraws");
// A null `on` toggles, as an omitted one does.
let r = s.execute("view.proofColors", &json!({"on": null})).unwrap();
assert_eq!(r["proofColors"], !view.proof_colors);
s.execute("view.proofColors", &json!({"on": view.proof_colors})).unwrap();
}
#[test]
fn set_spot_refuses_a_param_of_the_wrong_type() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 0, "m": 60, "y": 100, "k": 0}, "global": true})).unwrap();
let undo = s.doc().unwrap().history.undo.len();
refused(&mut s, "swatch.setSpot", json!({"name": "Ink", "spot": "true"}), "`spot` must be true or false");
refused(&mut s, "swatch.setSpot", json!({"name": 1}), "`name` must be a string");
assert!(!s.doc().unwrap().doc.swatch("Ink").unwrap().spot, "the swatch stays a process color");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
s.execute("swatch.setSpot", &json!({"name": "Ink", "spot": null})).unwrap();
assert!(s.doc().unwrap().doc.swatch("Ink").unwrap().spot, "a null `spot` is the default, true");
}
#[test]
fn gamut_check_refuses_colors_that_are_not_a_list() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!("#0000ff"));
s.execute("select.set", &json!({"ids": []})).unwrap();
refused(&mut s, "color.gamutCheck", json!({"colors": "#00ff00"}), "`colors` must be an array of colors, not \"#00ff00\"");
refused(&mut s, "color.gamutCheck", json!({"colors": 5}), "`colors` must be an array of colors, not 5");
refused(&mut s, "color.gamutCheck", json!({"colors": {"c": 100, "m": 0, "y": 0, "k": 0}}), "`colors` must be an array of colors");
// A null list checks the document, as an omitted one does.
let r = s.execute("color.gamutCheck", &json!({"colors": null})).unwrap();
assert_eq!(r, s.execute("color.gamutCheck", &json!({})).unwrap());
assert!(r["outOfGamut"].as_array().unwrap().iter().any(|v| v["hex"] == "#0000ff"), "{r}");
}
+467
View File
@@ -445,3 +445,470 @@ fn warped_type_in_a_symbol_reopens_unchanged() {
let differ = (0..300).flat_map(|y| (0..400).map(move |x| (x, y))).filter(|&(x, y)| before.pixel(x, y) != after.pixel(x, y)).count();
assert_eq!(differ, 0, "{differ} pixels changed on reopening");
}
/// The glyph outline bounds of type `id` in document space.
fn ink_of(s: &Session, id: NodeId) -> Rect {
match node(s, id).kind {
NodeKind::Text(t) => t.xf.transform_rect_bbox(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).ink_bounds().unwrap()),
k => panic!("{k:?}"),
}
}
fn assert_box(a: Rect, b: Rect, what: &str) {
let d = [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().fold(0.0f64, |m, v| m.max(v.abs()));
assert!(d < 1e-6, "{what}: {a:?} vs {b:?}");
}
/// The box envelope `id` maps its content from.
fn src_of(s: &Session, id: NodeId) -> Rect {
live::EnvelopeMap::of(&node(s, id)).unwrap().src()
}
/// Envelopes map point type, area type and type in a group from the glyph outline bounds, not
/// from the laid-out box (ascent to descent, or the area's frame): with a flat warp the distorted
/// type sits where the type was, and Make with Mesh lays its grid over the glyphs.
#[test]
fn envelopes_map_type_from_its_glyph_outline_bounds() {
let mut s = session();
let point = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "Envelope", "size": 48})).unwrap());
let area = id_of(
&s.execute("text.create", &json!({"x": 100, "y": 300, "text": "Area type", "size": 36, "area": {"width": 300, "height": 200}})).unwrap(),
);
let grouped = id_of(&s.execute("text.create", &json!({"x": 450, "y": 200, "text": "Group", "size": 40})).unwrap());
sel(&mut s, &[grouped]);
let group = id_of(&s.execute("object.group", &json!({})).unwrap());
for (t, target) in [(point, point), (area, area), (grouped, group)] {
let (ink, laid) = (ink_of(&s, t), node(&s, t).geometric_bounds().unwrap());
assert!(laid.height() - ink.height() > 1.0, "the laid-out box {laid:?} reaches past the glyphs {ink:?}");
let (stroked, plain) = live::envelope_content_boxes(&[std::sync::Arc::new(node(&s, target))], Affine::IDENTITY).unwrap();
assert_box(plain, ink, "geometric box");
assert_box(stroked, ink, "box with strokes (none)");
sel(&mut s, &[target]);
let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": "arc", "bend": 0})).unwrap());
assert_box(src_of(&s, e), ink, "warp");
assert_box(node(&s, e).geometric_bounds().unwrap(), ink, "flat warp's bounds");
s.execute("edit.undo", &json!({})).unwrap();
let e = id_of(&s.execute("object.envelope.makeWithMesh", &json!({"rows": 2, "cols": 2})).unwrap());
let EnvelopeKind::Mesh { points, .. } = kind(&s, e) else { panic!("mesh") };
let grid = points.iter().fold(Rect::from_points(points[0], points[0]), |r, p| r.union_pt(*p));
assert_box(grid, ink, "mesh grid");
assert_box(src_of(&s, e), ink, "mesh");
s.execute("edit.undo", &json!({})).unwrap();
}
}
/// Shrink Text to Fit lays type out by its size on the page: after the envelope is scaled, it
/// maps from the glyphs of the type laid out at its new size, not those measured before.
#[test]
fn a_scaled_envelope_of_shrunk_type_maps_from_its_new_glyphs() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Type", "size": 2, "area": {"width": 3, "height": 3}})).unwrap());
s.edit("shrink", |d, _| {
if let NodeKind::Text(tx) = &mut d.node_mut(t).unwrap().kind {
tx.area.fit = vectorcraft_doc::AreaFit::ShrinkText { min_percent: 10.0 };
}
Ok(())
})
.unwrap();
sel(&mut s, &[t]);
let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": "arc", "bend": 0})).unwrap());
let text = |s: &Session| match node(s, e).kind {
NodeKind::Envelope { content, .. } => match &content[0].kind {
NodeKind::Text(tx) => tx.clone(),
k => panic!("{k:?}"),
},
k => panic!("{k:?}"),
};
let ink = |tx: &vectorcraft_doc::TextObject| vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx).ink_bounds().unwrap();
let before = text(&s);
assert_box(src_of(&s, e), before.xf.transform_rect_bbox(ink(&before)), "before scaling");
s.execute("object.scale", &json!({"sx": 150, "sy": 150, "origin": [100, 100]})).unwrap();
let after = text(&s);
let fresh = after.xf.transform_rect_bbox(ink(&after));
let stale = after.xf.transform_rect_bbox(ink(&before));
assert!((fresh.width() - stale.width()).abs() > 1e-3 || (fresh.height() - stale.height()).abs() > 1e-3, "{fresh:?} vs {stale:?}");
assert_box(src_of(&s, e), fresh, "after scaling");
}
/// A rotated envelope keeps a frame of its own: shrunk type in it is measured as it is laid out on
/// the page, and its box is then taken into the frame.
#[test]
fn a_rotated_envelope_of_shrunk_type_maps_from_the_glyphs_on_the_page() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Type", "size": 2, "area": {"width": 3, "height": 3}})).unwrap());
s.edit("shrink", |d, _| {
if let NodeKind::Text(tx) = &mut d.node_mut(t).unwrap().kind {
tx.area.fit = vectorcraft_doc::AreaFit::ShrinkText { min_percent: 10.0 };
}
Ok(())
})
.unwrap();
sel(&mut s, &[t]);
let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": "arc", "bend": 0})).unwrap());
s.execute("object.rotate", &json!({"angle": 30, "origin": [100, 100]})).unwrap();
s.execute("object.scale", &json!({"sx": 150, "sy": 150, "origin": [100, 100]})).unwrap();
let (frame, tx) = match node(&s, e).kind {
NodeKind::Envelope { frame, content, .. } => match &content[0].kind {
NodeKind::Text(tx) => (*frame, tx.clone()),
k => panic!("{k:?}"),
},
k => panic!("{k:?}"),
};
assert!(frame != Affine::IDENTITY, "a rotated envelope has a frame");
let ink = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &tx).ink_bounds().unwrap();
assert_box(src_of(&s, e), (frame.inverse() * tx.xf).transform_rect_bbox(ink), "in the frame");
}
/// The bars of underlined type are part of what it draws, so the envelope maps from them too and
/// its bounds take them in.
#[test]
fn an_envelope_maps_underlined_type_from_its_glyphs_and_bars() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "HH", "size": 100})).unwrap());
s.execute("text.setFormat", &json!({"ids": [t.0], "underline": true})).unwrap();
let glyphs = ink_of(&s, t);
sel(&mut s, &[t]);
let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": "arc", "bend": 0})).unwrap());
let src = src_of(&s, e);
assert!(src.y1 > glyphs.y1 + 1.0, "the underline below the glyphs {glyphs:?} is in the box {src:?}");
assert_box(node(&s, e).geometric_bounds().unwrap(), src, "flat warp's bounds");
let drawn = vectorcraft_render::effects::expanded_live_group(Some(&s.doc().unwrap().doc), &node(&s, e)).geometric_bounds().unwrap();
let off = [drawn.x0 - src.x0, drawn.y0 - src.y0, drawn.x1 - src.x1, drawn.y1 - src.y1].iter().fold(0.0f64, |m, v| m.max(v.abs()));
assert!(off < 0.05, "the drawn art {drawn:?} fills the box {src:?}");
}
/// Undo of Make Envelope gives the type back with its laid-out box, and redo maps it from its
/// glyphs again.
#[test]
fn undo_and_redo_of_an_envelope_of_type_keep_the_glyph_mapping() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "Undo", "size": 60})).unwrap());
let (ink, laid) = (ink_of(&s, t), node(&s, t).geometric_bounds().unwrap());
sel(&mut s, &[t]);
let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": "bulge", "bend": 30})).unwrap());
let made = node(&s, e).geometric_bounds().unwrap();
assert_box(src_of(&s, e), ink, "made");
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(e).is_none());
assert_box(node(&s, t).geometric_bounds().unwrap(), laid, "the type after undo");
s.execute("edit.redo", &json!({})).unwrap();
assert_box(src_of(&s, e), ink, "redone");
assert_box(node(&s, e).geometric_bounds().unwrap(), made, "redone bounds");
}
/// A saved envelope of type reopens drawn by the same rule: from the glyph outline bounds, which
/// the file does not store.
#[test]
fn a_saved_envelope_of_type_reopens_mapped_from_its_glyphs() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "Saved", "size": 72})).unwrap());
let ink = ink_of(&s, t);
sel(&mut s, &[t]);
let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": "flag", "bend": 40})).unwrap());
let render = |s: &Session| vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 600, 400, Affine::IDENTITY, &Default::default());
let before = render(&s);
let dir = std::env::temp_dir().join(format!("vectorcraft-envelope-ink-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("type.vectorcraft");
s.execute("document.save", &json!({"path": path})).unwrap();
let mut o = Session::new();
o.execute("document.open", &json!({"path": path})).unwrap();
let _ = std::fs::remove_dir_all(&dir);
assert_box(src_of(&o, e), ink, "reopened");
let after = render(&o);
let differ = (0..400).flat_map(|y| (0..600).map(move |x| (x, y))).filter(|&(x, y)| before.pixel(x, y) != after.pixel(x, y)).count();
assert_eq!(differ, 0, "{differ} pixels changed on reopening");
}
/// The type of envelope `e`'s first content object.
fn content_text(s: &Session, e: NodeId) -> vectorcraft_doc::TextObject {
match node(s, e).kind {
NodeKind::Envelope { content, .. } => match &content[0].kind {
NodeKind::Text(tx) => (**tx).clone(),
k => panic!("{k:?}"),
},
k => panic!("{k:?}"),
}
}
/// The box of `tx`'s glyph outlines with text space mapped by `m`, each outline mapped point by point.
fn outlines_in(tx: &vectorcraft_doc::TextObject, m: Affine) -> Rect {
let path = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx).to_bezpath();
kurbo::Shape::bounding_box(&(m * path))
}
/// Rotated type maps from the box of its rotated glyph outlines, which is smaller than the box of
/// its rotated glyph box; in a rotated envelope whose frame turns by another angle than the type,
/// it maps from the outlines taken into the frame.
#[test]
fn an_envelope_of_rotated_type_maps_from_its_rotated_outlines() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 200, "y": 300, "text": "Rotated", "size": 60})).unwrap());
sel(&mut s, &[t]);
s.execute("object.rotate", &json!({"angle": 40, "origin": [200, 300]})).unwrap();
let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": "arc", "bend": 0})).unwrap());
let tx = content_text(&s, e);
let outlines = outlines_in(&tx, tx.xf);
let ink = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &tx).ink_bounds().unwrap();
let glyph_box = tx.xf.transform_rect_bbox(ink);
assert!(glyph_box.width() - outlines.width() > 1.0 || glyph_box.height() - outlines.height() > 1.0, "{glyph_box:?} vs {outlines:?}");
assert_box(src_of(&s, e), outlines, "rotated type");
s.execute("object.rotate", &json!({"angle": 15, "origin": [200, 300]})).unwrap();
let (frame, tx) = match node(&s, e).kind {
NodeKind::Envelope { frame, .. } => (*frame, content_text(&s, e)),
k => panic!("{k:?}"),
};
assert!(frame != Affine::IDENTITY, "a rotated envelope has a frame");
let in_frame = frame.inverse() * tx.xf;
assert!(in_frame.as_coeffs()[1].abs() > 0.1, "the type is turned against the frame: {in_frame:?}");
assert_box(src_of(&s, e), outlines_in(&tx, in_frame), "in the frame");
}
/// Type in perspective maps from the box of its outlines as its projection draws them, which is
/// smaller than the projected box of its glyphs. Where the projection can't map a point (past its
/// horizon), the point counts where it is, as the renderer draws it.
#[test]
fn an_envelope_of_type_in_perspective_maps_from_its_projected_outlines() {
use vectorcraft_geom::Homography;
// Every point of the type is past this one's horizon.
let horizon = Homography([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]]);
for (h, crosses) in [(Homography([[1.0, 0.3, 0.0], [0.1, 1.0, 0.0], [0.0015, 0.0008, 1.0]]), false), (horizon, true)] {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "Perspective", "size": 60})).unwrap());
s.edit("perspective", |d, _| {
let n = d.node_mut(t).unwrap();
n.extras_mut().perspective = Some(Box::new(vectorcraft_doc::PerspectiveAttachment {
projection: Some(h.to_array()),
..vectorcraft_doc::PerspectiveAttachment::new("left", 0.0)
}));
Ok(())
})
.unwrap();
assert!(node(&s, t).projection().is_some());
let NodeKind::Text(tx) = node(&s, t).kind else { panic!("type") };
let path = tx.xf * vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &tx).to_bezpath();
let (mut drawn, mut unmapped): (Option<Rect>, usize) = (None, 0);
kurbo::flatten(&path, 0.001, |el| {
if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = el {
let q = h.apply(p).unwrap_or_else(|| {
unmapped += 1;
p
});
drawn = Some(drawn.map_or(Rect::from_points(q, q), |r| r.union_pt(q)));
}
});
let drawn = drawn.unwrap();
assert_eq!(unmapped > 0, crosses, "{unmapped} points past the horizon");
if !crosses {
let ink = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &tx).ink_bounds().unwrap();
let boxed = h.map_rect_bbox(tx.xf.transform_rect_bbox(ink)).unwrap();
assert!(boxed.width() - drawn.width() > 1.0 || boxed.height() - drawn.height() > 1.0, "{boxed:?} vs {drawn:?}");
}
sel(&mut s, &[t]);
let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": "arc", "bend": 0})).unwrap());
let src = src_of(&s, e);
let off = [src.x0 - drawn.x0, src.y0 - drawn.y0, src.x1 - drawn.x1, src.y1 - drawn.y1].iter().fold(0.0f64, |m, v| m.max(v.abs()));
assert!(off < 0.05, "{src:?} vs {drawn:?}");
}
}
/// Type that draws nothing (only spaces) keeps its laid-out box.
#[test]
fn an_envelope_of_type_that_draws_nothing_maps_from_its_laid_out_box() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": " ", "size": 48})).unwrap());
let laid = node(&s, t).geometric_bounds().unwrap();
assert_box(live::envelope_content_bounds(&[std::sync::Arc::new(node(&s, t))]).unwrap(), laid, "spaces");
sel(&mut s, &[t]);
let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": "arc", "bend": 0})).unwrap());
assert_box(src_of(&s, e), laid, "warp");
}
/// The strikethrough bar runs to the last glyph's advance, past its outline: the envelope maps
/// from it too.
#[test]
fn an_envelope_maps_struck_through_type_from_its_glyphs_and_bars() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "HH", "size": 100})).unwrap());
let plain = ink_of(&s, t);
s.execute("text.setFormat", &json!({"ids": [t.0], "strikethrough": true})).unwrap();
let NodeKind::Text(tx) = node(&s, t).kind else { panic!("type") };
let db = vectorcraft_text::FontDb::global();
let laid = vectorcraft_text::layout(db, &tx);
let bars = vectorcraft_text::decorations(&laid, db, &tx);
assert!(!bars.is_empty(), "struck-through type has a bar");
let bar = tx.xf.transform_rect_bbox(kurbo::Shape::bounding_box(&bars[0].1));
assert!(bar.x1 > plain.x1 + 1.0, "the bar {bar:?} reaches past the glyphs {plain:?}");
sel(&mut s, &[t]);
let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": "arc", "bend": 0})).unwrap());
assert_box(src_of(&s, e), plain.union(bar), "glyphs and bar");
}
/// In a layer, the visible type is measured by its glyphs and hidden type isn't measured; in a
/// clip group whose clipping path is type, the envelope maps from that type's glyphs.
#[test]
fn type_in_layers_and_clip_groups_is_measured_by_its_glyphs() {
let mut s = session();
let shown = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "Shown", "size": 48})).unwrap());
let hidden = id_of(&s.execute("text.create", &json!({"x": 100, "y": 500, "text": "Hidden", "size": 48})).unwrap());
sel(&mut s, &[hidden]);
s.execute("object.hide", &json!({})).unwrap();
let ink = ink_of(&s, shown);
let layer = s.doc().unwrap().doc.layers[0].clone();
assert_box(live::envelope_content_bounds(&[layer]).unwrap(), ink, "layer");
let mut s = session();
let back = rect(&mut s, 50.0, 100.0, 500.0, 200.0);
let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "Clip", "size": 72})).unwrap());
let ink = ink_of(&s, t);
sel(&mut s, &[back, t]);
let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
assert!(matches!(node(&s, g).kind, NodeKind::Group { clip: true, .. }));
let (stroked, plain) = live::envelope_content_boxes(&[std::sync::Arc::new(node(&s, g))], Affine::IDENTITY).unwrap();
assert_box(plain, ink, "clip group");
assert_box(stroked, ink, "clip group with strokes (none)");
sel(&mut s, &[g]);
let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": "arc", "bend": 0})).unwrap());
assert_box(src_of(&s, e), ink, "warp of the clip group");
}
/// Stroked type: the box with strokes reaches past the glyphs as far as the type's strokes reach
/// past its laid-out box. In perspective, the glyphs are the projected outlines and the reach is
/// that of the strokes past the projected laid-out box.
#[test]
fn stroked_type_maps_from_its_glyphs_grown_by_its_strokes() {
let h = vectorcraft_geom::Homography([[1.0, 0.3, 0.0], [0.1, 1.0, 0.0], [0.0015, 0.0008, 1.0]]);
for perspective in [false, true] {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "Stroke", "size": 60})).unwrap());
sel(&mut s, &[t]);
s.execute("paint.setStroke", &json!({"color": "#ff0000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 6})).unwrap();
if perspective {
s.edit("perspective", |d, _| {
d.node_mut(t).unwrap().extras_mut().perspective = Some(Box::new(vectorcraft_doc::PerspectiveAttachment {
projection: Some(h.to_array()),
..vectorcraft_doc::PerspectiveAttachment::new("left", 0.0)
}));
Ok(())
})
.unwrap();
}
let n = node(&s, t);
assert_eq!(n.projection().is_some(), perspective);
let (v, g) = (n.visual_bounds().unwrap(), n.geometric_bounds().unwrap());
assert!(v.x0 < g.x0 - 1.0, "the strokes {v:?} reach past the laid-out box {g:?}");
let NodeKind::Text(tx) = &n.kind else { panic!("type") };
// The glyph outlines as drawn.
let ink = if perspective {
let path = tx.xf * vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx).to_bezpath();
let mut drawn: Option<Rect> = None;
kurbo::flatten(&path, 0.001, |el| {
if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = el {
let q = h.apply(p).unwrap();
drawn = Some(drawn.map_or(Rect::from_points(q, q), |r| r.union_pt(q)));
}
});
drawn.unwrap()
} else {
ink_of(&s, t)
};
let (stroked, plain) = live::envelope_content_boxes(&[std::sync::Arc::new(n.clone())], Affine::IDENTITY).unwrap();
let near = |a: Rect, b: Rect, what: &str| {
let d = [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().fold(0.0f64, |m, v| m.max(v.abs()));
assert!(d < 0.05, "{what} (perspective {perspective}): {a:?} vs {b:?}");
};
near(plain, ink, "geometric box");
near(stroked, Rect::new(ink.x0 - (g.x0 - v.x0), ink.y0 - (g.y0 - v.y0), ink.x1 + (v.x1 - g.x1), ink.y1 + (v.y1 - g.y1)), "with strokes");
}
}
/// Make with Top Object maps type from its glyphs onto the path's outline.
#[test]
fn a_top_object_envelope_of_type_maps_from_its_glyphs() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "Top", "size": 72})).unwrap());
let ink = ink_of(&s, t);
let top = rect(&mut s, 80.0, 100.0, 300.0, 150.0);
sel(&mut s, &[t, top]);
let e = id_of(&s.execute("object.envelope.makeWithTopObject", &json!({})).unwrap());
assert!(matches!(kind(&s, e), EnvelopeKind::TopObject { .. }));
assert_box(src_of(&s, e), ink, "top object");
}
/// Type in a symbol instance is measured as before: the envelope maps from the instance's own
/// bounds, not from the type's glyphs.
#[test]
fn an_envelope_of_a_symbol_instance_of_type_maps_from_the_instance_s_bounds() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "Symbol", "size": 60})).unwrap());
let ink = ink_of(&s, t);
sel(&mut s, &[t]);
s.execute("symbol.new", &json!({"name": "Type"})).unwrap();
let inst = s.doc().unwrap().selection.objects[0];
assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }));
let own = node(&s, inst).geometric_bounds().unwrap();
assert!((own.height() - ink.height()).abs() > 1.0, "{own:?} vs {ink:?}");
let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": "arc", "bend": 0})).unwrap());
assert_box(src_of(&s, e), own, "symbol instance");
}
/// Type inside a blend or a repeat is measured as before: the envelope maps from the object's own
/// bounds, not from the type's glyphs.
#[test]
fn an_envelope_of_a_blend_or_repeat_of_type_maps_from_its_own_bounds() {
for repeat in [false, true] {
let mut s = session();
let a = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "Blend", "size": 60})).unwrap());
let mut parts = vec![a];
if !repeat {
parts.push(id_of(&s.execute("text.create", &json!({"x": 300, "y": 400, "text": "Blend", "size": 60})).unwrap()));
}
let ink = parts.iter().map(|t| ink_of(&s, *t)).reduce(|a, b| a.union(b)).unwrap();
sel(&mut s, &parts);
let made = if repeat { "object.repeat.grid" } else { "object.blend.make" };
let holder = id_of(&s.execute(made, &json!({})).unwrap());
let own = node(&s, holder).geometric_bounds().unwrap();
let measured = live::envelope_content_bounds(&[std::sync::Arc::new(node(&s, holder))]).unwrap();
assert_box(measured, own, made);
assert!((own.height() - ink.height()).abs() > 1.0 || (own.width() - ink.width()).abs() > 1.0, "{made}: {own:?} vs {ink:?}");
sel(&mut s, &[holder]);
let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": "arc", "bend": 0})).unwrap());
assert_box(src_of(&s, e), own, made);
}
}
/// An inline graphic counts by its box: the envelope maps from the glyph outlines and the box of
/// the graphic, which reaches past the glyphs.
#[test]
fn an_envelope_maps_type_with_an_inline_graphic_from_its_glyphs_and_the_graphic() {
let mut s = session();
s.execute("shape.ellipse", &json!({"x": 600, "y": 500, "width": 40, "height": 40})).unwrap();
s.execute("symbol.new", &json!({"name": "Dot"})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "xx", "size": 40})).unwrap());
s.execute("text.insertInline", &json!({"id": t.0, "at": 1, "symbol": "Dot"})).unwrap();
let NodeKind::Text(tx) = node(&s, t).kind else { panic!("type") };
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &tx);
let [inline] = laid.inlines.as_slice() else { panic!("one inline graphic: {}", laid.inlines.len()) };
let graphic = tx.xf.transform_rect_bbox(inline.bounds);
let glyphs = outlines_in(&tx, tx.xf);
assert!(graphic.y0 < glyphs.y0 - 1.0, "the graphic {graphic:?} reaches above the glyphs {glyphs:?}");
sel(&mut s, &[t]);
let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": "arc", "bend": 0})).unwrap());
assert_box(src_of(&s, e), glyphs.union(graphic), "glyphs and graphic");
}
/// Reset with Mesh without Maintain Shape lays its flat grid over the glyphs.
#[test]
fn reset_with_mesh_lays_a_flat_grid_over_the_glyphs() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "Reset", "size": 72})).unwrap());
let ink = ink_of(&s, t);
sel(&mut s, &[t]);
let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": "bulge", "bend": 40})).unwrap());
s.execute("object.envelope.resetWithMesh", &json!({"rows": 2, "cols": 3, "maintainShape": false})).unwrap();
let EnvelopeKind::Mesh { points, .. } = kind(&s, e) else { panic!("mesh") };
let grid = points.iter().fold(Rect::from_points(points[0], points[0]), |r, p| r.union_pt(*p));
assert_box(grid, ink, "flat grid");
}
+56
View File
@@ -272,6 +272,62 @@ fn balance_trades_vector_regions_for_an_image() {
assert_eq!(flatten(&mut s, json!({"ids": [a, b], "balance": 5})).2, 1);
}
/// The balance's region limit, `10^(balance/20)` rounded down, is the most regions a group keeps.
#[test]
fn the_region_limit_is_the_most_regions_the_balance_keeps() {
use crate::cmd::FlattenOptions;
for balance in [0.0, 1.0, 5.0, 16.0, 17.0, 20.0, 40.0, 60.0, 75.0, 99.0, 99.99, 100.0] {
for clip in [false, true] {
let o = FlattenOptions::from_params(&json!({"balance": balance, "clipComplexRegions": clip})).unwrap();
match o.region_limit() {
Some(n) => {
assert!(!o.rasterize_all(n) && o.rasterize_all(n + 1), "balance {balance}: limit {n}");
assert!(!clip, "balance {balance}: a limit with Clip Complex Regions");
}
None => assert!(clip || balance <= 0.0 || balance >= 100.0, "balance {balance}: no limit"),
}
}
}
}
/// A row of four half-transparent rectangles splits into 7 regions. Under the balance's region
/// limit (10), at it (7), just over it (6) and far over it (1), Flatten Transparency, the flattened
/// document and the EPS file come out as they do when every region is built.
#[test]
fn groups_over_the_region_limit_flatten_as_with_every_region_built() {
use crate::cmd::FlattenOptions;
use crate::cmd::flatten::{flatten_document, with_every_region as every};
let _settings = settings_lock();
let setup = || {
let mut s = session();
let ids: Vec<u64> = (0..4).map(|k| rect(&mut s, 10.0 + 30.0 * f64::from(k), 10.0, 40.0, 60.0, "#ff8000")).collect();
run(&mut s, "transparency.set", json!({"ids": ids, "opacity": 50}));
(s, ids)
};
let eps = |s: &mut Session, balance: u32| {
let r = run(s, "document.exportEps", json!({"flattener": {"balance": balance}, "previewFormat": "none", "thumbnails": false}));
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
String::from_utf8_lossy(&bytes).lines().filter(|l| !l.contains("CreationDate")).collect::<Vec<_>>().join("\n")
};
for (balance, vector, rasterized) in [(20, 7, 0), (17, 7, 0), (16, 0, 1), (5, 0, 1)] {
let (mut s, _) = setup();
let o = FlattenOptions::from_params(&json!({"balance": balance})).unwrap();
let src = s.doc().unwrap().doc.clone();
let flat = flatten_document(&src, &o).unwrap();
assert!(flat == every(|| flatten_document(&src, &o).unwrap()), "balance {balance}: flattened document");
assert_eq!(eps(&mut s, balance), every(|| eps(&mut s, balance)), "balance {balance}: EPS");
let (mut s, ids) = setup();
let got = flatten(&mut s, json!({"ids": ids, "balance": balance}));
assert_eq!((got.1, got.2), (vector, rasterized), "balance {balance}");
let (mut t, ids) = setup();
let want = every(|| flatten(&mut t, json!({"ids": ids, "balance": balance})));
assert_eq!(got, want, "balance {balance}");
// The two documents were made apart, so their creation times can differ.
let (a, b) = (&s.doc().unwrap().doc, &t.doc().unwrap().doc);
assert!(a.layers == b.layers && a.images == b.images, "balance {balance}: Flatten Transparency");
}
}
#[test]
fn gradients_rasterize_and_flat_areas_stay_vector() {
let _settings = settings_lock();
+361
View File
@@ -0,0 +1,361 @@
//! History panel › New Document from State (`edit.newDocumentFromState`).
use std::sync::Arc;
use serde_json::{Value, json};
use super::{rect, session};
use crate::tests_links::{Folder, RED, place, png, write};
use crate::*;
const CMD: &str = "edit.newDocumentFromState";
fn objects(s: &Session) -> usize {
s.doc().unwrap().doc.layers[0].children().unwrap().len()
}
fn x(s: &Session, id: NodeId) -> f64 {
s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().x0
}
fn steps(s: &Session) -> (usize, usize) {
let h = &s.doc().unwrap().history;
(h.undo.len(), h.redo.len())
}
/// Three rectangles, the last one undone: rows 0 to 3 hold 0 to 3 of them, the current one row 2.
fn three_rectangles_one_undone() -> Session {
let mut s = session();
for x in [10.0, 200.0, 400.0] {
rect(&mut s, x, 10.0, 100.0, 50.0);
}
s.execute("edit.undo", &json!({})).unwrap();
s
}
/// Each row gives the art of its state, the steps to redo included. An omitted or null index gives
/// the current state. Each new document is added and made active.
#[test]
fn a_new_document_holds_the_art_of_the_state() {
let params = [
(json!({"index": 0}), 0),
(json!({"index": 1}), 1),
(json!({"index": 2}), 2),
(json!({"index": 3}), 3),
(json!({}), 2),
(json!({"index": null}), 2),
];
for (p, art) in params {
let mut s = three_rectangles_one_undone();
let r = s.execute(CMD, &p).unwrap();
assert_eq!((r["index"].as_u64(), s.active_index()), (Some(1), Some(1)), "{p}");
assert_eq!(objects(&s), art, "{p}");
assert_eq!(s.documents().len(), 2);
}
}
/// The source's document, steps, selection and saved state stay as they are, for a modified source
/// and for one at its saved state.
#[test]
fn the_source_stays_as_it_is() {
let mut s = three_rectangles_one_undone();
let source = s.doc().unwrap().doc.clone();
let selection = s.doc().unwrap().selection.clone();
assert!(s.doc().unwrap().is_dirty());
s.execute(CMD, &json!({"index": 0})).unwrap();
let st = &s.documents()[0];
assert!(Arc::ptr_eq(&st.doc, &source));
assert_eq!((st.history.undo.len(), st.history.redo.len()), (2, 1));
assert_eq!(st.selection, selection);
assert!(st.is_dirty());
let mut s = session();
rect(&mut s, 10.0, 10.0, 100.0, 50.0);
s.execute("edit.undo", &json!({})).unwrap();
assert!(!s.doc().unwrap().is_dirty());
s.execute(CMD, &json!({"index": 1})).unwrap();
assert!(!s.documents()[0].is_dirty(), "the source stays at its saved state");
assert!(s.doc().unwrap().is_dirty(), "the new document is unsaved");
}
/// An index that names no state, or is not a whole number, is an error and changes nothing: no
/// document, no step and no Untitled number is used up.
#[test]
fn a_bad_index_is_an_error_and_changes_nothing() {
let mut s = three_rectangles_one_undone();
let source = s.doc().unwrap().doc.clone();
let untitled = s.peek_untitled();
let bad: [Value; 8] = [json!(4), json!(99), json!(-1), json!(1.5), json!("1"), json!(true), json!([1]), json!(u64::MAX)];
for index in bad {
let e = s.execute(CMD, &json!({ "index": index })).unwrap_err();
assert!(matches!(e, EngineError::BadParams { .. }), "{index}: {e}");
assert!(e.to_string().contains(&format!("no history state {index}")), "{e}");
assert_eq!(s.documents().len(), 1, "{index}");
assert_eq!(steps(&s), (2, 1), "{index}");
assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &source), "{index}");
assert_eq!(s.peek_untitled(), untitled, "{index}");
}
let e = s.execute(CMD, &json!({"created": "today"})).unwrap_err();
assert!(matches!(e, EngineError::BadParams { .. }), "{e}");
assert_eq!(s.documents().len(), 1);
}
/// With no document the command is disabled.
#[test]
fn it_needs_a_document() {
let mut s = Session::new();
assert!(matches!(s.execute(CMD, &json!({})), Err(EngineError::Disabled(..))));
}
/// An edit in either document leaves the other as it is, and so does taking an artboard id.
#[test]
fn the_two_documents_are_independent() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0, 100.0, 50.0);
rect(&mut s, 200.0, 10.0, 100.0, 50.0);
s.execute(CMD, &json!({"index": 1})).unwrap();
s.execute("object.move", &json!({"ids": [a.0], "dx": 30, "dy": 0})).unwrap();
rect(&mut s, 400.0, 10.0, 100.0, 50.0);
assert_eq!((x(&s, a), objects(&s)), (40.0, 2));
s.execute("document.activate", &json!({"index": 0})).unwrap();
assert_eq!((x(&s, a), objects(&s)), (10.0, 2), "the source");
s.execute("object.move", &json!({"ids": [a.0], "dx": 5, "dy": 0})).unwrap();
assert_eq!(x(&s, a), 15.0);
let source_board = s.doc().unwrap().doc.next_artboard_id();
s.execute("document.activate", &json!({"index": 1})).unwrap();
assert_eq!((x(&s, a), objects(&s)), (40.0, 2), "the new document");
assert!(s.doc().unwrap().doc.retired_artboard_id.get() < source_board, "an artboard id the source took");
}
/// The new document starts with no steps, no selection, no path and the next untitled name, and is
/// unsaved. Undo and Redo then work in it alone, and undoing back to the start leaves it unsaved.
#[test]
fn undo_in_the_new_document() {
let mut s = three_rectangles_one_undone();
s.execute("select.all", &json!({})).unwrap();
let r = s.execute(CMD, &json!({"index": 1})).unwrap();
assert_eq!(r["title"], "Untitled-2");
let st = s.doc().unwrap();
assert_eq!(st.title(), "Untitled-2");
assert_eq!(st.path, None);
assert!(st.selection.objects.is_empty());
assert!(st.is_dirty());
let start = st.doc.clone();
assert_eq!(steps(&s), (0, 0));
assert!(matches!(s.execute("edit.undo", &json!({})), Err(EngineError::Disabled(..))), "the source's steps are not its own");
rect(&mut s, 600.0, 10.0, 100.0, 50.0);
assert_eq!(objects(&s), 2);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(objects(&s), 1);
assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &start));
assert!(s.doc().unwrap().is_dirty(), "still unsaved at the state it started from");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(objects(&s), 2);
assert_eq!(s.documents()[0].history.undo.len(), 2, "the source's steps");
}
/// A drag in progress is first kept as a step and its change goes into the new document. An index
/// names the state as listed before that, and a bad one leaves the drag going on.
#[test]
fn a_drag_in_progress_is_kept_first() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0, 100.0, 50.0);
s.begin_interaction("Move").unwrap();
s.preview("object.move", &json!({"dx": 30, "dy": 0})).unwrap();
assert!(s.execute(CMD, &json!({"index": 2})).is_err());
assert!(s.in_interaction(), "a bad index ends nothing");
assert_eq!(steps(&s), (1, 0));
s.execute(CMD, &json!({"index": 0})).unwrap();
assert_eq!(objects(&s), 0, "the row listed as 0");
assert_eq!(x_of_source(&s, a), 40.0);
assert_eq!(s.documents()[0].history.undo.len(), 2, "the drag is a step in the source");
let mut s = session();
let a = rect(&mut s, 10.0, 10.0, 100.0, 50.0);
s.begin_interaction("Move").unwrap();
s.preview("object.move", &json!({"dx": 30, "dy": 0})).unwrap();
s.execute(CMD, &json!({})).unwrap();
assert_eq!(x(&s, a), 40.0, "the current state holds the drag");
assert_eq!(x_of_source(&s, a), 40.0);
assert!(s.documents()[0].interaction.is_none());
}
fn x_of_source(s: &Session, id: NodeId) -> f64 {
s.documents()[0].doc.node(id).unwrap().geometric_bounds().unwrap().x0
}
/// A state saved while editing a symbol gives a document out of that mode and without the
/// temporary editing layer. The source stays in the mode.
#[test]
fn a_new_document_leaves_the_editing_modes() {
let mut s = session();
rect(&mut s, 10.0, 10.0, 100.0, 50.0);
s.execute("symbol.new", &json!({"name": "Box"})).unwrap();
let layers = s.doc().unwrap().doc.layers.len();
s.execute("symbol.edit", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.symbol_edit.is_some());
assert_eq!(s.doc().unwrap().doc.layers.len(), layers + 1);
s.execute(CMD, &json!({})).unwrap();
let st = s.doc().unwrap();
assert!(st.doc.symbol_edit.is_none());
assert_eq!(st.doc.layers.len(), layers);
assert!(s.documents()[0].doc.symbol_edit.is_some());
}
/// A state saved while editing a pattern gives a document out of that mode, without the editing
/// layer, and with the art drawn in the tile stored in the pattern, as Done stores it. The source
/// stays in the mode.
#[test]
fn a_new_document_finishes_pattern_editing() {
let mut s = session();
let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
s.execute("select.set", &json!({"ids": [r.0]})).unwrap();
let layers = s.doc().unwrap().doc.layers.len();
s.execute("object.pattern.make", &json!({"name": "P"})).unwrap();
rect(&mut s, 2.0, 2.0, 3.0, 3.0);
assert_eq!(s.doc().unwrap().doc.layers.len(), layers + 1);
s.execute(CMD, &json!({})).unwrap();
assert_eq!(s.active_index(), Some(1), "the new document");
let st = s.doc().unwrap();
assert!(st.doc.pattern_edit.is_none());
assert_eq!(st.doc.layers.len(), layers);
assert_eq!(st.doc.pattern("P").map(|p| p.art.len()), Some(2));
assert_eq!(st.isolation, None);
assert!(s.documents()[0].doc.pattern_edit.is_some());
}
/// A linked image still finds its file from the new document, which has no folder of its own, and
/// its pixels come along.
#[test]
fn links_resolve_in_the_new_document() {
let dir = Folder::new("history-document-links");
let pic = dir.file("photo.png");
write(&pic, &png(60, 30, RED));
let mut s = session();
let id = place(&mut s, &pic);
let list = |s: &mut Session| s.execute("links.list", &json!({})).unwrap();
assert_eq!(list(&mut s)["links"][0]["status"], "ok");
s.execute(CMD, &json!({})).unwrap();
assert_eq!(s.active_index(), Some(1), "the new document");
let links = list(&mut s);
assert_eq!((&links["links"][0]["status"], &links["links"][0]["path"]), (&json!("ok"), &json!(pic)), "{links}");
let st = s.doc().unwrap();
assert!(st.doc.node(id).is_some());
assert_eq!(st.doc.images.len(), s.documents()[0].doc.images.len());
}
/// A linked file the source finds in its own folder, away from the link's path, is found from the
/// new document too: its link takes the path where the source finds the file.
#[test]
fn a_file_the_source_finds_in_its_folder_is_found_from_the_new_document() {
let a = Folder::new("history-document-moved-a");
let b = Folder::new("history-document-moved-b");
let pic = a.file("photo.png");
write(&pic, &png(60, 30, RED));
let mut s = session();
place(&mut s, &pic);
s.execute("document.save", &json!({"path": b.file("poster.vectorcraft")})).unwrap();
let moved = b.file("photo.png");
std::fs::rename(&pic, &moved).unwrap();
let check = |s: &mut Session| s.execute("links.check", &json!({})).unwrap();
assert_eq!(check(&mut s)["links"][0]["status"], "ok", "the source finds it by name in its folder");
s.execute(CMD, &json!({})).unwrap();
assert_eq!(s.active_index(), Some(1), "the new document");
let c = check(&mut s);
assert_eq!((&c["links"][0]["status"], &c["links"][0]["path"]), (&json!("ok"), &json!(moved)), "{c}");
}
/// The same holds for a linked image only a symbol shows.
#[test]
fn a_file_a_symbol_shows_is_found_from_the_new_document() {
let a = Folder::new("history-document-symbol-a");
let b = Folder::new("history-document-symbol-b");
let pic = a.file("photo.png");
write(&pic, &png(60, 30, RED));
let mut s = session();
place(&mut s, &pic);
s.execute("symbol.new", &json!({"name": "Photo"})).unwrap();
s.execute("document.save", &json!({"path": b.file("poster.vectorcraft")})).unwrap();
let moved = b.file("photo.png");
std::fs::rename(&pic, &moved).unwrap();
s.execute(CMD, &json!({})).unwrap();
assert_eq!(s.active_index(), Some(1), "the new document");
let d = &s.doc().unwrap().doc;
assert!(!d.symbols.is_empty());
let mut paths = vec![];
d.visit_images(|_, im| paths.extend(im.link.as_ref().map(|l| l.path.clone())));
assert!(!paths.is_empty() && paths.iter().all(|p| *p == moved), "{paths:?}");
}
/// Files are looked for only within the roots of the caller that opened the source, or of a
/// confined caller asking now: a file outside them is not linked from the new document.
#[test]
fn a_file_outside_the_callers_roots_is_not_looked_for() {
let a = Folder::new("history-document-confined-a");
let b = Folder::new("history-document-confined-b");
let other = Folder::new("history-document-confined-other");
let pic = a.file("photo.png");
write(&pic, &png(60, 30, RED));
let mut s = session();
place(&mut s, &pic);
s.execute("document.save", &json!({"path": b.file("poster.vectorcraft")})).unwrap();
let moved = b.file("photo.png");
std::fs::rename(&pic, &moved).unwrap();
let narrow = crate::file_access::AutomationRoots::new(&[&other.0], &[]).unwrap().unwrap();
let link = |s: &Session| {
let mut paths = vec![];
s.doc().unwrap().doc.visit_images(|_, im| paths.extend(im.link.as_ref().map(|l| l.path.clone())));
paths
};
crate::file_access::confine(Some(&narrow), || s.execute(CMD, &json!({}))).unwrap();
assert_eq!(s.active_index(), Some(1), "the new document");
assert!(link(&s).iter().all(|p| *p != moved), "a confined caller: {:?}", link(&s));
s.execute("document.activate", &json!({"index": 0})).unwrap();
s.active_mut().unwrap().opened_by = Some(narrow);
s.execute(CMD, &json!({})).unwrap();
assert_eq!(s.active_index(), Some(2), "the second new document");
let paths = link(&s);
assert!(!paths.is_empty() && paths.iter().all(|p| *p != moved), "opened by a confined caller: {paths:?}");
}
/// What reading the source's file left out still guards that file from the new document, and the
/// new document is read within what the caller that opened the source may read.
#[test]
fn the_new_document_keeps_what_guards_the_source() {
let dir = Folder::new("history-document-roots");
let roots = crate::file_access::AutomationRoots::new(&[&dir.0], &[]).unwrap().unwrap();
let mut s = session();
let st = s.active_mut().unwrap();
st.imported_from = Some("art.ai".into());
st.import_losses = vec!["hidden text".into()];
st.opened_by = Some(roots.clone());
s.execute(CMD, &json!({})).unwrap();
assert_eq!(s.active_index(), Some(1), "the new document");
let st = s.doc().unwrap();
assert_eq!((st.imported_from.as_deref(), st.import_losses.as_slice()), (Some("art.ai"), &["hidden text".to_string()][..]));
assert!(st.opened_by.as_ref().is_some_and(|r| Arc::ptr_eq(r, &roots)));
}
/// The created date is the new document's own and joins the journal entry, so a replay gives the
/// same date. An action leaves it out. The new document has no modified date until it is saved.
#[test]
fn the_created_date_is_the_new_documents_own() {
let mut s = session();
Arc::make_mut(&mut s.active_mut().unwrap().doc).metadata.modified = Some(500);
let source = s.doc().unwrap().doc.metadata.created;
s.execute(CMD, &json!({"created": 1000})).unwrap();
assert_eq!(s.doc().unwrap().doc.metadata.created, Some(1000));
assert_eq!(s.doc().unwrap().doc.metadata.modified, None, "the new document has not been saved");
assert_eq!(s.documents()[0].doc.metadata.modified, Some(500));
assert_eq!(s.documents()[0].doc.metadata.created, source);
s.execute("document.activate", &json!({"index": 0})).unwrap();
s.execute(CMD, &json!({"created": null})).unwrap();
assert_eq!(s.doc().unwrap().doc.metadata.created, None);
s.execute("document.activate", &json!({"index": 0})).unwrap();
s.execute(CMD, &json!({})).unwrap();
let noted = s.journal.last().unwrap().1["created"].as_i64();
assert!(noted.is_some() && noted == s.doc().unwrap().doc.metadata.created, "{noted:?}");
let mut action = s.journal.last().unwrap().1.clone();
crate::command_sets::strip_replay_only(CMD, &mut action);
assert_eq!(action, json!({}), "an action leaves the date out");
}
+399
View File
@@ -244,6 +244,203 @@ fn the_relative_path_finds_the_file_after_the_folder_moves() {
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
}
/// Links in symbols, graph designs, patterns and opacity masks are saved with their relative
/// paths, as links in the layers are: after the folder moves, each file is found and its link takes
/// the new path, which the next save writes relative to the document again.
#[test]
fn links_outside_the_layers_find_their_files_after_the_folder_moves() {
let a = Folder::new("nested-move-a");
let b = Folder::new("nested-move-b");
let c = Folder::new("nested-move-c");
let names = ["layer", "symbol", "design", "pattern", "mask"];
for (i, name) in (0u8..).zip(names) {
write(&a.file(&format!("art/{name}.png")), &png(20, 10, [20 + 40 * i, 90, 160]));
}
let mut s = session();
place(&mut s, &a.file("art/layer.png"));
let id = place(&mut s, &a.file("art/symbol.png"));
s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap();
let id = place(&mut s, &a.file("art/design.png"));
s.execute("graph.design", &json!({"new": "Bar"})).unwrap();
s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap();
let id = place(&mut s, &a.file("art/pattern.png"));
s.execute("object.pattern.make", &json!({"ids": [id.0], "edit": false})).unwrap();
s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap();
let masked = super::rect(&mut s, 10.0, 10.0, 60.0, 60.0);
let mask = place(&mut s, &a.file("art/mask.png"));
s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, mask.0]})).unwrap();
let mut in_layers = vec![];
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Image(im) = &n.kind {
in_layers.extend(im.link.as_ref().map(|l| l.name().to_string()));
}
});
assert_eq!(in_layers, ["layer.png"], "only one file is shown by an object in the layers");
// The links' paths, each image checked to show its file's pixels rather than the saved preview.
let paths = |s: &Session| {
let d = &s.doc().unwrap().doc;
let mut out = vec![];
d.visit_images(|_, im| {
let l = im.link.as_ref().unwrap();
assert!(!d.images[&im.key].is_proxy(), "{} shows its preview", l.name());
out.push(PathBuf::from(&l.path));
});
out.sort();
out
};
let files = |dir: &Folder| {
let mut out: Vec<PathBuf> = names.iter().map(|n| PathBuf::from(dir.file(&format!("art/{n}.png")))).collect();
out.sort();
out
};
assert_eq!(paths(&s), files(&a));
save(&mut s, &a.file("poster.vectorcraft"));
// Move the document with its links: the old folder is gone.
std::fs::remove_dir_all(&b.0).unwrap();
std::fs::rename(&a.0, &b.0).unwrap();
let r = open(&mut s, &b.file("poster.vectorcraft"));
assert_eq!((r["missingLinks"].clone(), r["modifiedLinks"].clone()), (json!([]), json!([])), "{r}");
assert_eq!(paths(&s), files(&b), "the links follow the files");
// Saved again and moved again.
save(&mut s, &b.file("poster.vectorcraft"));
std::fs::remove_dir_all(&c.0).unwrap();
std::fs::rename(&b.0, &c.0).unwrap();
let r = open(&mut s, &c.file("poster.vectorcraft"));
assert_eq!((r["missingLinks"].clone(), r["modifiedLinks"].clone()), (json!([]), json!([])), "{r}");
assert_eq!(paths(&s), files(&c));
}
/// With Update Links: Automatically, a file in a symbol and in the layers that changed and moved
/// with the document is read again for the layers' image and for the symbol's, and both links take
/// its new path, size and hash.
#[test]
fn a_symbols_link_to_a_moved_and_modified_file_takes_its_new_path() {
let a = Folder::new("nested-modified-a");
let b = Folder::new("nested-modified-b");
let pic = a.file("art/photo.png");
write(&pic, &png(20, 10, RED));
let mut s = session();
s.execute("prefs.set", &json!({"key": "updateLinks", "value": "automatically"})).unwrap();
let id = place(&mut s, &pic);
s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap();
let id = place(&mut s, &pic);
save(&mut s, &a.file("poster.vectorcraft"));
write(&pic, &png(30, 30, BLUE));
std::fs::remove_dir_all(&b.0).unwrap();
std::fs::rename(&a.0, &b.0).unwrap();
let r = open(&mut s, &b.file("poster.vectorcraft"));
assert_eq!((r["modifiedLinks"].clone(), r["updatedLinks"][0]["ids"].clone()), (json!([]), json!([id.0])), "{r}");
let moved = PathBuf::from(b.file("art/photo.png"));
let blue = png(30, 30, BLUE);
let mut images = vec![];
s.doc().unwrap().doc.visit_images(|_, im| {
let l = im.link.as_ref().unwrap();
images.push((PathBuf::from(&l.path), l.size, l.hash.clone(), im.width, im.height, im.key.clone()));
});
let key = image(&s, id).key;
let new = (moved, Some(blue.len() as u64), Some(vectorcraft_doc::links::hash_bytes(&blue)), 30, 30, key);
assert_eq!(images, [new.clone(), new], "the layers' image, then the symbol's");
}
/// A link inside a symbol that the document records without a relative path, beside a link in the
/// layers to the same file that has one, takes the file's new path after the folder moves.
#[test]
fn a_symbols_link_without_a_relative_path_follows_the_moved_file() {
let a = Folder::new("nested-unrelative-a");
let b = Folder::new("nested-unrelative-b");
let pic = a.file("art/photo.png");
write(&pic, &png(20, 10, RED));
let mut s = session();
let id = place(&mut s, &pic);
s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap();
place(&mut s, &pic);
let doc_path = a.file("poster.vectorcraft");
save(&mut s, &doc_path);
// Removes the relative path of every link under `v` → how many it removed.
fn unrelative(v: &mut Value) -> usize {
match v {
Value::Object(o) => {
let own = match o.get_mut("link") {
Some(Value::Object(l)) => usize::from(l.remove("relative").is_some()),
_ => 0,
};
own + o.values_mut().map(unrelative).sum::<usize>()
}
Value::Array(a) => a.iter_mut().map(unrelative).sum(),
_ => 0,
}
}
let mut saved: Value = serde_json::from_slice(&std::fs::read(&doc_path).unwrap()).unwrap();
assert_eq!(unrelative(&mut saved["document"]["symbols"]), 1, "the symbol's link");
assert_eq!(unrelative(&mut saved["document"]["layers"].clone()), 1, "the layers' link keeps its relative path");
std::fs::write(&doc_path, serde_json::to_vec(&saved).unwrap()).unwrap();
std::fs::remove_dir_all(&b.0).unwrap();
std::fs::rename(&a.0, &b.0).unwrap();
let r = open(&mut s, &b.file("poster.vectorcraft"));
assert_eq!((r["missingLinks"].clone(), r["modifiedLinks"].clone()), (json!([]), json!([])), "{r}");
let mut paths = vec![];
s.doc().unwrap().doc.visit_images(|_, im| paths.push(PathBuf::from(&im.link.as_ref().unwrap().path)));
let moved = PathBuf::from(b.file("art/photo.png"));
assert_eq!(paths, [moved.clone(), moved], "the layers' link, then the symbol's");
}
/// Update Links reads a changed file again for the images inside symbols, patterns and opacity
/// masks too: those showing the same content as an image in the layers, and those no object in the
/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step.
#[test]
fn update_links_reads_files_again_inside_symbols_patterns_and_masks() {
let dir = Folder::new("nested-update");
let (photo, logo) = (dir.file("photo.png"), dir.file("logo.png"));
write(&photo, &png(20, 10, RED));
write(&logo, &png(20, 10, [200, 200, 20]));
let mut s = session();
// photo.png in the layers, and in a symbol filling its bounds, clipped to them.
let id = place(&mut s, &photo);
s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap();
s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap();
let id = place(&mut s, &photo);
// logo.png only in a pattern and in an opacity mask.
let p = place(&mut s, &logo);
s.execute("object.pattern.make", &json!({"ids": [p.0], "edit": false})).unwrap();
s.execute("edit.clear", &json!({"ids": [p.0]})).unwrap();
let masked = super::rect(&mut s, 10.0, 10.0, 60.0, 60.0);
let mask = place(&mut s, &logo);
s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, mask.0]})).unwrap();
// photo.png wider than the symbol's image is: filling its bounds overflows them.
let (blue, green) = (png(60, 20, BLUE), png(40, 20, [20, 200, 20]));
write(&photo, &blue);
write(&logo, &green);
let u = s.execute("links.update", &json!({})).unwrap();
assert_eq!(u, json!({"updated": [id.0], "missing": []}));
// (name, size, hash, pixel size) of each image, which shows its file's pixels.
let images = |s: &Session| {
let d = &s.doc().unwrap().doc;
let mut out = vec![];
d.visit_images(|_, im| {
let l = im.link.as_ref().unwrap();
assert!(!d.images[&im.key].is_proxy(), "{} shows its preview", l.name());
out.push((l.name().to_string(), l.size, l.hash.clone(), (im.width, im.height)));
});
out.sort();
out
};
let shown = |name: &str, bytes: &[u8], size| (name.to_string(), Some(bytes.len() as u64), Some(vectorcraft_doc::links::hash_bytes(bytes)), size);
let logo_now = shown("logo.png", &green, (40, 20));
let photo_now = shown("photo.png", &blue, (60, 20));
assert_eq!(images(&s), [logo_now.clone(), logo_now, photo_now.clone(), photo_now]);
// The symbol's image is clipped to its old bounds.
let mut clipped = false;
s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| {
if let NodeKind::Group { children, clip: true } = &n.kind {
clipped |=
matches!(&children[..], [c, im] if matches!(c.kind, NodeKind::Path { clipping: true, .. }) && matches!(im.kind, NodeKind::Image(_)));
}
});
assert!(clipped, "{:?}", s.doc().unwrap().doc.symbols[0].art);
s.execute("edit.undo", &json!({})).unwrap();
assert!(images(&s).iter().all(|(_, _, _, size)| *size == (20, 10)), "{:?}", images(&s));
}
#[test]
fn a_missing_link_renders_its_preview_and_relinks() {
let dir = Folder::new("missing");
@@ -283,6 +480,151 @@ fn a_missing_link_renders_its_preview_and_relinks() {
assert!(s.execute("links.relink", &json!({"ids": [id.0]})).is_err(), "path or folder");
}
/// The path of the file image `id` links to.
fn link_path(s: &Session, id: NodeId) -> String {
image(s, id).link.map(|l| l.path).unwrap_or_default()
}
/// Replace: All Instances relinks every image linked to the same file as the one given, in one
/// undo step; Selected Instances (the default) only the one given.
#[test]
fn relink_all_instances_takes_every_image_of_the_same_file() {
let dir = Folder::new("relink-all");
let (pic, other) = (dir.file("photo.png"), dir.file("other.png"));
write(&pic, &png(60, 30, RED));
write(&other, &png(60, 30, RED));
let mut s = session();
let (a, b, c) = (place(&mut s, &pic), place(&mut s, &pic), place(&mut s, &other));
let blue = dir.file("new/blue.png");
write(&blue, &png(60, 30, BLUE));
let r = s.execute("links.relink", &json!({"ids": [a.0], "path": blue, "scope": "selected"})).unwrap();
assert_eq!(r, json!({"relinked": [a.0], "notFound": []}));
assert_eq!(link_path(&s, b), pic, "selected instances: the other copy keeps its file");
s.execute("edit.undo", &json!({})).unwrap();
let r = s.execute("links.relink", &json!({"ids": [a.0], "path": blue, "scope": "all"})).unwrap();
assert_eq!(r, json!({"relinked": [a.0, b.0], "notFound": []}));
assert_eq!((link_path(&s, a), link_path(&s, b), link_path(&s, c)), (blue.clone(), blue.clone(), other.clone()));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((link_path(&s, a), link_path(&s, b)), (pic.clone(), pic.clone()), "one undo step");
// The selection stands in for ids.
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
let r = s.execute("links.relink", &json!({"path": blue, "scope": "all"})).unwrap();
assert_eq!(r["relinked"], json!([b.0, a.0]));
}
/// Replace: Missing Links from This Folder relinks the given links to the chosen file, then every
/// other missing link to the file of its name in that file's folder, in one undo step; names not
/// there are listed in notFound and stay missing.
#[test]
fn relink_missing_links_from_this_folder_finds_the_others_by_name() {
let dir = Folder::new("relink-missing-folder");
let names = ["a.png", "b.png", "c.png", "d.png"];
let mut s = session();
let ids: Vec<NodeId> = names
.iter()
.map(|n| {
write(&dir.file(n), &png(60, 30, RED));
place(&mut s, &dir.file(n))
})
.collect();
let doc_path = dir.file("poster.vectorcraft");
save(&mut s, &doc_path);
// d.png stays where it was: it isn't missing.
for n in &names[..3] {
std::fs::remove_file(dir.file(n)).unwrap();
}
open(&mut s, &doc_path);
let found = dir.file("found/a new name.png");
write(&found, &png(60, 30, BLUE));
write(&dir.file("found/b.png"), &png(60, 30, BLUE));
write(&dir.file("found/d.png"), &png(60, 30, BLUE));
let r = s.execute("links.relink", &json!({"ids": [ids[0].0], "path": found, "scope": "missingInFolder"})).unwrap();
assert_eq!(r, json!({"relinked": [ids[0].0, ids[1].0], "notFound": ["c.png"]}));
let b_found = dir.0.join("found").join("b.png").to_string_lossy().into_owned();
assert_eq!((link_path(&s, ids[0]), link_path(&s, ids[1])), (found.clone(), b_found));
assert_eq!((link_path(&s, ids[2]), link_path(&s, ids[3])), (dir.file("c.png"), dir.file("d.png")));
let c = s.execute("links.check", &json!({})).unwrap();
assert_eq!(c["missing"], 1, "{c}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.execute("links.check", &json!({})).unwrap()["missing"], 3, "one undo step");
}
/// Replace: Each Link Separately takes one file for each link, in one undo step.
#[test]
fn relink_each_link_separately_takes_a_file_for_each() {
let dir = Folder::new("relink-each");
let (one, two) = (dir.file("one.png"), dir.file("two.png"));
write(&one, &png(60, 30, RED));
write(&two, &png(60, 30, RED));
let mut s = session();
let (a, b, c) = (place(&mut s, &one), place(&mut s, &one), place(&mut s, &two));
let (x, y) = (dir.file("new/x.png"), dir.file("new/y.png"));
write(&x, &png(60, 30, BLUE));
write(&y, &png(30, 30, BLUE));
let paths = json!([{"ids": [a.0, b.0], "path": x}, {"ids": [c.0], "path": y}]);
let r = s.execute("links.relink", &json!({"scope": "each", "paths": paths})).unwrap();
assert_eq!(r, json!({"relinked": [a.0, b.0, c.0], "notFound": []}));
assert_eq!((link_path(&s, a), link_path(&s, b), link_path(&s, c)), (x.clone(), x.clone(), y.clone()));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((link_path(&s, a), link_path(&s, c)), (one.clone(), two.clone()), "one undo step");
// Two entries naming the same file read it once.
let paths = json!([{"ids": [a.0], "path": y}, {"ids": [c.0], "path": y}]);
let r = s.execute("links.relink", &json!({"scope": "each", "paths": paths})).unwrap();
assert_eq!(r["relinked"], json!([a.0, c.0]));
}
/// With copy, a file that can't be shown stops the call before any file is copied into the
/// document's folder.
#[test]
fn relink_each_with_copy_copies_nothing_when_a_file_cant_be_read() {
let dir = Folder::new("relink-each-copy");
let (one, two) = (dir.file("doc/one.png"), dir.file("doc/two.png"));
write(&one, &png(60, 30, RED));
write(&two, &png(60, 30, RED));
let mut s = session();
let (a, c) = (place(&mut s, &one), place(&mut s, &two));
save(&mut s, &dir.file("doc/poster.vectorcraft"));
let (x, bad) = (dir.file("new/x.png"), dir.file("new/broken.png"));
write(&x, &png(60, 30, BLUE));
write(&bad, b"not an image");
let paths = json!([{"ids": [a.0], "path": x}, {"ids": [c.0], "path": bad}]);
assert!(s.execute("links.relink", &json!({"scope": "each", "paths": paths, "copy": true})).is_err());
assert!(!Path::new(&dir.file("doc/x.png")).exists(), "no copy is left behind");
assert_eq!(link_path(&s, a), one);
}
/// A scope or paths that doesn't fit is refused, and nothing is relinked.
#[test]
fn relink_refuses_scopes_and_paths_that_dont_fit() {
let dir = Folder::new("relink-bad-scope");
let pic = dir.file("photo.png");
write(&pic, &png(60, 30, RED));
let mut s = session();
let a = place(&mut s, &pic);
let blue = dir.file("blue.png");
write(&blue, &png(60, 30, BLUE));
let bad = [
json!({"ids": [a.0], "path": blue, "scope": "everything"}),
json!({"ids": [a.0], "path": blue, "scope": 3}),
json!({"scope": "each"}),
json!({"scope": "each", "paths": []}),
json!({"scope": "each", "paths": [{"ids": [a.0]}]}),
json!({"scope": "each", "paths": [{"path": blue}]}),
json!({"scope": "each", "paths": [{"ids": ["one"], "path": blue}]}),
json!({"scope": "each", "paths": [{"ids": [a.0], "path": blue}, {"ids": [a.0], "path": pic}]}),
json!({"scope": "each", "paths": [{"ids": [a.0], "path": blue}], "path": blue}),
json!({"scope": "each", "paths": [{"ids": [a.0], "path": blue}], "ids": [a.0]}),
json!({"scope": "all", "paths": [{"ids": [a.0], "path": blue}]}),
json!({"ids": [a.0], "paths": [{"ids": [a.0], "path": blue}]}),
json!({"ids": [a.0], "folder": dir.0.to_string_lossy(), "scope": "missingInFolder"}),
json!({"ids": [a.0], "scope": "missingInFolder"}),
];
for p in bad {
assert!(s.execute("links.relink", &p).is_err(), "{p}");
assert_eq!(link_path(&s, a), pic, "{p} relinks nothing");
}
}
/// A link stored as a classic Mac OS path (`Disk:Folder:file`, as older `.ai` files keep them) is
/// named by its last component: the Links panel shows that name and its folder, Relink to Folder
/// looks for that name, and the document's own folder is searched for it. The stored path is kept.
@@ -452,6 +794,63 @@ fn low_res_proxy_eps_export_uses_full_resolution_from_the_linked_file() {
assert!(near(centre_colour(&s.doc().unwrap().doc), RED), "canvas still shows the preview");
}
/// An SVG linking two missing files: once one of them is found, export reads its pixels into its
/// own images only, and the other file's image keeps its placeholder.
#[test]
fn export_reads_a_found_svg_link_into_its_own_images_only() {
let dir = Folder::new("svg-missing-keys");
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"><image href="a.png" width="20" height="20"/><image href="b.png" x="20" width="20" height="20"/></svg>"#;
let svg_path = dir.file("art.svg");
write(&svg_path, svg.as_bytes());
let mut s = session();
open(&mut s, &svg_path);
let mut found = vec![];
s.doc().unwrap().doc.visit_images(|_, im| found.push(im.clone()));
let [a, b] = &found[..] else { panic!("two images: {found:?}") };
assert!(a.link.as_ref().unwrap().path.ends_with("a.png") && b.link.as_ref().unwrap().path.ends_with("b.png"));
let placeholder = s.doc().unwrap().doc.images[&b.key].bytes.clone();
let bytes = png(20, 20, RED);
write(&dir.file("a.png"), &bytes);
let (full, warnings) = cmd::links::full_linked_images(&s.doc().unwrap().doc, None);
assert_eq!(warnings.len(), 1, "b.png is still missing: {warnings:?}");
assert_eq!(*full.images[&a.key].bytes, bytes, "a.png's pixels");
assert_eq!(full.images[&b.key].bytes, placeholder, "b.png keeps its placeholder");
}
/// An SVG linking two files with the same pixels, saved with previews only: once one file is gone
/// and the other has changed, export reads the changed file into its own images only.
#[test]
fn export_reads_a_changed_svg_link_into_its_own_images_only() {
let dir = Folder::new("svg-same-pixels");
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"><image href="a.png" width="20" height="20"/><image href="b.png" x="20" width="20" height="20"/></svg>"#;
let svg_path = dir.file("art.svg");
write(&svg_path, svg.as_bytes());
write(&dir.file("a.png"), &png(600, 300, RED));
write(&dir.file("b.png"), &png(600, 300, RED));
let mut s = session();
open(&mut s, &svg_path);
let doc_path = dir.file("art.vectorcraft");
save(&mut s, &doc_path);
std::fs::remove_file(dir.file("a.png")).unwrap();
let blue = png(600, 300, BLUE);
write(&dir.file("b.png"), &blue);
open(&mut s, &doc_path);
let mut found = vec![];
s.doc().unwrap().doc.visit_images(|_, im| found.push(im.clone()));
let [a, b] = &found[..] else { panic!("two images: {found:?}") };
assert!(a.link.as_ref().unwrap().path.ends_with("a.png") && b.link.as_ref().unwrap().path.ends_with("b.png"));
assert_ne!(a.key, b.key, "two files, two keys");
let doc = &s.doc().unwrap().doc;
assert!(doc.images[&a.key].is_proxy() && doc.images[&b.key].is_proxy(), "previews");
let preview = doc.images[&a.key].bytes.clone();
let (full, warnings) = cmd::links::full_linked_images(doc, None);
assert_eq!(warnings.len(), 1, "a.png is missing: {warnings:?}");
assert_eq!(*full.images[&b.key].bytes, blue, "b.png's new pixels");
assert_eq!(full.images[&a.key].bytes, preview, "a.png keeps its preview");
}
/// The half of opening that the desktop app runs on a thread of its own (`read_for_open`) reads
/// the linked files and lays out the type. The half left for the UI thread (`open_read`) reads no
/// file: with a linked file moved away in between, it opens the document that `document.open` opens.
+80 -5
View File
@@ -2,7 +2,7 @@
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::live::{self, BlendOrientation, BlendSpacing, EnvelopeKind};
use vectorcraft_doc::live::{self, BlendOrientation, BlendSpacing, EnvelopeKind, PreserveShape};
use vectorcraft_doc::{Node, NodeKind};
use vectorcraft_geom::{Point, Rect};
@@ -87,6 +87,12 @@ fn refuses_non_boolean(s: &mut Session, cmd: &str, p: &Value, key: &str) {
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == want), "{cmd} {p}: {r:?}");
}
/// `cmd` with `p` fails with the error `want`.
fn refuses_with(s: &mut Session, cmd: &str, p: &Value, want: &str) {
let r = s.execute(cmd, p);
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{cmd} {p}: {r:?}");
}
// ---------- Blend ----------
#[test]
@@ -231,13 +237,13 @@ fn blend_smooth_colour_steps_from_colour_distance() {
let mut s = session();
let (_, _, g) = blend(&mut s, json!({}));
let n = steps_of(&s, g).len() - 2;
assert_eq!(n, 128, "black→white: one step per two levels");
// Consecutive steps differ by at most ~2 levels.
assert_eq!(n, 254, "black→white: one step per level");
// Consecutive steps differ by about a level.
let st = steps_of(&s, g);
for w in st.windows(2) {
let x = w[0].appearance.fill_paint().color().unwrap().to_rgb()[0];
let y = w[1].appearance.fill_paint().color().unwrap().to_rgb()[0];
assert!((x - y).abs() <= 2.5 / 255.0);
assert!((x - y).abs() <= 1.5 / 255.0);
}
}
@@ -248,7 +254,9 @@ fn blend_smooth_colour_same_colours_uses_distance() {
let b = rect(&mut s, 40.0, 0.0, 10.0, 10.0);
sel(&mut s, &[a, b]);
let g = id_of(&s.execute("object.blend.make", &json!({"smooth": true})).unwrap());
assert_eq!(steps_of(&s, g).len() - 2, 20);
// The edges are 40 pt apart, 3.6 times the keys' 11 pt visible width (their 1 pt strokes
// included): rounded, less one.
assert_eq!(steps_of(&s, g).len() - 2, 3);
}
#[test]
@@ -745,6 +753,73 @@ fn envelope_options_refuse_a_boolean_given_as_text() {
assert!(matches!(&node(&s, warp).kind, NodeKind::Envelope { options, .. } if !options.anti_alias && options.distort_appearance));
}
/// Make with Warp, Reset with Warp and Envelope Options refuse a warp `style` that is not text or
/// names no warp, and an `orientation` other than horizontal or vertical: no envelope is made, a
/// warp envelope keeps its warp, and no undo step is added. Null is read as the key left out.
#[test]
fn envelope_warps_refuse_an_invalid_style_or_orientation() {
let mut s = session();
let a = text_rect(&mut s);
sel(&mut s, &[a]);
let n = undo_len(&s);
let calls = [
(json!({"style": 5}), "`style` must be a string"),
(json!({"style": ["arch"], "bend": 40}), "`style` must be a string"),
(json!({"style": "foo"}), "unknown warp style `foo`"),
(json!({"orientation": 1}), "`orientation` must be one of horizontal, vertical"),
(json!({"orientation": true, "horizontal": true}), "`orientation` must be one of horizontal, vertical"),
(json!({"orientation": "diagonal"}), "`orientation` must be one of horizontal, vertical"),
];
for (p, want) in &calls {
refuses_with(&mut s, "object.envelope.makeWithWarp", p, want);
}
assert_eq!(undo_len(&s), n, "nothing changed");
assert!(matches!(node(&s, a).kind, NodeKind::Path { .. }), "not enveloped");
let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": null, "orientation": null, "bend": 30})).unwrap());
assert!(matches!(&node(&s, e).kind, NodeKind::Envelope { kind, .. }
if matches!(&**kind, EnvelopeKind::Warp { style, horizontal: true, .. } if style == "arc")));
let (before, n) = (node(&s, e), undo_len(&s));
for cmd in ["object.envelope.resetWithWarp", "object.envelope.options"] {
for (p, want) in &calls {
refuses_with(&mut s, cmd, p, want);
}
}
assert_eq!((node(&s, e), undo_len(&s)), (before, n), "nothing changed");
s.execute("select.none", &json!({})).unwrap();
for (p, want) in &calls {
refuses_with(&mut s, "object.envelope.options", p, want);
}
sel(&mut s, &[e]);
s.execute("object.envelope.resetWithWarp", &json!({"style": "warp.flag", "orientation": "vertical"})).unwrap();
assert!(matches!(&node(&s, e).kind, NodeKind::Envelope { kind, .. }
if matches!(&**kind, EnvelopeKind::Warp { style, horizontal: false, .. } if style == "flag")));
}
/// Envelope Options refuses a `preserveShape` that is not text, for the selected envelope and for
/// the options new envelopes get, and changes neither; null keeps the current value.
#[test]
fn envelope_options_refuse_a_preserve_shape_that_is_not_text() {
let mut s = session();
let a = text_rect(&mut s);
sel(&mut s, &[a]);
let e = id_of(&s.execute("object.envelope.makeWithMesh", &json!({"rows": 2, "cols": 2})).unwrap());
let calls = [json!({"preserveShape": 1}), json!({"preserveShape": true, "antiAlias": false}), json!({"preserveShape": ["transparency"]})];
for ids in [vec![e], vec![]] {
sel(&mut s, &ids);
let before = (node(&s, e), undo_len(&s));
for p in &calls {
refuses_with(&mut s, "object.envelope.options", p, "`preserveShape` must be a string");
}
assert_eq!((node(&s, e), undo_len(&s)), before, "nothing changed with {ids:?} selected");
}
assert_eq!(s.envelope_defaults, None, "the options new envelopes get stayed");
sel(&mut s, &[e]);
s.execute("object.envelope.options", &json!({"preserveShape": "transparency"})).unwrap();
s.execute("object.envelope.options", &json!({"preserveShape": null, "antiAlias": false})).unwrap();
assert!(matches!(&node(&s, e).kind, NodeKind::Envelope { options, .. }
if options.preserve_shape == PreserveShape::Transparency && !options.anti_alias));
}
#[test]
fn envelope_renders_distorted() {
let mut s = session();
+57
View File
@@ -2087,6 +2087,63 @@ fn find_next_cycles_through_text_objects() {
assert!(s.execute("edit.findNext", &json!({"find": "zzz"})).unwrap()["id"].is_null());
}
/// The Type menu's commands and Find and Replace and Find Next refuse a param of the wrong type, or
/// `ids` that name no object, with an error naming the param, and leave the text, the selection and
/// the undo history as they were, even when Insert Character is also given a source it would use
/// first. Null counts as a param left out, which keeps its default.
#[test]
fn type_menu_and_find_commands_refuse_a_param_of_the_wrong_type() {
let mut s = session();
let t = text(&mut s, "\"cat\" -- cat catalog...");
let pid = s.execute("path.create", &json!({"d": "M100 300 L500 300"})).unwrap()["id"].as_u64().unwrap();
let r = s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": "cat", "size": 12, "at": [300, 310]})).unwrap();
let on_path = id_of(&r);
select_with_a_step_to_redo(&mut s, &[t, on_path]);
let before = (history(&s), plain(&s, t), plain(&s, on_path), selected(&s));
let string = |k: &str| format!("`{k}` must be a string");
let switch = |k: &str| format!("`{k}` must be true or false");
let scope = "`scope` must be one of selection, document".to_string();
let not_a_list = "ids must be an array of non-negative integer object ids".to_string();
let not_an_id = "invalid object id \"x\": expected a non-negative integer".to_string();
for (cmd, p, want) in [
("edit.findReplace", json!({"find": "cat", "replace": 5}), string("replace")),
("edit.findReplace", json!({"find": 5, "replace": "dog"}), string("find")),
("edit.findReplace", json!({"find": "CAT", "replace": "dog", "matchCase": "true"}), switch("matchCase")),
("edit.findReplace", json!({"find": "cat", "replace": "dog", "wholeWord": "yes"}), switch("wholeWord")),
("edit.findReplace", json!({"find": "cat", "replace": "dog", "ids": t.0}), not_a_list),
("edit.findReplace", json!({"find": "cat", "replace": "dog", "ids": [t.0, 999_999]}), "no such object id 999999".to_string()),
("edit.findReplace", json!({"find": "cat", "replace": "dog", "ids": ["x"]}), not_an_id),
("edit.findNext", json!({"find": ["cat"]}), string("find")),
("edit.findNext", json!({"find": "cat", "matchCase": 1}), switch("matchCase")),
("edit.findNext", json!({"find": "cat", "wholeWord": "false"}), switch("wholeWord")),
("type.smartPunctuation", json!({"dashes": "false"}), switch("dashes")),
("type.smartPunctuation", json!({"ellipsis": 0}), switch("ellipsis")),
("type.smartPunctuation", json!({"quotes": "no"}), switch("quotes")),
("type.smartPunctuation", json!({"scope": 5}), scope.clone()),
("type.smartPunctuation", json!({"scope": "page"}), scope),
("type.changeCase", json!({"case": 5}), string("case")),
("type.insert", json!({"char": 5}), string("char")),
("type.insert", json!({"text": 5}), string("text")),
("type.insert", json!({"unicode": 176}), string("unicode")),
("type.insert", json!({"char": "bullet", "unicode": 176}), string("unicode")),
("type.insert", json!({"text": "x", "code": "a"}), "`code` must be a whole number".to_string()),
("type.insert", json!({"text": "x", "code": 1.5}), "`code` must be a whole number".to_string()),
("type.pathOptions", json!({"flip": "true"}), switch("flip")),
("type.pathOptions", json!({"effect": 1}), string("effect")),
("type.pathOptions", json!({"alignToPath": true}), string("alignToPath")),
("type.pathOptions", json!({"spacing": "4"}), "`spacing` must be a number, not \"4\"".to_string()),
] {
let r = s.execute(cmd, &p);
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == want), "{cmd} {p}: {r:?}");
assert_eq!((history(&s), plain(&s, t), plain(&s, on_path), selected(&s)), before, "{cmd} {p}");
}
// `code: null` gives way to `unicode`, and null switches and ids take their defaults.
s.execute("type.insert", &json!({"code": null, "unicode": "00B0", "ids": [on_path.0]})).unwrap();
assert_eq!(plain(&s, on_path), "cat°");
let r = s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog", "matchCase": null, "wholeWord": null, "ids": null})).unwrap();
assert_eq!((r["count"].as_u64(), plain(&s, t), plain(&s, on_path)), (Some(4), "\"dog\" -- dog dogalog...".to_string(), "dog°".to_string()));
}
// ---------- Select ----------
#[test]
+40 -3
View File
@@ -185,16 +185,53 @@ fn recent_colors_are_fed_by_every_paint_command() {
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap();
assert_eq!(hexes(&s).len(), 3);
// The list holds the newest `RECENT_MAX` colours.
for i in 0..20u8 {
for i in 0..40u8 {
s.execute("paint.setFill", &json!({"color": Color::rgb8(i, 0, 0).to_hex()})).unwrap();
}
assert_eq!(s.recent_colors.len(), Session::RECENT_MAX);
assert_eq!(s.recent_colors[0].to_hex(), "#130000");
assert_eq!(s.recent_colors[0].to_hex(), "#270000");
let r = s.execute("paint.recent", &json!({})).unwrap();
assert_eq!(r["colors"][0]["hex"], "#130000");
assert_eq!(r["colors"][0]["hex"], "#270000");
let _ = id;
}
#[test]
fn recent_colors_keep_thirty_colors_across_documents() {
let mut s = session();
rect(&mut s);
let red = |i: u8| Color::rgb8(i, 0, 0).to_hex();
for i in 1..=30u8 {
s.execute("paint.setFill", &json!({"color": red(i)})).unwrap();
}
assert_eq!(Session::RECENT_MAX, 30);
let all: Vec<String> = (1..=30u8).rev().map(red).collect();
assert_eq!(hexes(&s), all, "30 colors are kept, newest first");
// The 31st drops the oldest.
s.execute("paint.setFill", &json!({"color": red(31)})).unwrap();
assert_eq!(hexes(&s).len(), 30);
assert_eq!(hexes(&s)[0], red(31));
assert_eq!(hexes(&s)[29], red(2));
assert!(!hexes(&s).contains(&red(1)), "the oldest color is dropped");
// Applying a color already in the list moves it to the front, once.
s.execute("paint.setStroke", &json!({"color": red(10)})).unwrap();
assert_eq!(hexes(&s).len(), 30);
assert_eq!(hexes(&s)[0], red(10));
assert_eq!(hexes(&s).iter().filter(|h| **h == red(10)).count(), 1);
let before = hexes(&s);
// A new document, and going back to the first one, keep the list.
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
assert_eq!(hexes(&s), before);
s.execute("document.activate", &json!({"index": 0})).unwrap();
assert_eq!(hexes(&s), before);
// A color applied in the second document joins the same list.
s.execute("document.activate", &json!({"index": 1})).unwrap();
rect(&mut s);
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
s.execute("document.activate", &json!({"index": 0})).unwrap();
assert_eq!(hexes(&s)[0], "#00ff00");
assert_eq!(hexes(&s)[1..], before[..29]);
}
#[test]
fn live_previews_remember_only_the_committed_colour() {
let mut s = session();
@@ -488,6 +488,35 @@ fn relink_points_a_placed_document_at_another_file() {
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
}
/// Missing Links from This Folder finds a missing placed document by name, except with copy, which
/// takes images only: the placed document then stays as it is.
#[test]
fn relink_missing_in_folder_finds_placed_documents_except_with_copy() {
let dir = Folder::new("placed-missing-folder");
let (doc_file, pic) = (dir.file("art/a.vectorcraft"), dir.file("art/photo.png"));
write(&pic, &crate::tests_links::png(60, 30, RED));
source(&doc_file, 100.0, 50.0, RED, 0);
let mut s = session();
let (placed_id, image_id) = (place(&mut s, &doc_file), place(&mut s, &pic));
let doc_path = dir.file("poster.vectorcraft");
save(&mut s, &doc_path);
std::fs::remove_file(&doc_file).unwrap();
std::fs::remove_file(&pic).unwrap();
open(&mut s, &doc_path);
let found = dir.0.join("found");
let chosen = found.join("renamed.png").to_string_lossy().into_owned();
write(&chosen, &crate::tests_links::png(60, 30, BLUE));
source(&found.join("a.vectorcraft").to_string_lossy(), 100.0, 50.0, BLUE, 0);
let p = json!({"ids": [image_id.0], "path": chosen, "scope": "missingInFolder", "copy": true});
let r = s.execute("links.relink", &p).unwrap();
assert_eq!(r["relinked"], json!([image_id.0]), "{r}");
assert_eq!(placed(&s, placed_id).link.path, doc_file, "copy leaves the placed document");
s.execute("edit.undo", &json!({})).unwrap();
let p = json!({"ids": [image_id.0], "path": chosen, "scope": "missingInFolder"});
let r = s.execute("links.relink", &p).unwrap();
assert_eq!(r["relinked"], json!([image_id.0, placed_id.0]), "{r}");
}
/// A file made from scratch at `path` in `format` (`pdf`, or `ai`: a PDF-compatible .ai): one
/// 100×50 page per color of `pages`, filled with it (`extra` more rectangles on each change the
/// file's size).
@@ -891,6 +920,36 @@ fn saving_a_document_refreshes_the_open_documents_that_place_it() {
assert_eq!(s.active_index(), Some(child), "the saved document stays active");
}
/// Placed documents inside a symbol and a pattern of another open document are read again when
/// their file is saved, as one in the layers is.
#[test]
fn saving_a_document_refreshes_its_placed_copies_inside_symbols_and_patterns() {
let dir = Folder::new("placed-refresh-nested");
let src = dir.file("logo.vectorcraft");
source(&src, 100.0, 50.0, RED, 0);
let mut s = session();
let id = place(&mut s, &src);
s.execute("symbol.new", &json!({"name": "Logo", "ids": [id.0]})).unwrap();
let id = place(&mut s, &src);
s.execute("object.pattern.make", &json!({"ids": [id.0], "edit": false})).unwrap();
s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap();
let parent = s.active_index().unwrap();
let mut in_layers = 0;
s.doc().unwrap().doc.walk(|n| in_layers += usize::from(matches!(n.kind, NodeKind::PlacedDocument(_))));
assert_eq!(in_layers, 0, "no placed document in the layers");
s.execute("document.open", &json!({"path": src})).unwrap();
s.execute("select.all", &json!({})).unwrap();
s.execute("paint.setFill", &json!({"color": "#1414e6"})).unwrap();
s.execute("document.save", &json!({})).unwrap();
let hash = Some(vectorcraft_doc::links::hash_bytes(&std::fs::read(&src).unwrap()));
let doc = &s.documents()[parent];
assert_eq!(doc.history.undo.last().unwrap().label, "Update Links");
assert!(near(centre_colour(&doc.doc), BLUE), "the symbol's instance shows the saved version");
let mut hashes = vec![];
doc.doc.visit_placed(|_, p| hashes.push(p.link.hash.clone()));
assert_eq!(hashes, [hash.clone(), hash], "the symbol's, then the pattern's");
}
#[test]
fn link_info_gives_the_artboards_size_not_pixels() {
let dir = Folder::new("placed-info");
+100
View File
@@ -747,6 +747,77 @@ fn granted_permissions_are_kept_and_folders_skip_the_rest() {
run(&mut granted, "plugin.remove", json!({"id": id}));
}
/// A grants file entry this version can't use (a permission it doesn't know, an invalid id) is
/// skipped without dropping the other grants, and recording a grant writes it back as it was,
/// except an entry for the plug-in being granted or removed. A grants file that doesn't parse as a
/// list is never overwritten.
#[test]
fn grants_this_version_cant_read_are_kept() {
let folder = crate::tests_links::Folder::new("plugin-store-grants-unknown");
let kept = "test.engine.permissions.kept";
let added = "test.engine.permissions.added";
let later = "test.engine.permissions.later";
let empty = json!({"objects": []});
let kept_wasm = asking(kept, r#"["doc.read"]"#, &empty);
let added_wasm = asking(added, r#"["doc.read"]"#, &empty);
let later_wasm = asking(later, r#"["doc.read"]"#, &empty);
let future = json!({"id": later, "hash": "00", "permissions": ["doc.read", "ui.panel"]});
let invalid = json!({"id": "bad id/", "hash": "00", "permissions": ["doc.read"]});
let grant = json!({"id": kept, "hash": vectorcraft_plugins::permissions::sha256_hex(&kept_wasm), "permissions": ["doc.read"]});
let grants = folder.0.join("grants.json");
std::fs::write(&grants, serde_json::to_vec(&json!([future, grant, invalid])).unwrap()).unwrap();
std::fs::write(folder.0.join("kept.wasm"), &kept_wasm).unwrap();
let entries = || serde_json::from_slice::<Vec<Value>>(&std::fs::read(&grants).unwrap()).unwrap();
let mut s = session();
s.attach_plugin_store(folder.0.clone());
assert!(vectorcraft_plugins::registry::get(kept).is_some(), "the entries this version can't read don't drop the grant next to them");
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm), "grant": ["doc.read"]}));
let now = entries();
assert_eq!(now.len(), 4, "{now:?}");
assert!(now.contains(&future) && now.contains(&invalid), "written back as they were: {now:?}");
assert!(now.iter().any(|e| e["id"] == added), "{now:?}");
run(&mut s, "plugin.remove", json!({"id": added}));
assert_eq!(entries().len(), 3);
// Granting the plug-in an entry names replaces that entry.
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&later_wasm), "grant": ["doc.read"]}));
let now = entries();
assert!(!now.contains(&future), "{now:?}");
assert_eq!(now.iter().filter(|e| e["id"] == later).count(), 1, "{now:?}");
run(&mut s, "plugin.remove", json!({"id": later}));
run(&mut s, "plugin.remove", json!({"id": kept}));
assert_eq!(entries(), vec![invalid.clone()], "the last usable grant removed leaves the entry it can't read");
// A file that doesn't hold a list is left as it is: installing still works in this session.
for broken in [&b"[{\"id\": "[..], &b"{\"id\": \"x\"}"[..]] {
std::fs::write(&grants, broken).unwrap();
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm), "grant": ["doc.read"]}));
assert!(vectorcraft_plugins::registry::get(added).is_some());
assert_eq!(std::fs::read(&grants).unwrap(), broken, "not overwritten");
run(&mut s, "plugin.remove", json!({"id": added}));
assert_eq!(std::fs::read(&grants).unwrap(), broken, "not overwritten by a removal either");
}
// The file stays within the 1 MiB it is read up to: compact when pretty-printing would pass it,
// and left as it is when even compact would.
let cap = 1 << 20;
let many: Vec<Value> = (0..14_000).map(|i| json!({"id": format!("x.{i}"), "hash": "00", "permissions": ["ui.panel"]})).collect();
let compact = serde_json::to_vec(&many).unwrap();
assert!(compact.len() < cap && serde_json::to_vec_pretty(&many).unwrap().len() > cap);
std::fs::write(&grants, &compact).unwrap();
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm), "grant": ["doc.read"]}));
let written = std::fs::read(&grants).unwrap();
assert!(written.len() <= cap, "{}", written.len());
assert_eq!(entries().len(), many.len() + 1);
let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm)}));
assert_eq!(inspected["needsApproval"], json!(false), "the compact file is read back");
run(&mut s, "plugin.remove", json!({"id": added}));
let full = serde_json::to_vec(&json!([{"id": "x.full", "hash": "0".repeat(cap - 100), "permissions": ["ui.panel"]}])).unwrap();
std::fs::write(&grants, &full).unwrap();
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm), "grant": ["doc.read"]}));
assert_eq!(std::fs::read(&grants).unwrap(), full, "not written past the cap");
run(&mut s, "plugin.remove", json!({"id": added}));
}
/// The user agreed once: a heavy filter kept in the plug-in store is installed again at the next
/// start without asking, with its budget.
#[test]
@@ -840,6 +911,35 @@ fn a_filter_run_made_elsewhere_keeps_its_document_data() {
assert_eq!(s.doc().unwrap().doc.plugin_data(id), Some(&json!({"pens": 2})), "undone with its objects");
}
/// A plug-in of API level 2 that uses the host imports lists `progress`, which the user grants like
/// any permission; a filter run made elsewhere then reports its progress, as a share, to the
/// progress the caller shows, and sees the caller's Cancel.
#[test]
fn a_level_2_filter_installs_with_progress_granted_and_reports_to_the_caller() {
use crate::cmd::fileio::progress::{self, Progress};
use crate::cmd::plugin::FilterRun;
let mut s = session();
let id = "test.engine.level2";
let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["doc.read","doc.write","progress"]}}"#);
let wasm = wat::parse_str(tpl::cooperating(&manifest, 1000, r#"{"objects":[]}"#, r#"{"objects":[]}"#)).unwrap();
let data = vectorcraft_format::base64_encode(&wasm);
let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": data}));
assert_eq!((&inspected["needsApproval"], &inspected["permissions"]), (&json!(true), &json!(["doc.read", "doc.write", "progress"])));
let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read", "doc.write"]})).unwrap_err().to_string();
assert!(e.contains("asks for the permissions doc.read, doc.write, progress"), "{e}");
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read", "doc.write", "progress"]}));
let shown = Progress::new();
let r = FilterRun::prepare(&s, &json!({"id": id})).unwrap();
assert!(progress::scope(&shown, || r.run()).is_ok());
assert_eq!((shown.counts(), shown.counts_share()), ((999, 1000), true));
// Cancelled, it stops on its first step, and what it returns then is discarded.
shown.cancel();
let cancelled = progress::scope(&shown, || r.run());
assert!(matches!(cancelled, Err(EngineError::Cancelled)), "{cancelled:?}");
assert_eq!(shown.counts(), (0, 1000));
run(&mut s, "plugin.remove", json!({"id": id}));
}
/// A filter run the caller cancels (MCP's `notifications/cancelled`, the app's Cancel) stops between
/// two slices of its budget and changes nothing.
#[test]
+340
View File
@@ -814,6 +814,37 @@ fn invoke_distance_guides_measures_the_selection_to_the_object_under_alt() {
assert!(shown(&mut s, v).is_empty(), "Invoke Distance Guides off");
}
/// Smart Guides › Snap to Last Location (off by default): on, a square dragged 6 pt right and 5 pt
/// down with a 10 px Snapping Tolerance goes back to where it was; dragged 12 pt away, or with the
/// option or View › Smart Guides off, it lands where it is dragged. A value that is not a boolean
/// is refused.
#[test]
fn snap_to_last_location_puts_a_dragged_square_back() {
use vectorcraft_tools::PointerKind::{Down, Drag, Up};
let mut s = new_doc();
// Its edges and center stay out of reach of the 400 pt artboard's.
let m = square(&mut s, 100.0, 250.0);
let v = ViewInfo::default();
s.select_tool("selection", v).unwrap();
let drag = |s: &mut Session, v: ViewInfo, to: (f64, f64)| {
gesture(s, v, &[(Down, 125.0, 275.0), (Drag, 140.0, 290.0), (Drag, to.0, to.1), (Up, to.0, to.1)]);
let at = top_left(s, m);
if at != (100.0, 250.0) {
s.execute("edit.undo", &json!({})).unwrap();
}
at
};
set_pref(&mut s, "snappingTolerance", json!(10));
assert_eq!(drag(&mut s, v, (131.0, 280.0)), (106.0, 255.0), "off by default");
set_pref(&mut s, "snapToLastLocation", json!(true));
assert_eq!(drag(&mut s, v, (131.0, 280.0)), (100.0, 250.0), "7.8 pt away: back where it was");
assert_eq!(drag(&mut s, v, (134.0, 283.0)), (109.0, 258.0), "12 pt away");
assert_eq!(drag(&mut s, ViewInfo { smart_guides: false, ..v }, (131.0, 280.0)), (106.0, 255.0), "View › Smart Guides off");
let refused = s.execute("prefs.set", &json!({"key": "snapToLastLocation", "value": "yes"}));
assert!(refused.is_err(), "{refused:?}");
assert_eq!(s.execute("prefs.get", &json!({"key": "snapToLastLocation"})).unwrap(), json!(true), "unchanged");
}
/// Preferences › Smart Guides (#394): Color, Alignment Guides, Anchor/Path Labels, Measurement
/// Labels, Transform Tools and Snapping Tolerance change what the Selection tool shows while a
/// square is dragged into line with another, and how far the pull reaches; a hidden guide still
@@ -1936,6 +1967,315 @@ fn real_time_drawing_off_draws_the_bounds_of_a_selection_too_big_to_outline() {
assert!(moved.0 > 1.0 && moved.1 > 1.0 && moved.2.abs() < 1e-6 && moved.3.abs() < 1e-6, "the bounds moved with the drag: {moved:?}");
}
/// The bounding boxes (left, top, width) of the Real-time Drawing off feedback after a drag by (30, 40)
/// from (x, y), left to right.
fn dragged_feedback_boxes(s: &mut Session, x: f64, y: f64) -> Vec<(f64, f64, f64)> {
use vectorcraft_tools::Overlay;
use vectorcraft_tools::draw2::FEEDBACK;
let v = ViewInfo::default();
s.select_tool("selection", v).unwrap();
set_pref(s, "realTimeDrawing", json!(false));
s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, x + 30.0, y + 40.0), v).unwrap();
let mut boxes: Vec<_> = s
.overlays(v)
.into_iter()
.filter_map(|o| match o {
Overlay::Path { path, color, .. } if color == FEEDBACK => Some(kurbo::Shape::bounding_box(&path)),
_ => None,
})
.map(|b| ((b.x0 * 1e3).round() / 1e3, (b.y0 * 1e3).round() / 1e3, (b.width() * 1e3).round() / 1e3))
.collect();
boxes.sort_by(|p, q| p.0.total_cmp(&q.0));
boxes
}
/// The number of subpaths in each path of the Real-time Drawing off feedback the session shows now.
fn feedback_subpaths(s: &mut Session) -> Vec<usize> {
use vectorcraft_tools::Overlay;
use vectorcraft_tools::draw2::FEEDBACK;
s.overlays(ViewInfo::default())
.into_iter()
.filter_map(|o| match o {
Overlay::Path { path, color, .. } if color == FEEDBACK => {
Some(path.elements().iter().filter(|el| matches!(el, kurbo::PathEl::MoveTo(_))).count())
}
_ => None,
})
.collect()
}
/// With Real-time Drawing off, a dragged group draws the outline of each member, nested groups'
/// members included, at the dragged position instead of one union of them all.
#[test]
fn real_time_drawing_off_outlines_a_dragged_group_member_by_member() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let rect = |s: &mut Session, x: f64| s.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
let (a, b, c) = (rect(&mut s, 100.0), rect(&mut s, 150.0), rect(&mut s, 200.0));
s.execute("select.set", &json!({"ids": [b, c]})).unwrap();
let inner = s.execute("object.group", &json!({})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [a, inner]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
let boxes = dragged_feedback_boxes(&mut s, 120.0, 120.0);
assert_eq!(boxes, [(130.0, 140.0, 100.0), (180.0, 140.0, 100.0), (230.0, 140.0, 100.0)], "one moved outline per member");
}
/// With Real-time Drawing off, a hidden member of a dragged group draws no outline.
#[test]
fn real_time_drawing_off_skips_a_hidden_member_of_a_dragged_group() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let rect = |s: &mut Session, x: f64| s.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
let (a, b, c) = (rect(&mut s, 100.0), rect(&mut s, 150.0), rect(&mut s, 200.0));
s.execute("select.set", &json!({"ids": [b]})).unwrap();
s.execute("object.hide", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
let boxes = dragged_feedback_boxes(&mut s, 120.0, 120.0);
assert_eq!(boxes, [(130.0, 140.0, 100.0), (230.0, 140.0, 100.0)]);
}
/// With Real-time Drawing off, a dragged blend draws the outline of each of its objects and steps.
#[test]
fn real_time_drawing_off_outlines_a_dragged_blend_step_by_step() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let a = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
let b = s.execute("shape.rectangle", &json!({"x": 300, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("object.blend.make", &json!({"steps": 3})).unwrap();
let lefts: Vec<f64> = dragged_feedback_boxes(&mut s, 120.0, 120.0).iter().map(|b| b.0).collect();
assert_eq!(lefts, [130.0, 180.0, 230.0, 280.0, 330.0], "one moved outline per blended object and step");
}
/// With Real-time Drawing off, a dragged compound shape draws the outline of the area it makes.
#[test]
fn real_time_drawing_off_outlines_a_dragged_compound_shape_by_its_area() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let a = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
let b = s.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let shape = s.execute("object.compoundShape.make", &json!({"mode": "intersect"})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [shape]})).unwrap();
assert_eq!(dragged_feedback_boxes(&mut s, 170.0, 120.0), [(180.0, 140.0, 50.0)]);
}
/// With Real-time Drawing off, a dragged group with a Pathfinder effect draws the outline of the area
/// the effect makes.
#[test]
fn real_time_drawing_off_outlines_a_dragged_pathfinder_group_by_its_area() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let a = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
let b = s.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.execute("effect.apply", &json!({"effect": "pathfinder.intersect"})).unwrap();
assert_eq!(dragged_feedback_boxes(&mut s, 170.0, 120.0), [(180.0, 140.0, 50.0)]);
}
/// With Real-time Drawing off, a dragged group with a Drop Shadow draws the outline of each member
/// instead of one union of them.
#[test]
fn real_time_drawing_off_outlines_a_dragged_group_with_an_effect_member_by_member() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let a = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
let b = s.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "item": null})).unwrap();
assert_eq!(dragged_feedback_boxes(&mut s, 120.0, 120.0), [(130.0, 140.0, 100.0), (180.0, 140.0, 100.0)]);
}
/// With Real-time Drawing off, a dragged clip group draws only its clipping path, as its selection
/// highlight does.
#[test]
fn real_time_drawing_off_outlines_a_dragged_clip_group_by_its_clipping_path() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let art = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 200, "height": 100})).unwrap()["id"].clone();
let clip = s.execute("shape.rectangle", &json!({"x": 120, "y": 110, "width": 50, "height": 50})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [art, clip]})).unwrap();
s.execute("object.clippingMask.make", &json!({})).unwrap();
assert_eq!(dragged_feedback_boxes(&mut s, 140.0, 130.0), [(150.0, 150.0, 50.0)]);
}
/// With Real-time Drawing off, a dragged envelope draws the outline of each object it evaluates to: each
/// rectangle's fill and its outlined stroke.
#[test]
fn real_time_drawing_off_outlines_a_dragged_envelope_object_by_object() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let a = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
let b = s.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("object.envelope.makeWithMesh", &json!({"rows": 1, "cols": 1})).unwrap();
let boxes = dragged_feedback_boxes(&mut s, 120.0, 120.0);
assert_eq!(boxes, [(129.5, 139.5, 101.0), (130.0, 140.0, 100.0), (179.5, 139.5, 101.0), (180.0, 140.0, 100.0)]);
}
/// With Real-time Drawing off, a dragged Shaper group draws the outline of its result and not of the
/// source art it keeps.
#[test]
fn real_time_drawing_off_skips_the_source_art_of_a_dragged_shaper_group() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap();
s.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap();
let points = [[125.0, 120.0], [175.0, 135.0], [130.0, 150.0], [225.0, 165.0], [175.0, 180.0], [225.0, 185.0]];
let shaper = s.execute("shaper.scribble", &json!({"points": points})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [shaper]})).unwrap();
let boxes = dragged_feedback_boxes(&mut s, 120.0, 120.0);
assert_eq!(boxes, [(130.0, 140.0, 150.0), (130.0, 140.0, 150.0)], "the merged result's fill and stroke");
}
/// With Real-time Drawing off, a dragged symbol instance draws the bounds its selection highlight
/// shows, alone and as a member of a group.
#[test]
fn real_time_drawing_off_outlines_a_dragged_symbol_instance_by_its_bounds() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let a = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [a]})).unwrap();
s.execute("symbol.new", &json!({"name": "Box"})).unwrap();
assert_eq!(dragged_feedback_boxes(&mut s, 120.0, 120.0), [(130.0, 140.0, 100.0)]);
s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 160.0), ViewInfo::default()).unwrap();
s.execute("shape.rectangle", &json!({"x": 400, "y": 100, "width": 50, "height": 50})).unwrap();
s.execute("select.all", &json!({})).unwrap();
s.execute("object.group", &json!({})).unwrap();
assert_eq!(dragged_feedback_boxes(&mut s, 150.0, 160.0), [(160.0, 180.0, 100.0), (430.0, 140.0, 50.0)]);
}
/// With Real-time Drawing off, a handle resize of a group draws each member's outline at its new size.
#[test]
fn real_time_drawing_off_outlines_a_resized_group_member_by_member() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let a = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
let b = s.execute("shape.rectangle", &json!({"x": 300, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
// The Right handle, dragged 30 pt out: the group goes from 300 pt wide to 330.
assert_eq!(dragged_feedback_boxes(&mut s, 400.0, 125.0), [(100.0, 100.0, 110.0), (320.0, 100.0, 110.0)]);
}
/// With Real-time Drawing off, each copy of a gradient mesh in a dragged repeat draws its mesh lines
/// once, without the pieces the mesh is drawn with.
#[test]
fn real_time_drawing_off_outlines_each_mesh_of_a_dragged_repeat_once() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let a = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [a]})).unwrap();
s.execute("object.mesh.create", &json!({"rows": 2, "cols": 2})).unwrap();
s.execute("object.repeat.grid", &json!({"rows": 1, "cols": 2})).unwrap();
let boxes = dragged_feedback_boxes(&mut s, 120.0, 120.0);
assert_eq!(boxes.len(), 2, "one outline per copy: {boxes:?}");
assert_eq!(boxes[0], (130.0, 140.0, 100.0), "the first copy's mesh lines, moved");
let subpaths = feedback_subpaths(&mut s);
assert!(subpaths.len() == 2 && subpaths.iter().all(|&n| n > 1), "each copy's mesh lines, not one boundary: {subpaths:?}");
}
/// With Real-time Drawing off, a dragged gradient mesh with a Drop Shadow draws its mesh lines as one
/// outline, without the pieces the mesh is drawn with.
#[test]
fn real_time_drawing_off_outlines_a_dragged_mesh_with_an_effect_by_its_lines() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let a = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [a]})).unwrap();
s.execute("object.mesh.create", &json!({"rows": 2, "cols": 2})).unwrap();
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "item": null})).unwrap();
assert_eq!(dragged_feedback_boxes(&mut s, 120.0, 120.0), [(130.0, 140.0, 100.0)]);
let subpaths = feedback_subpaths(&mut s);
assert!(matches!(subpaths.as_slice(), [n] if *n > 1), "the mesh's lines, not one boundary: {subpaths:?}");
}
/// With Real-time Drawing off, a dragged group with a Vector Halftone keeps its own fill, which is what
/// the effect samples, so an unpainted member still gives an outline.
#[test]
fn real_time_drawing_off_outlines_a_dragged_halftone_group_with_its_own_fill() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let a = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"ids": [a], "none": true})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [a], "none": true})).unwrap();
s.execute("select.set", &json!({"ids": [a]})).unwrap();
let group = s.execute("object.group", &json!({})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"color": "#000000", "ids": []})).unwrap();
s.execute("select.set", &json!({"ids": [group]})).unwrap();
s.execute("appearance.addFill", &json!({})).unwrap();
let fill = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(group.as_u64().unwrap())).unwrap().appearance.fill_paint().label();
assert_eq!(fill, "#000000", "the group's own fill");
s.execute("effect.apply", &json!({"effect": "addon.color.halftone", "item": null})).unwrap();
// The Right handle: the unpainted member gives nothing to press on.
assert!(!dragged_feedback_boxes(&mut s, 200.0, 150.0).is_empty(), "the halftone's dots are outlined");
}
/// With Real-time Drawing off, a dragged object with Crop Marks draws the object's outline without its
/// marks.
#[test]
fn real_time_drawing_off_outlines_a_dragged_object_without_its_crop_marks() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let a = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [a]})).unwrap();
s.execute("effect.apply", &json!({"effect": "cropMarks", "item": null})).unwrap();
assert_eq!(dragged_feedback_boxes(&mut s, 120.0, 120.0), [(130.0, 140.0, 100.0)]);
}
/// With Real-time Drawing off, the objects a dragged repeat evaluates to count toward the limit with
/// the points of their outlines: 18,000 rectangles have 90,000 points, and with the objects they come
/// to 108,000.
#[test]
fn real_time_drawing_off_draws_the_bounds_of_a_repeat_with_too_many_objects() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let a = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [a]})).unwrap();
s.execute("object.repeat.grid", &json!({"rows": 120, "cols": 150})).unwrap();
let boxes = dragged_feedback_boxes(&mut s, 105.0, 105.0);
assert_eq!(boxes.len(), 1, "one bounds rectangle: {} boxes", boxes.len());
}
/// With Real-time Drawing off, a dragged intertwine draws the outline of each member, without the
/// area one of them is arranged over the other in.
#[test]
fn real_time_drawing_off_outlines_a_dragged_intertwine_member_by_member() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let a = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
let b = s.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 100, "height": 50})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("object.intertwine.make", &json!({})).unwrap();
s.execute("object.intertwine.arrange", &json!({"at": [175, 125], "order": "back"})).unwrap();
let boxes = dragged_feedback_boxes(&mut s, 120.0, 120.0);
assert_eq!(boxes, [(130.0, 140.0, 100.0), (180.0, 140.0, 100.0)]);
}
/// With Real-time Drawing off, a dragged group whose members have more than 100,000 points between
/// them shows its moved bounds, as a single path of that size does.
#[test]
fn real_time_drawing_off_draws_the_bounds_of_a_group_too_big_to_outline() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let path = |s: &mut Session, y: f64| {
let anchors: Vec<Value> =
(0..60_000).map(|i| json!({"x": 100.0 + f64::from(i) * 0.003, "y": if i % 2 == 0 { y } else { y + 50.0 }})).collect();
s.execute("path.create", &json!({"anchors": anchors, "closed": false})).unwrap()["id"].clone()
};
let (a, b) = (path(&mut s, 100.0), path(&mut s, 200.0));
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
let at_rest = s.doc().unwrap().doc.bounds_of(&s.doc().unwrap().selection.objects, true).unwrap();
let boxes = dragged_feedback_boxes(&mut s, 200.0, 100.0);
let [(x, y, width)] = boxes.as_slice() else { panic!("one bounds rectangle, got {boxes:?}") };
assert!((x - at_rest.x0 - 30.0).abs() < 1e-2 && (y - at_rest.y0 - 40.0).abs() < 1e-2 && (width - at_rest.width()).abs() < 1e-2, "{boxes:?}");
}
/// A deferred commit that fails its preview cancels the interaction instead of leaving it open.
#[test]
fn deferred_commit_preview_failure_cancels_interaction() {
+1 -1
View File
@@ -140,7 +140,7 @@ fn pipes_and_folders_are_not_read() {
let direct = s.execute("script.check", &json!({ "path": pipe })).map_err(|e| e.to_string());
let _ = tx.send((included.map_err(|e| e.to_string()), direct));
});
let (included, direct) = rx.recv_timeout(std::time::Duration::from_secs(20)).expect("the checks return");
let (included, direct) = rx.recv_timeout(std::time::Duration::from_secs(300)).expect("the checks return");
let statuses: Vec<String> = included.unwrap().as_array().unwrap().iter().map(|i| i["status"].as_str().unwrap().to_string()).collect();
assert_eq!(statuses, ["missing", "missing"]);
assert!(direct.is_err_and(|e| e.contains("not a file")));
+271 -2
View File
@@ -3,7 +3,7 @@
//! document's colour mode.
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_color::{Color, Paint};
use crate::*;
@@ -125,6 +125,275 @@ fn add_used_colors_skips_colours_that_have_swatches() {
assert!(doc(&s).swatch("R=171 G=205 B=239").unwrap().global);
}
/// Give `id` the fill `p` exactly as written (a command would round or convert some colors).
fn set_fill(s: &mut Session, id: NodeId, p: Paint) {
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().appearance.set_fill(p);
}
/// Rectangles filled with repeated colors, near-equal colors that get the same name, a color and
/// its twin with a -0.0 component, a color whose name a swatch already has, and colors two
/// swatches already have (one of them through -0.0). Returns the rectangles in paint order.
fn used_colors_doc(s: &mut Session) -> Vec<NodeId> {
run(s, "swatch.new", json!({"name": "Gray K=33", "color": "#00ff00"}));
run(s, "swatch.new", json!({"name": "Zeroed", "color": "#0080ff"}));
let red = doc(s).swatch("Red").unwrap().paint.color().unwrap();
let colors = [
Color::rgb(0.2, 0.4, 0.6),
Color::rgb(0.2, 0.4, 0.6),
Color::rgb(0.2, 0.4, 0.6001),
Color::rgb(0.0, 0.4, 0.6),
Color::rgb(-0.0, 0.4, 0.6),
Color::gray(0.33),
Color::gray(0.3301),
red,
Color::rgb(-0.0, 128.0 / 255.0, 1.0),
Color::rgb(0.2, 0.4, 0.6001),
];
colors
.into_iter()
.map(|c| {
let id = rect_filled(s, json!({"color": "#000000"}));
set_fill(s, id, Paint::solid(c));
id
})
.collect()
}
const USED_NAMES: [&str; 5] = ["R=51 G=102 B=153", "R=51 G=102 B=153 2", "R=0 G=102 B=153", "Gray K=33 2", "Gray K=33 3"];
#[test]
fn add_used_colors_adds_each_new_color_once_with_free_names() {
let mut s = session();
used_colors_doc(&mut s);
let before = doc(&s).clone();
let undo = undo_len(&s);
let r = run(&mut s, "swatch.addUsedColors", json!({}));
assert_eq!(r, json!({"added": USED_NAMES, "linked": 0}));
assert_eq!(names(&s, None)[names(&s, None).len() - 5..], USED_NAMES);
let color = |n: &str| doc(&s).swatch(n).unwrap().paint.color().unwrap();
assert_eq!(color("R=51 G=102 B=153 2"), Color::rgb(0.2, 0.4, 0.6001));
assert_eq!(color("Gray K=33 3"), Color::gray(0.3301));
assert_eq!(undo_len(&s), undo + 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!(*doc(&s), before);
}
#[test]
fn add_used_colors_global_links_every_paint_of_a_new_color() {
let mut s = session();
let ids = used_colors_doc(&mut s);
let r = run(&mut s, "swatch.addUsedColors", json!({"global": true}));
assert_eq!(r, json!({"added": USED_NAMES, "linked": 8}));
let link = |s: &Session, id: NodeId| match fill(s, id) {
Paint::Solid { swatch, .. } => swatch,
p => panic!("{p:?}"),
};
// The index in USED_NAMES of the swatch each rectangle links to.
let want = [Some(0), Some(0), Some(1), Some(2), Some(2), Some(3), Some(4), None, None, Some(1)];
let got: Vec<Option<String>> = ids.iter().map(|id| link(&s, *id)).collect();
assert_eq!(got, want.map(|i: Option<usize>| i.map(|i| USED_NAMES[i].to_string())));
assert!(USED_NAMES.iter().all(|n| doc(&s).swatch(n).unwrap().global));
}
/// A paint linked to Registration keeps its link when a new global swatch has the same color.
#[test]
fn add_used_colors_global_leaves_registration_links_alone() {
let mut s = session();
let reg_paint = Paint::Solid { color: Color::cmyk(1.0, 1.0, 1.0, 1.0), swatch: Some(vectorcraft_color::swatch::REGISTRATION.into()), tint: 1.0 };
let registration = rect_filled(&mut s, json!({"color": "#000000"}));
set_fill(&mut s, registration, reg_paint.clone());
let plain = rect_filled(&mut s, json!({"color": "#000000"}));
set_fill(&mut s, plain, Paint::solid(Color::cmyk(1.0, 1.0, 1.0, 1.0)));
let r = run(&mut s, "swatch.addUsedColors", json!({"global": true}));
assert_eq!(r["linked"], json!(1), "{r}");
let name = r["added"][0].as_str().unwrap().to_string();
assert_eq!(fill(&s, registration), reg_paint);
assert_eq!(fill(&s, plain), Paint::Solid { color: Color::cmyk(1.0, 1.0, 1.0, 1.0), swatch: Some(name), tint: 1.0 });
}
#[test]
fn unused_matches_links_tints_colors_gradients_and_patterns_exactly() {
let mut s = session();
run(&mut s, "swatch.edit", json!({"name": "Teal", "global": true}));
run(&mut s, "swatch.new", json!({"swatch": "Teal", "tint": 40}));
run(&mut s, "swatch.new", json!({"swatch": "Teal", "tint": 70}));
run(&mut s, "swatch.new", json!({"name": "Zeroed", "color": "#0080ff"}));
let teal = doc(&s).swatch("Teal").unwrap().paint.color().unwrap();
let tinted = rect_filled(&mut s, json!({"color": "#000000"}));
set_fill(&mut s, tinted, Paint::Solid { color: teal.tinted(0.4), swatch: Some("Teal".into()), tint: 0.4 });
let zero = rect_filled(&mut s, json!({"color": "#000000"}));
set_fill(&mut s, zero, Paint::solid(Color::rgb(-0.0, 128.0 / 255.0, 1.0)));
// Sunset's gradient without a link to it, beside gradients with Sunset's stop colors and a
// different midpoint or opacity; Ocean's with one stop moved, and Ocean's with another kind,
// method or dither.
let gradient = |s: &Session, n: &str| match &doc(s).swatch(n).unwrap().paint {
Paint::Gradient(g) => g.gradient.clone(),
p => panic!("{p:?}"),
};
let sunset = gradient(&s, "Sunset");
let (mut midpoint, mut opacity) = (sunset.clone(), sunset.clone());
midpoint.stops[0].midpoint = 0.3;
opacity.stops[1].opacity = 0.5;
let ocean = gradient(&s, "Ocean");
let (mut moved, mut radial, mut perceptual, mut dither) = (ocean.clone(), ocean.clone(), ocean.clone(), ocean);
moved.stops[0].offset += 0.25;
radial.kind = vectorcraft_color::GradientKind::Radial;
perceptual.method = vectorcraft_color::GradientMethod::Perceptual;
dither.dither = true;
for g in [midpoint, sunset.clone(), opacity, sunset, moved, radial, perceptual, dither] {
let id = rect_filled(&mut s, json!({"color": "#000000"}));
set_fill(&mut s, id, Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(g))));
}
let r = rect_filled(&mut s, json!({"color": "#ff0000"}));
run(&mut s, "select.set", json!({"ids": [r.0]}));
run(&mut s, "object.pattern.make", json!({"name": "Dots", "width": 20, "height": 20}));
run(&mut s, "object.pattern.done", json!({}));
rect_filled(&mut s, json!({"swatch": "Dots"}));
let names = run(&mut s, "swatch.unused", json!({}))["names"].clone();
let names: Vec<&str> = names.as_array().unwrap().iter().filter_map(Value::as_str).collect();
for used in ["Teal", "Teal 40%", "Zeroed", "Sunset", "Dots"] {
assert!(!names.contains(&used), "{used} is used: {names:?}");
}
for unused in ["Teal 70%", "Ocean", "Orange", "Red"] {
assert!(names.contains(&unused), "{unused} is unused: {names:?}");
}
}
#[test]
fn new_swatches_from_colors_are_numbered_after_names_already_taken() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "R=255 G=0 B=0 2", "color": "#0000ff"}));
run(&mut s, "swatch.newGroup", json!({"name": "Mine"}));
let before = doc(&s).clone();
let undo = undo_len(&s);
// Near-equal colors with the same name, and a Lab color and its twin with a -0.0 component.
let colors = json!([
"#ff0000",
"#ff0000",
"#ff0000",
"#00ff00",
"#00ff00",
[0.2, 0.4, 0.6],
[0.2, 0.4, 0.6001],
{"l": 50, "a": 0.0, "b": 0},
{"l": 50, "a": -0.0, "b": 0}
]);
let r = run(&mut s, "swatch.new", json!({ "colors": colors }));
let want = [
"R=255 G=0 B=0",
"R=255 G=0 B=0 3",
"R=255 G=0 B=0 4",
"R=0 G=255 B=0",
"R=0 G=255 B=0 2",
"R=51 G=102 B=153",
"R=51 G=102 B=153 2",
"L=50 a=0 b=0",
"L=50 a=0 b=0 2",
];
assert_eq!(r, json!({"name": want[0], "names": want}));
assert_eq!(names(&s, None)[names(&s, None).len() - want.len()..], want);
assert!(matches!(doc(&s).swatch("L=50 a=0 b=0 2").unwrap().paint.color(), Some(Color::Lab { a, .. }) if a.is_sign_negative()));
assert_eq!(undo_len(&s), undo + 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!(*doc(&s), before);
let r = run(&mut s, "swatch.new", json!({"colors": ["#ff0000", "#ff0000", "#ff0000"]}));
assert_eq!(r["names"], json!(["R=255 G=0 B=0", "R=255 G=0 B=0 3", "R=255 G=0 B=0 4"]));
let r = run(&mut s, "swatch.new", json!({"colors": ["#ff0000", "#ff0000"], "group": "Mine"}));
assert_eq!(r["names"], json!(["R=255 G=0 B=0 5", "R=255 G=0 B=0 6"]));
assert_eq!(names(&s, Some("Mine")), ["R=255 G=0 B=0 5", "R=255 G=0 B=0 6"]);
}
#[test]
fn new_color_group_numbers_its_colors_after_the_group_and_its_moved_swatches() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "R=255 G=0 B=0 2", "color": "#0000ff"}));
let r = run(
&mut s,
"swatch.newGroup",
json!({"name": "R=255 G=0 B=0", "swatches": ["R=255 G=0 B=0 2"], "colors": ["#ff0000", "#ff0000", "#00ff00", "#ff0000"]}),
);
let want = ["R=255 G=0 B=0 2", "R=255 G=0 B=0 3", "R=255 G=0 B=0 4", "R=0 G=255 B=0", "R=255 G=0 B=0 5"];
assert_eq!(r, json!({"name": "R=255 G=0 B=0", "swatches": want, "linked": 0}));
}
/// New Color Group from artwork lists each color once in paint order: a repeat and a twin with a
/// -0.0 component are the same color, near-equal colors with the same name are numbered after the
/// names already taken, and a paint linked to Registration brings no color. One undo step.
#[test]
fn new_color_group_from_artwork_lists_each_color_once_with_free_names() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "R=0 G=102 B=153", "color": "#00ff00"}));
let colors = [
Color::rgb(0.2, 0.4, 0.6),
Color::rgb(0.0, 0.4, 0.6),
Color::rgb(0.2, 0.4, 0.6001),
Color::rgb(-0.0, 0.4, 0.6),
Color::rgb(0.2, 0.4, 0.6),
Color::lab(50.0, 0.0, 0.0),
Color::lab(50.0, -0.0, 0.0),
Color::lab(50.0, 0.0001, 0.0),
];
let mut ids: Vec<u64> = vec![];
for c in colors {
let id = rect_filled(&mut s, json!({"color": "#000000"}));
set_fill(&mut s, id, Paint::solid(c));
ids.push(id.0);
}
let registration = rect_filled(&mut s, json!({"color": "#000000"}));
let reg_paint = Paint::Solid { color: Color::cmyk(1.0, 1.0, 1.0, 1.0), swatch: Some(vectorcraft_color::swatch::REGISTRATION.into()), tint: 1.0 };
set_fill(&mut s, registration, reg_paint);
ids.push(registration.0);
run(&mut s, "select.set", json!({ "ids": ids }));
let before = doc(&s).clone();
let undo = undo_len(&s);
let r = run(&mut s, "swatch.newGroup", json!({"name": "R=51 G=102 B=153 2", "fromArtwork": true}));
let want = ["R=51 G=102 B=153", "R=0 G=102 B=153 2", "R=51 G=102 B=153 3", "L=50 a=0 b=0", "L=50 a=0 b=0 2"];
assert_eq!(r, json!({"name": "R=51 G=102 B=153 2", "swatches": want, "linked": 8}));
assert_eq!(names(&s, Some("R=51 G=102 B=153 2")), want);
assert_eq!(undo_len(&s), undo + 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!(*doc(&s), before);
}
#[test]
fn edit_color_group_numbers_extra_colors_after_the_names_it_keeps() {
let mut s = session();
run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": ["#ff0000", "#00ff00", "#0000ff"]}));
let before = doc(&s).clone();
let undo = undo_len(&s);
// Near-equal colors with the same name, and a Lab color and its twin with a -0.0 component.
let colors = json!([
"#0000ff",
"#ff0000",
"#ff0000",
"#ff0000",
"#ff0000",
"#00ff00",
[0.2, 0.4, 0.6],
[0.2, 0.4, 0.6001],
{"l": 50, "a": 0.0, "b": 0},
{"l": 50, "a": -0.0, "b": 0}
]);
let r = run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": colors, "rename": "R=255 G=0 B=0 2"}));
let want = [
"R=255 G=0 B=0",
"R=0 G=255 B=0",
"R=0 G=0 B=255",
"R=255 G=0 B=0 3",
"R=255 G=0 B=0 4",
"R=0 G=255 B=0 2",
"R=51 G=102 B=153",
"R=51 G=102 B=153 2",
"L=50 a=0 b=0",
"L=50 a=0 b=0 2",
];
assert_eq!(r, json!({"name": "R=255 G=0 B=0 2", "swatches": want, "relinked": 0}));
assert_eq!(names(&s, Some("R=255 G=0 B=0 2")), want);
assert_eq!(undo_len(&s), undo + 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!(*doc(&s), before);
}
#[test]
fn unused_leaves_out_linked_colours_gradients_and_patterns_in_use() {
let mut s = session();
@@ -234,7 +503,7 @@ fn a_cmyk_document_starts_with_cmyk_swatches_and_stores_new_colours_as_cmyk() {
// A swatch made from a hex colour is CMYK as well; the document round-trips natively.
let name = run(&mut s, "swatch.new", json!({"color": "#00ff00"}))["name"].as_str().unwrap().to_string();
assert_eq!(doc(&s).swatch(&name).and_then(|w| w.paint.color()), Some(managed(Color::rgb(0.0, 1.0, 0.0))));
assert_eq!(name, "C=62 M=0 Y=100 K=0");
assert_eq!(name, "C=61 M=0 Y=100 K=0");
let json = serde_json::to_string(doc(&s)).unwrap();
assert_eq!(serde_json::from_str::<vectorcraft_doc::Document>(&json).unwrap(), *doc(&s));
}
+9 -18
View File
@@ -339,6 +339,7 @@ impl Session {
transform_tools_guides: self.prefs.transform_tools_guides,
spacing_guides: self.prefs.spacing_guides,
distance_guides: self.prefs.distance_guides,
snap_to_last_location: self.prefs.snap_to_last_location,
snapping_tolerance: self.prefs.snapping_tolerance,
construction_angles: if self.prefs.construction_guides {
vectorcraft_tools::guides::construction_angles(&self.prefs.construction_angles)
@@ -1041,23 +1042,13 @@ impl Session {
/// `crates/ui-egui/src/canvas/outline.rs`). Past it the selection's bounds are drawn instead.
const FEEDBACK_MAX_POINTS: usize = 100_000;
/// The outline of every selected object, or the selection's bounds when the outlines have more than
/// [`FEEDBACK_MAX_POINTS`] points.
/// The outlines of every selected object, a group's members each with their own, or the selection's
/// bounds when the outlines' points and the objects evaluated to make them come to more than
/// [`FEEDBACK_MAX_POINTS`].
fn outlines_for_selection(doc: &vectorcraft_doc::Document, selection: &Selection) -> Vec<Overlay> {
let mut left = FEEDBACK_MAX_POINTS;
let mut outlines = vec![];
for &id in &selection.objects {
let Some((path, _)) = doc.node(id).and_then(|n| vectorcraft_render::drawn_outline(doc, n)) else { continue };
let points = path.elements().iter().filter(|el| !matches!(el, kurbo::PathEl::ClosePath)).count();
let Some(l) = left.checked_sub(points) else {
return doc
.bounds_of(&selection.objects, true)
.map(|b| Overlay::Path { path: vectorcraft_geom::shapes::rectangle(b).to_bezpath(), color: FEEDBACK, width: 1.0, dashed: false })
.into_iter()
.collect();
};
left = l;
outlines.push(Overlay::Path { path, color: FEEDBACK, width: 1.0, dashed: false });
}
outlines
let nodes = selection.objects.iter().filter_map(|&id| doc.node(id));
let outlines = vectorcraft_render::drawn_outlines(doc, nodes, FEEDBACK_MAX_POINTS).unwrap_or_else(|| {
doc.bounds_of(&selection.objects, true).map(|b| vectorcraft_geom::shapes::rectangle(b).to_bezpath()).into_iter().collect()
});
outlines.into_iter().map(|path| Overlay::Path { path, color: FEEDBACK, width: 1.0, dashed: false }).collect()
}
+12
View File
@@ -243,6 +243,10 @@ fn structured_junk() {
("addon.select.byLinkStatus", json!({"status": "embedded", "ids": {"a": 1}, "add": [1], "zoom": "yes"})),
("addon.select.byLinkStatus", json!({"status": ["modified", "embedded"], "ids": [], "add": true, "zoom": true})),
("addon.select.byLinkStatus", json!({"status": [[["linked"]]], "ids": null})),
("links.relink", json!({"scope": "each", "paths": [{"ids": [2, u64::MAX, -1, "x"], "path": ""}, null, 7, {"path": [1]}]})),
("links.relink", json!({"scope": ["all"], "path": "/no/such/file.png", "ids": {"a": 1}})),
("links.relink", json!({"scope": "missingInFolder", "path": "", "folder": [], "paths": "x"})),
("links.relink", json!({"scope": "all", "path": "/no/such/file.png", "ids": [2, u64::MAX, -1, 1.5]})),
("object.transform", json!({"matrix": [0, 0, 0, 0, 0, 0]})),
("object.transform", json!({"matrix": [1e308, 1e308, 1e308, 1e308, 1e308, 1e308]})),
("object.transform", json!({"matrix": [1, 2, 3]})),
@@ -911,7 +915,15 @@ fn every_command_undoes_exactly() {
let mut s = Fixture::Multi.session();
let before = doc_json(&s.doc().unwrap().doc);
let depth = s.doc().unwrap().history.undo.len();
let source = s.active_index().unwrap();
let Ok(Ok(_)) = catch_quiet(|| s.execute(c.id, &json!({}))) else { continue };
// A command that makes a new document and makes it active leaves the source document as it is.
if s.active_index() != Some(source) {
if s.documents().get(source).map(|d| doc_json(&d.doc)).as_ref() != Some(&before) {
failures.push(format!("{}: changed the source document while making another active", c.id));
}
continue;
}
if s.doc().unwrap().history.undo.len() > depth {
let _ = no_panic(s.execute("edit.undo", &json!({})));
let after = doc_json(&s.doc().unwrap().doc);
+194 -3
View File
@@ -1148,6 +1148,42 @@ fn styles(what: &str, data: &str) -> Result<(), TestCaseError> {
})
}
/// A document with type and a character and a paragraph style, saved as pretty native text: what
/// Load All Styles reads.
fn saved_text_styles() -> String {
static TEXT: std::sync::OnceLock<String> = std::sync::OnceLock::new();
TEXT.get_or_init(|| {
let mut s = vectorcraft_engine::Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Styled"})).unwrap();
s.execute("charStyle.new", &json!({"name": "Lead", "attrs": {"size": 30, "tracking": 50, "underline": true, "leading": 36}})).unwrap();
s.execute("paraStyle.new", &json!({"name": "Centered", "attrs": {"justify": "Center", "space_after": 6, "hyphenate": true}})).unwrap();
let options = vectorcraft_format::SaveOptions { version: 2, pretty: true, ..vectorcraft_format::SaveOptions::default() };
let text = String::from_utf8(vectorcraft_format::save_with(&s.doc().unwrap().doc, &options).unwrap()).unwrap();
// Undamaged, it loads both styles.
let r = rich_session().execute("textStyle.loadAll", &json!({"data": text, "name": "fuzz.vectorcraft"})).unwrap();
assert_eq!((&r["charStyles"]["added"], &r["paraStyles"]["added"]), (&json!(["Lead"]), &json!(["Centered"])));
text
})
.clone()
}
/// Native file text `data`'s styles loaded into the rich document by Load All Styles, and each
/// style it added applied to all of its type.
fn text_styles(what: &str, data: &str) -> Result<(), TestCaseError> {
survive(what, || {
let mut s = rich_session();
let r = no_panic(s.execute("textStyle.loadAll", &json!({"data": data, "name": "fuzz.vectorcraft"}))).ok()?;
let _ = no_panic(s.execute("select.all", &json!({})));
for (list, kind) in [("charStyles", "charStyle"), ("paraStyles", "paraStyle")] {
for name in r[list]["added"].as_array().into_iter().flatten() {
let _ = no_panic(s.execute(&format!("{kind}.apply"), &json!({"name": name})));
}
}
Some((*s.doc().ok()?.doc).clone())
})
}
/// Libraries panel library file `data` imported, then each kind's first item used on the rich
/// document, moved into its first group and next to its kind's last item, a colour and the
/// selection added into that group next to the first ones, the group moved and deleted and the
@@ -1312,6 +1348,11 @@ proptest! {
styles("mutated style library", &mutate_text(&text, cut, &edits))?;
}
#[test]
fn mutated_text_style_files_never_panic(cut in 0usize..20_000, edits in prop::collection::vec(arb_edit(), 0..10)) {
text_styles("mutated text styles", &mutate_text(&saved_text_styles(), cut, &edits))?;
}
#[test]
fn mutated_flattener_presets_never_panic(cut in 0usize..5_000, edits in prop::collection::vec(arb_edit(), 0..10)) {
let text = saved("flattener.presets.export", json!({"names": ["high", "medium", "low"]}));
@@ -3288,6 +3329,40 @@ proptest! {
survive("hostile .ai envelope", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?;
}
/// A `.ai` whose warped type is damaged or hostile: any warp style and settings, on the object or
/// on a fill, a look that reaches far away or holds type of its own, the text cut short.
#[test]
fn ai_warped_type_never_panics(
style in prop::sample::select(vec![0i64, 1, 8, 15, 16, -3, i64::MAX]),
bend in prop::sample::select(vec!["0.5", "0", "1", "-1", "2", "1e308", "-1e308", "nan"]),
distort in prop::sample::select(vec!["0", "0.4", "-1", "1e308", "nan"]),
reach in prop::sample::select(vec!["90", "16000", "1e7", "1e308", "-1e308", "nan"]),
on_fill in any::<bool>(),
look_type in any::<bool>(),
objects in 1usize..4,
cut in 0usize..3_000,
edits in prop::collection::vec((0usize..3_000, prop::sample::select(vec!['0', '9', '-', ' ', '\n', '(', ')', '/', ':', ';', ',', '[', ']', '%', '_', 'X', 'u', 'U'])), 0..8),
) {
let basic = |name: &str, body: &str| format!("/BasicFilter :\n({name}) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{body}; /Dict ;\n /Part ,\n");
let chain = |kids: &[String]| format!("/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n{};\n /Part ,\n", kids.concat());
let fill = basic("Fill Style Filter", "/FillStyle : 0 O\n0 1 1 0 1 0 0 Xa\n0 1 0 0 0 Xy\n0 1 Xd\n/Def ;\n (FillStyle) ,\n");
let warp = basic("Adobe Deform", &format!("{style} /Int (DeformStyle) ,\n{bend} /Real (DeformValue) ,\n{distort} /Real (DeformHoriz) ,\n{distort} /Real (DeformVert) ,\n0 /Bool (Rotate) ,\n"));
let root = if on_fill {
let stack = format!("/CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n{}{};\n /Part ,\n", chain(&[warp, fill]), basic("Conduit Filter", ""));
chain(&[stack])
} else {
chain(&[fill, warp])
};
let styles = format!("%AI9_BeginArtStyles\n/KnownStyle :\n(Warped) /Name ,\n/ActiveStyle :\n{root}%AI9_EndArtStyles\n");
let slot = if look_type { "/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n" } else { "" };
let object = format!(
"u\n{slot}0 1 1 0 1 0 0 Xa\n10 10 m\n{reach} 10 L\n{reach} {reach} L\n10 90 L\nf\nU\n9 () XW\n%_/AI11Text :\n%_0 /FreeUndo ,\n%_0 /FrameIndex ,\n%_0 /StoryIndex ,\n%_;\n1 (Warped) XW\n"
);
let data = mutate_text(&text_editing_of(&vertical_document_text(), &(styles + &object.repeat(objects))), cut, &edits);
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat();
survive("hostile .ai warped type", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?;
}
/// A `.ai` whose editing data is damaged or hostile.
#[test]
fn ai_editing_data_never_panics(cut in 0usize..3_000, edits in prop::collection::vec((0usize..3_000, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', ':', ';', '[', ']', '%', 'q', 'Q', 'W', 'u', 'U', 'L', 'l', 'c', 'C', 'v', 'V', 'y', 'Y', 'k', 'x'])), 0..12), damage in prop::collection::vec((0usize..4_000, any::<u8>()), 0..4)) {
@@ -3390,6 +3465,26 @@ proptest! {
survive("hostile .ai line widths", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?;
}
/// A `.ai` whose legacy type is set in a CJK composite font (a predefined CMap the reader
/// carries, one it reads through another, one it decodes byte by byte, a Unicode CMap, or a
/// name that only looks like one), with any bytes in its strings.
#[test]
fn ai_legacy_type_in_cjk_fonts_never_panics(
cmap in prop::sample::select(vec![
"83pv-RKSJ-H", "90ms-RKSJ-V", "90pv-RKSJ-V", "H", "V", "EUC-H", "GBK2K-H", "CNS-EUC-V", "KSCpc-EUC-H", "KSCms-UHC-HW-V",
"78-RKSJ-H", "GB-H", "KSC-V", "HKdlb-B5-H", "GBT-H", "UniJIS-UCS2-H", "UniGB-UTF8-V", "UniKS-UTF32-H", "UniAKR-UTF16-H",
"Identity-H", "UniFoo-UTF8-H", "-H", "RKSJ",
]),
strings in prop::collection::vec(prop::collection::vec(any::<u8>(), 0..24), 1..4),
) {
use vectorcraft_testkit::ai;
let tx: String = strings.iter().map(|s| format!("({}) Tx\n", s.iter().map(|b| format!("\\{b:03o}")).collect::<String>())).collect();
let art = format!("0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n/_Test-W3-{cmap} 9 Tf\n{tx}(\\r) TX\nTO\n");
let data = ai::editing_data(100.0, 100.0, &ai::layer("L", &art));
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat();
survive("legacy type in CJK fonts", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?;
}
/// A `.ai` whose pattern definition (a marked tile box, a gradient placed by `Bg`'s matrix) and
/// pattern fill are damaged or hostile.
#[test]
@@ -3704,8 +3799,9 @@ proptest! {
}
/// Brush objects of every kind with any parameters, the brush manager's order with any names,
/// and brush art sections nested or cut short: read with the layers, or as a library without
/// them, the brushes kept within their ranges.
/// and brush art sections nested or cut short, their art alone or in a group after a frame of
/// any corners, painted or not, open or closed, the group ended or not: read with the layers,
/// or as a library without them, the brushes kept within their ranges.
#[test]
fn ai_brushes_never_panic(
kind in 0usize..7,
@@ -3714,6 +3810,7 @@ proptest! {
nest in 0usize..6,
cut in any::<bool>(),
layers in any::<bool>(),
frame in prop::option::of((prop::collection::vec(prop_oneof![arb_num(), Just("0".to_string()), Just("4".to_string())], 4), prop::sample::select(vec!["n", "N", "f", "S"]), any::<bool>())),
) {
use vectorcraft_testkit::ai;
let kinds = ["Adobe Calligraphic Brush Tool", "Adobe Scatter Brush Tool", "Adobe ArtOnPath Brush Tool", "Adobe PatternOnPath Brush Tool", "Adobe dBrush Brush Tool", "Adobe Brush Manager Order", "Other"];
@@ -3727,7 +3824,14 @@ proptest! {
for _ in 0..nest {
art.push_str("%AI8_BeginBrushPattern\n(A)\n");
}
art.push_str("0 g\n0 0 m\n4 0 L\n4 4 L\nf\n");
match &frame {
Some((c, op, ended)) => {
let (x0, y0, x1, y1) = (&c[0], &c[1], &c[2], &c[3]);
let end = if *ended { "U\n" } else { "" };
art.push_str(&format!("u\n{x0} {y0} m\n{x1} {y0} L\n{x1} {y1} L\n{x0} {y1} L\n{x0} {y0} L\n{op}\n0 g\n0 0 m\n4 0 L\n4 4 L\nf\n{end}"));
}
None => art.push_str("0 g\n0 0 m\n4 0 L\n4 4 L\nf\n"),
}
for _ in 0..nest.saturating_sub(usize::from(cut)) {
art.push_str("%AI8_EndBrushPattern\n");
}
@@ -3750,6 +3854,91 @@ proptest! {
survive("mutated .ai symbols", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?;
survive("mutated .ai symbols, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?;
}
/// A `.ai` whose art styles, as the writer writes them, are damaged: the styles, the style
/// list, a styled object's drawn look, the object on `%_` lines and its `1 (style) XW`, cut
/// short or edited.
#[test]
fn ai_written_styles_never_panic(cut in 0usize..STYLES_FUZZ_CHARS, edits in prop::collection::vec((0usize..STYLES_FUZZ_CHARS, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', ':', ';', ',', '%', '_', 'u', 'U', 'X', 'W'])), 0..12)) {
let text = mutate_text(styles_text(), cut, &edits);
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat();
survive("mutated .ai art styles", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?;
survive("mutated .ai art styles, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?;
}
}
/// The range of [`ai_written_styles_never_panic`]'s cuts and edits: past the end of [`styles_text`].
const STYLES_FUZZ_CHARS: usize = 64_000;
/// The editing data VectorCraft writes for a document with a drop shadow on a path, a gradient fill
/// and a width profile on others, a stroked even-odd path with an opacity mask and Pathfinder › Add
/// on a group.
fn styles_text() -> &'static str {
static TEXT: std::sync::OnceLock<String> = std::sync::OnceLock::new();
TEXT.get_or_init(|| {
use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Node, NodeKind, OpacityMask, StrokeLayer, WidthProfile};
use vectorcraft_geom::{FillRule, Rect, shapes};
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let fx = |id: &str| vectorcraft_render::effects::new_effect(id, &json!({})).unwrap();
let mut ap = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::WHITE), 2.0);
ap.effects = vec![fx("stylize.dropShadow")];
let shaded = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap.clone());
doc.insert(Some(layer), usize::MAX, shaded).unwrap();
let ramp = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)]);
let mut graded = Appearance::basic(Paint::Gradient(Box::new(GradientPaint::new(ramp))), Paint::None, 0.0);
graded.effects = vec![fx("stylize.outerGlow")];
let n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 50.0, 50.0, 90.0)), graded);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let mut tapered = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0);
tapered.profile = Some(WidthProfile { points: vec![(0.0, 1.0, 0.5), (1.0, 0.0, 1.0)] });
let profiled = Appearance { items: vec![AppearanceItem::Stroke(tapered)], effects: vec![fx("stylize.roundCorners")], contents_index: None };
let n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 10.0, 150.0, 40.0)), profiled);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let mut stroked = Appearance::basic(Paint::None, Paint::solid(Color::WHITE), 2.0);
stroked.effects = vec![fx("stylize.dropShadow")];
let mut odd = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 50.0, 150.0, 90.0)), stroked);
if let NodeKind::Path { rule, .. } = &mut odd.kind {
*rule = FillRule::EvenOdd;
}
let mask_art = Node::path(
doc.alloc_id(),
shapes::rectangle(Rect::new(100.0, 50.0, 150.0, 70.0)),
Appearance::basic(Paint::solid(Color::gray(0.0)), Paint::None, 0.0),
);
odd.extras_mut().mask = Some(Box::new(OpacityMask::new(mask_art, false)));
doc.insert(Some(layer), usize::MAX, odd).unwrap();
let square = |doc: &mut Document, x: f64| {
Node::path(
doc.alloc_id(),
shapes::rectangle(Rect::new(x, 50.0, x + 30.0, 80.0)),
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
)
};
let (a, b) = (square(&mut doc, 60.0), square(&mut doc, 80.0));
let mut merged = Node::group(doc.alloc_id(), vec![std::sync::Arc::new(a), std::sync::Arc::new(b)]);
merged.appearance = Appearance { effects: vec![fx("pathfinder.add")], ..Appearance::default() }.into();
doc.insert(Some(layer), usize::MAX, merged).unwrap();
let out = vectorcraft_eps::export_ai_editing(&doc, &vectorcraft_eps::AiEditingOptions::default()).unwrap();
String::from_utf8(out.program).unwrap()
})
}
/// The data [`ai_written_styles_never_panic`] damages, as it is, opens with its styles live, and the
/// property's cuts and edits reach all of it.
#[test]
fn the_written_styles_fuzz_data_opens_live() {
let text = styles_text();
assert!(text.chars().count() < STYLES_FUZZ_CHARS, "{}", text.chars().count());
for mark in ["%AI9_BeginArtStyles", "%AI5_BeginLayer", "\n6 () XW", "\n1 (Anon", "(BSLeftWidthsArray)", "0 /Bool (UseEvenOdd)", "Bb"] {
assert!(text.contains(mark), "{mark}");
}
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(text)].concat();
let (d, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0);
assert!(layered, "{warnings:?}");
let art = d.layers[0].children().unwrap();
assert_eq!(art.iter().map(|n| n.appearance.effects.len()).collect::<Vec<_>>(), [1, 1, 1, 1, 1]);
}
/// Editing data with symbols (S2's art holds an instance of S1, F's holds non-native art), the
@@ -4382,6 +4571,8 @@ fn arb_ai_token() -> impl Strategy<Value = String> {
"1e308 Ty",
"1 TY",
"(x) TY",
"3 Tg",
"1e308 Tg",
"1 1 1e308 -1e308 4e9 Th",
"1 1 (2) 3 4 Th",
"36 2 Xb",
@@ -0,0 +1,102 @@
//! The JavaScript parser's lexer (`vectorcraft-js`) and the script checker's (`vectorcraft-scriptcheck`)
//! read the same scripts the same way: both crates stand alone, so each has its own lexer, and these
//! tests run both over one set of scripts and fail on any disagreement about the lines a script has,
//! its preprocessor lines, and where a string, comment or regular expression that is never closed
//! starts. The scripts stay inside ECMAScript 3, the language both read (no XML literals, which
//! only the checker reads).
use vectorcraft_js::{Options, TokenKind, parse, tokenize};
use vectorcraft_scriptcheck::{Limits, check};
/// The problems the checker reports from its lexer, which the parser reports as a `SyntaxError`.
const LEXICAL: [(&str, &str); 3] = [
("unterminatedString", "unterminated string"),
("unterminatedComment", "unterminated comment"),
("unterminatedRegExp", "unterminated regular expression"),
];
/// Scripts both lexers read without a problem, each with a `/` or a quote in a place where reading
/// it the other way would change the tokens.
const VALID: &[&str] = &[
"var a = b / c / d;\nvar r = /ab+c/gi;\n",
"if (x) /re/.test(y);\nwhile (z) /q/g.exec(w);\n",
"function f() { return /x/; }\nvar g = function () {} / 2;\n",
"{}\n/re/.test(s);\n",
"x = {a: 1} / 2;\n",
"a = b\n/c/g\n",
"s = 'it\\'s \"q\" // not a comment';\nt = \"/* nor this */\";\n",
"s = 'line\\\ncontinued';\nu = 1;\n",
"x = a++ / 2;\ny = (b) / 2;\nz = c[0] / 2;\n",
"r = /[/]/;\nq = /\\//;\n",
"#target vectorcraft\n#include \"lib.jsxinc\"\n//@includepath \"~/x\"\nvar a = 1;\n#targetengine session\n",
"a = 1;\r\nb = 2;\r\nc = 3;",
"a = 1;\u{2028}b = 2;\u{2029}c = 3;\n",
"typeof /x/ === 'object';\nvoid /y/;\n",
"switch (x) { case /a/.test(y): break; }\n",
"x = y ? /a/ : /b/;\n",
"label: for (;;) { break label; }\n/* multi\nline */ z = 1 / 2;\n",
"var o = { re: /x/, d: 4 / 2 };\n",
"x = [/a/, 1 / 2];\n",
"if (a) {\n} else /x/.test(b);\n",
"a = 'q' + \"r\";\n// a comment with a 'quote\n",
"x = a\n++b\n",
"for (var i = 0; i < n / 2; i++) { s += /\\d/.exec(t[i]) ? 1 : 0; }\n",
"",
"\n\n",
];
/// Scripts with a string, comment or regular expression that is never closed: the problem the
/// checker gives and the line it starts on.
const INVALID: &[(&str, &str, usize)] = &[
("var a = 1;\nvar s = 'abc;\n", "unterminatedString", 2),
("a = 1;\n/* never closed\nb = 2;\n", "unterminatedComment", 2),
("x = 1;\ny = /abc\n", "unterminatedRegExp", 2),
("if (x)\n /abc\n", "unterminatedRegExp", 2),
("a = 1;\r\nb = \"x\r\n", "unterminatedString", 2),
("q = 2 / 3;\nr = /[/]\n", "unterminatedRegExp", 2),
];
fn js_options() -> Options {
Options { preprocessor_lines: true, ..Options::default() }
}
#[test]
fn both_lexers_count_the_same_lines_and_read_the_same_directives() {
for src in VALID {
let program = parse(src, &js_options()).unwrap_or_else(|e| panic!("{src:?}: {e}"));
let report = check("script.jsx", src.as_bytes(), None, &Limits::default());
assert_eq!(report.lines, program.line_count() as usize, "lines of {src:?}");
let lexical: Vec<_> = report.problems.iter().filter(|p| LEXICAL.iter().any(|(code, _)| *code == p.code)).collect();
assert!(lexical.is_empty(), "{src:?}: the checker reports {lexical:?}");
let theirs: Vec<(String, usize)> = report.directives.iter().map(|d| (d.name.to_string(), d.line)).collect();
let ours: Vec<(String, usize)> = program.directives.iter().map(|d| (d.name.to_lowercase(), d.line as usize)).collect();
assert_eq!(ours, theirs, "directives of {src:?}");
}
}
#[test]
fn both_lexers_find_the_same_unclosed_token_on_the_same_line() {
for (src, code, line) in INVALID {
let report = check("script.jsx", src.as_bytes(), None, &Limits::default());
let theirs = report.problems.iter().find(|p| LEXICAL.iter().any(|(c, _)| *c == p.code));
let theirs = theirs.unwrap_or_else(|| panic!("{src:?}: the checker reports no lexical problem"));
assert_eq!((theirs.code, theirs.line), (*code, Some(*line)), "{src:?}");
let ours = parse(src, &js_options()).expect_err(src);
let message = LEXICAL.iter().find(|(c, _)| c == code).map(|(_, m)| *m).unwrap();
assert!(ours.message.contains(message), "{src:?}: {}", ours.message);
assert_eq!(ours.line as usize, *line, "{src:?}");
}
}
#[test]
fn the_parser_reads_a_regexp_wherever_the_checker_does() {
// Each `/` that divides has no second `/` after it on its line, so a lexer that read one as a
// regular expression would report it as never closed. The checker reports nothing, and the
// parser reads regular expressions on lines 2 and 3 only.
let src = "a = b / c;\nr = /x/;\nif (a) /y/.test(b);\nz = (1) / 2;\n";
let tokens = tokenize(src, &js_options()).unwrap();
let lines: Vec<u32> = tokens.iter().filter(|t| matches!(t.kind, TokenKind::RegExp { .. })).map(|t| t.line).collect();
assert_eq!(lines, [2, 3]);
let report = check("script.jsx", src.as_bytes(), None, &Limits::default());
assert!(report.problems.iter().all(|p| !LEXICAL.iter().any(|(c, _)| *c == p.code)), "{:?}", report.problems);
}
+1
View File
@@ -18,6 +18,7 @@ mod dimensions;
mod eyedropper_sources;
mod find_replace_paras;
mod inline_text;
mod js_lexer_vs_scriptcheck;
mod known_bugs;
mod lossy_overwrite;
mod model_based;
+50 -4
View File
@@ -304,9 +304,13 @@ proptest! {
0..6,
),
permissions in prop::option::weighted(0.8, prop_oneof![Just(Value::Null), arb_junk()]),
api in prop_oneof![3 => Just(json!(1)), 1 => arb_junk()],
api in prop_oneof![2 => Just(json!(1)), 1 => Just(json!(2)), 1 => arb_junk()],
name in prop_oneof![3 => "[a-z\u{202E}\u{2066}\u{200F} ]{1,64}", 1 => "[a-z\u{202E}\u{2066}\u{0007}\u{200F} ]{1,80}"],
grant in prop_oneof![Just(Value::Null), arb_junk(), Just(json!(["doc.read", "doc.write", "state", "effect.render", "export.write", "import.read"]))],
grant in prop_oneof![
Just(Value::Null),
arb_junk(),
Just(json!(["doc.read", "doc.write", "state", "effect.render", "export.write", "import.read", "progress"]))
],
) {
let mut m = json!({"id": "fuzz.permissions", "name": name, "kind": kind, "api": api});
if matches!(kind, "exporter" | "importer") {
@@ -320,8 +324,7 @@ proptest! {
let parsed = catch_quiet(|| vectorcraft_plugins::Manifest::parse(text.as_bytes()));
let parsed = parsed.map_err(|msg| TestCaseError::fail(format!("panicked on {text}: {msg}")))?;
if let Ok(man) = &parsed {
let implied = vectorcraft_plugins::permissions::Permission::implied(man.kind);
prop_assert!(man.permissions().iter().all(|p| implied.contains(p)), "{}", text);
prop_assert!(man.permissions().iter().all(|p| p.applies(man.kind)), "{}", text);
let shown = vectorcraft_plugins::permissions::display_text(&man.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME);
prop_assert!(!shown.chars().any(|c| c.is_control() || matches!(c, '\u{202E}' | '\u{2066}' | '\u{200F}')), "{}", shown);
prop_assert!(shown.chars().count() <= vectorcraft_plugins::permissions::MAX_SHOWN_NAME);
@@ -338,4 +341,47 @@ proptest! {
vectorcraft_plugins::registry::remove("fuzz.permissions");
vectorcraft_plugins::registry::revoke("fuzz.permissions");
}
/// A plug-in of API level 2 that calls the host imports with hostile arguments (any progress
/// counts, any log level, pointers and lengths in and out of its memory, text that isn't
/// UTF-8) runs to an error or an output, never a panic, and its report stays within the caps.
#[test]
fn hostile_host_import_arguments_never_crash(
calls in prop::collection::vec(
prop_oneof![
(any::<i64>(), any::<i64>()).prop_map(|(d, t)| format!("(call $vc_progress (i64.const {d}) (i64.const {t}))")),
Just("(drop (call $vc_cancelled))".to_string()),
(prop_oneof![any::<i32>(), -1..5i32], prop_oneof![any::<i32>(), 0x1ff00..0x20100i32], prop_oneof![any::<i32>(), 0..5000i32])
.prop_map(|(l, p, n)| format!("(drop (call $vc_log (i32.const {l}) (i32.const {p}) (i32.const {n})))")),
],
0..24,
),
bytes in prop::collection::vec(any::<u8>(), 0..64),
effect in any::<bool>(),
) {
use vectorcraft_plugins::host::{LOG_TRUNCATED, MAX_LOG_BYTES, MAX_LOG_LINE, MAX_LOG_LINES};
let manifest = if effect {
r#"{"id":"fuzz.host","name":"F","kind":"effect","api":2,"permissions":["doc.read","effect.render","progress"]}"#
} else {
r#"{"id":"fuzz.host","name":"F","kind":"filter","api":2,"permissions":["doc.read","doc.write","progress"]}"#
};
let text: String = bytes.iter().map(|b| format!("\\{b:02x}")).collect();
let imports = format!(r#"{} (data (i32.const 0x2000) "{text}")"#, tpl::HOST_IMPORTS);
let wasm = wat::parse_str(tpl::with_imports(manifest, &imports, &calls.concat(), r#"{"objects":[]}"#)).unwrap();
let r = catch_quiet(|| {
let p = vectorcraft_plugins::Plugin::load(&wasm, vectorcraft_plugins::Limits::default())?;
let token = vectorcraft_doc::cancel::CancelToken::new();
let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(|_, _, _| {});
Ok::<_, vectorcraft_plugins::Error>(vectorcraft_doc::cancel::scope(&token, Some(sink), || p.run_reporting(b"{\"objects\":[]}", b"{}", p.limits())))
});
let r = r.map_err(|msg| TestCaseError::fail(format!("panicked on {calls:?}: {msg}")))?;
let (out, report) = r.map_err(|e| TestCaseError::fail(format!("refused at load: {e}")))?;
prop_assert!(out.is_ok(), "{:?}", out);
prop_assert!(report.lines.len() <= MAX_LOG_LINES + 1);
prop_assert!(report.lines.iter().all(|l| l.text.chars().count() <= MAX_LOG_LINE));
prop_assert!(report.lines.iter().filter(|l| l.text != LOG_TRUNCATED).map(|l| l.text.len()).sum::<usize>() <= MAX_LOG_BYTES);
if let Some((done, total)) = report.progress {
prop_assert!(total == 0 || done <= total);
}
}
}
+2
View File
@@ -21,6 +21,8 @@ vectorcraft-text = { workspace = true }
vectorcraft-metafile = { workspace = true }
# Non-native art in Illustrator editing data (a placed PDF's content, kept as a PDF).
vectorcraft-pdf = { workspace = true }
# The predefined CMaps that strings of legacy type in CJK fonts are decoded by.
craft-pdf = { workspace = true }
# The TIFF writer (previews) and PackBits, shared with raster export.
vectorcraft-render = { workspace = true }
kurbo = { workspace = true }
+69 -10
View File
@@ -98,7 +98,8 @@
//! a preview of at most 256 pixels a side between `%AI26_BeginPlacedObjectPreview` and its end
//! (`w h rowBytes 32 17 `, then rows of premultiplied ARGB), each in versioned content, `~`,
//! `%AI5_EndPlace`. The box is the file's pixels at art space's origin on the canvas; the matrix
//! takes it into art space. In opacity masks and pattern tiles, linked images are embedded.
//! takes it into art space. In opacity masks, pattern tiles and symbols, linked images are
//! embedded.
//! - Type: a text object `/AI11Text :` naming its story and frame (`/StoryIndex`, `/FrameIndex`),
//! for area type and type on a path with its frame's path (`/Art :` … `; /ConfiningPath ,`), and
//! the text document after the document data (`%AI11_BeginTextDocument`, see
@@ -107,30 +108,66 @@
//! the alignment, indents, spacing, hyphenation and direction of each paragraph, and the frame:
//! point type's point and matrix, area type's frame, rows, columns, gutters and first baseline,
//! type on a path's path and span, vertical type, and the frames a threaded story flows through.
//! - Symbols, as the reader reads them ([`crate::import`]'s `.ai` reader, `read.rs`): every symbol
//! of the document defined in the setup after the patterns, in a non-printing block
//! (`%AI14_BeginSymbol`, `(name)`, `0 A`, `0 Xw`, `0 Ae`, the art in the symbol's space with y
//! down, the registration point as `AI13PatternRegistrationType` 1 to 9 from the top left, row by
//! row (VectorCraft's numbering, in the order the scripting reference lists the points), in the
//! art's dictionary, `%AI10_EndSymbol`), each after those its art uses; the symbol
//! list after the palette (`%AI24_BeginSymbolList`, the names in the Symbols panel's order,
//! `%AI24_EndSymbolList`); each instance as `/SymbolInstance :`, `(name) /SymbolRef ,`, the
//! matrix taking the art to art space as `a b c d tx ty /RTransformMatrix`, `;`, then its name
//! and opacity mask and a state block as a group's with its opacity and blending mode (an
//! instance with isolation, knockout or knockout shape of its own is written as its art). The
//! definitions are at most the reader's 4,096. In a symbol's art, an instance's matrix and
//! a gradient's take the art to the canvas's space turned y up about art space's origin there.
//! - Art styles, as the reader reads them (`style.rs`, `read/ops.rs`): a path, compound path or
//! group with live effects is written as its drawn look (`u`, its vector art as its geometry
//! effects leave it, without shadows, glows or feathers, `U`, its transparency, `0 0 Xd`,
//! `6 () XW`), then the object itself on `%_` lines (its points painted
//! with nothing, or with its gradient fill; a group with its members) with its name and opacity
//! mask, then `1 (style) XW`. The styles are written in a non-printing block after the symbols
//! (`%AI9_BeginArtStyles`, each `/KnownStyle :` with its name and a filter tree: a chain of the
//! stack of fills and strokes with the contents among them, the effects and the blend filter). A
//! fill filter fills by the non-zero rule (`0 /Bool (UseEvenOdd)`), so a filled object that fills by
//! the even-odd rule is written as its drawn look. A style is written only when the reader reads it
//! back as the object's appearance.
//!
//! Lines end in CR LF. Strings are written in UTF-8. Art space is ruler space: y up, its origin at
//! the first artboard's top-left corner. On the canvas ([`CANVAS_SIZE`] points square, y down) the
//! artboards together are centered; each artboard's `RulerOrigin` is its top-left corner there, and
//! `%AI3_TemplateBox` holds the canvas's center in art space. What the form above can't hold is written as plain filled and stroked paths, each such
//! loss a warning: type the text document can't hold (in opacity masks, pattern tiles and art cut to
//! a clipping object, mirrored, turned or unevenly scaled area type and type on a path, inline graphics, ruby,
//! loss a warning: type the text document can't hold (in opacity masks, pattern tiles, symbols and
//! art cut to a clipping object, mirrored, turned or unevenly scaled area type and type on a path, inline graphics, ruby,
//! gradient or pattern paint, an appearance of its own) as its outlines and its inline graphics'
//! art, the character and paragraph attributes the text document doesn't hold, freeform gradients, gradients
//! along or across a stroke and gradients without stops, with more than 256 stops or without extent
//! as their average color
//! (gradients that dither or mix perceptually are written as classic ones, and gradient stops linked
//! to global process colors as their colors), pattern fills whose tiles aren't a grid, whose art reaches past
//! the tile or is painted with patterns as their tiles cut to the shape, clipping groups and clipping layers whose clipping object isn't a path,
//! the tile or is painted with patterns, and pattern fills in symbols, as their tiles cut
//! to the shape, clipping groups and clipping layers whose clipping object isn't a path,
//! and the clipping groups inside them, as their art cut to that object (its fill cut too, its
//! stroke not; an image in a clipping group of the region it is cut to), images that can't be
//! decoded or have more than 33,554,432 pixels as their outlines filled mid gray, images of 16 bits
//! a channel at 8 bits, linked images in opacity masks and pattern tiles as embedded images,
//! symbols and live objects (placed documents included) as their art (symbol art past
//! [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects in all left out), strokes a plain line can't draw
//! a channel at 8 bits, linked images in opacity masks, pattern tiles and symbols as embedded images,
//! symbol instances with a fill, appearance changes, isolation, knockout or knockout shape of their
//! own, instances of symbols with 9-slice guides or pattern paint, instances in pattern tiles or in art cut to a
//! clipping object, instances scaled almost flat, instances that turn, mirror or scale symbols holding
//! type, live objects, instances written as their art, shapes with rounded live corners or strokes
//! written as outlines or brush art,
//! instances that scale their symbol more than 100 times, instances on the layers of a large canvas
//! and instances of
//! symbols past 4,096 as their art (symbol art past [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects
//! in all left out), instances of symbols the document doesn't have as empty groups, symbols' 9-slice
//! guides, export types and dynamic type left out, live objects (placed documents included) as their art,
//! strokes a plain line can't draw
//! as their filled outlines, several fills or strokes as a group of a path for each, freeform
//! gradient swatches, gradient swatches of more than 256 stops, swatches of patterns written as
//! tiles and the placement of pattern swatches that move, turn or scale their pattern, the opacity and blending modes of single fills and strokes, opacity masks on
//! layers and opacity masks nested too deep, and live effects other than geometry effects left out.
//! layers and opacity masks nested too deep, and, on objects written without an art style, live
//! effects other than geometry effects left out; graphic styles, links to them and every art style
//! on a large canvas are left out.
//!
//! The data streams hold the program compressed with Zstandard after `%AI24_ZStandard_Data`, with
//! the version numbers of the newest files users sent ([`private_data`]).
@@ -207,11 +244,15 @@ pub fn export_ai_editing(doc: &Document, o: &AiEditingOptions) -> Result<AiEditi
if !(board.is_finite() && board.width() > 0.0 && board.height() > 0.0) {
return Err("the document has no artboard".into());
}
// Artboards that don't fit on the canvas are written on a large canvas, at 1/scale.
let scale = canvas_scale(doc);
// The objects that may keep their effects in an art style, as they are before baking (not on
// a large canvas, whose scale the styles' strokes and effects would need).
let styled = writer::styled_objects(doc);
let graphic_styles = writer::has_graphic_styles(doc);
// Live geometry effects as their result, as the PDF part draws them.
let baked = baked(doc);
let doc = baked.as_ref().unwrap_or(doc);
// Artboards that don't fit on the canvas are written on a large canvas, at 1/scale.
let scale = canvas_scale(doc);
let reduced = (scale != 1.0).then(|| {
let mut d = doc.clone();
crate::import::scale_document(&mut d, 1.0 / scale, true);
@@ -227,6 +268,8 @@ pub fn export_ai_editing(doc: &Document, o: &AiEditingOptions) -> Result<AiEditi
}
d
});
// Symbols are defined at their own size, whatever the canvas.
let symbol_doc = doc;
let doc = reduced.as_ref().unwrap_or(doc);
let board = doc.artboards.first().map_or(board, |a| a.rect);
// The document is y down; art space is ruler space: y up, its origin the first artboard's
@@ -234,10 +277,23 @@ pub fn export_ai_editing(doc: &Document, o: &AiEditingOptions) -> Result<AiEditi
let to_art = Affine::new([1.0, 0.0, 0.0, -1.0, -board.x0, board.y0]);
let origin = ruler_origin(doc, to_art);
let mut w = Writer::new(doc, to_art, origin);
// On a large canvas the layers' symbol instances are written as their art.
w.symbols_live = scale == 1.0;
w.symbol_doc = symbol_doc;
w.reserve_swatch_gradients();
if scale == 1.0 {
w.styled = styled;
} else if !styled.is_empty() {
w.warnings.push(writer::LARGE_CANVAS_STYLES.to_string());
}
if graphic_styles {
w.warnings.push(writer::GRAPHIC_STYLES.to_string());
}
for layer in &doc.layers {
w.layer(layer);
}
// The symbols no instance uses too; their art adds definitions.
w.symbols();
// The palette first: its gradient and pattern swatches add definitions.
let mut palette = String::new();
w.palette(&mut palette);
@@ -256,7 +312,10 @@ pub fn export_ai_editing(doc: &Document, o: &AiEditingOptions) -> Result<AiEditi
let mut s = header.clone();
s.push_str("%%BeginProlog\n%%EndProlog\n%%BeginSetup\n");
w.definitions(&mut s);
w.symbol_definitions(&mut s);
w.art_styles(&mut s);
s.push_str(&palette);
w.symbol_list(&mut s);
artboards(&mut s, doc, to_art, origin, &library);
if !w.texts.is_empty() {
s.push_str(&w.texts.section(doc));
File diff suppressed because it is too large. Load diff
+125 -11
View File
@@ -17,15 +17,23 @@ use crate::ps;
mod images;
mod paints;
mod styles;
mod symbols;
mod texts;
mod variables;
#[cfg(test)]
pub(super) use styles::same_appearance;
pub(super) use styles::{GRAPHIC_STYLES, LARGE_CANVAS_STYLES, has_graphic_styles, styled_objects};
pub(super) use images::PAYLOAD;
#[cfg(test)]
pub(super) use images::{IMAGE_DEPTH, IMAGES, LINKS_EMBEDDED};
#[cfg(test)]
pub(super) use paints::{GRADIENT_MIX, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name};
#[cfg(test)]
pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS};
#[cfg(test)]
pub(super) use texts::TYPE_ATTRIBUTES;
#[cfg(test)]
pub(super) use variables::{ACTIVE, BINDINGS, LIMITS, VALUES};
@@ -35,14 +43,14 @@ pub(super) use variables::{ACTIVE, BINDINGS, LIMITS, VALUES};
/// [`vectorcraft_doc::MAX_DEPTH`].
const MAX_NEST: u32 = 8;
pub(super) const TYPE: &str = "type in opacity masks, pattern tiles and art cut to a clipping object, mirrored type, area type and type on a path that is turned or unevenly scaled or whose frame or path has several parts, area type in an open frame, type on an open path whose ends meet, area type that flows around a text wrap, type of only white space, threads of type on a path, threads whose frames differ in orientation or hold a frame written as outlines, type of sizes past what the reader reads, stories past what the reader reads (1,048,576 bytes a story, 16,777,216 bytes in all, and the size of text document it reads), and type with inline graphics, ruby, gradient or pattern paint, or fills, strokes, effects or an opacity mask of the object's own, is written as its outlines in the editing data for other apps";
pub(super) const PATTERNS: &str = "pattern fills whose tiles aren't a grid or whose art reaches past the tile, pattern fills in another pattern's tile and pattern fills nested more than 8 deep are written as their tiles cut to the shape in the editing data for other apps";
pub(super) const TYPE: &str = "type in opacity masks, pattern tiles, symbols and art cut to a clipping object, mirrored type, area type and type on a path that is turned or unevenly scaled or whose frame or path has several parts, area type in an open frame, type on an open path whose ends meet, area type that flows around a text wrap, type of only white space, threads of type on a path, threads whose frames differ in orientation or hold a frame written as outlines, type of sizes past what the reader reads, stories past what the reader reads (1,048,576 bytes a story, 16,777,216 bytes in all, and the size of text document it reads), and type with inline graphics, ruby, gradient or pattern paint, or fills, strokes, effects or an opacity mask of the object's own, is written as its outlines in the editing data for other apps";
pub(super) const PATTERNS: &str = "pattern fills whose tiles aren't a grid or whose art reaches past the tile, pattern fills in another pattern's tile or in a symbol, and pattern fills nested more than 8 deep are written as their tiles cut to the shape in the editing data for other apps";
pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fill places are written filled gray in the editing data for other apps";
pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps";
pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps";
pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps";
pub(super) const LIVE: &str =
"symbols, blends, envelopes, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps";
"blends, envelopes, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps";
const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps";
pub(super) const ITEM_TRANSPARENCY: &str =
"the opacity and blending modes of single fills and strokes are left out of the editing data for other apps";
@@ -172,6 +180,57 @@ pub(super) struct Writer<'a> {
bound: Vec<(vectorcraft_doc::NodeId, String, Vec<String>)>,
/// The text document: the stories of the type written as text.
pub(super) texts: texts::TextDoc,
/// Symbol instances on the layers may be written as instances ([`Self::live_instance`]); false
/// on a large canvas, where they are written as their art.
pub(super) symbols_live: bool,
/// The document symbols are defined from: on a large canvas, the document at its own size
/// (symbols' art is in its own space, which the canvas's scale doesn't change).
pub(super) symbol_doc: &'a Document,
/// A symbol's art is being written ([`Self::define_symbol`]).
in_symbol: bool,
/// The document → the space an instance's `RTransformMatrix` takes its symbol's art to: art
/// space, and in a symbol's art the canvas's turned y up about art space's origin there.
instance_space: Affine,
/// The symbol definitions written (`%AI14_BeginSymbol` … `%AI10_EndSymbol`), each after those
/// its art uses, and their names.
symbol_defs: Vec<String>,
defined_symbols: HashSet<String>,
/// The symbols whose definitions are being written.
defining_symbols: Vec<String>,
/// Whether each symbol's own art paints with a pattern, and the symbols its instances use
/// ([`Self::symbol_own_patterns`]).
pattern_symbols: HashMap<String, (bool, Vec<String>)>,
/// Whether each symbol's art paints with a pattern, nested symbols included
/// ([`Self::symbol_paints_pattern`]).
patterned_symbols: HashMap<String, bool>,
/// Pattern tiles were written in the art being written ([`Self::define_symbol`] starts it over
/// for each symbol's art).
wrote_pattern: bool,
/// The symbols whose definitions hold pattern tiles: a brushed stroke's brush art or a live
/// object's art can paint with a pattern that the symbol's own objects don't name.
pattern_written: HashSet<String>,
/// Art that draws as it should only where it is was written in the art being written
/// ([`Self::define_symbol`] starts it over for each symbol's art): a stroke as its outline or its
/// brush's art, type as its outlines, a live object or a symbol instance as its art, or a shape
/// with rounded live corners.
wrote_fixed: bool,
/// The symbols whose definitions hold such art, nested symbols' included
/// ([`Self::keeps_scale`]).
fixed_symbols: HashSet<String>,
/// The largest scale a live instance in the art being written applies, nested symbols' scales
/// included, and that of each symbol's definition.
inner_scale: f64,
symbol_scales: HashMap<String, f64>,
/// The entries a symbol's dictionary adds to its art's dictionary, and the art's id.
root_entries: Option<(vectorcraft_doc::NodeId, String)>,
/// The objects that may be written with an art style, as they were before baking, by id
/// ([`styles::styled_objects`]).
pub(super) styled: HashMap<NodeId, Arc<Node>>,
/// The art styles written ([`styles`]).
styles: styles::Styles,
/// An object's drawn look is being written: no object in it is written with a style, and its
/// effects are the style's.
in_look: bool,
}
impl<'a> Writer<'a> {
@@ -208,6 +267,25 @@ impl<'a> Writer<'a> {
next: HashMap::new(),
brushes: None,
symbol_nodes: 0,
symbols_live: true,
symbol_doc: doc,
in_symbol: false,
instance_space: to_art,
symbol_defs: vec![],
defined_symbols: HashSet::new(),
defining_symbols: vec![],
pattern_symbols: HashMap::new(),
patterned_symbols: HashMap::new(),
wrote_pattern: false,
pattern_written: HashSet::new(),
wrote_fixed: false,
fixed_symbols: HashSet::new(),
inner_scale: 1.0,
symbol_scales: HashMap::new(),
root_entries: None,
styled: HashMap::new(),
styles: styles::Styles::default(),
in_look: false,
}
}
@@ -396,6 +474,9 @@ impl<'a> Writer<'a> {
/// Warn when `n` has effects the data leaves out.
fn effects(&mut self, n: &Node) {
if self.in_look {
return;
}
let items = n.appearance.items.iter().filter(|i| i.visible()).flat_map(|i| i.effects());
if n.appearance.effects.iter().chain(items).any(|e| e.visible) {
self.warn(EFFECTS);
@@ -407,6 +488,20 @@ impl<'a> Writer<'a> {
if let NodeKind::Layer { .. } = n.kind {
return self.write_layer(n, &[]);
}
if self.in_symbol {
self.wrote_fixed |= symbols::redrawn(n);
}
// On the layers, outside art cut to a clipping object: with its art style, when it has one.
if !self.in_look
&& self.hidden == 0
&& self.nest == 0
&& self.clip.is_none()
&& !self.in_symbol
&& let Some(orig) = self.styled.get(&n.id).cloned()
&& let Some(name) = self.object_style(n, &orig)
{
return self.styled_object(n, &orig, &name);
}
self.effects(n);
self.state(n.locked, !n.visible);
let xy = Xy::of(n);
@@ -435,10 +530,18 @@ impl<'a> Writer<'a> {
NodeKind::Compound { rule, .. } => self.shape(n, &compound_path(n), *rule, xy),
NodeKind::Text(_) => self.text(n, xy),
NodeKind::Image(im) => self.image(im, xy),
NodeKind::SymbolInstance { symbol, xf } if self.live_instance(n, symbol, *xf) => self.symbol_instance(symbol, *xf, xy),
NodeKind::SymbolInstance { symbol, xf } => {
self.warn(LIVE);
self.line("u");
// The canvas places an instance inside a symbol's art where the outer instance puts
// it (9-slice guides, stains and patterns included), and this art doesn't move with it.
self.wrote_fixed |= self.in_symbol;
let doc = self.doc;
if doc.symbols.iter().any(|s| &s.name == symbol) {
self.warn(symbols::SYMBOL_ART);
} else {
self.warn(symbols::MISSING_SYMBOL);
}
self.line("u");
if let Some(sym) = doc.symbols.iter().find(|s| &s.name == symbol)
&& self.nest < MAX_NEST
{
@@ -506,7 +609,8 @@ impl<'a> Writer<'a> {
/// `n`'s `/ArtDictionary`, after it, when it has a name (`AI10_ArtUID`, see [`Self::take_id`]),
/// is bound to variables ([`Self::bound_variables`]; without a name, it gets an XML id and an
/// empty `AIArtName`) or has an opacity mask (`AI9_Mask`, see [`Self::mask`]).
/// empty `AIArtName`), has an opacity mask (`AI9_Mask`, see [`Self::mask`]), or is a symbol's
/// art (its symbol's entries first, see [`Self::define_symbol`]).
fn dictionary(&mut self, n: &Node) {
let name = n.name.as_deref().filter(|s| !s.is_empty());
let placed = std::mem::take(&mut self.placed);
@@ -518,10 +622,17 @@ impl<'a> Writer<'a> {
self.warn(DEEP_MASKS);
mask = None;
}
if name.is_none() && mask.is_none() && bound.is_empty() {
let entries = match &self.root_entries {
Some((id, _)) if *id == n.id => self.root_entries.take().map(|(_, e)| e),
_ => None,
};
if name.is_none() && mask.is_none() && bound.is_empty() && entries.is_none() {
return;
}
self.body.push_str("%_/ArtDictionary :\n");
if let Some(e) = entries {
self.body.push_str(&e);
}
if name.is_some() || !bound.is_empty() {
let id = self.take_id(name.unwrap_or("XMLID"));
let _ = writeln!(self.body, "%_/XMLUID : {} ; (AI10_ArtUID) ,", ps::bytes(id.as_bytes()));
@@ -775,6 +886,7 @@ impl<'a> Writer<'a> {
AppearanceItem::Stroke(s) if self.direct_stroke(s) => self.path_object(path, rule, None, Some(s), xy),
AppearanceItem::Stroke(s) => {
self.warn(STROKES);
self.wrote_fixed = true;
if self.brush_art(path, s, xy) {
return;
}
@@ -836,6 +948,7 @@ impl<'a> Writer<'a> {
let flat = FillLayer { paint: Paint::solid(Color::gray(0.5)), ..f.clone() };
return self.path_object(path, rule, Some(&flat), None, xy);
}
self.wrote_pattern = true;
let outer = self.clip.clone();
let region = self.cut(path, rule);
self.clip = Some(region);
@@ -874,6 +987,7 @@ impl<'a> Writer<'a> {
self.plain_object(&region, FillRule::NonZero, fill, None, own);
}
if let Some(s) = stroke {
self.wrote_fixed = true;
let outline = stroke::outline_region(path, rule, s);
let region = self.cut(&outline, FillRule::NonZero);
let fill = FillLayer { overprint: s.overprint, ..FillLayer::new(s.paint.clone()) };
@@ -937,13 +1051,13 @@ impl<'a> Writer<'a> {
// ---------- type ----------
/// Type `n`: a text object stub naming its story in the text document ([`texts`]) when the
/// text document can hold it, outside opacity masks, pattern tiles and art cut to a clipping
/// object; else its outlines ([`Self::outlined_text`]). A frame of threaded area type names the
/// story of its thread, which its first frame holds.
/// text document can hold it, outside opacity masks, pattern tiles, symbols' art and art cut to
/// a clipping object; else its outlines ([`Self::outlined_text`]). A frame of threaded area type
/// names the story of its thread, which its first frame holds.
fn text(&mut self, n: &Node, xy: Xy) {
let NodeKind::Text(t) = &n.kind else { return };
let doc = self.doc;
let placed = if self.hidden > 0 || self.clip.is_some() {
let placed = if self.hidden > 0 || self.clip.is_some() || self.in_symbol {
None
} else if let Some(thread) = doc.text_threads.iter().find(|th| th.contains(&n.id)) {
// A thread is checked for what it loses, in every frame, when its story is written.
+9 -6
View File
@@ -13,7 +13,7 @@ use crate::ps;
pub(in crate::ai_editing) const IMAGES: &str = "images that can't be decoded or have more than 33,554,432 pixels are written as their outlines filled mid gray in the editing data for other apps";
pub(in crate::ai_editing) const IMAGE_DEPTH: &str = "images of 16 bits a channel are written at 8 bits a channel in the editing data for other apps";
pub(in crate::ai_editing) const LINKS_EMBEDDED: &str =
"linked images in opacity masks and pattern tiles are written as embedded images in the editing data for other apps";
"linked images in opacity masks, pattern tiles and symbols are written as embedded images in the editing data for other apps";
/// The most pixels an image is written with: as many as the reader reads.
pub(super) const MAX_PIXELS: u64 = 1 << 25;
@@ -94,7 +94,7 @@ impl Samples {
impl Writer<'_> {
/// Image object `im` of transparency `xy`: embedded, a raster ([`Self::raster`]); linked, a
/// placed file with a preview ([`Self::placed_file`]), except in a part of the data written on
/// `%_` lines. One whose pixels can't be read is its outline filled mid gray. Where the art is
/// `%_` lines and in a symbol's art. One whose pixels can't be read is its outline filled mid gray. Where the art is
/// cut to a clipping path, the image is in a clipping group of that path.
pub(super) fn image(&mut self, im: &ImageObject, xy: Xy) {
let doc = self.doc;
@@ -120,7 +120,7 @@ impl Writer<'_> {
let fit =
Affine::scale_non_uniform(f64::from(im.width.max(1)) / f64::from(samples.width), f64::from(im.height.max(1)) / f64::from(samples.height));
match &im.link {
Some(link) if self.hidden == 0 => {
Some(link) if self.hidden == 0 && !self.in_symbol => {
// Cut to a region, the placed file is in a clipping group.
self.placed = cut.is_none();
self.placed_file(link, &samples, (im.width.max(1), im.height.max(1)), im.xf);
@@ -158,9 +158,12 @@ impl Writer<'_> {
/// `[matrix] 0 0 w h w h 8 type alpha reserved 1 0 4 4 0 0`, `%%BeginData:` counting `XI`, its
/// line end and the color samples, `XI`, the color samples then the alpha channel in binary,
/// `%%EndData`, `XH`, `%AI5_EndRaster`, `N`. The matrix is an art-space matrix applied to the
/// pixels with their rows running downwards, `(u, -v)`, as §8.1's image matrix.
/// pixels with their rows running downwards, `(u, -v)`, as §8.1's image matrix; in a symbol's
/// art (outside a pattern's tile in it), a matrix in the canvas's space turned y up about art
/// space's origin there, as an instance's matrix in it is.
fn raster(&mut self, s: &Samples, xf: Affine) {
let m = matrix(self.to_art * xf * Affine::FLIP_Y);
let space = if self.in_symbol && self.defining.is_empty() { self.instance_space } else { self.to_art };
let m = matrix(space * xf * Affine::FLIP_Y);
let (w, h) = (s.width, s.height);
let alpha = u8::from(s.alpha.is_some());
let mut payload = Vec::with_capacity(2 + s.color.len() + s.alpha.as_ref().map_or(0, Vec::len));
@@ -237,7 +240,7 @@ fn matrix(m: Affine) -> String {
}
/// `v` rounded to ten decimals, without trailing zeros (0 when not finite).
fn precise(v: f64) -> String {
pub(super) fn precise(v: f64) -> String {
let r = (v * 1e10).round() / 1e10;
if !r.is_finite() {
return if v.is_finite() { format!("{}", v + 0.0) } else { "0".into() };
+45 -16
View File
@@ -103,6 +103,22 @@ impl Writer<'_> {
name
}
/// The gradient definitions' state, for [`Self::gradient_rollback`]: their count, which ones the
/// art uses, and the next name's number.
pub(super) fn gradient_mark(&self) -> (usize, Vec<bool>, u64) {
(self.gradients.len(), self.gradients.iter().map(|d| d.used).collect(), self.next_gradient)
}
/// The gradient definitions as they were at `mark` ([`Self::gradient_mark`]).
pub(super) fn gradient_rollback(&mut self, mark: (usize, Vec<bool>, u64)) {
let (len, used, next) = mark;
self.gradients.truncate(len);
for (d, u) in self.gradients.iter_mut().zip(used) {
d.used = u;
}
self.next_gradient = next;
}
/// `p` as the paint of a fill or stroke whose gradient is placed on `bounds`: a gradient is
/// placed there (it then no longer depends on the shape it paints, which may be cut); one the
/// data can't hold is its average color, with a warning.
@@ -222,24 +238,11 @@ impl Writer<'_> {
/// last stop; a radial one's `… Bm` (the unit circle onto its extent ellipse).
fn instance(&mut self, g: &GradientPaint, stroke: bool, clip: bool, path: &BezPath) {
let Some(geom) = g.geom else { return };
let name = self.define_gradient(&g.gradient, g.swatch.as_deref());
self.line(if stroke { "1 Bb" } else { "Bb" });
self.instance_head(g, clip, path);
let m = self.grad_space;
let u = geom.end - geom.start;
let radial = g.gradient.kind == GradientKind::Radial;
let place = placement(&geom, radial, &(self.canvas * path.clone()), self.canvas);
if radial {
let c = m * geom.start;
let off = geom.focal.map_or(Vec2::ZERO, |f| m * f - c);
let (angle, fraction) = if off.hypot() > 1e-9 { place.focal } else { (0.0, 0.0) };
let off = if fraction > 0.0 { off } else { Vec2::ZERO };
ps::push_nums(&mut self.body, &[off.x, off.y, angle, fraction]);
self.line("Bh");
}
let _ = write!(self.body, "{} {} ", u8::from(!clip), ps::bytes(name.as_bytes()));
ps::push_nums(&mut self.body, &place.bg);
ps::push_nums(&mut self.body, &place.transform.as_coeffs());
self.line("1 Bg");
// The unit vector along the gradient, and across it as long.
let frame = |from: f64, to: f64| {
let p = geom.start + u * from;
@@ -267,6 +270,28 @@ impl Writer<'_> {
matrix(frame(last, last + CAP / len), "Bc");
}
/// A gradient instance's focal point (`Bh`, radial gradients only) and its `Bg` line, as
/// [`Self::instance`] writes them; also what a fill's art style holds after its `Bb`.
pub(super) fn instance_head(&mut self, g: &GradientPaint, clip: bool, path: &BezPath) {
let Some(geom) = g.geom else { return };
let name = self.define_gradient(&g.gradient, g.swatch.as_deref());
let m = self.grad_space;
let radial = g.gradient.kind == GradientKind::Radial;
let place = placement(&geom, radial, &(self.canvas * path.clone()), self.canvas);
if radial {
let c = m * geom.start;
let off = geom.focal.map_or(Vec2::ZERO, |f| m * f - c);
let (angle, fraction) = if off.hypot() > 1e-9 { place.focal } else { (0.0, 0.0) };
let off = if fraction > 0.0 { off } else { Vec2::ZERO };
ps::push_nums(&mut self.body, &[off.x, off.y, angle, fraction]);
self.line("Bh");
}
let _ = write!(self.body, "{} {} ", u8::from(!clip), ps::bytes(name.as_bytes()));
ps::push_nums(&mut self.body, &place.bg);
ps::push_nums(&mut self.body, &place.transform.as_coeffs());
self.line("1 Bg");
}
/// A gradient definition: `%AI5_BeginGradient: (name)`, `(name) type stops Bd` (type 0 linear,
/// 1 radial), `[`, each stop on a `%_` line (`color style opacity 6 midpoint rampPoint Bs`), a
/// linear gradient's from the last to the first and a radial one's from the first to the last,
@@ -341,9 +366,10 @@ impl Writer<'_> {
/// Can pattern `name` be written as a definition and painted with from here: the document has
/// it, its tiles make a grid, its art is within its tile and holds something, and it isn't used
/// in another pattern's tile or nested more than [`MAX_NEST`] deep?
/// in another pattern's tile or a symbol's art (the reader keeps no symbol whose art paints with
/// a pattern) or nested more than [`MAX_NEST`] deep?
pub(super) fn pattern_writable(&self, name: &str) -> bool {
if !self.defining.is_empty() || self.nest >= MAX_NEST {
if !self.defining.is_empty() || self.nest >= MAX_NEST || self.in_symbol {
return false;
}
if self.patterns.iter().any(|p| p.name == name) {
@@ -389,9 +415,12 @@ impl Writer<'_> {
self.line("n\n%_/ArtDictionary :\n%_1 /Bool (AIPattern_Editor_Backing_Tile_Rect) ,\n%_;\n%_");
self.nest += 1;
self.hidden += 1;
// The tile's effects are its own, not those of a drawn look that first uses it.
let in_look = std::mem::take(&mut self.in_look);
for a in &def.art {
self.node(a);
}
self.in_look = in_look;
self.hidden -= 1;
self.nest -= 1;
let art;
+684
View File
@@ -0,0 +1,684 @@
//! Art styles: objects with live effects a plain path can't hold, written as their drawn look, the
//! object itself on `%_` lines and `1 (style) XW`, and the styles they name in
//! `%AI9_BeginArtStyles` (see [`crate::ai_editing`] for the form). Each style is read back before it
//! is written ([`crate::import::read_art_style`]: the `.ai` reader's style parser and its reading of
//! a graphic style, with the object's own gradient): one that reads back differently is not
//! written, and the object is written as its drawn look alone.
use std::collections::HashMap;
use std::fmt::Write;
use std::sync::Arc;
use serde_json::Value;
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Knockout, Node, NodeId, NodeKind, StrokeLayer};
use vectorcraft_geom::{BezPath, FillRule, Rect, Shape};
use super::{Writer, Xy, blend_code, compound_path, hide};
use crate::ai_ops;
use crate::ps;
pub(in crate::ai_editing) const LARGE_CANVAS_STYLES: &str = "on a large canvas, no art styles or graphic styles are written: objects with live effects are written with their geometry effects applied to the artwork, where they can no longer be edited, and their other effects are left out of the editing data for other apps";
pub(in crate::ai_editing) const GRAPHIC_STYLES: &str = "graphic styles and links to them are left out of the editing data for other apps";
/// Does `doc` have graphic styles other than a new document's, or an object in its layers, opacity
/// masks or symbols linked to a graphic style?
pub(in crate::ai_editing) fn has_graphic_styles(doc: &Document) -> bool {
fn linked(n: &Node) -> bool {
n.extras().graphic_style.is_some()
|| n.extras().mask.as_ref().is_some_and(|m| linked(&m.art))
|| n.children().is_some_and(|c| c.iter().any(|m| linked(m)))
}
doc.graphic_styles != Document::new(1.0, 1.0).graphic_styles || doc.layers.iter().any(|l| linked(l)) || doc.symbols.iter().any(|s| linked(&s.art))
}
/// The objects of `doc`'s layers that may be written with an art style ([`Writer::styled_object`]),
/// by id: paths and compound paths with points and groups, with live effects, without Opacity &
/// Mask Define Knockout Shape (the reader takes an object's transparency from its look, which
/// doesn't carry it). A group's members are paths, compound paths or such groups, none with effects
/// or anything baking changes.
pub(in crate::ai_editing) fn styled_objects(doc: &Document) -> HashMap<NodeId, Arc<Node>> {
fn walk(nodes: &[Arc<Node>], out: &mut HashMap<NodeId, Arc<Node>>) {
for n in nodes {
if candidate(n) {
out.insert(n.id, n.clone());
continue;
}
// Baking a container with effects of its own changes its members, which keep their ids:
// they are written as baking left them.
if let NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } = &n.kind
&& !bakes_members(n)
{
walk(children, out);
}
}
}
let mut out = HashMap::new();
walk(&doc.layers, &mut out);
out
}
/// Does container `n` need baking for what it has itself, whatever its members hold?
fn bakes_members(n: &Node) -> bool {
let mut own = n.clone();
if let Some(children) = own.children_mut() {
children.clear();
}
vectorcraft_effects::needs_bake(&own)
}
/// Whether `n` may be written with an art style ([`styled_objects`]).
fn candidate(n: &Node) -> bool {
if n.appearance.effects.is_empty() || n.knockout_shape {
return false;
}
match &n.kind {
NodeKind::Path { path, guide: false, clipping: false, .. } => has_points(path),
NodeKind::Compound { .. } => has_points(&compound_path(n)),
NodeKind::Group { children, clip: false } => !n.is_compound_shape() && children.iter().all(|c| plain_member(c)),
_ => false,
}
}
/// Does `path` write anything ([`Writer::plain_object`] skips subpaths without points)?
fn has_points(path: &vectorcraft_geom::PathData) -> bool {
path.subpaths.iter().any(|sp| !sp.anchors.is_empty())
}
/// A member of a group written with an art style: written as it is, and read back as it is.
fn plain_member(n: &Node) -> bool {
let quiet = n.appearance.effects.is_empty() && n.appearance.items.iter().all(|i| i.effects().is_empty()) && !vectorcraft_effects::needs_bake(n);
quiet
&& match &n.kind {
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => true,
NodeKind::Group { children, .. } => children.iter().all(|c| plain_member(c)),
_ => false,
}
}
/// The art styles objects name, each with its text after its name (`/ActiveStyle :` to `/Def ;`).
#[derive(Default)]
pub(in crate::ai_editing) struct Styles {
/// Every style, in the order written: its name and text.
known: Vec<(String, String)>,
/// The name of each style by its text.
by_text: HashMap<String, String>,
next_anon: u64,
}
impl Styles {
/// The name of an object style of `text`: a style with the same text already written, else a
/// new one named `Anon` and a number.
fn object_style(&mut self, text: String) -> String {
if let Some(name) = self.by_text.get(&text) {
return name.clone();
}
self.next_anon += 1;
let name = format!("Anon {}", self.next_anon);
self.by_text.insert(text.clone(), name.clone());
self.known.push((name.clone(), text));
name
}
}
/// One style as the reader's section holds it: `/KnownStyle :`, `(name) /Name ,`, its text.
fn known_style(name: &str, text: &str) -> String {
format!("/KnownStyle :\n{} /Name ,\n{text}", ps::bytes(name.as_bytes()))
}
/// The number transparency's `Xy` gives the blending mode a live effect's `mode` names (any case,
/// spaces and dashes ignored).
fn mode_code(mode: &str) -> Option<u8> {
let key: String = mode.chars().filter(char::is_ascii_alphanumeric).collect::<String>().to_ascii_lowercase();
BlendMode::ALL.iter().find(|m| format!("{m:?}").to_ascii_lowercase() == key).map(|m| blend_code(*m))
}
/// A filter's `Xy` line: `mode opacity isolate knockout shape Xy`.
fn xy_line(s: &mut String, xy: Xy) {
let knockout = match xy.knockout {
Knockout::Off => 0,
Knockout::On => 1,
Knockout::Neutral => 2,
};
let _ = write!(s, "{} ", blend_code(xy.blend));
ps::push_num(s, f64::from(xy.opacity));
let _ = writeln!(s, " {} {knockout} {} Xy", u8::from(xy.isolate), u8::from(xy.shape));
}
/// The line style of a paint style that isn't a stroke's.
const NO_LINE: &str = "0 J 0 j 1 w 10 M []0 d\n";
/// A basic filter's start: its name and kind numbers (`1 0` for an effect, `0 0` for the
/// style's own filters), `/Visible` and the dictionary's start.
fn basic(s: &mut String, name: &str, effect: bool, visible: bool) {
let _ = write!(s, "/BasicFilter :\n{} {} 0 /Filter ,\n{} /Visible ,\n", ps::bytes(name.as_bytes()), u8::from(effect), u8::from(visible));
}
/// The filter that stands for the object's contents in its stack.
const CONDUIT: &str = "/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n";
/// A basic filter's end.
const END_BASIC: &str = "; /Dict ;\n /Part ,\n";
/// The blend filter of transparency `xy`.
fn blend_filter(s: &mut String, xy: Xy) {
basic(s, "Blend Style Filter", false, true);
s.push_str("/Dictionary : /NotRecorded ,\n/BlendStyle : ");
xy_line(s, xy);
s.push_str(NO_LINE);
s.push_str("0 XR\n/Def ; \n (BlendStyle) ,\n");
s.push_str(END_BASIC);
}
/// A live effect's dictionary entries.
#[derive(Default)]
struct Entries(String);
impl Entries {
fn real(&mut self, key: &str, v: f64) {
ps::push_num(&mut self.0, v);
let _ = writeln!(self.0, " /Real {} ,", ps::bytes(key.as_bytes()));
}
fn int(&mut self, key: &str, v: i64) {
let _ = writeln!(self.0, "{v} /Int {} ,", ps::bytes(key.as_bytes()));
}
fn bool(&mut self, key: &str, v: bool) {
let _ = writeln!(self.0, "{} /Bool {} ,", u8::from(v), ps::bytes(key.as_bytes()));
}
}
/// `p`'s entry `key` as a number.
fn num(p: &Value, key: &str) -> Option<f64> {
p.get(key)?.as_f64().filter(|v| v.is_finite())
}
/// `p`'s entry `key` as text, for comparing: lower case, letters and digits only.
fn word(p: &Value, key: &str) -> Option<String> {
Some(p.get(key)?.as_str()?.chars().filter(char::is_ascii_alphanumeric).collect::<String>().to_ascii_lowercase())
}
/// `p`'s entry `key` as a switch.
fn flag(p: &Value, key: &str) -> Option<bool> {
p.get(key)?.as_bool()
}
impl Writer<'_> {
/// What `paint` writes with [`Self::color`] (a color, a spot or global color), as a string.
fn color_ops(&mut self, paint: &Paint, stroke: bool) -> String {
let saved = std::mem::take(&mut self.body);
self.color(paint, stroke);
std::mem::replace(&mut self.body, saved)
}
/// A fill style holding a color, as an effect's entry `key` or a fill's own.
fn fill_style(&mut self, s: &mut String, color: vectorcraft_color::Color, key: &str) {
let ops = self.color_ops(&Paint::solid(color), false);
let _ = write!(s, "/FillStyle : 0 O\n{ops}0 1 0 0 0 Xy\n{NO_LINE}0 XR\n0 1 Xd\n/Def ; \n {} ,\n", ps::bytes(key.as_bytes()));
}
/// A fill's basic filter: a color, or a gradient placed on the object's outline (`on`: the
/// object's own outline and rule), filling by the non-zero rule. `None` for other paint.
fn fill_filter(&mut self, s: &mut String, f: &FillLayer, visible: bool, on: Option<(&BezPath, FillRule)>) -> Option<()> {
if f.overprint {
return None;
}
// A color comes before the paint state, a gradient's instance after it.
let (color, gradient) = match &f.paint {
Paint::Solid { .. } => (self.color_ops(&f.paint, false), String::new()),
Paint::Gradient(_) => {
let (path, _) = on?;
let Paint::Gradient(placed) = self.placed(&f.paint, path.bounding_box()) else { return None };
(String::new(), format!("Bb\n{}0 BB\n", self.gradient_bg(&placed, path)?))
}
Paint::Pattern { .. } | Paint::None => return None,
};
basic(s, "Fill Style Filter", false, visible);
let _ = write!(
s,
"/Dictionary : /NotRecorded ,\n0 /Bool (UseEvenOdd) ,\n/FillStyle : 0 O\n{color}0 1 0 0 0 Xy\n{NO_LINE}0 XR\n0 1 Xd\n{gradient}"
);
s.push_str("/Def ; \n (FillStyle) ,\n");
s.push_str(END_BASIC);
Some(())
}
/// A stroke's basic filter: a color, its line style, and its width profile as the arrays
/// `BSVariableWidthTValuesArray`, `BSLeftWidthsArray` and `BSRightWidthsArray`. `None` for
/// other paint.
fn stroke_filter(&mut self, s: &mut String, st: &StrokeLayer, visible: bool) -> Option<()> {
if !matches!(st.paint, Paint::Solid { .. }) || st.overprint {
return None;
}
let ops = self.color_ops(&st.paint, true);
basic(s, "Stroke Style Filter", false, visible);
s.push_str("2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 R\n");
s.push_str(&ops);
s.push_str("0 1 0 0 0 Xy\n");
ai_ops::line_style(s, st);
s.push_str("0 XR\n1 0 Xd\n/Def ; \n (StrokeStyle) ,\n");
if let Some(p) = &st.profile {
let array = |s: &mut String, key: &str, values: &mut dyn Iterator<Item = f64>| {
s.push_str("/Array :");
for v in values {
s.push(' ');
ps::push_num(s, v);
s.push_str(" /Real ,");
}
let _ = writeln!(s, " ; {} ,", ps::bytes(key.as_bytes()));
};
array(s, "BSVariableWidthTValuesArray", &mut p.points.iter().map(|q| q.0));
array(s, "BSLeftWidthsArray", &mut p.points.iter().map(|q| q.1));
array(s, "BSRightWidthsArray", &mut p.points.iter().map(|q| q.2));
}
s.push_str(END_BASIC);
Some(())
}
/// A gradient instance's focal point (`Bh`, radial gradients only) and its `flag (name) x y
/// angle length a b c d tx ty 1 Bg` line for placed gradient `g` on `path`, as a fill's style
/// holds them ([`Self::instance_head`]).
fn gradient_bg(&mut self, g: &vectorcraft_color::GradientPaint, path: &BezPath) -> Option<String> {
let saved = std::mem::take(&mut self.body);
self.instance_head(g, false, path);
let line = std::mem::replace(&mut self.body, saved);
(!line.is_empty()).then_some(line)
}
/// An appearance item's basic filter. `None` for an item with transparency or effects of its
/// own, which the reader doesn't read on an object.
fn item_filter(&mut self, s: &mut String, item: &AppearanceItem, on: Option<(&BezPath, FillRule)>) -> Option<()> {
if item.opacity() < 1.0 || item.blend() != BlendMode::Normal || !item.effects().is_empty() {
return None;
}
match item {
AppearanceItem::Fill(f) => self.fill_filter(s, f, item.visible(), on),
AppearanceItem::Stroke(st) => self.stroke_filter(s, st, item.visible()),
}
}
/// The text of a style of appearance `ap` and transparency `xy` (after its name): the chain
/// of its stack (the fills and strokes that paint, the top one first, the contents among them
/// where the appearance puts them), its effects and its blend filter. A gradient fill is
/// placed on the outline of `on`, and a fill fills by its rule (`None`: the non-zero rule, on no
/// object). `None` when a fill, stroke or effect isn't one written here.
pub(super) fn style_text(&mut self, ap: &Appearance, xy: Xy, on: Option<(&BezPath, FillRule)>) -> Option<String> {
let mut s = String::from(
"/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
/CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n",
);
let ci = ap.contents_index.unwrap_or(0).min(ap.items.len());
let painting: Vec<(usize, &AppearanceItem)> = ap.items.iter().enumerate().filter(|(_, i)| !i.paint().is_none()).collect();
let below = painting.iter().filter(|(at, _)| *at < ci).count();
// Listed top first: the contents go above the `below` fills and strokes under them.
for (written, (_, item)) in painting.iter().rev().enumerate() {
if painting.len() - written == below {
s.push_str(CONDUIT);
}
self.item_filter(&mut s, item, on)?;
}
if below == 0 {
s.push_str(CONDUIT);
}
s.push_str(";\n /Part ,\n");
for e in &ap.effects {
s.push_str(&self.effect_filter(e)?);
}
blend_filter(&mut s, xy);
s.push_str(";\n\n/Execution ;\n /Def ;\n");
Some(s)
}
/// A live effect's basic filter, with the settings the reader reads
/// ([`crate::import`]'s `.ai` reader, `style.rs`), in the units it reads them in. `None` for an
/// effect, or a setting, that isn't written here.
fn effect_filter(&mut self, e: &Effect) -> Option<String> {
let p = vectorcraft_effects::merged_params(&e.id, &e.params);
let mut d = Entries::default();
let id = e.id.as_str();
let name = if id.starts_with("stylize.") { self.stylize_entries(id, &p, &mut d)? } else { Self::path_entries(id, &p, &mut d)? };
let mut s = String::new();
basic(&mut s, name, true, e.visible);
s.push_str("/Dictionary : /NotRecorded ,\n");
s.push_str(&d.0);
s.push_str(END_BASIC);
Some(s)
}
/// A Stylize effect's entries ([`Self::effect_filter`]) and its filter's name.
fn stylize_entries(&mut self, id: &str, p: &Value, d: &mut Entries) -> Option<&'static str> {
Some(match id {
"stylize.dropShadow" => {
d.int("blnd", i64::from(mode_code(p.get("mode")?.as_str()?)?));
d.real("opac", num(p, "opacity")? / 100.0);
let darkness = word(p, "shade").as_deref() == Some("darkness");
if darkness {
d.real("dark", num(p, "darkness")?);
}
d.real("vert", num(p, "y")?);
d.real("horz", num(p, "x")?);
d.real("blur", num(p, "blur")? / 2.0);
let color = vectorcraft_effects::color_param(p, vectorcraft_color::Color::BLACK);
self.fill_style(&mut d.0, color, "sclr");
d.int("csrc", i64::from(darkness));
"Adobe Drop Shadow" // brand-ok: the filter's name in the files
}
"stylize.innerGlow" => {
d.int("blnd", i64::from(mode_code(p.get("mode")?.as_str()?)?));
d.real("opac", num(p, "opacity")? / 100.0);
d.real("blur", num(p, "blur")?);
let color = vectorcraft_effects::color_param(p, vectorcraft_color::Color::WHITE);
self.fill_style(&mut d.0, color, "gclr");
d.int("gtyp", i64::from(word(p, "source").as_deref() == Some("edge")));
"Adobe Inner Glow" // brand-ok: the filter's name in the files
}
"stylize.outerGlow" => {
d.int("blnd", i64::from(mode_code(p.get("mode")?.as_str()?)?));
d.real("opac", num(p, "opacity")? / 100.0);
d.real("blur", num(p, "blur")? / 2.0);
let color = vectorcraft_effects::color_param(p, vectorcraft_color::Color::BLACK);
self.fill_style(&mut d.0, color, "sclr");
"Adobe Outer Glow" // brand-ok: the filter's name in the files
}
"stylize.feather" => {
d.real("Radius", num(p, "radius")?);
"Adobe Fuzzy Mask" // brand-ok: the filter's name in the files
}
"stylize.roundCorners" => {
d.real("radius", num(p, "radius")?);
"Adobe Round Corners" // brand-ok: the filter's name in the files
}
"stylize.scribble" => {
d.real("Angle", num(p, "angle")?);
d.real("EdgeOverlap", num(p, "overlap")?);
d.real("EdgeOverlapVariation", num(p, "overlapVariation")?);
d.real("StrokeWidth", num(p, "strokeWidth")?);
d.real("Scribbliness", num(p, "curviness")? / 100.0);
d.real("ScribbleVariation", num(p, "curvinessVariation")? / 100.0);
d.real("Spacing", num(p, "spacing")?);
d.real("SpacingVariation", num(p, "spacingVariation")?);
"Adobe Scribble Fill" // brand-ok: the filter's name in the files
}
_ => return None,
})
}
/// Convert to Shape's, a Path effect's or Pathfinder › Add's entries ([`Self::effect_filter`])
/// and its filter's name.
fn path_entries(id: &str, p: &Value, d: &mut Entries) -> Option<&'static str> {
Some(match id {
"convertToShape.rectangle" | "convertToShape.roundedRectangle" | "convertToShape.ellipse" => {
let shape = match id {
"convertToShape.rectangle" => 0,
"convertToShape.roundedRectangle" => 1,
_ => 2,
};
let relative = flag(p, "relative")?;
d.int("Shape", shape);
d.real("Absolute", if relative { 0.0 } else { 1.0 });
d.real("AbsWidth", num(p, "width")?);
d.real("AbsHeight", num(p, "height")?);
d.real("RelWidth", num(p, "extraW")? / 2.0);
d.real("RelHeight", num(p, "extraH")? / 2.0);
if shape == 1 {
d.real("CornerRadius", num(p, "radius")?);
}
"Adobe Shape Effects" // brand-ok: the filter's name in the files
}
"path.offsetPath" => {
d.real("ofst", num(p, "offset")?);
let joins = match word(p, "joins")?.as_str() {
"round" => 0,
"bevel" => 1,
"miter" => 2,
_ => return None,
};
d.int("jntp", joins);
d.real("mlim", num(p, "miterLimit")?);
"Adobe Offset Path" // brand-ok: the filter's name in the files
}
"path.outlineObject" => "Adobe Outline Type", // brand-ok: the filter's name in the files
"path.outlineStroke" => "Adobe Outline Stroke", // brand-ok: the filter's name in the files
"pathfinder.add" => {
d.int("Command", 0);
d.bool("ConvertCustom", true);
d.bool("ExtractUnpainted", true);
d.real("Mix", 0.5);
d.real("Precision", 10.0);
d.bool("RemovePoints", false);
d.real("TrapAspect", 1.0);
d.bool("TrapConvertCustom", false);
d.real("TrapMaxTint", 1.0);
d.bool("TrapReverse", false);
d.real("TrapThickness", 0.25);
d.real("TrapTint", 0.4);
d.real("TrapTintTolerance", 0.05);
"Adobe Pathfinder" // brand-ok: the filter's name in the files
}
_ => return None,
})
}
/// The style object `orig` (`n` before baking) is written with; `None` when the reader wouldn't
/// read the object as it is with it. A gradient fill is placed on `n`'s outline, as the object
/// draws it. A style that isn't written leaves no gradient definition or warning behind.
pub(super) fn object_style(&mut self, n: &Node, orig: &Node) -> Option<String> {
if let NodeKind::Group { children, .. } = &orig.kind
&& bakes_members(orig)
&& !children.iter().all(|c| self.member_keeps_outline(c))
{
return None;
}
let graded = orig.appearance.items.iter().any(|i| matches!(i.paint(), Paint::Gradient(_)));
let saved = (graded.then(|| self.gradient_mark()), self.warnings.len());
let path = drawn_outline(n, orig);
let rule = object_rule(orig);
let text = self.style_text(&orig.appearance, Xy::of(orig), path.as_ref().map(|p| (p, rule))).filter(|t| object_reads(orig, t));
let Some(text) = text else {
if let Some(mark) = saved.0 {
self.gradient_rollback(mark);
}
self.warnings.truncate(saved.1);
return None;
};
Some(self.styles.object_style(text))
}
/// Is member `m` of a styled group whose effects change its members' outlines (and each of its
/// own members) written on the outline those effects draw on: every fill and stroke as the
/// object paints it ([`Self::direct`], [`Self::direct_stroke`]), not as filled outlines, brush
/// art or pattern tiles, and no gradient that fits its object, which the effects would fit to
/// the new outline?
fn member_keeps_outline(&self, m: &Node) -> bool {
let items_keep = m.appearance.items.iter().all(|i| match i {
AppearanceItem::Fill(f) => f.paint.is_none() || self.direct(&f.paint),
AppearanceItem::Stroke(s) => s.paint.is_none() || self.direct_stroke(s),
});
items_keep && m.children().is_none_or(|c| c.iter().all(|c| self.member_keeps_outline(c)))
}
/// Object `n` (as baking left it; `orig` before baking) with the style `name`: its lock and
/// hidden state; its drawn look (a group of its vector art as baking left it, without shadows,
/// glows or feathers, the object's transparency
/// after the group's end, `0 0 Xd`, `6 () XW`); the object itself on `%_` lines (a path's or
/// compound path's points painted with nothing, or with its gradient fill when its style has
/// one; a group with its members), its name and opacity mask; then `1 (name) XW`.
pub(super) fn styled_object(&mut self, n: &Node, orig: &Node, name: &str) {
self.state(orig.locked, !orig.visible);
let xy = Xy::of(orig);
let was = self.in_look;
self.in_look = true;
self.line("u");
let mut look = n.clone();
(look.name, look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape) =
(None, 1.0, BlendMode::Normal, false, Knockout::Neutral, false);
if look.extras().mask.is_some() {
look.extras_mut().mask = None;
}
match &look.kind {
NodeKind::Group { children, clip: false } => {
for c in children.clone() {
self.node(&c);
}
}
_ => self.node(&look),
}
self.line("U");
self.write_xy(xy);
self.line("0 0 Xd\n6 () XW");
self.in_look = was;
// The object, on `%_` lines, in its own state (the look's members may have changed it).
self.state(orig.locked, !orig.visible);
let saved = std::mem::take(&mut self.body);
self.hidden += 1;
let fit = drawn_outline(n, orig).map(|p| p.bounding_box());
match &orig.kind {
NodeKind::Path { path, rule, .. } => self.styled_outline(orig, path, *rule, fit, xy),
NodeKind::Compound { rule, .. } => self.styled_outline(orig, &compound_path(orig), *rule, fit, xy),
NodeKind::Group { children, .. } => {
self.line("u");
for c in children {
self.node(c);
}
self.line("U");
}
_ => {}
}
self.dictionary(orig);
self.hidden -= 1;
let part = std::mem::replace(&mut self.body, saved);
hide(&part, &mut self.body);
self.block_end = usize::MAX;
let _ = writeln!(self.body, "1 {} XW", ps::bytes(name.as_bytes()));
}
/// A styled path's or compound path's points: painted with nothing, or with its gradient fill
/// (which its style's gradient fill is), placed on `fit` (the outline's bounds when `None`).
fn styled_outline(&mut self, orig: &Node, path: &vectorcraft_geom::PathData, rule: vectorcraft_geom::FillRule, fit: Option<Rect>, xy: Xy) {
let bounds = fit.unwrap_or_else(|| path.to_bezpath().bounding_box());
let gradient = orig.appearance.items.iter().find_map(|i| match i {
AppearanceItem::Fill(f) if matches!(f.paint, Paint::Gradient(_)) => Some(f),
_ => None,
});
match gradient {
Some(f) => {
let fill = FillLayer { paint: self.placed(&f.paint, bounds), ..f.clone() };
self.plain_object(path, rule, Some(&fill), None, xy.object());
}
None => self.plain_object(path, rule, None, None, xy.object()),
}
}
/// The art styles written, in a non-printing block: `%AI9_BeginArtStyles`, each style,
/// `%AI9_EndArtStyles`.
pub(in crate::ai_editing) fn art_styles(&self, s: &mut String) {
if self.styles.known.is_empty() {
return;
}
s.push_str("%AI5_Begin_NonPrinting\nNp\n%AI9_BeginArtStyles\n");
for (name, text) in &self.styles.known {
s.push_str(&known_style(name, text));
}
s.push_str("%AI9_EndArtStyles\n%AI5_End_NonPrinting--\n");
}
}
/// The outline a path's or compound path's style places a gradient fill on.
fn object_outline(n: &Node) -> Option<BezPath> {
match &n.kind {
NodeKind::Path { path, .. } => Some(path.to_bezpath()),
NodeKind::Compound { .. } => Some(compound_path(n).to_bezpath()),
_ => None,
}
}
/// The outline a styled path or compound path draws: `n`'s, as baking left it, when it is still a
/// path or compound path, else `orig`'s.
fn drawn_outline(n: &Node, orig: &Node) -> Option<BezPath> {
object_outline(orig)?;
object_outline(n).or_else(|| object_outline(orig))
}
/// The fill rule of a path or compound path (a group's is the default).
fn object_rule(n: &Node) -> FillRule {
match &n.kind {
NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. } => *rule,
_ => FillRule::NonZero,
}
}
/// Does the reader read object `n` written with style text `text` as it is: a path or compound
/// path with a style it reads on any object, filled by the non-zero rule when the style fills it,
/// or a group with no fills or strokes of its own?
fn object_reads(n: &Node, text: &str) -> bool {
let section = known_style("x", text);
let own = n.appearance.fill().map(|f| &f.paint).filter(|p| matches!(p, Paint::Gradient(_)));
let Some(mut read) = crate::import::read_art_style(section.as_bytes(), "x", own) else { return false };
let group = matches!(n.kind, NodeKind::Group { .. });
if !read.simple || (group && !read.appearance.items.is_empty()) || (!group && read.pathfinder) {
return false;
}
if !group {
let filled = n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_)) && !i.paint().is_none());
if filled && object_rule(n) == FillRule::EvenOdd {
return false;
}
// A path's contents are nothing: the reader keeps the object's own.
read.appearance.contents_index = n.appearance.contents_index;
}
same_appearance(&read.appearance, &n.appearance)
}
/// Do appearances `a` and `b` draw the same, as the reader reads one written from the other: the
/// fills and strokes that paint, within the written numbers' precision, and the effects with
/// their settings filled in from their defaults (blending modes in any case, colors as colors).
pub(in crate::ai_editing) fn same_appearance(a: &Appearance, b: &Appearance) -> bool {
let norm = |ap: &Appearance| -> Value {
let mut ap = ap.clone();
let ci = ap.contents_index.unwrap_or(0).min(ap.items.len());
let below = ap.items.iter().take(ci).filter(|i| !i.paint().is_none()).count();
ap.items.retain(|i| !i.paint().is_none());
ap.contents_index = (below > 0).then_some(below);
for e in ap.effects.iter_mut().chain(ap.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut())) {
e.params = normalized_params(e);
}
serde_json::to_value(&ap).unwrap_or(Value::Null)
};
near(&norm(a), &norm(b))
}
/// Effect `e`'s settings with its defaults filled in, its blending mode in lower case and its color as
/// `#rrggbb`.
fn normalized_params(e: &Effect) -> Value {
let mut p = vectorcraft_effects::merged_params(&e.id, &e.params);
if let Some(m) = word(&p, "mode") {
p["mode"] = Value::String(m);
}
if p.get("color").is_some() {
p["color"] = Value::String(vectorcraft_effects::color_param(&p, vectorcraft_color::Color::BLACK).to_hex());
}
for key in ["shade", "source", "joins", "points", "orientation"] {
if let Some(w) = word(&p, key) {
p[key] = Value::String(w);
}
}
p
}
/// How far apart two numbers may read in [`near`]: a number written to 4 decimals, then converted
/// from a fraction to a percentage (`5e-3`) or from radians to degrees (`3e-3`).
const NEAR: f64 = 6e-3;
/// JSON values equal but for numbers within the written numbers' precision.
fn near(a: &Value, b: &Value) -> bool {
match (a, b) {
(Value::Number(x), Value::Number(y)) => match (x.as_f64(), y.as_f64()) {
(Some(x), Some(y)) => (x - y).abs() <= NEAR,
_ => x == y,
},
(Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(x, y)| near(x, y)),
(Value::Object(x), Value::Object(y)) => x.len() == y.len() && x.iter().all(|(k, v)| y.get(k).is_some_and(|w| near(v, w))),
_ => a == b,
}
}
+339
View File
@@ -0,0 +1,339 @@
//! Symbols: their definitions, the symbol list and their instances (see [`crate::ai_editing`] for
//! the form).
use std::collections::HashSet;
use std::fmt::Write;
use vectorcraft_color::Paint;
use vectorcraft_doc::{Knockout, Node, NodeKind, SymbolExportType};
use vectorcraft_geom::Affine;
use super::{MAX_NEST, Writer, Xy};
use crate::import::MAX_SYMBOLS;
use crate::ps;
pub(in crate::ai_editing) const SYMBOL_ART: &str = "symbol instances with a fill, appearance changes, isolation, knockout or knockout shape of their own, instances of symbols with 9-slice guides or pattern paint, instances in pattern tiles or in art cut to a clipping object, instances scaled almost flat, instances that turn, mirror or scale symbols holding type, live objects, instances written as their art, shapes with rounded live corners or strokes written as outlines or brush art, instances that scale their symbol more than 100 times, instances on the layers of a large canvas and instances of symbols past 4,096 are written as their art in the editing data for other apps";
pub(in crate::ai_editing) const SYMBOL_OPTIONS: &str =
"the 9-slice guides, export types and dynamic type of symbols are left out of the editing data for other apps";
pub(in crate::ai_editing) const MISSING_SYMBOL: &str =
"symbol instances of symbols the document doesn't have are written as empty groups in the editing data for other apps";
/// The most an instance may scale its symbol's art, nested instances' scales included: the art's
/// numbers are written to four decimals, so a scale of 100 places them within 0.005 pt.
const MAX_SCALE: f64 = 100.0;
pub(in crate::ai_editing) const SYMBOL_COUNT: &str = "symbols past 4,096 are left out of the editing data for other apps";
/// Whether the canvas works `n` itself (not its children) out again after placing an instance:
/// type, live objects and shapes with rounded live corners, whose strokes, steps and corners depend
/// on where the instance puts them.
pub(super) fn redrawn(n: &Node) -> bool {
let rounded = |l: &vectorcraft_doc::LiveShape| match l {
vectorcraft_doc::LiveShape::Rectangle { radii, .. } => radii.iter().any(|r| *r > 0.0),
vectorcraft_doc::LiveShape::Polygon { radii, .. } | vectorcraft_doc::LiveShape::Path { radii, .. } => radii.iter().any(|r| *r > 0.0),
vectorcraft_doc::LiveShape::Ellipse { .. } | vectorcraft_doc::LiveShape::Line { .. } => false,
};
match &n.kind {
NodeKind::Path { live: Some(l), .. } => rounded(l),
NodeKind::Text(_)
| NodeKind::Blend { .. }
| NodeKind::Envelope { .. }
| NodeKind::Mesh(_)
| NodeKind::Repeat(_)
| NodeKind::PlacedDocument(_)
| NodeKind::Intertwine { .. } => true,
_ => false,
}
}
impl Writer<'_> {
/// Whether instance `n` of symbol `symbol`, placed by `xf`, is written as an instance: not on the
/// layers of a large canvas, in a pattern's tile or in art cut to a clipping object, without a
/// fill or appearance changes of its own (which stain or change the art it draws) and without
/// isolation, knockout or knockout shape of its own (which an instance's transparency doesn't
/// hold), of a symbol without 9-slice guides and without pattern paint in its art (the canvas
/// keeps an instance's pattern tiles where the document puts them, and a definition's art moves
/// with each instance) whose definition can be written ([`Self::define_symbol`]), by a matrix
/// that keeps the art's area as it is written and scales it as the definition allows
/// ([`Self::keeps_scale`]).
pub(super) fn live_instance(&mut self, n: &Node, symbol: &str, xf: Affine) -> bool {
let own = vectorcraft_brush::stain(n).is_some() || !n.extras().symbol_overrides.is_empty();
let group_state = n.isolate || n.knockout != Knockout::Neutral || n.knockout_shape;
// The matrix as written (to ten decimals) must still keep the art's area.
let m = Affine::new((self.instance_space * xf).as_coeffs().map(|v| (v * 1e10).round() / 1e10));
(self.symbols_live || self.in_symbol)
&& self.defining.is_empty()
&& self.clip.is_none()
&& !own
&& !group_state
&& self.doc.symbol_nine_slice(symbol).is_none()
&& m.as_coeffs().iter().all(|v| v.is_finite())
&& m.determinant().abs() >= 1e-12
&& self.define_symbol(symbol)
&& !self.symbol_paints_pattern(symbol)
&& self.keeps_scale(symbol, xf)
}
/// Whether instance matrix `xf` places symbol `symbol`'s definition as the canvas draws the
/// instance. A definition holding art the canvas works out again after placing an instance
/// ([`redrawn`], strokes written as outlines or brush art, and instances written as their art)
/// takes only matrices that move it;
/// any other takes a scale up to [`MAX_SCALE`], nested instances' scales included. A live
/// instance in a symbol's art passes both to that symbol.
fn keeps_scale(&mut self, symbol: &str, xf: Affine) -> bool {
let [a, b, c, d, ..] = xf.as_coeffs();
let fixed = self.fixed_symbols.contains(symbol);
let scale = a.hypot(b).max(c.hypot(d)) * self.symbol_scales.get(symbol).copied().unwrap_or(1.0);
let keeps = if fixed { (a - 1.0).abs() < 1e-9 && b.abs() < 1e-9 && c.abs() < 1e-9 && (d - 1.0).abs() < 1e-9 } else { scale <= MAX_SCALE };
if keeps && self.in_symbol {
self.wrote_fixed |= fixed;
self.inner_scale = self.inner_scale.max(scale);
}
keeps
}
/// Whether the art of symbol `name`, an opacity mask in it or the art of a symbol it holds an
/// instance of, at any depth, fills or strokes something (type included) with a pattern, or its
/// definition holds pattern tiles. Worked out once a symbol, after it is defined.
fn symbol_paints_pattern(&mut self, name: &str) -> bool {
if self.pattern_written.contains(name) {
return true;
}
if let Some(known) = self.patterned_symbols.get(name) {
return *known;
}
let mut seen = HashSet::from([name.to_string()]);
let mut todo = vec![name.to_string()];
let mut found = false;
while let Some(next) = todo.pop() {
let (own, used) = self.symbol_own_patterns(&next);
if own {
found = true;
break;
}
for u in used {
if seen.insert(u.clone()) {
todo.push(u);
}
}
}
self.patterned_symbols.insert(name.to_string(), found);
found
}
/// Whether the art of symbol `name` or an opacity mask in it fills or strokes something (type
/// included) with a pattern, and the symbols its instances and inline graphics there use; looked
/// at once a symbol.
fn symbol_own_patterns(&mut self, name: &str) -> (bool, Vec<String>) {
if let Some(known) = self.pattern_symbols.get(name) {
return known.clone();
}
let doc = self.symbol_doc;
let mut own = false;
let mut used = vec![];
if let Some(sym) = doc.symbols.iter().find(|s| s.name == name) {
let pattern = |p: &Paint| matches!(p, Paint::Pattern { .. });
vectorcraft_doc::swatches::walk_with_masks(&sym.art, &mut |m| {
own |= vectorcraft_doc::pattern::uses_pattern(m, None);
match &m.kind {
NodeKind::Text(t) => {
own |= t.runs.iter().any(|r| pattern(&r.style.fill) || pattern(&r.style.stroke));
// Inline graphics are written as their symbols' art.
used.extend(t.runs.iter().filter_map(|r| r.inline.as_ref()).map(|art| art.symbol.clone()));
}
NodeKind::SymbolInstance { symbol, .. } => used.push(symbol.clone()),
_ => {}
}
});
}
self.pattern_symbols.insert(name.to_string(), (own, used.clone()));
(own, used)
}
/// An instance of `symbol` placed by `xf`, of transparency `xy`: `/SymbolInstance :`, `(name)
/// /SymbolRef ,`, the matrix taking the symbol's art to art space (in a symbol's art, to the
/// canvas's space turned y up about art space's origin there) as `a b c d tx ty
/// /RTransformMatrix` (to ten decimals), `;`, then its state block as a group's: `Xy`, `0 0 Xd`
/// and `6 () XW` when it has transparency, else `9 () XW`. Its dictionary goes between the two.
pub(super) fn symbol_instance(&mut self, symbol: &str, xf: Affine, xy: Xy) {
let m = self.instance_space * xf;
let _ = write!(self.body, "/SymbolInstance :\n{} /SymbolRef ,\n", ps::bytes(symbol.as_bytes()));
for v in m.as_coeffs() {
self.body.push_str(&super::images::precise(v));
self.body.push(' ');
}
self.body.push_str("/RTransformMatrix\n;\n");
// An instance with isolation, knockout or knockout shape of its own is written as its art
// ([`Self::live_instance`]); these are the values of the others.
let xy = Xy { isolate: false, knockout: Knockout::Neutral, shape: false, ..xy };
self.block_start = self.body.len();
if xy == Xy::PLAIN {
self.line("9 () XW");
} else {
self.write_xy(xy);
self.line("0 0 Xd\n6 () XW");
}
self.block_end = self.body.len();
}
/// Write symbol `name`'s definition, once: `%AI14_BeginSymbol`, `(name)`, `0 A`, `0 Xw`, `0 Ae`,
/// the art in the symbol's space (y down: its numbers are the symbol's own) as a group (`u` …
/// `U`; art that isn't a group, or is a plain group of one object, in a group of its own), the
/// symbol's registration point (`AI13PatternRegistrationType`, 1 to 9 from the top left, row by
/// row) in that group's dictionary, `9 () XW`, `%AI10_EndSymbol`. Linked images in the
/// art are embedded. The symbols its art's instances use are defined first, and the art is
/// written from the top of the nesting whatever the instance that asks for it, so a definition
/// is the same wherever its first instance lies. False when it can't be: the document doesn't
/// have the symbol, it is being written (its art holds an instance of itself), it is reached
/// through more than [`MAX_NEST`] definitions being written, or the definitions written and
/// being written leave no place under [`MAX_SYMBOLS`].
pub(super) fn define_symbol(&mut self, name: &str) -> bool {
if self.defined_symbols.contains(name) {
return true;
}
let doc = self.symbol_doc;
let Some(sym) = doc.symbols.iter().find(|s| s.name == name) else { return false };
if self.defining_symbols.iter().any(|d| d == name) || self.defining_symbols.len() >= MAX_NEST as usize {
return false;
}
// The reader keeps no more definitions than this, and each definition being written takes
// one when it ends.
if self.symbol_defs.len() + self.defining_symbols.len() >= MAX_SYMBOLS {
self.warn(SYMBOL_COUNT);
return false;
}
if sym.dynamic || doc.symbol_export_type(name) != SymbolExportType::default() || doc.symbol_nine_slice(name).is_some() {
self.warn(SYMBOL_OPTIONS);
}
self.defining_symbols.push(name.to_string());
let mut used = vec![];
vectorcraft_doc::swatches::walk_with_masks(&sym.art, &mut |m| {
if let NodeKind::SymbolInstance { symbol, .. } = &m.kind {
used.push(symbol.as_str());
}
});
for u in used {
self.define_symbol(u);
}
if self.symbol_defs.len() + self.defining_symbols.len() > MAX_SYMBOLS {
self.defining_symbols.pop();
self.warn(SYMBOL_COUNT);
return false;
}
// The art is written in the symbol's space, from the state `0 A` and `0 Xw` set, from the
// document at its own size.
let origin = self.canvas_origin;
let about_origin = Affine::new([1.0, 0.0, 0.0, -1.0, -origin.0, origin.1]);
let page_doc = std::mem::replace(&mut self.doc, doc);
let saved = (
std::mem::take(&mut self.body),
(self.to_art, self.grad_space, self.canvas, self.instance_space),
self.state.replace((false, false)),
self.gs.replace(Xy::OPAQUE),
self.clip.take(),
(self.block_start, self.block_end),
(std::mem::replace(&mut self.in_symbol, true), std::mem::take(&mut self.hidden)),
self.root_entries.take(),
std::mem::take(&mut self.wrote_pattern),
(std::mem::take(&mut self.wrote_fixed), std::mem::replace(&mut self.inner_scale, 1.0)),
);
// Gradients' matrices and instances' matrices are written about the canvas point of art
// space's origin, y up; `Bg` places a gradient on the art as it lies in the symbol's space.
(self.to_art, self.grad_space, self.canvas, self.instance_space) = (Affine::IDENTITY, about_origin, Affine::IDENTITY, about_origin);
self.block_end = usize::MAX;
let registration = u16::from(doc.symbol_registration(name).0.min(8)) + 1;
let entries = format!("%_{registration} /Int (AI13PatternRegistrationType) ,\n");
// The canvas draws a symbol's art even when its root is hidden, so the root is written shown.
let shown;
let root: &Node = if sym.art.visible {
&sym.art
} else {
let mut a = (*sym.art).clone();
a.visible = true;
shown = a;
&shown
};
// A definition holds a group: art of another kind, and a plain group of one object (which
// the reader takes for that group), are written in one.
let wrap = !matches!(root.kind, NodeKind::Group { clip: false, .. }) || crate::import::symbol_art_member(root).is_some();
let nest = std::mem::replace(&mut self.nest, 1);
if wrap {
self.line("u");
self.node(root);
let _ = write!(self.body, "U\n%_/ArtDictionary :\n{entries}%_;\n%_\n9 () XW\n");
} else {
// A group always writes its dictionary ([`Self::dictionary`]), which takes the entries.
self.root_entries = Some((root.id, entries));
self.node(root);
}
self.nest = nest;
// Objects the writing doesn't pass through one by one (clipping paths, a clipping group's
// own path) count as well.
vectorcraft_doc::swatches::walk_with_masks(&sym.art, &mut |m| self.wrote_fixed |= redrawn(m));
if self.wrote_pattern {
self.pattern_written.insert(name.to_string());
}
if self.wrote_fixed {
self.fixed_symbols.insert(name.to_string());
}
if self.inner_scale > 1.0 {
self.symbol_scales.insert(name.to_string(), self.inner_scale);
}
let art;
(
art,
(self.to_art, self.grad_space, self.canvas, self.instance_space),
self.state,
self.gs,
self.clip,
(self.block_start, self.block_end),
(self.in_symbol, self.hidden),
self.root_entries,
self.wrote_pattern,
(self.wrote_fixed, self.inner_scale),
) = saved;
self.doc = page_doc;
let art = std::mem::replace(&mut self.body, art);
self.defining_symbols.pop();
let text = format!("%AI14_BeginSymbol\n{}\n0 A\n0 Xw\n0 Ae\n{art}%AI10_EndSymbol\n", ps::bytes(name.as_bytes()));
self.defined_symbols.insert(name.to_string());
self.symbol_defs.push(text);
true
}
/// Every symbol of the document defined, in its order (those its art uses before it): the
/// Symbols panel keeps the ones no instance uses too, and on a large canvas all of them.
pub(in crate::ai_editing) fn symbols(&mut self) {
let doc = self.symbol_doc;
for s in &doc.symbols {
self.define_symbol(&s.name);
}
}
/// The symbol definitions, in the setup after the patterns: `%AI5_Begin_NonPrinting`, `Np`, each
/// definition, `%AI5_End_NonPrinting--`.
pub(in crate::ai_editing) fn symbol_definitions(&self, s: &mut String) {
if self.symbol_defs.is_empty() {
return;
}
s.push_str("%AI5_Begin_NonPrinting\nNp\n");
for d in &self.symbol_defs {
s.push_str(d);
}
s.push_str("%AI5_End_NonPrinting--\n");
}
/// The symbol list, after the palette: the names of the symbols defined in the document's order
/// (the Symbols panel's), between `%AI24_BeginSymbolList` and `%AI24_EndSymbolList` in a
/// non-printing block.
pub(in crate::ai_editing) fn symbol_list(&self, s: &mut String) {
if self.symbol_defs.is_empty() {
return;
}
s.push_str("%AI5_Begin_NonPrinting\nNp\n%AI24_BeginSymbolList\n");
for sym in &self.symbol_doc.symbols {
if self.defined_symbols.contains(&sym.name) {
let _ = writeln!(s, "{}", ps::bytes(sym.name.as_bytes()));
}
}
s.push_str("%AI24_EndSymbolList\n%AI5_End_NonPrinting--\n");
}
}
+1 -1
View File
@@ -70,7 +70,7 @@ use graphics::{GState, Out};
use interp::{Fault, Interp};
use obj::PsError;
pub(crate) use ai::MAX_GRADIENT_STOPS;
pub(crate) use ai::{MAX_GRADIENT_STOPS, MAX_SYMBOLS, read_art_style, symbol_art_member};
pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES};
pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from};
pub(crate) use native::{MAX_TEXT, scale_document};
+22 -2
View File
@@ -35,13 +35,16 @@ use super::lex::find;
use crate::ps;
pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN;
#[cfg(test)]
pub(crate) use envelope::MAX_CHECKED;
pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType};
pub(crate) use frames::text_frames;
pub(crate) use paint::MAX_STOPS as MAX_GRADIENT_STOPS;
pub use read::{
BindingRef, Brushes, IMAGE_TOO_LARGE, PaletteSwatches, Structure, active_artboard, artboards, bindings_note, brushes, graphic_styles, palette,
read, read_beside, variables,
};
pub(crate) use read::{join_and, slot_frame, slot_of};
pub(crate) use read::{MAX_SYMBOLS, join_and, read_art_style, slot_frame, slot_of, symbol_art_member};
pub(crate) use read::is_look_slot;
@@ -74,6 +77,19 @@ const MAX_ZSTD_WINDOW: u64 = 64 << 20;
/// Most Zstandard frames read (the app writes one).
const MAX_FRAMES: usize = 4096;
#[cfg(test)]
thread_local! {
/// How many bytes [`Codec::decode`] has looked at on this thread to find whether another
/// Zstandard frame follows or only zero padding is left.
static PADDING_LOOKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// [`PADDING_LOOKS`] of this thread.
#[cfg(test)]
fn padding_looks() -> u64 {
PADDING_LOOKS.get()
}
const EPS_BEGIN: &[u8] = b"%AI9_PrivateDataBegin";
const EPS_END: &[u8] = b"%AI9_PrivateDataEnd";
@@ -171,7 +187,11 @@ impl Codec {
// can itself end in a zero byte, so the padding is what is left after the last frame.
let mut src = data;
let mut frames = 0usize;
while src.iter().any(|b| *b != 0) {
while src.iter().any(|b| {
#[cfg(test)]
PADDING_LOOKS.set(PADDING_LOOKS.get().saturating_add(1));
*b != 0
}) {
frames += 1;
if frames > MAX_FRAMES {
return Err(damaged("its Zstandard compression"));
Loaded 100 of 287 files, more files were not shown because too many files have changed in this diff. Show more