diff --git a/.github/workflows/print.yml b/.github/workflows/print.yml
index 400a819442..058705ce29 100644
--- a/.github/workflows/print.yml
+++ b/.github/workflows/print.yml
@@ -13,27 +13,27 @@ on:
workflow_dispatch:
permissions:
contents: read
-env:
- CARGO_TERM_COLOR: always
- CARGO_INCREMENTAL: 0
+# A newer push to a PR branch cancels its older run.
+concurrency:
+ group: print-${{ github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
+ # Desktop printing on Windows, through the suite's shared gate. Pull requests restore the cache
+ # but never save one; a manual run on main saves the cache they restore.
windows:
- runs-on: windows-2022
- timeout-minutes: 90
- steps:
- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- - uses: dtolnay/rust-toolchain@e2a55d2ffb04f378e9626c28d38b36d230d1e12f # master
- with:
- toolchain: stable
- components: clippy
- - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
- with:
- key: desktop-print
- - run: cargo clippy --locked -p vectorcraft --all-targets -- -D warnings
- - run: cargo test --locked -p vectorcraft
- - name: Check pending submission and queue refusal feedback
- shell: bash
- # A filter that matches nothing still passes, so fail unless some test ran.
- run: |
- cargo test --locked -p vectorcraft-ui-egui --lib -- tests::printps | tee printps.log
- grep -Eq 'test result: ok\. [1-9][0-9]* passed' printps.log || { echo "::error::tests::printps matched no tests"; exit 1; }
+ # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
+ uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
+ with:
+ os: '["windows-2022"]'
+ timeout-minutes: 90
+ # As before: printing builds and tests without craft-fonts, nextest or the wasm target.
+ craft-fonts-ref: ""
+ tools: ""
+ targets: ""
+ # A filter that matches nothing still passes, so the printps run fails unless some test ran.
+ command: |
+ cargo clippy --locked -p vectorcraft --all-targets -- -D warnings
+ cargo test --locked -p vectorcraft
+ log="$RUNNER_TEMP/printps.log"
+ cargo test --locked -p vectorcraft-ui-egui --lib -- tests::printps | tee "$log"
+ grep -Eq 'test result: ok\. [1-9][0-9]* passed' "$log" || { echo "::error::tests::printps matched no tests"; exit 1; }
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index d1677e538c..07b3c6b7fe 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -63,6 +63,7 @@ jobs:
needs: git-sources
permissions:
contents: write
+ packages: write
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
diff --git a/Cargo.lock b/Cargo.lock
index 951f60bb05..308a974df5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6061,7 +6061,7 @@ dependencies = [
[[package]]
name = "vectorcraft"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"arboard",
"block2 0.6.2",
@@ -6106,7 +6106,7 @@ dependencies = [
[[package]]
name = "vectorcraft-affinity"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"crc32fast",
"flate2",
@@ -6117,7 +6117,7 @@ dependencies = [
[[package]]
name = "vectorcraft-brush"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"kurbo 0.13.1",
"serde",
@@ -6129,7 +6129,7 @@ dependencies = [
[[package]]
name = "vectorcraft-cad"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6145,7 +6145,7 @@ dependencies = [
[[package]]
name = "vectorcraft-cli"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"log",
"objc2-core-foundation",
@@ -6167,7 +6167,7 @@ dependencies = [
[[package]]
name = "vectorcraft-color"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"kurbo 0.13.1",
"moxcms",
@@ -6179,7 +6179,7 @@ dependencies = [
[[package]]
name = "vectorcraft-doc"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"chrono",
"hayro-ccitt",
@@ -6198,7 +6198,7 @@ dependencies = [
[[package]]
name = "vectorcraft-effects"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6214,7 +6214,7 @@ dependencies = [
[[package]]
name = "vectorcraft-engine"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"cfb",
"craft-docpath",
@@ -6255,7 +6255,7 @@ dependencies = [
[[package]]
name = "vectorcraft-eps"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"fax",
"flate2",
@@ -6280,7 +6280,7 @@ dependencies = [
[[package]]
name = "vectorcraft-format"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"flate2",
"proptest",
@@ -6295,7 +6295,7 @@ dependencies = [
[[package]]
name = "vectorcraft-geom"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"kurbo 0.13.1",
"proptest",
@@ -6307,7 +6307,7 @@ dependencies = [
[[package]]
name = "vectorcraft-mcp"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"image",
"log",
@@ -6326,7 +6326,7 @@ dependencies = [
[[package]]
name = "vectorcraft-metafile"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6340,7 +6340,7 @@ dependencies = [
[[package]]
name = "vectorcraft-pathops"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"kurbo 0.13.1",
"linesweeper",
@@ -6352,7 +6352,7 @@ dependencies = [
[[package]]
name = "vectorcraft-pdf"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"aes",
"chrono",
@@ -6384,7 +6384,7 @@ dependencies = [
[[package]]
name = "vectorcraft-plugins"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"serde",
"serde_json",
@@ -6398,7 +6398,7 @@ dependencies = [
[[package]]
name = "vectorcraft-render"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"flate2",
"gif 0.14.2",
@@ -6428,14 +6428,14 @@ dependencies = [
[[package]]
name = "vectorcraft-scriptcheck"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"proptest",
]
[[package]]
name = "vectorcraft-svg"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"craft-docpath",
"flate2",
@@ -6460,7 +6460,7 @@ dependencies = [
[[package]]
name = "vectorcraft-testkit"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"fax",
"image",
@@ -6478,7 +6478,7 @@ dependencies = [
[[package]]
name = "vectorcraft-text"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"harfrust 0.13.3",
"icu_segmenter",
@@ -6499,7 +6499,7 @@ dependencies = [
[[package]]
name = "vectorcraft-three-d"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"vectorcraft-geom",
"vectorcraft-pathops",
@@ -6507,7 +6507,7 @@ dependencies = [
[[package]]
name = "vectorcraft-tools"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6524,7 +6524,7 @@ dependencies = [
[[package]]
name = "vectorcraft-trace"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6536,7 +6536,7 @@ dependencies = [
[[package]]
name = "vectorcraft-ui-egui"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"bytemuck",
"craft-keymap",
@@ -6574,7 +6574,7 @@ dependencies = [
[[package]]
name = "vectorcraft-web"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"eframe",
"egui",
@@ -7705,7 +7705,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
[[package]]
name = "xtask"
-version = "0.19.0"
+version = "0.20.0"
dependencies = [
"serde_json",
]
diff --git a/Cargo.toml b/Cargo.toml
index b5b4312eae..3088b469b3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
[workspace.package]
-version = "0.19.0"
+version = "0.20.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
diff --git a/README.md b/README.md
index 0b7b9932bb..8a3c453c5c 100644
--- a/README.md
+++ b/README.md
@@ -328,12 +328,21 @@ stand on its own.
| | App | What it's for | Code | Learn more |
|:-:|---|---|---|---|
| | **PhotoCraft** | Image editing: layers, masks, type and real PSD files | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) |
-| | **VectorCraft** | **Vector illustration · you are here** | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) |
+| | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) |
| | **FilmCraft** | Video editing, color and sound | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) |
| | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) |
| | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) |
| | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) |
| | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) |
+| | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) |
+| | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) |
+| | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) |
+| | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) |
+| | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) |
+| | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) |
+| | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) |
+| | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) |
+| | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | |
And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control.
diff --git a/ROADMAP.md b/ROADMAP.md
index c85be5aefd..4d5918cba5 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -9,7 +9,7 @@
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Path Precision Tools add-on's Expand Dashes into Paths; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Color Effects add-on's Find Nearest Swatch; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs
on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON
@@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
## Progress log
+- 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923).
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
@@ -211,6 +212,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| Date | Change | Summary |
|---|---|---|
+| 2026-11-01 | minor | Progress log row for the Color Effects add-on's Find Nearest Swatch (#4923); headline numbers unchanged. |
| 2026-11-01 | minor | Progress log row for the Path Precision Tools add-on's Expand Dashes into Paths (#4922); headline numbers unchanged. |
| 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Randomize Opacity (#4925); headline numbers unchanged. |
| 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Sort Objects (#4917); headline numbers unchanged. |
diff --git a/crates/cad/Cargo.toml b/crates/cad/Cargo.toml
index 4886d9ea5b..2ea6dea4fb 100644
--- a/crates/cad/Cargo.toml
+++ b/crates/cad/Cargo.toml
@@ -21,5 +21,6 @@ image = { workspace = true }
[dev-dependencies]
serde_json = { workspace = true }
-# The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine).
-vectorcraft-text = { workspace = true, features = ["bundled-fonts"] }
+# The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine)
+# and in fonts built in code (`vectorcraft_text::test_fonts`).
+vectorcraft-text = { workspace = true, features = ["bundled-fonts", "test-fonts"] }
diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs
index 6ae29487a8..ea3b8558d7 100644
--- a/crates/cad/src/scene.rs
+++ b/crates/cad/src/scene.rs
@@ -1062,7 +1062,8 @@ impl<'a> Scene<'a> {
}
/// Type: glyph outlines (Preserve Appearance, Outline Text, type on a path), else one text
- /// entity per run of each line.
+ /// entity per run of each line, whose height (group 40) is [`CAP_HEIGHT`] times the em size its
+ /// run is drawn at ([`vectorcraft_text::FontDb::font_heights_resolved`]).
fn text(&mut self, n: &Node, t: &TextObject) {
let outline = self.o.preserve == Preserve::Appearance || self.o.outline_text || matches!(t.kind, TextKind::OnPath { .. });
if outline {
@@ -1074,6 +1075,8 @@ impl<'a> Scene<'a> {
if !n.appearance.items.is_empty() {
self.warn(TYPE_ITEMS);
}
+ let resolved = vectorcraft_text::FontDb::global().font_heights_resolved(t);
+ let t = &*resolved;
let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let plain = t.plain_text();
let xf = self.to_dxf * t.xf;
diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs
index ba0a13b768..f1b537b70b 100644
--- a/crates/cad/src/tests.rs
+++ b/crates/cad/src/tests.rs
@@ -906,6 +906,23 @@ fn text_outside_ascii_is_escaped_before_2007() {
assert_eq!(text(DxfVersion::R2018), "Größe");
}
+/// Type whose font size measures the cap height is written at the em size it is drawn at: 14 pt
+/// measuring a 0.7 em cap height is 20 pt type, whose TEXT height is 14.
+#[test]
+fn a_font_height_reference_is_written_as_the_size_drawn() {
+ use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
+ vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap());
+ let mut d = text_doc("Plan A", 14.0);
+ let id = d.layers[0].children().and_then(|c| c.first()).map(|n| n.id).unwrap();
+ if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) {
+ t.runs[0].style.font_family = HEIGHT_FAMILY.into();
+ t.runs[0].style.font_height_reference = vectorcraft_doc::FontHeightReference::CapHeight;
+ }
+ let editable = export(&d, &DxfOptions { preserve: Preserve::Editability, ..opts(&d) }).unwrap();
+ let e = entities(&editable);
+ assert!((all(&e[0], 40)[0] - 14.0).abs() < 1e-6, "{:?}", all(&e[0], 40));
+}
+
#[test]
fn images_link_png_or_jpeg_files() {
let mut png = vec![];
diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs
index bde5fc8099..e44b0be9ea 100644
--- a/crates/color/src/gradient.rs
+++ b/crates/color/src/gradient.rs
@@ -108,6 +108,30 @@ fn perceptual_steps(a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out:
}
}
+/// The mix positions (`v`, 0..1) of the stops a Perceptual gradient's curve has between stops `a`
+/// and `b`, in order: [`perceptual_steps`] on either side of the midpoint, and the midpoint (½).
+fn perceptual_mixes(a: &GradientStop, b: &GradientStop) -> Vec {
+ let mut vs = Vec::new();
+ perceptual_steps(&a.color, &b.color, (0.0, 0.5), 1, &mut vs);
+ vs.push(0.5);
+ perceptual_steps(&a.color, &b.color, (0.5, 1.0), 1, &mut vs);
+ vs
+}
+
+/// The offset of mix position `v` between stops `a` and `b`, placed through `a`'s midpoint
+/// (`v` = ½ at the midpoint) as [`Gradient::sample`] maps it.
+fn curve_offset(a: &GradientStop, b: &GradientStop, v: f32) -> f32 {
+ let m = a.midpoint.clamp(0.01, 0.99);
+ let u = if v == 0.5 {
+ a.midpoint
+ } else if v < 0.5 {
+ 2.0 * v * m
+ } else {
+ m + (v - 0.5) * 2.0 * (1.0 - m)
+ };
+ a.offset + (b.offset - a.offset) * u
+}
+
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GradientStop {
/// 0..=1 along the gradient.
@@ -270,21 +294,9 @@ impl Gradient {
// Perceptual: stops along the mix (`v`) where a straight line would stray from it, the
// midpoint (v = ½) among them, placed through the midpoint as [`Self::sample`] maps them.
let perceptual = next.filter(|_| !self.method.is_classic()).map(|n| {
- let mut vs = Vec::new();
- perceptual_steps(&s.color, &n.color, (0.0, 0.5), 1, &mut vs);
- vs.push(0.5);
- perceptual_steps(&s.color, &n.color, (0.5, 1.0), 1, &mut vs);
- let m = s.midpoint.clamp(0.01, 0.99);
- vs.into_iter().map(move |v| {
+ perceptual_mixes(s, n).into_iter().map(move |v| {
let mid = v == 0.5;
- let u = if mid {
- s.midpoint
- } else if v < 0.5 {
- 2.0 * v * m
- } else {
- m + (v - 0.5) * 2.0 * (1.0 - m)
- };
- let t = s.offset + (n.offset - s.offset) * u;
+ let t = curve_offset(s, n, v);
let o = s.opacity + (n.opacity - s.opacity) * v;
(t, self.method.mix(&s.color, &n.color, v), o, (mid && off_centre).then_some(s.midpoint))
})
@@ -329,6 +341,47 @@ impl Gradient {
pub fn fits_ink_tints(&self) -> bool {
self.expanded().nth(MAX_INK_TINTS).is_none()
}
+ /// A Perceptual gradient's curve ([`Self::expanded_stops`]) as mixes of its stops' inks:
+ /// (offset, `i`, weight, opacity) at each stop on it, where the inks there are those of stop
+ /// `i` and stop `i + 1` mixed linearly at the weight (0..1; 0 on the gradient's own stops).
+ /// The weight is the one at which the two stops' colors mixed in display RGB have the OKLab
+ /// lightness of the color on the curve there, found to [`TINT_STEPS`] halvings, or the mix
+ /// position itself when the two colors' lightness differs by less than
+ /// [`MIN_INK_LIGHTNESS_SPAN`]. `None` for a Classic gradient, and when the curve has more than
+ /// [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
+ pub fn ink_mixes(&self) -> Option> {
+ use crate::libraries::srgb_to_oklab;
+ if self.method.is_classic() || !self.fits_ink_tints() {
+ return None;
+ }
+ let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0];
+ let mut out = Vec::new();
+ for (i, s) in self.stops.iter().enumerate() {
+ out.push((s.offset, i, 0.0, s.opacity));
+ let Some(n) = self.stops.get(i + 1) else { continue };
+ let (l0, l1) = (lightness(&s.color), lightness(&n.color));
+ for v in perceptual_mixes(s, n) {
+ let weight = if (l1 - l0).abs() < MIN_INK_LIGHTNESS_SPAN {
+ v
+ } else {
+ let want = lightness(&self.method.mix(&s.color, &n.color, v));
+ let (mut lo, mut hi) = (0.0f32, 1.0f32);
+ for _ in 0..TINT_STEPS {
+ let mid = (lo + hi) / 2.0;
+ // The mix at `mid` has not yet gone from stop `i`'s lightness to the wanted one.
+ if (lightness(&GradientMethod::Classic.mix(&s.color, &n.color, mid)) - want) * (l1 - l0) < 0.0 {
+ lo = mid;
+ } else {
+ hi = mid;
+ }
+ }
+ (lo + hi) / 2.0
+ };
+ out.push((curve_offset(s, n, v), i, weight, s.opacity + (n.opacity - s.opacity) * v));
+ }
+ }
+ Some(out)
+ }
/// The same ramp the other way round: the stops in reverse order at mirrored offsets, each
/// segment's midpoint mirrored with it.
pub fn reverse(&mut self) {
diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs
index c2d7d23d74..ab195b347c 100644
--- a/crates/color/src/gradient/tests.rs
+++ b/crates/color/src/gradient/tests.rs
@@ -486,3 +486,40 @@ fn ink_tints_follow_the_perceptual_curve() {
assert_eq!(g.ink_tints(&ink), None);
assert!(!g.fits_ink_tints());
}
+
+/// A Perceptual gradient's curve as mixes of its stops' inks: the stops on the curve at their
+/// offsets, each weighted so the two stops' colors mixed in display RGB have the lightness of
+/// the color on the curve there.
+#[test]
+fn ink_mixes_follow_the_perceptual_curve() {
+ use crate::libraries::srgb_to_oklab;
+ let (magenta, yellow) = (Color::cmyk(0.0, 1.0, 0.0, 0.0), Color::cmyk(0.0, 0.0, 0.6, 0.0));
+ let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, magenta), GradientStop::new(1.0, yellow)]);
+ g.stops[0].midpoint = 0.3;
+ assert_eq!(g.ink_mixes(), None, "a Classic gradient");
+ g.method = GradientMethod::Perceptual;
+ let mixes = g.ink_mixes().expect("a Perceptual gradient's curve");
+ let curve = g.expanded_stops();
+ assert_eq!(mixes.len(), curve.len(), "a mix for each stop on the curve");
+ assert_eq!((mixes[0], mixes[mixes.len() - 1]), ((0.0, 0, 0.0, 1.0), (1.0, 1, 0.0, 1.0)), "the gradient's own stops");
+ let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0];
+ for ((t, i, w, _), (ct, c, _)) in mixes.iter().zip(&curve) {
+ assert!((t - ct).abs() < 1e-6, "{t} on the curve at {ct}");
+ if *i == 0 && *t > 0.0 {
+ let mixed = GradientMethod::Classic.mix(&magenta, &yellow, *w);
+ assert!((lightness(&mixed) - lightness(c)).abs() < 1e-3, "at {t}: weight {w}");
+ }
+ }
+ let mid = mixes.iter().find(|m| (m.0 - 0.3).abs() < 1e-6).expect("the midpoint");
+ assert!((mid.2 - 0.5).abs() > 0.01, "not halfway at the midpoint: {mid:?}");
+ assert!(mixes.windows(2).all(|w| w[0].0 <= w[1].0), "in order: {mixes:?}");
+ // Two colors of one lightness: the weights are the mix positions.
+ g.stops[1].color = magenta;
+ let mixes = g.ink_mixes().expect("the curve");
+ let mid = mixes.iter().find(|m| (m.0 - 0.3).abs() < 1e-6).expect("the midpoint");
+ assert!((mid.2 - 0.5).abs() < 1e-6, "{mid:?}");
+ // More stops on the curve than MAX_INK_TINTS: no mixes.
+ let n = MAX_INK_TINTS + 1;
+ g.stops = (0..n).map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { magenta } else { Color::WHITE })).collect();
+ assert_eq!(g.ink_mixes(), None);
+}
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index 478e54ca81..976d48485f 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -47,6 +47,7 @@ impl Document {
patterns,
pattern_edit,
mask_edit,
+ symbol_edit,
next_id: _,
unknown,
page_isolate,
@@ -113,6 +114,7 @@ impl Document {
(a, b) => a.is_none() && b.is_none(),
}
&& *mask_edit == other.mask_edit
+ && *symbol_edit == other.symbol_edit
&& *unknown == other.unknown
&& *page_isolate == other.page_isolate
&& *page_knockout == other.page_knockout
@@ -221,6 +223,7 @@ impl Document {
patterns: vec![],
pattern_edit: None,
mask_edit: None,
+ symbol_edit: None,
next_id: 1,
unknown: Default::default(),
page_isolate: false,
diff --git a/crates/doc/src/document_ext.rs b/crates/doc/src/document_ext.rs
index c0c85b124e..b52e850c76 100644
--- a/crates/doc/src/document_ext.rs
+++ b/crates/doc/src/document_ext.rs
@@ -98,18 +98,22 @@ impl Document {
self.views = kept;
}
- /// Leave opacity-mask editing: drop the temporary editing layer, a working copy of art the
- /// mask already holds (the engine syncs it after every edit).
+ /// Leave opacity-mask editing and symbol editing: drop the temporary editing layer, a working
+ /// copy of art the mask or the symbol already holds (the engine syncs it after every edit).
pub fn drop_edit_modes(&mut self) {
if let Some(me) = self.mask_edit.take() {
self.layers.retain(|l| l.id != me.layer);
}
+ if let Some(se) = self.symbol_edit.take() {
+ self.layers.retain(|l| l.id != se.layer);
+ }
}
- /// The document as saved and exported: without the opacity-mask editing layer. Borrowed when
- /// no mask is being edited. (Pattern editing is saved: its tile layer holds unapplied edits.)
+ /// The document as saved and exported: without the opacity-mask or symbol editing layer.
+ /// Borrowed when neither mode is on. (Pattern editing is saved: its tile layer holds unapplied
+ /// edits.)
pub fn without_edit_modes(&self) -> std::borrow::Cow<'_, Document> {
- if self.mask_edit.is_none() {
+ if self.mask_edit.is_none() && self.symbol_edit.is_none() {
return std::borrow::Cow::Borrowed(self);
}
let mut d = self.clone();
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 26e2bfebf1..b742a1dd75 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -106,6 +106,7 @@ pub use selection::{AnchorRef, SegmentRef, Selection};
pub use setup::{Background, DocSetup, ExportText, GridSize, Quotes};
pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOptions, SliceSource};
pub use style_libs::StyleLibrary;
+pub use text::FontHeightReference;
pub use text::{
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
JustificationOptions, Justify, Kinsoku, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign, RubyPosition,
@@ -141,7 +142,7 @@ pub use guides::{GridPrefs, Guide, RulerMode};
#[cfg(test)]
use limits::MAX_NEXT_ID;
pub use limits::{DocError, FORMAT_VERSION, MAX_COORD};
-pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, Symbol};
+pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, Symbol, SymbolEdit};
pub use units::{ColorMode, Unit, parse_number};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -221,6 +222,10 @@ pub struct Document {
/// still read so files saved mid-edit by older versions load without the editing layer.
#[serde(default, skip_serializing)]
pub mask_edit: Option,
+ /// Symbol editing mode, while active. Never saved (see [`Document::without_edit_modes`]): the
+ /// symbol already holds the art of its editing layer.
+ #[serde(default, skip_serializing)]
+ pub symbol_edit: Option,
next_id: u64,
/// Foreign data preserved on round-trip.
#[serde(default, skip_serializing_if = "skip::is_empty_map")]
diff --git a/crates/doc/src/records.rs b/crates/doc/src/records.rs
index 434a85a8fa..a6988f5020 100644
--- a/crates/doc/src/records.rs
+++ b/crates/doc/src/records.rs
@@ -1,4 +1,4 @@
-use super::{Arc, Deserialize, Node, NodeId, Point, Serialize};
+use super::{Affine, Arc, Deserialize, Node, NodeId, Point, Serialize};
/// New art on a locked artboard ([`Document::new_art`]). Setting it changes the document in
/// place, so a selection change that sets it doesn't replace the document.
@@ -44,6 +44,29 @@ pub struct MaskEdit {
pub layer: NodeId,
}
+/// Symbol editing mode: the art of symbol `symbol` lives on the temporary `layer` while editing,
+/// placed by `xf` (from the symbol's coordinates to the document's), and goes back into the symbol
+/// after each edit, so every instance follows it.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct SymbolEdit {
+ pub symbol: String,
+ pub layer: NodeId,
+ /// The instance editing was entered from (a double-click on it), selected again on leaving after an edit;
+ /// `None` when it was entered from the Symbols panel.
+ pub instance: Option,
+ pub xf: Affine,
+ /// The symbol's art is a group whose members are on the layer: the group takes them back.
+ pub group: bool,
+ /// An edit changed the art since editing was entered.
+ pub changed: bool,
+ /// The isolated object from before editing was entered, isolated again on leaving.
+ #[serde(default)]
+ pub back_isolation: Option,
+ /// The current layer from before editing was entered, current again on leaving.
+ #[serde(default)]
+ pub back_layer: Option,
+}
+
/// A saved view (View → New View…): zoom, centre and rotation, listed at the bottom of the View menu.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SavedView {
diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs
index c1a36e0583..675245b56b 100644
--- a/crates/doc/src/text.rs
+++ b/crates/doc/src/text.rs
@@ -15,7 +15,7 @@ mod tabs_lists;
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
use char_style::yes;
-pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, ScriptMetrics};
+pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, ScriptMetrics};
pub use para_style::{
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, LeadingModel, Mojikumi, ParaDirection,
ParaStyle, SingleWordJustify,
diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs
index dd84912f09..b5bc7e0654 100644
--- a/crates/doc/src/text/char_style.rs
+++ b/crates/doc/src/text/char_style.rs
@@ -116,6 +116,10 @@ pub struct CharStyle {
/// these characters are drawn in, whatever digits were typed.
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub digits: Digits,
+ /// Font height reference (Character panel menu › Show Font Height Options): the height of the
+ /// font that [`Self::size`] measures, the em box by default.
+ #[serde(default, rename = "fontHeightReference", skip_serializing_if = "crate::skip::is_default")]
+ pub font_height_reference: FontHeightReference,
/// No Break (Character panel menu): these characters are not broken across lines, including
/// at a space or a hyphenation point inside the run. A run longer than the line stays together
/// and can overflow it.
@@ -130,6 +134,21 @@ pub struct CharStyle {
pub language: Option,
}
+/// What a character's font size measures ([`CharStyle::font_height_reference`]): the em square
+/// of the font, the height of its capitals or of its lowercase letters (the cap height and x
+/// height of its OS/2 table), or its ideographic character face (ICF, OpenType's `icfb` and
+/// `icft` baselines). Layout sets the characters at the em size at which the chosen height equals
+/// the font size; with a font that has no such value, the size measures the em box.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum FontHeightReference {
+ #[default]
+ EmBox,
+ CapHeight,
+ XHeight,
+ IcfBox,
+}
+
/// The numeral system digits are drawn in ([`CharStyle::digits`]): as typed, or every digit of
/// the Western, Arabic-Indic and Eastern Arabic-Indic sets drawn in one of them or in the digits
/// of an Indic script. The text keeps the digits that were typed; only the glyphs change (like
@@ -380,6 +399,7 @@ impl Default for CharStyle {
standard_vertical_roman: false,
small_caps: None,
digits: Digits::Default,
+ font_height_reference: FontHeightReference::EmBox,
no_break: false,
language: None,
}
diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs
index bd53024b1c..04deae8ee3 100644
--- a/crates/doc/src/text/tests.rs
+++ b/crates/doc/src/text/tests.rs
@@ -60,6 +60,24 @@ fn digits_map_between_the_numeral_systems() {
assert_eq!(serde_json::from_value::(serde_json::to_value(&farsi).unwrap()).unwrap(), farsi);
}
+/// The font height reference is the em box by default and is saved only when it is another.
+#[test]
+fn font_height_reference_is_saved_only_when_not_the_em_box() {
+ let st = CharStyle::default();
+ assert_eq!(st.font_height_reference, FontHeightReference::EmBox);
+ assert!(serde_json::to_value(&st).unwrap().get("fontHeightReference").is_none());
+ for (r, key) in
+ [(FontHeightReference::CapHeight, "capHeight"), (FontHeightReference::XHeight, "xHeight"), (FontHeightReference::IcfBox, "icfBox")]
+ {
+ let set = CharStyle { font_height_reference: r, ..CharStyle::default() };
+ assert_eq!(serde_json::to_value(&set).unwrap()["fontHeightReference"], key);
+ assert_eq!(serde_json::from_value::(serde_json::to_value(&set).unwrap()).unwrap(), set);
+ }
+ // Styles written before the attribute existed read as the em box.
+ let old = serde_json::to_value(&st).unwrap();
+ assert_eq!(serde_json::from_value::(old).unwrap().font_height_reference, FontHeightReference::EmBox);
+}
+
/// Each Indic numeral system draws 0–9 (and the Arabic-Indic sets) as the ten digits of its
/// script's block; every system saves under its id, which reads back, and other names are refused.
#[test]
diff --git a/crates/doc/src/variables.rs b/crates/doc/src/variables.rs
index 96bccbd0a5..8656e216ce 100644
--- a/crates/doc/src/variables.rs
+++ b/crates/doc/src/variables.rs
@@ -6,7 +6,7 @@ use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
-use super::{Document, NodeId, NodeKind};
+use super::{Document, NodeId, NodeKind, TextKind};
/// What a variable drives.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
@@ -117,7 +117,8 @@ pub struct Variables {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub active_dataset: Option,
/// Lock Variables: while set, variables can't be defined, deleted or renamed. Objects can
- /// still be bound to them and unbound, and datasets still change and apply.
+ /// still be bound to them and unbound, and datasets still change and apply, except that an
+ /// import whose header would define a variable is refused.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub locked: bool,
}
@@ -202,17 +203,46 @@ impl Document {
self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| !n.locked)))
}
- /// What the object `id` holds for the variable of `kind`: its characters, whether it shows,
- /// or a linked image's path. `None` when the object is gone, is not of that kind, has no
- /// link path yet (an embedded image), or is locked or in a locked layer or group (the
- /// document's value is whatever it was left at).
+ /// The type objects of the story that the type object `id` belongs to, in thread order: the
+ /// frames of its threaded text (area type and type on a path), else `id` alone.
+ pub fn story_of(&self, id: NodeId) -> Vec {
+ let frame = |f: &NodeId| matches!(self.node(*f).map(|n| &n.kind), Some(NodeKind::Text(t)) if !matches!(t.kind, TextKind::Point));
+ match self.text_threads.iter().find(|thread| thread.contains(&id)) {
+ Some(thread) if frame(&id) => thread.iter().filter(|f| frame(f)).copied().collect(),
+ _ => vec![id],
+ }
+ }
+
+ /// The characters of the story that the type object `id` belongs to ([`Document::story_of`]):
+ /// every frame's text joined in thread order.
+ pub fn story_text(&self, id: NodeId) -> String {
+ self.story_of(id)
+ .into_iter()
+ .filter_map(|f| match self.node(f).map(|n| &n.kind) {
+ Some(NodeKind::Text(t)) => Some(t.plain_text()),
+ _ => None,
+ })
+ .collect()
+ }
+
+ /// Whether a data set reads and rewrites the text of the type object `id`: every frame of its
+ /// story ([`Document::story_of`]) is a [`Document::dataset_target`].
+ pub fn story_target(&self, id: NodeId) -> bool {
+ self.story_of(id).into_iter().all(|f| self.dataset_target(f))
+ }
+
+ /// What the object `id` holds for the variable of `kind`: its characters (the whole story
+ /// for a frame of threaded text), whether it shows, or a linked image's path. `None` when the
+ /// object is gone, is not of that kind, has no link path yet (an embedded image), or is locked
+ /// or in a locked layer or group, or for text when a frame of its story is (the document's
+ /// value is whatever it was left at).
pub fn variable_value(&self, id: NodeId, kind: VariableKind) -> Option {
if !self.dataset_target(id) {
return None;
}
let node = self.node(id)?;
match (kind, &node.kind) {
- (VariableKind::Text, NodeKind::Text(t)) => Some(DataValue::Text(t.plain_text())),
+ (VariableKind::Text, NodeKind::Text(_)) if self.story_target(id) => Some(DataValue::Text(self.story_text(id))),
(VariableKind::Visibility, _) => Some(DataValue::Visible(node.visible)),
(VariableKind::Image, NodeKind::Image(im)) => im.link.as_ref().map(|l| DataValue::Image(l.path.clone())),
(VariableKind::Graph, _) => node.extras().graph.as_ref().map(|g| DataValue::Graph(g.to_csv())),
diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs
index 8758262628..31d0ca2cb2 100644
--- a/crates/engine/src/cmd.rs
+++ b/crates/engine/src/cmd.rs
@@ -84,6 +84,7 @@ mod style;
pub mod stylelib;
mod swatch;
pub mod swatchlib;
+pub(crate) mod symboledit;
pub mod symbollib;
pub(crate) mod tabs;
mod textedit;
@@ -183,11 +184,15 @@ pub fn has_multi(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
if st.selection.len() < 2 { Err("select at least two objects".into()) } else { Ok(()) }
}
-/// The isolated group, layer or object in isolation mode. Pattern editing mode and opacity mask
-/// editing isolate their own layer, which does not count here; an object isolated inside them
-/// counts.
+/// The isolated group, layer or object in isolation mode. Pattern editing mode, opacity mask
+/// editing and symbol editing mode isolate their own layer, which does not count here; an object
+/// isolated inside them counts.
pub(crate) fn ordinary_isolation(st: &crate::DocState) -> Option {
- st.isolation.filter(|l| !st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l) && !st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l))
+ st.isolation.filter(|l| {
+ !st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l)
+ && !st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l)
+ && !st.doc.symbol_edit.as_ref().is_some_and(|e| e.layer == *l)
+ })
}
/// Objects are selected ([`has_selection`]), and in isolation mode ([`ordinary_isolation`]) at
/// least one of them is inside the isolated object: Object › Lock's and Object › Hide's items.
diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs
index 9b11a71153..735d721335 100644
--- a/crates/engine/src/cmd/addons/arrange.rs
+++ b/crates/engine/src/cmd/addons/arrange.rs
@@ -120,7 +120,7 @@ fn number_in(p: &Value, key: &str, default: f64, (lo, hi): (f64, f64), cmd: &str
}
/// Whole-number param `key` within `lo..=hi`, `None` when left out.
-fn whole_in(p: &Value, key: &str, (lo, hi): (u64, u64), cmd: &str) -> Result> {
+pub(super) fn whole_in(p: &Value, key: &str, (lo, hi): (u64, u64), cmd: &str) -> Result > {
let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(None) };
let n = v.as_u64().ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number")))?;
if (lo..=hi).contains(&n) { Ok(Some(n)) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) }
diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs
index 4426624ccf..3dc037a2fa 100644
--- a/crates/engine/src/cmd/addons/color.rs
+++ b/crates/engine/src/cmd/addons/color.rs
@@ -2,9 +2,11 @@
//! Duotone and Invert Colors, in Effect › Color Effects) are the effects crate's; here, Apply as
//! Filter writes any colour adjustment into the colours themselves, Select by Color Kind selects the
//! objects that use spot colours, carry a live colour adjustment, or are images of a colour model,
-//! and Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print. Its panel and
-//! its submenu, Object › Plug-ins › Color Effects, are the UI's.
+//! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, and Find Nearest
+//! Swatch ([`nearest`]) matches colours to a swatch library's. Its panel and its submenu, Object ›
+//! Plug-ins › Color Effects, are the UI's.
+mod nearest;
mod print_fixes;
#[cfg(test)]
mod tests;
@@ -50,6 +52,24 @@ pub fn specs() -> Vec {
has_doc,
print_fixes::run
),
+ cmd!(
+ query "addon.color.nearestSwatch",
+ "Find Nearest Swatch",
+ ["Object", "Plug-ins", "Color Effects"],
+ None,
+ "{library?: a swatch library's id or name (swatch.library.list: the built-in ones, and the colour books and libraries the user saved or loaded) or \"document\" (the document's swatches; the default), color?: colour (look this colour up; default: the selection's), fill?: true, stroke?: true (the selected objects' fills and strokes, their type's and those of the objects inside them: solid colours and gradient stops, once each, the first 100), count?: 1..50 (5), ids?: [id…] (default: the selection)} list the library's colour swatches closest to each colour, closest first, by CIEDE2000 difference (ΔE; under 1 hardly tells apart, about 2 to 3 close). Tint swatches, None and Registration aren't matched → {library, colors: [{values, hex, matches: [{name, values, hex, spot, deltaE}]}]}",
+ has_doc,
+ nearest::find
+ ),
+ cmd!(
+ "addon.color.applyNearestSwatch",
+ "Apply Nearest Swatch",
+ ["Object", "Plug-ins", "Color Effects"],
+ None,
+ "{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step: a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}",
+ has_selection,
+ nearest::apply
+ ),
]
}
diff --git a/crates/engine/src/cmd/addons/color/nearest.rs b/crates/engine/src/cmd/addons/color/nearest.rs
new file mode 100644
index 0000000000..5a9d0e7c75
--- /dev/null
+++ b/crates/engine/src/cmd/addons/color/nearest.rs
@@ -0,0 +1,198 @@
+//! Find Nearest Swatch (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`; Object ›
+//! Plug-ins › Color Effects › Find Nearest Swatch…): the swatches of a library, a colour book the
+//! user loaded or the document closest to each colour of the selection (CIEDE2000), and the
+//! colours replaced by them as one undo step (#4923).
+
+use serde_json::{Value, json};
+use vectorcraft_color::cms::{Lab, delta_e2000};
+use vectorcraft_color::{Color, Paint, Swatch};
+use vectorcraft_doc::swatches::color_name;
+use vectorcraft_doc::{Document, NodeId, NodeKind};
+
+use super::super::super::colorcmds::recolor_links;
+use super::super::super::menucmds::squash;
+use super::super::super::swatchlib::{DOCUMENT_SWATCHES, library_swatches};
+use super::super::super::{bad, checked_ids_or_selection, color_value, index, switch_or, text_param};
+use super::super::arrange::whole_in;
+use crate::{Result, Session};
+
+const FIND: &str = "addon.color.nearestSwatch";
+const APPLY: &str = "addon.color.applyNearestSwatch";
+/// The most colours of the selection looked up.
+const MAX_COLORS: usize = 100;
+
+/// The `library` param ([`DOCUMENT_SWATCHES`] when left out) and its colour swatches with their Lab
+/// values.
+fn candidates(s: &Session, p: &Value, cmd: &str) -> Result<(String, Vec<(Swatch, Lab)>)> {
+ let key = text_param(p, "library", cmd)?.unwrap_or(DOCUMENT_SWATCHES).to_string();
+ let swatches = library_swatches(s, &key).ok_or_else(|| bad(cmd, format!("no swatch library `{key}` (see swatch.library.list)")))?;
+ let labs: Vec<(Swatch, Lab)> = swatches
+ .into_iter()
+ .filter(|w| !w.is_reserved())
+ .filter_map(|w| {
+ let lab = w.paint.color()?.to_lab();
+ Some((w, lab))
+ })
+ .collect();
+ if labs.is_empty() {
+ return Err(bad(cmd, format!("`{key}` has no colours")));
+ }
+ Ok((key, labs))
+}
+
+/// The `count` swatches of `among` closest to `c`, closest first, with their difference (ΔE 2000).
+fn nearest(among: &[(Swatch, Lab)], c: Color, count: usize) -> Vec<(&Swatch, f32)> {
+ let lab = c.to_lab();
+ let mut v: Vec<(&Swatch, f32)> = among.iter().map(|(w, l)| (w, delta_e2000(*l, lab))).collect();
+ v.sort_by(|a, b| a.1.total_cmp(&b.1));
+ v.truncate(count);
+ v
+}
+
+/// The solid colours and gradient stops of the fills (`fill`) and strokes (`stroke`) of `ids`, of
+/// everything inside them and of their type, once each and at most [`MAX_COLORS`].
+fn art_colors(d: &Document, ids: &[NodeId], fill: bool, stroke: bool) -> Vec {
+ let mut out: Vec = vec![];
+ let mut add = |p: &Paint| {
+ let colors: Vec = match p {
+ Paint::Solid { color, .. } => vec![*color],
+ Paint::Gradient(g) => g.gradient.stops.iter().map(|s| s.color).collect(),
+ _ => vec![],
+ };
+ for c in colors {
+ if out.len() < MAX_COLORS && !out.contains(&c) {
+ out.push(c);
+ }
+ }
+ };
+ for n in ids.iter().filter_map(|id| d.node(*id)) {
+ n.walk(&mut |m| {
+ for it in &m.appearance.items {
+ if if it.is_fill() { fill } else { stroke } {
+ add(it.paint());
+ }
+ }
+ if let NodeKind::Text(t) = &m.kind {
+ for r in &t.runs {
+ if fill {
+ add(&r.style.fill);
+ }
+ if stroke {
+ add(&r.style.stroke);
+ }
+ }
+ }
+ });
+ }
+ out
+}
+
+/// A swatch's name and values as the results give them.
+fn described(w: &Swatch) -> Value {
+ let c = w.paint.color().unwrap_or_default();
+ json!({ "name": w.name, "values": color_name(c), "hex": c.to_hex(), "spot": w.spot })
+}
+
+pub(super) fn find(s: &mut Session, p: &Value) -> Result {
+ let count = whole_in(p, "count", (1, 50), FIND)?.map_or(5, index);
+ let (fill, stroke) = (switch_or(p, "fill", true, FIND)?, switch_or(p, "stroke", true, FIND)?);
+ let colors = match p.get("color").filter(|v| !v.is_null()) {
+ Some(v) => vec![color_value(v).ok_or_else(|| bad(FIND, "`color` is not a colour"))?],
+ None => {
+ let ids = checked_ids_or_selection(s, p, FIND)?;
+ if ids.is_empty() {
+ return Err(bad(FIND, "select objects or give `color`"));
+ }
+ art_colors(&s.doc()?.doc, &ids, fill, stroke)
+ }
+ };
+ let (library, among) = candidates(s, p, FIND)?;
+ let found: Vec = colors
+ .iter()
+ .map(|c| {
+ let matches: Vec = nearest(&among, *c, count)
+ .into_iter()
+ .map(|(w, de)| {
+ let mut m = described(w);
+ m["deltaE"] = json!((f64::from(de) * 100.0).round() / 100.0);
+ m
+ })
+ .collect();
+ json!({ "values": color_name(*c), "hex": c.to_hex(), "matches": matches })
+ })
+ .collect();
+ Ok(json!({ "library": library, "colors": found }))
+}
+
+pub(super) fn apply(s: &mut Session, p: &Value) -> Result {
+ let (fill, stroke) = (switch_or(p, "fill", true, APPLY)?, switch_or(p, "stroke", true, APPLY)?);
+ let ids = checked_ids_or_selection(s, p, APPLY)?;
+ if ids.is_empty() {
+ return Err(bad(APPLY, "nothing selected"));
+ }
+ let (library, among) = candidates(s, p, APPLY)?;
+ // The swatch each colour takes, once each.
+ let colors = art_colors(&s.doc()?.doc, &ids, fill, stroke);
+ let mut used: Vec<&Swatch> = vec![];
+ for c in &colors {
+ if let Some((w, _)) = nearest(&among, *c, 1).first()
+ && !used.iter().any(|u| u.name == w.name)
+ {
+ used.push(w);
+ }
+ }
+ if used.is_empty() {
+ return Ok(json!({ "changed": 0, "swatches": [], "added": [] }));
+ }
+ let undo = s.doc()?.history.undo.len();
+ // A library's swatches join the document's first, as Add to Swatches adds them, so spot and
+ // global colours stay linked to theirs.
+ let mut added = vec![];
+ let mut names: Vec = used.iter().map(|w| w.name.clone()).collect();
+ if library != DOCUMENT_SWATCHES {
+ let r = s.execute("swatch.library.add", &json!({ "library": library, "names": names }))?;
+ let listed = |k: &str| r.get(k).and_then(Value::as_array).cloned().unwrap_or_default();
+ let in_doc: Vec = listed("added").iter().chain(&listed("existing")).filter_map(Value::as_str).map(str::to_string).collect();
+ let d = &s.doc()?.doc;
+ // Each library swatch's copy: the document swatch with its paint among those added or kept.
+ names = used
+ .iter()
+ .map(|w| in_doc.iter().find(|n| d.swatch(n).is_some_and(|x| x.paint == w.paint)).cloned().unwrap_or_else(|| w.name.clone()))
+ .collect();
+ added = listed("added");
+ }
+ // Each used swatch's paint as art takes it: linked to a global or spot swatch.
+ let d = &s.doc()?.doc;
+ let paints: Vec<(Lab, Paint)> = used
+ .iter()
+ .zip(&names)
+ .filter_map(|(w, name)| {
+ let lab = w.paint.color()?.to_lab();
+ let paint = d.swatch(name).filter(|x| x.global).and_then(|_| d.tint_paint(name, 1.0)).unwrap_or_else(|| w.paint.clone());
+ Some((lab, paint))
+ })
+ .collect();
+ // shortcut: a colour past the MAX_COLORS looked up takes the closest of the swatches those
+ // took; look up every colour if documents with more colours need their own matches.
+ let to = |c: Color| -> Option<&Paint> {
+ let lab = c.to_lab();
+ paints.iter().min_by(|a, b| delta_e2000(a.0, lab).total_cmp(&delta_e2000(b.0, lab))).map(|(_, p)| p)
+ };
+ let links = |c: &mut Color, link: &mut Option, tint: &mut f32| {
+ let Some(Paint::Solid { color, swatch, .. }) = to(*c) else { return false };
+ if *c == *color && *link == *swatch {
+ return false;
+ }
+ (*c, *link, *tint) = (*color, swatch.clone(), 1.0);
+ true
+ };
+ let given = json!({
+ "ids": ids.iter().map(|i| i.0).collect::>(), "fill": fill, "stroke": stroke, "includeImages": false, "includePatterns": false,
+ });
+ let r = recolor_links(s, &given, "Apply Nearest Swatch", &|c| to(c).and_then(Paint::color).unwrap_or(c), &links)?;
+ squash(s, undo, "Apply Nearest Swatch");
+ Ok(json!({ "changed": r["changed"], "swatches": names, "added": added }))
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/engine/src/cmd/addons/color/nearest/tests.rs b/crates/engine/src/cmd/addons/color/nearest/tests.rs
new file mode 100644
index 0000000000..0436d19c89
--- /dev/null
+++ b/crates/engine/src/cmd/addons/color/nearest/tests.rs
@@ -0,0 +1,115 @@
+//! Find Nearest Swatch.
+
+use serde_json::{Value, json};
+use vectorcraft_color::{Color, Paint};
+use vectorcraft_doc::NodeId;
+
+use crate::Session;
+
+const FIND: &str = "addon.color.nearestSwatch";
+const APPLY: &str = "addon.color.applyNearestSwatch";
+
+/// A document with a global swatch "Brand" and a selected rectangle filled `fill`, stroked `stroke`.
+fn doc(fill: &str, stroke: Option<&str>) -> (Session, NodeId) {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
+ s.execute("swatch.new", &json!({"name": "Brand", "color": "#ff8000", "global": true})).unwrap();
+ let id = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap());
+ s.execute("paint.setFill", &json!({"color": fill})).unwrap();
+ match stroke {
+ Some(c) => s.execute("paint.setStroke", &json!({"color": c})).unwrap(),
+ None => s.execute("paint.setStroke", &json!({"none": true})).unwrap(),
+ };
+ (s, id)
+}
+
+fn paints(s: &Session, id: NodeId) -> (Paint, Paint) {
+ let n = s.doc().unwrap().doc.node(id).unwrap().clone();
+ (n.appearance.fill_paint(), n.appearance.items.iter().find(|i| !i.is_fill()).unwrap().paint().clone())
+}
+
+fn names(matches: &Value) -> Vec<&str> {
+ matches.as_array().unwrap().iter().map(|m| m["name"].as_str().unwrap()).collect()
+}
+
+#[test]
+fn the_closest_swatches_of_a_library_are_listed_closest_first() {
+ let (mut s, _) = doc("#ff6634", None);
+ let v = s.execute(FIND, &json!({"library": "web-safe-216", "count": 3})).unwrap();
+ assert_eq!(v["library"], "web-safe-216");
+ let colors = v["colors"].as_array().unwrap();
+ assert_eq!(colors.len(), 1, "the fill; no stroke");
+ assert_eq!((colors[0]["hex"].as_str(), colors[0]["values"].as_str()), (Some("#ff6634"), Some("R=255 G=102 B=52")));
+ let m = &colors[0]["matches"];
+ assert_eq!(names(m)[0], "#FF6633");
+ let de: Vec = m.as_array().unwrap().iter().map(|x| x["deltaE"].as_f64().unwrap()).collect();
+ assert_eq!(de.len(), 3);
+ assert!(de[0] < 1.0 && de.windows(2).all(|w| w[0] <= w[1]), "{de:?}");
+ // A colour given is looked up instead of the selection's.
+ let v = s.execute(FIND, &json!({"library": "web-safe-216", "color": "#010203", "count": 1})).unwrap();
+ assert_eq!(names(&v["colors"][0]["matches"]), ["#000000"]);
+}
+
+#[test]
+fn the_document_swatches_are_the_default_library() {
+ let (mut s, _) = doc("#ff8010", Some("#ff8010"));
+ let v = s.execute(FIND, &json!({})).unwrap();
+ assert_eq!(v["library"], "document");
+ assert_eq!(v["colors"].as_array().unwrap().len(), 1, "fill and stroke share a colour: looked up once");
+ assert_eq!(names(&v["colors"][0]["matches"])[0], "Brand");
+ assert!(!names(&v["colors"][0]["matches"]).contains(&"[Registration]"));
+}
+
+#[test]
+fn applying_links_each_colour_to_its_nearest_document_swatch_as_one_undo_step() {
+ let (mut s, id) = doc("#ff8010", Some("#ff8010"));
+ let undo = s.doc().unwrap().history.undo.len();
+ let v = s.execute(APPLY, &json!({"stroke": false})).unwrap();
+ assert_eq!((v["changed"].as_u64(), v["swatches"].clone(), v["added"].clone()), (Some(1), json!(["Brand"]), json!([])));
+ let (fill, stroke) = paints(&s, id);
+ assert!(matches!(&fill, Paint::Solid { swatch: Some(n), color, .. } if n == "Brand" && color.to_hex() == "#ff8000"), "{fill:?}");
+ assert_eq!(stroke.color().unwrap().to_hex(), "#ff8010", "strokes left alone");
+ let st = s.doc().unwrap();
+ assert_eq!((st.history.undo.len(), st.history.undo.last().unwrap().label.as_str()), (undo + 1, "Apply Nearest Swatch"));
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(paints(&s, id).0.color().unwrap().to_hex(), "#ff8010");
+}
+
+#[test]
+fn a_library_spot_colour_joins_the_document_and_stays_spot() {
+ let (mut s, id) = doc("#e01525", None);
+ // A colour book of one spot colour, loaded as a user would load one they own.
+ s.execute("swatch.new", &json!({"name": "Ink Red", "color": "#e01020", "spot": true})).unwrap();
+ let data = s.execute("swatch.library.save", &json!({"names": ["Ink Red"]})).unwrap()["data"].as_str().unwrap().to_string();
+ s.execute("swatch.delete", &json!({"names": ["Ink Red"]})).unwrap();
+ let lib = s.execute("swatch.library.load", &json!({"data": data, "name": "Book.vcswatches"})).unwrap()["library"].as_str().unwrap().to_string();
+ s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
+ let undo = s.doc().unwrap().history.undo.len();
+ let v = s.execute(APPLY, &json!({"library": lib})).unwrap();
+ assert_eq!((v["swatches"].clone(), v["added"].clone()), (json!(["Ink Red"]), json!(["Ink Red"])));
+ let d = &s.doc().unwrap().doc;
+ assert!(d.swatch("Ink Red").is_some_and(|w| w.spot && w.global));
+ assert!(matches!(paints(&s, id).0, Paint::Solid { swatch: Some(n), .. } if n == "Ink Red"));
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "adding and applying undo together");
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert!(s.doc().unwrap().doc.swatch("Ink Red").is_none());
+ assert_eq!(paints(&s, id).0, Paint::solid(Color::from_hex("#e01525").unwrap()));
+}
+
+#[test]
+fn bad_requests_are_refused() {
+ let (mut s, _) = doc("#ff8010", None);
+ for (p, why) in [
+ (json!({"library": "nope"}), "no swatch library `nope`"),
+ (json!({"library": "spectrum-gradients"}), "has no colours"),
+ (json!({"count": 0}), "`count` must be from 1 to 50"),
+ (json!({"color": "zzz"}), "`color` is not a colour"),
+ (json!({"fill": "yes"}), "`fill` must be true or false"),
+ ] {
+ let e = s.execute(FIND, &p).unwrap_err().to_string();
+ assert!(e.contains(why), "{p}: {e}");
+ }
+ s.execute("select.none", &json!({})).unwrap();
+ assert!(s.execute(FIND, &json!({})).unwrap_err().to_string().contains("select objects or give `color`"));
+ assert!(s.execute(APPLY, &json!({})).is_err(), "nothing selected");
+}
diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs
index faa02efc26..30548b80a7 100644
--- a/crates/engine/src/cmd/addons/document.rs
+++ b/crates/engine/src/cmd/addons/document.rs
@@ -36,7 +36,7 @@ pub fn specs() -> Vec {
"Export All Open Documents",
["Object", "Plug-ins", "Document Tools"],
None,
- "{folder, format?: vectorcraft|pdf|svg|svgz|ai|eps (default: pdf)} write a copy of every open document, in tab order, to `folder` as File › Save a Copy writes it, each named after its document (.; -2, -3… added when that name is taken, so no file is replaced): every document keeps its path, title and modified state, and no undo step is made. A document that can't be written is listed in `failed` and the others are still written; the active document stays active → {files: [{title, path, warnings}], failed: [{title, error}], format}",
+ "{folder, format?: vectorcraft|pdf|svg|svgz|ai|eps (default: pdf)} write a copy of every open document, in tab order, to `folder` as File › Save a Copy writes it, each named after its document (.; -2, -3… added when that name is taken, so no file is replaced), one self-contained file each with all of its art (images embedded or included, every artboard; no remembered save options apply): every document keeps its path, title and modified state, and no undo step is made. A document that can't be written is listed in `failed` and the others are still written; the active document stays active → {files: [{title, path, warnings}], failed: [{title, error}], format}",
has_doc,
export_all_open
),
@@ -98,6 +98,20 @@ fn save_timestamped_copy(s: &mut Session, p: &Value) -> Result {
fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "format": format.id }))
}
+/// The save options of every copy, given in full so that no document's remembered options (linked
+/// SVG images, a PDF page range, separate artboard files) apply: one self-contained file per
+/// document with all of its art. Each format reads only the options it has, and `range` is left
+/// out of SVG, where it would pick artboards over `useArtboards`.
+fn copy_options(format: &str) -> Value {
+ match format {
+ "svg" | "svgz" => json!({ "images": "embed", "useArtboards": false }),
+ "pdf" => json!({ "range": "all" }),
+ "eps" => json!({ "includeLinkedFiles": true, "useArtboards": false }),
+ "ai" | "ait" => json!({ "range": "all", "includeLinked": true, "separateArtboards": false }),
+ _ => json!({ "includeLinked": true, "separateArtboards": false }),
+ }
+}
+
fn export_all_open(s: &mut Session, p: &Value) -> Result {
const C: &str = "addon.document.exportAllOpen";
let format = fileio::save_format(Some(str_param(p, "format").unwrap_or("pdf")), None).map_err(|e| bad(C, e))?;
@@ -117,9 +131,18 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result {
failed.push(json!({ "title": title, "error": "every numbered name for the copy is taken" }));
continue;
};
- match fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "format": format.id })) {
+ let options = copy_options(format.id);
+ match fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "format": format.id, "options": options })) {
Ok(r) => {
written.push(path.clone());
+ // Any other file the save wrote is taken for the copies still to come.
+ for key in ["files", "linked"] {
+ for f in r.get(key).and_then(Value::as_array).into_iter().flatten() {
+ if let Some(f) = f.as_str().or_else(|| f.get("path").and_then(Value::as_str)) {
+ written.push(f.to_string());
+ }
+ }
+ }
files.push(json!({ "title": title, "path": r.get("path").cloned().unwrap_or(json!(path)), "warnings": r.get("warnings").cloned().unwrap_or(json!([])) }));
}
Err(e) => failed.push(json!({ "title": title, "error": e.to_string() })),
diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs
index aef604eb36..562a389e8a 100644
--- a/crates/engine/src/cmd/addons/document/tests.rs
+++ b/crates/engine/src/cmd/addons/document/tests.rs
@@ -217,3 +217,62 @@ fn export_all_open_documents_writes_each_and_reports_failures() {
assert_eq!(s.active_index(), Some(0));
let _ = std::fs::remove_dir_all(&dir);
}
+
+/// An SVG document last saved with linked images exports as one SVG with its images embedded: no
+/// image file is written beside the copies (#4920 review).
+#[test]
+fn export_all_open_documents_writes_one_file_each() {
+ let dir = std::env::temp_dir().join(format!("vc-export-all-one-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(dir.join("out")).unwrap();
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 100, "height": 100, "name": "pic"})).unwrap();
+ let mut png = vec![];
+ image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
+ s.execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
+ s.execute("document.save", &json!({"path": dir.join("pic.svg"), "format": "svg", "options": {"images": "link"}})).unwrap();
+ let saved: Vec<_> = std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).filter(|e| e.path().is_file()).collect();
+ assert!(saved.len() > 1, "the linked save wrote its image beside it: {saved:?}");
+ let out = dir.join("out");
+ let r = s.execute("addon.document.exportAllOpen", &json!({"folder": out, "format": "svg"})).unwrap();
+ let names: Vec = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
+ assert_eq!(names, ["pic.svg"], "{r}");
+ assert!(std::fs::read_to_string(out.join("pic.svg")).unwrap().contains("data:image/png;base64,"), "the image is embedded");
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+/// A PDF document last saved with a page range exports with every page, and an SVG document with
+/// two artboards exports as one SVG holding the art of both (#4920 review).
+#[test]
+fn export_all_open_documents_keeps_every_page_and_artboard() {
+ let dir = std::env::temp_dir().join(format!("vc-export-all-pages-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(dir.join("out")).unwrap();
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2, "name": "pages"})).unwrap();
+ s.execute("document.save", &json!({"path": dir.join("pages.pdf"), "format": "pdf", "options": {"range": "1"}})).unwrap();
+ let pages = |b: &[u8]| {
+ String::from_utf8_lossy(b).matches("/Type /Page\n").count()
+ + String::from_utf8_lossy(b).matches("/Type/Page/").count()
+ + String::from_utf8_lossy(b).matches("/Type /Page/").count()
+ + String::from_utf8_lossy(b).matches("/Type /Page ").count()
+ };
+ let first = pages(&std::fs::read(dir.join("pages.pdf")).unwrap());
+ let out = dir.join("out");
+ s.execute("addon.document.exportAllOpen", &json!({"folder": out, "format": "pdf"})).unwrap();
+ let copy = pages(&std::fs::read(out.join("pages.pdf")).unwrap());
+ assert!(copy > first, "the copy has every page: {first} saved, {copy} exported");
+ // SVG: one file with the art on both artboards.
+ let a = s.doc().unwrap().doc.artboards[1].rect;
+ s.execute("shape.rectangle", &json!({"x": a.x0 + 10.0, "y": a.y0 + 10.0, "width": 20, "height": 20})).unwrap();
+ s.execute("addon.document.exportAllOpen", &json!({"folder": out, "format": "svg"})).unwrap();
+ let svgs: Vec =
+ std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).filter(|n| n.ends_with(".svg")).collect();
+ assert_eq!(svgs, ["pages.svg"]);
+ let svg = std::fs::read_to_string(out.join("pages.svg")).unwrap();
+ // Not the first artboard alone (its 100 × 100 box at the origin): the art's own bounds.
+ let view = svg.split("viewBox=\"").nth(1).and_then(|v| v.split('"').next()).unwrap();
+ let w: f64 = view.split_whitespace().nth(2).unwrap().parse().unwrap();
+ assert!(w > 19.0 && w < 30.0, "the SVG shows the art (the square on the second artboard), not the first artboard: viewBox {view}");
+ let _ = std::fs::remove_dir_all(&dir);
+}
diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs
index 7f78aa2465..a1f03b6a35 100644
--- a/crates/engine/src/cmd/brushsym.rs
+++ b/crates/engine/src/cmd/brushsym.rs
@@ -35,10 +35,10 @@ use brushes::{
};
use dynamic::{symbol_instance_reset, symbol_instance_set_appearance};
use symbols::selected_instances;
-pub(crate) use symbols::{instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol};
+pub(crate) use symbols::{fit_instances_of, instance_in_place, instances_of, natural_size, normalize, place_xf, set_natural_size, store_symbol};
use symbols::{
- symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_edit, 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_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;
@@ -210,9 +210,18 @@ pub fn specs() -> Vec {
"Edit Symbol",
[],
None,
- "{id?, ids?: [id…] (instead of id)} break the link of the selected instance so the symbol's art can be edited (without the instance's own appearance changes to a dynamic symbol); finish with symbol.update → {name, ids}",
- has_selection,
- symbol_edit
+ "{id?, ids?: [id…] (instead of id), name?, x?, y?, artboard?: index=0 (the active artboard; the app passes it), viewCenter?: [x, y] (the app passes the view's center)} edit a symbol's art in symbol editing mode: the instance `id` (default: the selected instances, which must share one symbol) where it shows the art, else the symbol `name` (default: the current symbol) centered on (x, y) (default: the center of artboard `artboard`, or of the first artboard when there is no such artboard; in a document without artboards, viewCenter, else (0, 0)); every instance follows each edit and the instance stays linked (symbol.breakLink expands one); refused while a pattern or an opacity mask is edited → {name, layer, id?}",
+ has_doc,
+ super::symboledit::enter
+ ),
+ cmd!(
+ "symbol.exitEditing",
+ "Exit Symbol Editing Mode",
+ [],
+ None,
+ "{} leave symbol editing mode; after an edit, select the instance it was entered from; leaving without having changed the art adds no undo step and restores the selection from before entry (object.exitIsolation also leaves it) → {name?}",
+ has_doc,
+ super::symboledit::leave
),
cmd!(
"symbol.update",
diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs
index 556926309e..0b69b7f8ac 100644
--- a/crates/engine/src/cmd/brushsym/symbols.rs
+++ b/crates/engine/src/cmd/brushsym/symbols.rs
@@ -95,7 +95,14 @@ pub(crate) fn normalize(mut art: Node) -> Result<(Node, (f64, f64), Point)> {
Ok((art, (w, h), c))
}
-fn instances_of(d: &Document, name: Option<&str>) -> Vec {
+/// After the art of symbol `name` changed: each of its instances keeps its appearance changes to
+/// the objects the art still has.
+pub(crate) fn fit_instances_of(d: &mut Document, name: &str) {
+ let ids = instances_of(d, Some(name));
+ fit_overrides(d, &ids);
+}
+
+pub(crate) fn instances_of(d: &Document, name: Option<&str>) -> Vec {
let mut v = vec![];
d.walk(|n| {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
@@ -274,6 +281,14 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result {
if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) {
d.unknown.insert(CURRENT_SYMBOL.into(), json!(n));
}
+ // Symbol editing mode follows the new name, and so does its layer.
+ if let Some(e) = d.symbol_edit.as_mut().filter(|e| e.symbol == name) {
+ e.symbol = n.clone();
+ let layer = e.layer;
+ if let Some(l) = d.node_mut(layer) {
+ l.name = Some(n.clone());
+ }
+ }
}
if let Some(r) = reg {
d.set_symbol_registration(&final_name, r);
@@ -398,34 +413,35 @@ pub(super) fn symbol_break_link(s: &mut Session, p: &Value) -> Result {
Ok(json!({ "ids": ids_json(&out) }))
}
-pub(super) fn symbol_edit(s: &mut Session, p: &Value) -> Result {
- let ids = selected_instances(s, p)?;
- let first = *ids.first().ok_or_else(|| EngineError::Other("select a symbol instance".into()))?;
- let name = match &s.doc()?.doc.node(first).map(|n| n.kind.clone()) {
- Some(NodeKind::SymbolInstance { symbol, .. }) => symbol.clone(),
- _ => return Err(EngineError::Other("select a symbol instance".into())),
- };
- // The symbol's own art: one instance's appearance changes would become every instance's.
- let out = s.edit("Edit Symbol", |d, sel| {
- let out = break_links(d, &[first], false)?;
- sel.set(out.iter().copied());
- Ok(out)
- })?;
- Ok(json!({ "name": name, "ids": ids_json(&out) }))
-}
-
pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result {
const C: &str = "symbol.update";
let name = name_param(p, C)?.to_string();
if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) {
return Err(bad(C, format!("no symbol named `{name}`")));
}
+ // Redefining the symbol being edited leaves symbol editing mode in the same step.
+ let session = s.doc()?.doc.symbol_edit.clone().filter(|e| e.symbol == name);
+ if session.is_some() {
+ crate::cmd::settle_interaction(s)?;
+ s.end_text_edit();
+ }
let ids = roots(s, p)?;
+ // The art on the editing layer can't redefine it: the symbol would hold an instance of itself.
+ if let Some(se) = &session {
+ let d = &s.doc()?.doc;
+ if ids.iter().any(|i| d.ancestry(*i).is_some_and(|a| a.contains(&se.layer))) {
+ return Err(EngineError::Other("a symbol can't hold an instance of itself".into()));
+ }
+ }
let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?;
crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art);
let (art, size, c) = normalize(art)?;
let old = natural_size(&s.doc()?.doc, &name);
+ let editing = session.is_some();
let id = s.edit("Redefine Symbol", |d, sel| {
+ if editing {
+ crate::cmd::symboledit::finish(d, sel);
+ }
let art = d.reid(&art);
if let Some(sym) = d.symbols.iter_mut().find(|x| x.name == name) {
sym.art = Arc::new(art);
@@ -445,6 +461,9 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result {
sel.set([id]);
Ok(id)
})?;
+ if let Some(se) = &session {
+ crate::cmd::symboledit::leave_editing(s, se)?;
+ }
Ok(json!({ "name": name, "id": id.0 }))
}
@@ -476,8 +495,18 @@ pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result {
return Err(bad(C, format!("no symbol named `{name}`")));
}
let expand = switch_or(p, "expandInstances", true, C)?;
+ // Deleting the symbol being edited leaves symbol editing mode in the same step.
+ let session = s.doc()?.doc.symbol_edit.clone().filter(|e| names.contains(&e.symbol));
+ let editing = session.is_some();
+ if editing {
+ crate::cmd::settle_interaction(s)?;
+ s.end_text_edit();
+ }
let label = if names.len() == 1 { "Delete Symbol" } else { "Delete Symbols" };
- s.edit(label, |d, _| {
+ s.edit(label, |d, sel| {
+ if editing {
+ crate::cmd::symboledit::finish(d, sel);
+ }
// Every instance goes before any definition, whatever the order of `names`: expanding an
// instance of one symbol can bring out instances of another being deleted (nested in its
// art), which expand in turn while their definitions are still there. Each round expands
@@ -519,6 +548,9 @@ pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result {
}
Ok(())
})?;
+ if let Some(se) = &session {
+ crate::cmd::symboledit::leave_editing(s, se)?;
+ }
ok()
}
diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs
index 3534d40ac5..62a17bda3b 100644
--- a/crates/engine/src/cmd/edit.rs
+++ b/crates/engine/src/cmd/edit.rs
@@ -481,6 +481,7 @@ fn undo(s: &mut Session, _: &Value) -> Result {
let label = e.label.clone();
let costs = e.costs();
let editing = st.doc.mask_edit.map(|m| m.layer);
+ let editing_symbol = st.doc.symbol_edit.clone();
let doc = std::mem::replace(&mut st.doc, e.doc);
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
let selection = shared_selection(selection, st.history.redo.last());
@@ -494,6 +495,7 @@ fn undo(s: &mut Session, _: &Value) -> Result {
crate::deselect_hidden(&menu, &st.doc, &mut st.selection);
st.sync_new_art();
super::maskedit::follow_history(st, editing);
+ super::symboledit::follow_history(st, editing_symbol.as_ref());
leave_isolation_if_gone(st);
super::globaledit::follow_history(st);
Ok(json!({ "undone": label }))
@@ -507,6 +509,7 @@ fn redo(s: &mut Session, _: &Value) -> Result {
let label = e.label.clone();
let costs = e.costs();
let editing = st.doc.mask_edit.map(|m| m.layer);
+ let editing_symbol = st.doc.symbol_edit.clone();
let doc = std::mem::replace(&mut st.doc, e.doc);
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
let selection = shared_selection(selection, st.history.undo.last());
@@ -519,6 +522,7 @@ fn redo(s: &mut Session, _: &Value) -> Result {
crate::deselect_hidden(&menu, &st.doc, &mut st.selection);
st.sync_new_art();
super::maskedit::follow_history(st, editing);
+ super::symboledit::follow_history(st, editing_symbol.as_ref());
leave_isolation_if_gone(st);
super::globaledit::follow_history(st);
Ok(json!({ "redone": label }))
@@ -809,11 +813,13 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
&& (st.doc.paste_remembers_layers || boards.is_some())
&& parent.is_some_and(|p| st.doc.node(p).is_some_and(Node::is_layer));
// Front/back: relative to the selection (top-most / bottom-most selected object); with
- // nothing selected, the top / bottom of the current layer.
+ // nothing selected, the top / bottom of the current layer. Art other than paths goes beside
+ // the compound path that holds the selected object, not into it.
let anchor = if front || back {
let order = st.selection.in_paint_order(&st.doc);
let a = if front { order.last() } else { order.first() };
- a.and_then(|id| st.doc.position(*id))
+ let paths_only = clip.nodes.iter().all(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }));
+ a.map(|id| paste_anchor(&st.doc, *id, paths_only)).and_then(|id| st.doc.position(id))
} else {
None
};
@@ -856,17 +862,20 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
Some(Some(name)) if remember => Some(*layers.entry(name).or_insert_with(|| layer_named(d, name))),
_ => None,
};
+ // In a clip group or a clipping layer the bottom child is the clipping path: art pasted
+ // in back goes above it, not below it.
+ let floor = |d: &Document, par: Option| usize::from(par.and_then(|p| d.node(p)).is_some_and(Node::clips));
let (par, idx) = match (into, anchor, layer) {
// Inside the object Draw Inside draws into, on top of what is in it already.
(Some(group), ..) => (Some(group), usize::MAX),
// Next to the anchor, unless the object goes back to another layer.
(None, Some((par, i, _)), l) if l.is_none() || l == par => {
let k = placed.get(&par).copied().unwrap_or(0);
- (par, if front { i + 1 + k } else { i + k })
+ (par, if front { i + 1 + k } else { i.max(floor(d, par)) + k })
}
(None, _, l) => {
let par = l.or(parent);
- (par, if back { placed.get(&par).copied().unwrap_or(0) } else { usize::MAX })
+ (par, if back { floor(d, par) + placed.get(&par).copied().unwrap_or(0) } else { usize::MAX })
}
};
*placed.entry(par).or_default() += 1;
@@ -896,6 +905,15 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
}))
}
+/// What pasted art goes beside: `id`, or the compound path holding it when the art isn't only
+/// paths (a compound path holds paths only).
+fn paste_anchor(doc: &Document, id: NodeId, paths_only: bool) -> NodeId {
+ match doc.parent_of(id) {
+ Some(p) if !paths_only && doc.node(p).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. })) => p,
+ _ => id,
+ }
+}
+
/// The first unlocked layer or sublayer called `name` (topmost first), or a new top layer.
fn layer_named(d: &mut Document, name: &str) -> NodeId {
let mut found = None;
diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs
index 4079b42301..fb9419052e 100644
--- a/crates/engine/src/cmd/fileio.rs
+++ b/crates/engine/src/cmd/fileio.rs
@@ -121,7 +121,7 @@ use access::{may_read, may_write};
pub use commands::specs;
pub use export_names::artboard_file_names;
pub(crate) use export_names::{default_name, merge, unique_file_names, with_black_output, write_or_return};
-use export_names::{distinct_names, write_encoded};
+use export_names::{distinct_names_by, write_encoded};
use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, writable};
pub use formats::{
DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, export_extensions, extension,
diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs
index 4588b58aaa..f80302eee3 100644
--- a/crates/engine/src/cmd/fileio/commands.rs
+++ b/crates/engine/src/cmd/fileio/commands.rs
@@ -54,7 +54,7 @@ pub fn specs() -> Vec {
"Export for Screens",
["File", "Export"],
None,
- "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with for the document, for the artboard, asset, layer or object, from 1, #### for the counter zero-padded to the run of #, , , (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, , , , , , , and ; a trailing .ext is dropped, as in `COMPANY-Logo--####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)",
+ "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with for the document, for the artboard, asset, layer or object, from 1, #### for the counter zero-padded to the run of #, , , (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, , , , , , , and ; a trailing .ext is dropped, as in `COMPANY-Logo--####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)",
has_doc,
screens::export_for_screens
),
@@ -90,7 +90,7 @@ pub fn specs() -> Vec {
"Batch",
[],
None,
- "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing or select.allOnArtboard step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
+ "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
has_doc,
batch::batch
),
diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs
index 66bd6d3954..af0e49563c 100644
--- a/crates/engine/src/cmd/fileio/export_names.rs
+++ b/crates/engine/src/cmd/fileio/export_names.rs
@@ -20,6 +20,12 @@ pub(crate) fn unique_file_names<'a>(names: impl IntoIterator- ) -> Vec
{
+ distinct_names_by(names, str::to_lowercase)
+}
+
+/// `names` with `-2`, `-3`… after a name already used, two names matching when `key` gives the same
+/// key for them.
+pub(super) fn distinct_names_by(names: impl IntoIterator- , key: impl Fn(&str) -> String) -> Vec
{
let mut taken = std::collections::HashSet::new();
// The next number to try for each base: a name repeated many times doesn't search the numbers
// taken before it.
@@ -28,8 +34,8 @@ pub(super) fn distinct_names(names: impl IntoIterator- ) -> Vec
Result<()> {
rows_of(s, p, ScreenParams::of(p)?.preset.as_deref()).map(|_| ())
}
+/// `name` the way a case-insensitive file system compares names: lower-cased, then each character
+/// upper-cased where its upper case is one character. Names with the same lower case give the
+/// same key, and so do `ΟΣ`, `ος` and `οσ` (`ΟΣ`); `ᾈ` and `ᾀ` give `ᾀ`, and `ß` stays `ß`.
+fn fold(name: &str) -> String {
+ name.to_lowercase()
+ .chars()
+ .map(|c| {
+ let mut upper = c.to_uppercase();
+ match (upper.next(), upper.next()) {
+ (Some(u), None) => u,
+ _ => c,
+ }
+ })
+ .collect()
+}
+
/// The file names (and bytes) an export wrote, or the files it returns.
#[derive(Default)]
struct Output {
- /// Lower-case relative names already used, with what wrote each (two identical rows write
- /// one file; different files that would share a name get `-2`, `-3`…).
+ /// Relative names already used, by their [`fold`]ed spelling, with what wrote each (two
+ /// identical rows write one file; different files that would share a name get `-2`, `-3`…).
taken: std::collections::HashMap,
- /// Sub-folders already made.
+ /// Each sub-folder as the first file in it spells it, by its [`fold`]ed name.
+ folders: std::collections::HashMap,
+ /// Sub-folders already made, by their [`fold`]ed names.
made: HashSet,
/// `(relative name, bytes)` kept to return or zip (empty when written to a folder).
kept: Vec<(String, Vec)>,
@@ -505,12 +523,19 @@ struct Output {
}
impl Output {
- /// The name the file `key` writes as `name` takes: `name`, else (with `number`) `name-2`,
- /// `name-3`… when another file has it; `None` when the same file (`key`) was written as `name`
- /// already, or, without `number`, when any file was (the first row wins, as Export for Screens
- /// always did when no name pattern is given).
- fn claim(&mut self, name: &str, key: &str, number: bool) -> Option {
- let (base, ext) = name.rsplit_once('.').map_or((name, ""), |(b, e)| (b, e));
+ /// The name the file `key` writes as `name` takes: `name`, else `name-2`, `name-3`… when
+ /// another file has it, with or without a name pattern; `None` when the same file (`key`) was
+ /// written as `name` already. Names are compared without case, and a sub-folder keeps the
+ /// spelling of the first file put in it.
+ fn claim(&mut self, name: &str, key: &str) -> Option {
+ let name = match name.rsplit_once('/') {
+ Some((dir, file)) => {
+ let dir = self.folders.entry(fold(dir)).or_insert_with(|| dir.to_string());
+ format!("{dir}/{file}")
+ }
+ None => name.to_string(),
+ };
+ let (base, ext) = name.rsplit_once('.').map_or((name.as_str(), ""), |(b, e)| (b, e));
for n in 1.. {
let candidate = if n == 1 {
name.to_string()
@@ -519,11 +544,11 @@ impl Output {
} else {
format!("{base}-{n}.{ext}")
};
- match self.taken.get(&candidate.to_lowercase()) {
- Some(k) if k == key || !number => return None,
+ match self.taken.get(&fold(&candidate)) {
+ Some(k) if k == key => return None,
Some(_) => continue,
None => {
- self.taken.insert(candidate.to_lowercase(), key.to_string());
+ self.taken.insert(fold(&candidate), key.to_string());
return Some(candidate);
}
}
@@ -543,7 +568,7 @@ impl Output {
match folder {
Some(dir) if !keep => {
if let Some((sub, _)) = name.rsplit_once('/')
- && self.made.insert(sub.to_lowercase())
+ && self.made.insert(fold(sub))
{
create_dir(&format!("{dir}/{sub}"))?;
}
@@ -686,8 +711,8 @@ pub(super) fn presets_delete(s: &mut Session, p: &Value) -> Result {
/// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF
/// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard,
/// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and
-/// so do different files the `name` pattern gives one name. The reply's `warnings` lists every
-/// warning the encoders give for the files, each once.
+/// so do different files that would share a name, with or without the `name` pattern. The reply's
+/// `warnings` lists every warning the encoders give for the files, each once.
pub(crate) fn export(s: &mut Session, p: &Value) -> Result {
let o = ScreenParams::of(p)?;
let rows = rows_of(s, p, o.preset.as_deref())?;
@@ -818,7 +843,7 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
});
let (sub, file) = naming.file(document.as_ref().unwrap_or(item), index, files, r);
let name = sub.map_or_else(|| file.clone(), |d| format!("{d}/{file}"));
- let Some(name) = out.claim(&name, &format!("{}|{}", item.stem, r.key), o.name.is_some()) else { continue };
+ let Some(name) = out.claim(&name, &format!("{}|{}", item.stem, r.key)) else { continue };
let bytes = if let Some(boards) = single {
let mut options = r.options.clone();
options["range"] = json!(boards.iter().map(|b| (b + 1).to_string()).collect::>().join(", "));
@@ -938,8 +963,9 @@ fn items(
}
isolated(doc, &doc.paint_order(ids.iter().copied()), name).map(|(d, r)| (Arc::new(d), r))
};
- // Each item's stem follows Windows' file-naming rules, and no two items share one.
- let safe = |stems: Vec| distinct_names(stems.iter().map(|s| safe_file_name(s)));
+ // Each item's stem follows Windows' file-naming rules, and no two items share one, compared as
+ // the item folders are (`fold`).
+ let safe = |stems: Vec| distinct_names_by(stems.iter().map(|s| safe_file_name(s)), fold);
let named = |pieces: Vec<(String, Arc, Option, Rect)>, fallback: &str| -> Vec- {
let stems = safe(unique_file_names(pieces.iter().map(|(n, ..)| (n.as_str(), fallback.to_string()))));
pieces
diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs
index 6f603b2006..29e0b06801 100644
--- a/crates/engine/src/cmd/fileio/tests_aiimport.rs
+++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs
@@ -410,6 +410,33 @@ fn an_ai_file_with_a_variable_library_says_its_variables_werent_read() {
assert!(notes(&r).is_empty(), "{r}");
}
+/// An Objects on Path group in a `.ai` file opens as one: its record names the group's children by
+/// their ids in the opened document.
+#[test]
+fn an_ai_file_opens_its_objects_on_path_group_live() {
+ let ids = ["9b1c0e7a-0000-4000-8000-000000000001", "9b1c0e7a-0000-4000-8000-000000000002", "9b1c0e7a-0000-4000-8000-000000000003"];
+ let options = ai::on_path_options(2, 4, std::f64::consts::FRAC_PI_2, "");
+ let record = ai::on_path_record("Adobe Align On Path", &ids, &options); // brand-ok: the record's name in the files
+ let group = format!(
+ "0 Ae\nu\n/ConstraintGroup :\n128 /GroupType ,\n;\n0 0 1 0 0 0 1 XA\n10 50 m\n190 50 L\nS\n{}0 1 1 0 1 0 0 Xa\n{}f\n{}{}f\n{}U\n",
+ ai::on_path_member(ids[0], None, 0.0),
+ ai::rect(5.0, 45.0, 15.0, 55.0),
+ ai::on_path_member(ids[1], Some(0), 0.0),
+ ai::rect(185.0, 45.0, 195.0, 55.0),
+ ai::on_path_member(ids[2], Some(1), 0.0),
+ );
+ let data = ai::editing_data(200.0, 100.0, &format!("{record}{}", ai::layer("Art", &group)));
+ let mut s = Session::new();
+ let r = open(&mut s, "on-path.ai", &ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 5 45 10 10 re f 185 45 10 10 re f"), json!({})).unwrap();
+ assert_eq!(r["format"], json!("ai"), "{r}");
+ let doc = &s.doc().unwrap().doc;
+ let g = &doc.layers[0].children().unwrap()[0];
+ let rec = g.extras().objects_on_path.as_deref().expect("an Objects on Path group");
+ let kids: Vec
= g.children().unwrap().iter().map(|c| c.id).collect();
+ assert!(kids.contains(&rec.path) && rec.members.iter().all(|m| kids.contains(&m.id)), "{rec:?} {kids:?}");
+ assert_eq!((rec.members.len(), rec.pivot, rec.rotate.round()), (2, 4, 90.0));
+}
+
/// A page showing only a placeholder line, as a `.ai` saved without PDF compatibility has.
const PLACEHOLDER: &str = "BT /F1 12 Tf 10 50 Td (Saved without its PDF part) Tj ET";
diff --git a/crates/engine/src/cmd/fileio/tests_screens.rs b/crates/engine/src/cmd/fileio/tests_screens.rs
index bb4e356259..2f9e80cfca 100644
--- a/crates/engine/src/cmd/fileio/tests_screens.rs
+++ b/crates/engine/src/cmd/fileio/tests_screens.rs
@@ -533,13 +533,97 @@ fn png_8_rows_write_indexed_colour() {
let f = files(&r);
// The IHDR colour type: 3 (indexed) for PNG 8, 6 (RGBA) for PNG; both are .png, the PNG 8 row
// written first.
- assert_eq!(names(&r), ["Artboard-1.png"], "the same file name: the first row wins");
- assert_eq!(f[0].1[25], 3);
+ assert_eq!(names(&r), ["Artboard-1.png", "Artboard-1-2.png"], "the same file name: the second row's file is numbered");
+ assert_eq!((f[0].1[25], f[1].1[25]), (3, 6));
let r = export(&mut s, json!({"formats": [{"format": "png8", "suffix": "-8"}, {"format": "png"}]}));
let f = files(&r);
assert_eq!((f[0].1[25], f[1].1[25]), (3, 6));
}
+/// Without a name pattern, a row that writes a different file under a name another row's file
+/// already has gets `-2`, `-3`… as a name pattern's files do, compared without case; the first
+/// file keeps its name, and two identical rows still write one file.
+#[test]
+fn a_second_file_with_a_taken_name_is_numbered() {
+ let mut s = session(1);
+ let px = |png: &[u8]| image::load_from_memory(png).unwrap().to_rgba8().get_pixel(1, 1).0;
+ let rows = json!([{"format": "png", "background": "black"}, {"format": "png", "background": "white"}, {"format": "png", "background": "black"}]);
+ let r = export(&mut s, json!({ "formats": rows }));
+ assert_eq!(names(&r), ["Artboard-1.png", "Artboard-1-2.png"]);
+ let f = files(&r);
+ assert_eq!((px(&f[0].1), px(&f[1].1)), ([0, 0, 0, 255], [255, 255, 255, 255]));
+ // Row folders that differ only in case are one folder, spelled as the first row spells it.
+ let rows = json!([{"format": "png", "folder": "Print"}, {"format": "png", "folder": "print", "scale": 2, "suffix": ""}, {"format": "svg", "folder": "PRINT"}]);
+ let r = export(&mut s, json!({"subfolders": true, "formats": rows}));
+ assert_eq!(names(&r), ["Print/Artboard-1.png", "Print/Artboard-1-2.png", "Print/Artboard-1.svg"]);
+ assert_eq!(size(&files(&r)[1].1), (80, 60));
+}
+
+/// Names and folders that differ only in case match when a letter's lower case depends on where
+/// it stands: Greek `ΟΣ` lower-cases to `ος`, which a case-insensitive file system treats as `οσ`.
+#[test]
+fn names_that_differ_only_in_greek_sigmas_are_numbered() {
+ let mut s = session(2);
+ s.execute("artboard.setProps", &json!({"index": 0, "name": "ΟΣ"})).unwrap();
+ s.execute("artboard.setProps", &json!({"index": 1, "name": "οσ"})).unwrap();
+ let r = export(&mut s, json!({"name": "", "formats": [{"format": "svg"}]}));
+ assert_eq!(names(&r), ["ΟΣ.svg", "οσ-2.svg"]);
+ let rows = json!([{"format": "png", "folder": "ΟΣ"}, {"format": "svg", "folder": "οσ"}]);
+ let r = export(&mut s, json!({"range": "1", "subfolders": true, "formats": rows}));
+ assert_eq!(names(&r), ["ΟΣ/ΟΣ.png", "ΟΣ/ΟΣ.svg"]);
+ // Each item still gets a folder of its own.
+ let r = export(&mut s, json!({"folders": "item", "formats": [{"format": "svg"}]}));
+ assert_eq!(names(&r), ["ΟΣ/ΟΣ.svg", "οσ-2/οσ-2.svg"]);
+ // Letters whose full upper case is two characters still match their other case.
+ s.execute("artboard.setProps", &json!({"index": 0, "name": "ᾀ"})).unwrap();
+ s.execute("artboard.setProps", &json!({"index": 1, "name": "ᾈ"})).unwrap();
+ let r = export(&mut s, json!({"name": "", "formats": [{"format": "svg"}]}));
+ assert_eq!(names(&r), ["ᾀ.svg", "ᾈ-2.svg"]);
+ // So do names whose lower case is longer than the name: `İ` lower-cases to `i̇`.
+ s.execute("artboard.setProps", &json!({"index": 0, "name": "İ"})).unwrap();
+ s.execute("artboard.setProps", &json!({"index": 1, "name": "i\u{307}"})).unwrap();
+ let r = export(&mut s, json!({"name": "", "formats": [{"format": "svg"}]}));
+ assert_eq!(names(&r), ["İ.svg", "i\u{307}-2.svg"]);
+}
+
+/// A fresh folder for one test, emptied first and removed when dropped (also when an assertion
+/// fails).
+#[cfg(not(target_arch = "wasm32"))]
+struct Folder(std::path::PathBuf);
+
+#[cfg(not(target_arch = "wasm32"))]
+impl Folder {
+ fn new(name: &str) -> Self {
+ let dir = std::env::temp_dir().join(format!("vc-screens-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ Self(dir)
+ }
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+impl Drop for Folder {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+}
+
+/// The numbered file is written beside the first one, and the reply lists both paths.
+#[cfg(not(target_arch = "wasm32"))]
+#[test]
+fn a_numbered_file_is_written_into_the_first_rows_folder() {
+ let mut s = session(1);
+ let tmp = Folder::new("taken");
+ let dir = &tmp.0;
+ let folder = dir.to_string_lossy().replace('\\', "/");
+ let rows = json!([{"format": "png", "folder": "Print"}, {"format": "png", "folder": "print", "background": "white"}]);
+ let r = export(&mut s, json!({"folder": folder, "subfolders": true, "formats": rows}));
+ let written: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect();
+ assert_eq!(written, [format!("{folder}/Print/Artboard-1.png"), format!("{folder}/Print/Artboard-1-2.png")]);
+ let entries: Vec = std::fs::read_dir(dir.join("Print")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
+ assert_eq!(entries.len(), 2, "{entries:?}");
+ assert_eq!(std::fs::read_dir(dir).unwrap().count(), 1, "one sub-folder");
+}
+
#[test]
fn format_settings_apply_to_their_rows_and_rows_win() {
let mut s = session(1);
diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs
index ccaf3eeee0..b506c18f83 100644
--- a/crates/engine/src/cmd/gradient.rs
+++ b/crates/engine/src/cmd/gradient.rs
@@ -23,7 +23,7 @@ pub fn specs() -> Vec {
"Gradient",
["Window", "Gradient"],
None,
- "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even, which SVG and PDF exports draw as an image, except that PDF writes one made of tints of one spot color in that ink; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
+ "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even, which SVG and PDF exports draw as an image, except that PDF writes one with spot color stops in its inks when every other stop is paper white, CMYK or gray; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
has_doc,
edit_gradient
),
diff --git a/crates/engine/src/cmd/graph/data.rs b/crates/engine/src/cmd/graph/data.rs
index e81f24febd..0e69e0240e 100644
--- a/crates/engine/src/cmd/graph/data.rs
+++ b/crates/engine/src/cmd/graph/data.rs
@@ -86,7 +86,8 @@ pub(super) fn to_csv(g: &GraphSpec) -> String {
g.to_csv()
}
-/// Apply CSV graph data to the graph root `id` and rebuild its art (Variables data merge).
+/// Apply CSV graph data to the graph root `id` and rebuild its art (Variables data merge), as `graph.setData` with
+/// `csv` does.
pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> {
let Some(node) = d.node(id) else {
return Err(EngineError::NoNode(id));
@@ -94,13 +95,17 @@ pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> {
let Some(mut spec) = node.extras().graph.as_deref().cloned() else {
return Err(bad("graph.applyCsv", format!("node {} is not a graph", id.0)));
};
- let (series, categories, rows) = parse_csv(csv);
- spec.series = series;
- spec.categories = categories;
- spec.set_cells(rows);
+ apply_data(&mut spec, &json!({ "csv": csv }));
+ keep_right_series(&mut spec);
regenerate(d, id, spec)
}
+/// Drop right-axis series the data no longer has, so a series added later starts on the left.
+fn keep_right_series(g: &mut GraphSpec) {
+ let count = g.rows.iter().map(Vec::len).max().unwrap_or(0);
+ g.right_series.retain(|i| *i < count);
+}
+
pub(super) fn apply_data(g: &mut GraphSpec, p: &Value) -> bool {
let mut changed = false;
if let Some(csv) = str_param(p, "csv") {
@@ -131,9 +136,17 @@ pub(super) fn apply_data(g: &mut GraphSpec, p: &Value) -> bool {
changed
}
-/// Drop rows with neither a value nor a label; a label-only row stays, its values blank.
+/// Drop rows with neither a value nor a label; a label-only row stays, its values blank. Each kept row keeps its own
+/// width, so a dropped row wider than the rest adds no blank series.
fn drop_empty_rows(g: &mut GraphSpec) {
- let mut cells = g.cells();
+ let blank: std::collections::HashSet<[usize; 2]> = g.blanks.iter().copied().collect();
+ let mut cells: Vec>> = g
+ .rows
+ .iter()
+ .take(vectorcraft_doc::MAX_GRAPH_CATEGORIES)
+ .enumerate()
+ .map(|(c, r)| r.iter().take(vectorcraft_doc::MAX_GRAPH_SERIES).enumerate().map(|(s, v)| (!blank.contains(&[c, s])).then_some(*v)).collect())
+ .collect();
let keep: Vec = (0..cells.len())
.map(|c| cells.get(c).is_some_and(|r| r.iter().any(Option::is_some)) || g.categories.get(c).is_some_and(|l| !l.is_empty()))
.collect();
@@ -185,10 +198,7 @@ pub(super) fn set_data(s: &mut Session, p: &Value) -> Result {
// Blank cells come back as null, so the rows can be edited and sent back as they are.
return Ok(json!({ "csv": to_csv(&spec), "series": spec.series, "categories": spec.categories, "rows": spec.cells() }));
}
- // Series assigned to the right axis that the new data no longer has are dropped, so a series added later starts
- // on the left.
- let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0);
- spec.right_series.retain(|i| *i < count);
+ keep_right_series(&mut spec);
s.edit("Graph Data", |d, _| regenerate(d, id, spec))?;
Ok(json!({ "id": id.0 }))
}
diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs
index 9cafae899a..69d2baa9c2 100644
--- a/crates/engine/src/cmd/object/arrange.rs
+++ b/crates/engine/src/cmd/object/arrange.rs
@@ -334,13 +334,27 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result {
}
pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result {
- // Opacity mask editing and pattern editing isolate their editing layer. Leaving isolation mode
- // then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's Done do.
+ // Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving
+ // isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's
+ // Done do. A group isolated inside the symbol's art goes back to the symbol's layer.
let st = s.doc()?;
+ if let Some(layer) = st.doc.symbol_edit.as_ref().map(|e| e.layer)
+ && let Some(inner) = st.isolation.filter(|i| *i != layer)
+ {
+ crate::cmd::settle_interaction(s)?;
+ let st = s.doc_mut()?;
+ crate::cmd::distortcmds::finish_edit_text(st, inner);
+ st.isolation = Some(layer);
+ st.selection.set([inner]);
+ st.revision += 1;
+ return ok();
+ }
let leave_mode: Option Result> = if st.doc.mask_edit.is_some() {
Some(crate::cmd::maskedit::leave)
} else if st.doc.pattern_edit.is_some() {
Some(crate::cmd::patterncmds::pattern_done)
+ } else if st.doc.symbol_edit.is_some() {
+ Some(crate::cmd::symboledit::leave)
} else {
None
};
diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs
index 7f504dcc4f..68449f5ebd 100644
--- a/crates/engine/src/cmd/panelcmds.rs
+++ b/crates/engine/src/cmd/panelcmds.rs
@@ -43,7 +43,7 @@ pub fn specs() -> Vec {
"Character / Paragraph",
[],
None,
- "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)",
+ "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)",
has_doc,
set_format
),
@@ -318,6 +318,22 @@ fn spacing_param(p: &Value, key: &str, c: &str) -> Result; 3
fn set_format(s: &mut Session, p: &Value) -> Result {
const C: &str = "text.setFormat";
let ids = super::typecmd::text_targets(s, p, C)?;
+ check_switches(
+ p,
+ &[
+ "underline",
+ "strikethrough",
+ "allCaps",
+ "proportionalMetrics",
+ "tateChuYoko",
+ "standardVerticalRoman",
+ "noBreak",
+ "hyphenate",
+ "hyphenateCapitalized",
+ "romanHangingPunctuation",
+ ],
+ C,
+ )?;
let num = |k: &str| p.get(k).and_then(Value::as_f64);
let flag = |k: &str| p.get(k).and_then(Value::as_bool);
let kerning = match p.get("kerning") {
@@ -373,6 +389,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result {
"standardVerticalRoman",
"noBreak",
"digits",
+ "fontHeightReference",
"language",
"fontAxes",
"burasagari",
@@ -397,6 +414,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result {
let digits = super::textedit::digits_param(p, C)?;
let language = super::textedit::language_param(p, C)?;
let font_axes = super::textedit::font_axes_param(p, C)?;
+ let font_height_reference = super::textedit::font_height_reference_param(p, C)?;
let mojikumi = match p.get("mojikumi") {
None => None,
Some(v) => Some(match v.as_str() {
@@ -545,6 +563,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result {
if let Some(v) = &font_axes {
super::textedit::change_font_axes(st, v);
}
+ if let Some(v) = font_height_reference {
+ st.font_height_reference = v;
+ }
};
s.edit("Character", |d, _| {
for id in &ids {
diff --git a/crates/engine/src/cmd/patterncmds.rs b/crates/engine/src/cmd/patterncmds.rs
index aea1aeb58a..8f1e993203 100644
--- a/crates/engine/src/cmd/patterncmds.rs
+++ b/crates/engine/src/cmd/patterncmds.rs
@@ -161,12 +161,18 @@ fn in_pattern_edit(s: &Session) -> std::result::Result<(), String> {
editing(s).map(|_| ()).ok_or_else(|| "not in pattern editing mode".into())
}
-/// Make: a selection, and no opacity mask is being edited
-/// ([`super::maskedit::outside_mask_editing`]), since the tile layer would replace the mask editing
-/// layer as the isolated layer.
+/// Make: a selection, and no opacity mask or symbol is being edited
+/// ([`super::maskedit::outside_mask_editing`], [`outside_symbol_editing`]), since the tile layer
+/// would replace that mode's editing layer as the isolated layer.
fn can_make_pattern(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
- super::maskedit::outside_mask_editing(s)
+ super::maskedit::outside_mask_editing(s)?;
+ outside_symbol_editing(s)
+}
+
+/// No symbol is being edited (symbol editing mode shows the symbol in isolation mode).
+fn outside_symbol_editing(s: &Session) -> std::result::Result<(), String> {
+ if s.active().is_some_and(|st| st.doc.symbol_edit.is_some()) { Err("exit isolation mode first".into()) } else { Ok(()) }
}
fn can_edit_pattern(s: &Session) -> std::result::Result<(), String> {
@@ -175,6 +181,7 @@ fn can_edit_pattern(s: &Session) -> std::result::Result<(), String> {
return Err("already editing a pattern".into());
}
super::maskedit::outside_mask_editing(s)?;
+ outside_symbol_editing(s)?;
if s.active().is_some_and(|st| st.doc.patterns.is_empty()) { Err("the document has no patterns".into()) } else { Ok(()) }
}
diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs
index 82d1f1cfd5..b1fd2489e9 100644
--- a/crates/engine/src/cmd/recolor.rs
+++ b/crates/engine/src/cmd/recolor.rs
@@ -33,7 +33,7 @@ pub fn specs() -> Vec {
"Recolor Artwork",
["Edit", "Edit Colors"],
None,
- "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null, exclude?: false (the row's colours are kept)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model)}",
+ "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null, exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model)}",
has_doc,
apply
),
@@ -260,6 +260,44 @@ struct Row {
from: Vec,
to: Option,
exclude: bool,
+ /// The tint (0..1) of a global or spot swatch the new color is (with `limitTo`): art linked to
+ /// the swatch takes this share of the tint the method gives it.
+ tint: f32,
+ /// The row's own `model`, which takes the place of the command's for its colors.
+ model: Option,
+}
+
+/// The color model a row's colors take (`model`): each color's own, the new color's, or the
+/// document's.
+#[derive(Clone, Copy, PartialEq)]
+enum ModelRule {
+ Keep,
+ New,
+ Document,
+}
+
+impl ModelRule {
+ /// The `model` of `v` (a row or the command's parameters); a given `model` must be a string.
+ fn param(v: &Value, cmd: &str) -> Result> {
+ match v.get("model") {
+ None => Ok(None),
+ Some(Value::String(m)) => match m.as_str() {
+ "keep" => Ok(Some(Self::Keep)),
+ "new" => Ok(Some(Self::New)),
+ "document" => Ok(Some(Self::Document)),
+ other => Err(bad(cmd, format!("unknown model `{other}` (keep, new or document)"))),
+ },
+ Some(other) => Err(bad(cmd, format!("bad model {other} (keep, new or document)"))),
+ }
+ }
+
+ fn id(self) -> &'static str {
+ match self {
+ Self::Keep => "keep",
+ Self::New => "new",
+ Self::Document => "document",
+ }
+ }
}
impl Row {
@@ -280,7 +318,9 @@ fn parse_rows(p: &Value, cmd: &str) -> Result> {
};
let cur = |v: &Value| Match::of(v).ok_or_else(|| bad(cmd, format!("bad current colour {v}")));
match p.get("map") {
- Some(Value::Object(m)) => m.iter().map(|(k, v)| Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false })).collect(),
+ Some(Value::Object(m)) => {
+ m.iter().map(|(k, v)| Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0, model: None })).collect()
+ }
Some(Value::Array(rows)) => rows
.iter()
.map(|r| {
@@ -289,7 +329,9 @@ fn parse_rows(p: &Value, cmd: &str) -> Result> {
Some(v) => vec![cur(v)?],
None => return Err(bad(cmd, "each row needs `from`")),
};
- Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)? })
+ let tint = (super::number_or(r, "tint", 100.0, cmd)? / 100.0).clamp(0.0, 1.0) as f32;
+ let model = ModelRule::param(r, cmd)?;
+ Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model })
})
.collect(),
_ => Err(bad(cmd, "missing `map` (rows [{from, to}] or {current: new})")),
@@ -303,6 +345,8 @@ struct Link {
name: String,
global: bool,
color: Color,
+ /// The row's tint of the swatch (0..1).
+ tint: f32,
}
/// A global swatch of the color group `recolor.apply` rewrites: its name, the color it is
@@ -330,17 +374,21 @@ struct ColorMap {
impl ColorMap {
/// `links`: the swatch of each of `rows`' new colours (as many as `rows`, or none); `group`: the
- /// global swatches of the color group being rewritten.
- fn new(rows: &[Row], method: Method, own_model: bool, links: &[Option ], group: Vec) -> Self {
+ /// global swatches of the color group being rewritten; `model`: the model rule of a row without
+ /// its own.
+ fn new(rows: &[Row], method: Method, model: ModelRule, links: &[Option ], group: Vec) -> Self {
let mut out =
Self { rows: vec![], links: vec![], tos: vec![], group, keys: HashMap::new(), hexes: HashMap::new(), converted: Default::default() };
for (n, r) in rows.iter().enumerate().filter(|(_, r)| !r.from.is_empty()) {
let Some(to) = r.new_color() else { continue };
let i = out.rows.len();
let colors: Vec = r.from.iter().map(Match::color).collect();
- out.rows.push(RowMap::new(method, &colors, to).with_own_model(own_model));
+ let link = links.get(n).cloned().flatten();
+ // Colors that can't link to the swatch take the row's tint of it too.
+ let mapped = link.as_ref().filter(|l| l.global && l.tint < 1.0).map_or(to, |l| to.tinted(l.tint));
+ out.rows.push(RowMap::new(method, &colors, mapped).with_own_model(r.model.unwrap_or(model) != ModelRule::Keep));
out.tos.push(to);
- out.links.push(links.get(n).cloned().flatten());
+ out.links.push(link);
for m in &r.from {
match m {
Match::Key(k) => out.keys.entry(*k).or_insert(i),
@@ -365,7 +413,8 @@ impl ColorMap {
}
/// Recolour a colour that can link to a swatch: a row whose new colour is a global or spot
- /// swatch links its colours to it (at their tints; shades and other hues stay unlinked), a
+ /// swatch links its colours to it (at their tints times the row's tint; shades and other hues
+ /// stay unlinked), a
/// process swatch gives its colour in its own model; a color linked to a global swatch of the
/// rewritten group that takes the row's new color keeps its link (at its tint in the row) when
/// the row gives it the new color in that color's model;
@@ -388,7 +437,7 @@ impl ColorMap {
}
let new = match (l, row.tint(*c)) {
(Some(l), Some(t)) if l.global => {
- let t = t.clamp(0.0, 1.0);
+ let t = (t * l.tint).clamp(0.0, 1.0);
let shown = l.color.tinted(t);
let changed = link.as_deref() != Some(l.name.as_str()) || *tint != t || *c != shown;
(*c, *link, *tint) = (shown, Some(l.name.clone()), t);
@@ -441,26 +490,14 @@ fn apply(s: &mut Session, p: &Value) -> Result {
let scope = Scope { fill: true, stroke: true, ..Scope::of(p) };
let label = if ids.is_empty() { "Edit Color Group" } else { "Recolor Artwork" };
// `model`: keep each colour's model (default), take the new colour's own, or the document's.
- // A given `model` must be a string; only a missing one means "keep".
- let model = match p.get("model") {
- None => "keep",
- Some(Value::String(m)) => m.as_str(),
- Some(other) => return Err(bad(C, format!("bad model {other} (keep, new or document)"))),
- };
- let mut doc_model = None;
- let own_model = match model {
- "keep" => false,
- "new" => true,
- "document" => {
- let m = s.doc()?.doc.color_mode.model();
- doc_model = Some(m);
- for r in &mut rows {
- r.to = r.to.map(|c| c.in_model(m));
- }
- true
- }
- other => return Err(bad(C, format!("unknown model `{other}` (keep, new or document)"))),
- };
+ // A given `model` must be a string; only a missing one means "keep". A row's own `model`
+ // takes its place for that row.
+ let model = ModelRule::param(p, C)?.unwrap_or(ModelRule::Keep);
+ let mode_model = s.doc()?.doc.color_mode.model();
+ for r in rows.iter_mut().filter(|r| r.model.unwrap_or(model) == ModelRule::Document) {
+ r.to = r.to.map(|c| c.in_model(mode_model));
+ }
+ let doc_model = (model == ModelRule::Document).then_some(mode_model);
// The colours a colour group takes follow the model too (`document` converts them).
let in_doc_model = |c: Color| doc_model.map_or(c, |m| c.in_model(m));
let group_colors = match p.get("groupColors") {
@@ -487,7 +524,8 @@ fn apply(s: &mut Session, p: &Value) -> Result {
let mut added = vec![];
let links: Vec> = row_swatches
.iter()
- .map(|w| {
+ .zip(&rows)
+ .map(|(w, row)| {
let w = w.as_ref()?;
let name = match d.swatch(&w.name) {
Some(x) if x.paint == w.paint => w.name.clone(),
@@ -499,7 +537,7 @@ fn apply(s: &mut Session, p: &Value) -> Result {
}
};
let color = d.global_color(&name).filter(|_| w.global).or(w.paint.color())?;
- Some(Link { name, global: w.global, color })
+ Some(Link { name, global: w.global, color, tint: row.tint })
})
.collect();
// The group's global swatches that its rewrite gives a color: art linked to one of them
@@ -515,7 +553,7 @@ fn apply(s: &mut Session, p: &Value) -> Result {
.collect()
})
.unwrap_or_default();
- let map = ColorMap::new(&rows, method, own_model, &links, kept);
+ let map = ColorMap::new(&rows, method, model, &links, kept);
let f = |c: Color| map.map(c);
let lf = |c: &mut Color, link: &mut Option, tint: &mut f32| map.map_link(c, link, tint);
let changed = Recolor::with_links(scope, &f, &lf).run(d, &ids);
@@ -542,22 +580,37 @@ fn randomize(_: &mut Session, p: &Value) -> Result {
let rows = parse_rows(p, C)?;
let mut rng = Rng::new(super::menucmds::whole_or(p, "seed", 0, C)?);
let (order, saturation_brightness) = (switch_or(p, "order", true, C)?, switch_or(p, "saturationBrightness", false, C)?);
- let mut news: Vec = rows.iter().filter_map(Row::new_color).collect();
+ // Each new color with its row's tint and model: a tint moves with its color, and goes when
+ // the color changes; a model moves with its color.
+ let mut news: Vec<(Color, f32, Option)> = rows.iter().filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect();
if order {
rng.shuffle(&mut news);
}
if saturation_brightness {
- news = news.into_iter().map(|c| rng.saturation_brightness(c)).collect();
+ news = news
+ .into_iter()
+ .map(|(c, tint, model)| {
+ let n = rng.saturation_brightness(c);
+ (n, if ColorKey::of(&n) == ColorKey::of(&c) { tint } else { 1.0 }, model)
+ })
+ .collect();
}
let mut news = news.into_iter();
let map: Vec = rows
.iter()
.map(|r| {
- let to = if r.new_color().is_some() { news.next() } else { r.to };
+ let (to, tint, model) =
+ if r.new_color().is_some() { news.next().map_or((None, 1.0, None), |(c, t, m)| (Some(c), t, m)) } else { (r.to, r.tint, r.model) };
let mut row = json!({"from": r.from.iter().map(Match::to_json).collect::>(), "to": to.as_ref().map(key_str)});
if r.exclude {
row["exclude"] = json!(true);
}
+ if tint < 1.0 {
+ row["tint"] = json!(f64::from((tint * 10_000.0).round()) / 100.0);
+ }
+ if let Some(m) = model {
+ row["model"] = json!(m.id());
+ }
row
})
.collect();
diff --git a/crates/engine/src/cmd/shaper.rs b/crates/engine/src/cmd/shaper.rs
index 9a952082a0..511e8ce4fb 100644
--- a/crates/engine/src/cmd/shaper.rs
+++ b/crates/engine/src/cmd/shaper.rs
@@ -773,9 +773,10 @@ fn select(s: &mut Session, p: &Value) -> Result {
}
Ok(json!({"id": target.0}))
}
-/// The layer an opacity mask or a pattern is edited in, which stays isolated while that mode is on.
+/// The layer an opacity mask, a pattern or a symbol is edited in, which stays isolated while that
+/// mode is on.
fn editing_layer(d: &Document) -> Option {
- d.mask_edit.map(|m| m.layer).or_else(|| d.pattern_edit.as_ref().map(|e| e.layer))
+ d.mask_edit.map(|m| m.layer).or_else(|| d.pattern_edit.as_ref().map(|e| e.layer)).or_else(|| d.symbol_edit.as_ref().map(|e| e.layer))
}
/// Leave isolation mode, Construction mode included. While an opacity mask or a pattern is edited,
/// its editing layer stays isolated.
diff --git a/crates/engine/src/cmd/symboledit.rs b/crates/engine/src/cmd/symboledit.rs
new file mode 100644
index 0000000000..a89fbe8d61
--- /dev/null
+++ b/crates/engine/src/cmd/symboledit.rs
@@ -0,0 +1,445 @@
+//! Symbol editing mode (Edit Symbol, a double-click on an instance or on a symbol in the Symbols
+//! panel).
+//!
+//! The symbol's art moves onto a temporary isolated layer, placed where the instance it was
+//! entered from shows it (from the panel: at the center of the active artboard, or of the view in a
+//! document without artboards), where every tool and command can edit it while the rest of the
+//! document is dimmed. After each edit [`sync`] writes the layer's art back into the symbol, so
+//! every instance updates live. Leaving the mode
+//! (`symbol.exitEditing`, Escape, the isolation bar's back button, a double-click outside the art)
+//! removes the layer, and saving or exporting never writes it ([`Document::without_edit_modes`]).
+//! Symbol editing is not entered while a pattern or an opacity mask is edited, and neither of those
+//! is entered while a symbol is edited.
+
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use serde_json::{Value, json};
+use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection, SymbolEdit, SymbolRegistration};
+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};
+
+/// The name of the undo step that enters symbol editing mode.
+const ENTER: &str = "Edit Symbol";
+
+/// The symbol instances among the selected objects, members of selected groups included.
+fn selected_instances(st: &crate::DocState) -> Vec {
+ let mut out = vec![];
+ for id in &st.selection.objects {
+ if let Some(n) = st.doc.node(*id) {
+ n.walk(&mut |c| {
+ if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !out.contains(&c.id) {
+ out.push(c.id);
+ }
+ });
+ }
+ }
+ out
+}
+
+/// The symbol and transform of instance `id`.
+fn instance_of(d: &Document, id: NodeId) -> Option<(String, Affine)> {
+ match &d.node(id)?.kind {
+ NodeKind::SymbolInstance { symbol, xf } => Some((symbol.clone(), *xf)),
+ _ => None,
+ }
+}
+
+/// Where editing places the art: the instance's own transform, or for one that flattens the art,
+/// a placement at the symbol's natural size around the same point.
+fn editing_xf(d: &Document, name: &str, xf: Affine) -> Affine {
+ let det = xf.determinant();
+ if det.is_finite() && det.abs() > 1e-12 { xf } else { place_xf(xf * Point::ZERO, natural_size(d, name), SymbolRegistration::CENTER) }
+}
+
+/// Enter symbol editing mode (`symbol.edit`).
+pub(crate) fn enter(s: &mut Session, p: &Value) -> Result {
+ const C: &str = "symbol.edit";
+ let st = s.doc()?;
+ if st.doc.mask_edit.is_some() {
+ return Err(bad(C, "stop editing the opacity mask first"));
+ }
+ 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 (name, xf, instance) = match given {
+ Some(ids) => {
+ let symbols = ids.iter().map(|id| instance_of(&st.doc, *id)).collect::>>();
+ let symbols = symbols.ok_or_else(|| bad(C, "select a symbol instance"))?;
+ let (name, xf) = symbols.first().cloned().ok_or_else(|| bad(C, "select a symbol instance"))?;
+ if symbols.iter().any(|(n, _)| *n != name) {
+ return Err(bad(C, "select instances of one symbol"));
+ }
+ let xf = editing_xf(&st.doc, &name, xf);
+ (name, xf, ids.first().copied())
+ }
+ None => {
+ let picked = if str_param(p, "name").is_some() { vec![] } else { selected_instances(st) };
+ let symbols: Vec<(String, Affine)> = picked.iter().filter_map(|id| instance_of(&st.doc, *id)).collect();
+ match symbols.first() {
+ Some((first, xf)) => {
+ if symbols.iter().any(|(n, _)| n != first) {
+ return Err(bad(C, "select instances of one symbol"));
+ }
+ (first.clone(), editing_xf(&st.doc, first, *xf), picked.first().copied())
+ }
+ None => {
+ let d = &st.doc;
+ let name = match str_param(p, "name") {
+ Some(n) if d.symbols.iter().any(|x| x.name == n) => n.to_string(),
+ Some(n) => return Err(bad(C, format!("no symbol named `{n}`"))),
+ None => d
+ .unknown
+ .get(super::brushsym::CURRENT_SYMBOL)
+ .and_then(Value::as_str)
+ .filter(|n| d.symbols.iter().any(|x| x.name == *n))
+ .or_else(|| d.symbols.first().map(|x| x.name.as_str()))
+ .map(str::to_string)
+ .ok_or_else(|| EngineError::Other("the document has no symbols".into()))?,
+ };
+ let artboard = p.get("artboard").and_then(Value::as_u64).map_or(0, super::index);
+ let center = match d.artboards.get(artboard).or(d.artboards.first()) {
+ Some(a) => a.rect.center(),
+ None => super::point_param(p, "viewCenter").unwrap_or(Point::ZERO),
+ };
+ let at = Point::new(number_or(p, "x", center.x, C)?, number_or(p, "y", center.y, C)?);
+ (name.clone(), place_xf(at, natural_size(d, &name), SymbolRegistration::CENTER), None)
+ }
+ }
+ }
+ };
+ // Editing another symbol (one from the Symbols panel, or through the API): the current edit
+ // ends first.
+ if st.doc.symbol_edit.is_some() {
+ if instance.is_some_and(|i| st.doc.symbol_edit.as_ref().is_some_and(|e| st.doc.ancestry(i).unwrap_or_default().contains(&e.layer))) {
+ return Err(bad(C, "exit isolation mode first"));
+ }
+ leave(s, &json!({}))?;
+ }
+ if let Some(i) = s.doc()?.isolation {
+ super::settle_interaction(s)?;
+ super::distortcmds::finish_edit_text(s.doc_mut()?, i);
+ }
+ s.end_text_edit();
+ let st = s.doc()?;
+ let back = Return { redo: st.history.redo.clone(), before: Some(st.doc.clone()) };
+ let (isolation, active_layer) = (st.isolation, st.active_layer);
+ let layer = s.edit(ENTER, |d, sel| {
+ let layer = begin(d, sel, &name, xf, instance)?;
+ if let Some(e) = d.symbol_edit.as_mut() {
+ e.back_isolation = isolation;
+ e.back_layer = active_layer;
+ }
+ Ok(layer)
+ })?;
+ s.doc_mut()?.symbol_edit_return = back;
+ show_editing(s, layer)?;
+ let mut out = json!({ "name": name, "layer": layer.0 });
+ if let Some(i) = instance {
+ out["id"] = json!(i.0);
+ }
+ Ok(out)
+}
+
+/// A group whose members editing spreads out on the layer: nothing of its own that they would lose
+/// while they are edited.
+fn spreads(art: &Node) -> bool {
+ matches!(art.kind, NodeKind::Group { clip: false, .. })
+ && art.has_default_transparency()
+ && art.appearance.items.is_empty()
+ && art.appearance.effects.is_empty()
+}
+
+/// Enter symbol editing for `name` inside an edit: copy its art, placed by `xf`, onto a new
+/// editing layer and select it. Returns the layer.
+fn begin(d: &mut Document, sel: &mut Selection, name: &str, xf: Affine, instance: Option) -> Result {
+ let art =
+ d.symbols.iter().find(|x| x.name == name).map(|x| x.art.clone()).ok_or_else(|| EngineError::Other(format!("no symbol named `{name}`")))?;
+ let group = spreads(&art);
+ let parts = match art.children() {
+ Some(ch) if group => ch.clone(),
+ _ => vec![art],
+ };
+ let layer = d.add_layer(Some(name));
+ let mut ids = Vec::with_capacity(parts.len());
+ for part in &parts {
+ let mut copy = d.reid(part);
+ copy.transform(xf, false);
+ ids.push(d.insert(Some(layer), usize::MAX, copy)?);
+ }
+ // Copied type whose layout caches `reid` dropped has them again.
+ super::typecmd::refresh_bounds_of(d, &ids);
+ d.symbol_edit = Some(SymbolEdit { symbol: name.to_string(), layer, instance, xf, group, changed: false, back_isolation: None, back_layer: None });
+ sel.set(ids);
+ Ok(layer)
+}
+
+/// Leave symbol editing mode (`symbol.exitEditing`); a no-op outside it. `object.exitIsolation` runs
+/// it too while a symbol is edited. Isolation and the current layer go back to what they were
+/// before. When nothing changed the art since editing was entered, the entering step is taken back
+/// instead of a step being added, so the document and its redo steps are as they were.
+pub(crate) fn leave(s: &mut Session, _: &Value) -> Result {
+ let Some(se) = s.doc()?.doc.symbol_edit.clone() else { return ok() };
+ super::settle_interaction(s)?;
+ super::distortcmds::finish_edit_text(s.doc_mut()?, se.layer);
+ s.end_text_edit();
+ let st = s.doc_mut()?;
+ let unchanged = !st.doc.symbol_edit.as_ref().is_some_and(|e| e.changed);
+ let Return { redo, before } = std::mem::take(&mut st.symbol_edit_return);
+ // Saved while editing: the saved file holds no editing layer, so leaving keeps it saved.
+ let saved_here = st.saved_doc.symbol_edit.as_ref().is_some_and(|e| e.layer == se.layer);
+ let clean = !st.is_dirty();
+ // Not after edits that were undone (their redo steps hold the editing layer), nor after a save
+ // (taking the entering step back would undo what the save changed). The last step is the
+ // entering step only when it starts from the document entering started from: a batch step
+ // that entered after other edits starts from before them.
+ if unchanged
+ && !saved_here
+ && st.history.redo.is_empty()
+ && let Some(entry) = st.history.undo.last()
+ && before.as_ref().is_some_and(|b| Arc::ptr_eq(b, &entry.doc))
+ && let Some(entry) = st.history.undo.pop()
+ {
+ let now = std::mem::replace(&mut st.doc, entry.doc);
+ // What changed outside the undo history while editing (the current symbol and brush, the
+ // perspective grid's view, export settings, the grid preferences) stays as it is now.
+ if st.doc.unknown != now.unknown || st.doc.export_settings != now.export_settings || st.doc.grid != now.grid {
+ let d = Arc::make_mut(&mut st.doc);
+ d.unknown = now.unknown.clone();
+ d.export_settings = now.export_settings.clone();
+ d.grid = now.grid.clone();
+ }
+ st.selection = Arc::unwrap_or_clone(entry.selection);
+ st.selection.prune(&st.doc);
+ st.history.redo = redo;
+ st.revision += 1;
+ } else {
+ s.edit("Exit Symbol Editing Mode", |d, sel| {
+ finish(d, sel);
+ Ok(())
+ })?;
+ if saved_here && clean {
+ s.doc_mut()?.mark_saved();
+ }
+ }
+ leave_editing(s, &se)?;
+ Ok(json!({ "name": se.symbol }))
+}
+
+/// Leave symbol editing inside an edit (no-op when not editing): drop the editing layer and select
+/// the instance editing was entered from. The symbol already holds the layer's art ([`sync`]).
+pub(crate) fn finish(d: &mut Document, sel: &mut Selection) {
+ let Some(se) = d.symbol_edit.take() else { return };
+ let _ = d.remove(se.layer);
+ match se.instance.filter(|i| d.node(*i).is_some()) {
+ Some(i) => sel.set([i]),
+ None => sel.clear(),
+ }
+}
+
+/// The redo steps entering symbol editing mode cleared, which leaving without an edit gives back,
+/// and the document entering started from, which tells the entering step apart from any other.
+#[derive(Clone, Debug, Default)]
+pub(crate) struct Return {
+ redo: Vec,
+ before: Option>,
+}
+
+/// Isolate the editing layer `layer` and draw into it.
+fn show_editing(s: &mut Session, layer: NodeId) -> Result<()> {
+ let st = s.doc_mut()?;
+ st.isolation = Some(layer);
+ st.active_layer = Some(layer);
+ st.revision += 1;
+ Ok(())
+}
+
+/// Return to the document after leaving the editing session `se`: to the isolation and current
+/// layer from before it, while they are still there.
+pub(crate) fn leave_editing(s: &mut Session, se: &SymbolEdit) -> Result<()> {
+ let st = s.doc_mut()?;
+ st.symbol_edit_return = Return::default();
+ go_back(st, se);
+ st.revision += 1;
+ Ok(())
+}
+
+/// Out of the editing session `se`: the isolation and current layer from before it, else none and
+/// the default layer.
+pub(crate) fn go_back(st: &mut crate::DocState, se: &SymbolEdit) {
+ st.isolation = se.back_isolation.filter(|i| st.doc.node(*i).is_some());
+ st.active_layer = se.back_layer.filter(|l| st.doc.node(*l).is_some_and(|n| n.is_layer())).or_else(|| st.doc.default_layer());
+}
+
+/// After undo or redo, isolation follows the restored document into or out of symbol editing
+/// (`was` is the editing session before, if any), so it never names a layer that is gone. A group
+/// isolated inside the symbol's art stays isolated while it is there.
+pub(crate) fn follow_history(st: &mut crate::DocState, was: Option<&SymbolEdit>) {
+ match st.doc.symbol_edit.as_ref().map(|e| e.layer) {
+ Some(layer) => {
+ let inside = st.isolation.is_some_and(|i| i != layer && st.doc.ancestry(i).is_some_and(|a| a.contains(&layer)));
+ if !inside {
+ st.isolation = Some(layer);
+ }
+ st.active_layer = Some(layer);
+ }
+ None => {
+ // Out of the mode: isolation on the editing layer or inside it, and a current layer
+ // that is gone, go back to what they were before it.
+ let Some(was) = was else { return };
+ let gone = |id: Option| id.is_some_and(|i| i == was.layer || st.doc.node(i).is_none());
+ if gone(st.isolation) || gone(st.active_layer) {
+ go_back(st, was);
+ }
+ }
+ }
+}
+
+/// Does `n` hold an instance of symbol `name`, directly or through the art of the symbols it holds
+/// instances of?
+fn holds_symbol(d: &Document, n: &Node, name: &str, seen: &mut HashSet) -> bool {
+ let mut found = false;
+ let mut nested = vec![];
+ n.walk(&mut |c| {
+ if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
+ if symbol == name {
+ found = true;
+ } else if !seen.contains(symbol) {
+ nested.push(symbol.clone());
+ }
+ }
+ });
+ if found {
+ return true;
+ }
+ for symbol in nested {
+ if seen.insert(symbol.clone())
+ && let Some(art) = d.symbols.iter().find(|x| x.name == symbol).map(|x| x.art.clone())
+ && holds_symbol(d, &art, name, seen)
+ {
+ return true;
+ }
+ }
+ false
+}
+
+/// The object at `path` (child indices, paint order) among `nodes` and the groups they hold.
+fn at_path<'a>(nodes: &'a [Arc], path: &[u32]) -> Option<&'a Node> {
+ let (first, rest) = path.split_first()?;
+ let mut n: &Node = nodes.get(*first as usize)?;
+ for i in rest {
+ n = n.children()?.get(*i as usize)?;
+ }
+ Some(n)
+}
+
+/// The path of object `id` among `nodes` and the groups they hold, at most `depth` levels down.
+fn path_of(nodes: &[Arc], id: NodeId, depth: usize) -> Option> {
+ if depth == 0 {
+ return None;
+ }
+ for (i, n) in nodes.iter().enumerate() {
+ let i = u32::try_from(i).ok()?;
+ if n.id == id {
+ return Some(vec![i]);
+ }
+ if let Some(mut p) = n.children().and_then(|ch| path_of(ch, id, depth - 1)) {
+ p.insert(0, i);
+ return Some(p);
+ }
+ }
+ None
+}
+
+/// Each instance's appearance changes to objects of symbol `name`'s art follow those objects
+/// through an edit of the editing layer: `old` and `new` are the layer's objects before and after
+/// with whether the symbol's art is a group of them (else it is the one object). A change to an
+/// object the edit removed names no object afterwards.
+fn follow_objects(d: &mut Document, name: &str, old: (&[Arc], bool), new: (&[Arc], bool)) {
+ let depth = vectorcraft_doc::symbol_overrides::MAX_PATH_DEPTH + 1;
+ for id in super::brushsym::instances_of(d, Some(name)) {
+ let Some(n) = d.node_mut(id) else { continue };
+ if n.extras().symbol_overrides.is_empty() {
+ continue;
+ }
+ let mut e = n.extras_mut();
+ e.symbol_overrides.retain_mut(|o| {
+ // The art's own group stays the art's root.
+ if old.1 && o.path.is_empty() {
+ return true;
+ }
+ let on_layer: Vec = if old.1 { o.path.clone() } else { std::iter::once(0).chain(o.path.iter().copied()).collect() };
+ let moved = at_path(old.0, &on_layer).and_then(|obj| path_of(new.0, obj.id, depth)).and_then(|p| match new.1 {
+ true => Some(p),
+ false => p.split_first().filter(|(first, _)| **first == 0).map(|(_, rest)| rest.to_vec()),
+ });
+ match moved {
+ Some(p) => {
+ o.path = p;
+ true
+ }
+ None => false,
+ }
+ });
+ }
+}
+
+/// Write the editing layer's art back into the symbol (called after every edit, with the document
+/// as it was before); each instance of a dynamic symbol keeps its appearance changes to the objects
+/// the art still has. Leaves the mode when the symbol or the layer is gone. Refuses art that holds
+/// an instance of the symbol itself.
+pub(crate) fn sync(before: &Document, d: &mut Document) -> Result<()> {
+ let Some(se) = d.symbol_edit.clone() else { return Ok(()) };
+ let art: Option>> = d.node(se.layer).and_then(|l| l.children().cloned());
+ let (Some(art), Some(index)) = (art, d.symbols.iter().position(|x| x.name == se.symbol)) else {
+ d.symbol_edit = None;
+ let _ = d.remove(se.layer);
+ return Ok(());
+ };
+ // Entering, and edits that left the layer's art alone, write nothing.
+ let same = |b: &[Arc]| b.len() == art.len() && b.iter().zip(&art).all(|(a, b)| Arc::ptr_eq(a, b));
+ let (old, old_group) = match before.symbol_edit.as_ref().filter(|b| b.layer == se.layer) {
+ None => return Ok(()),
+ Some(_) if before.node(se.layer).and_then(|l| l.children()).is_some_and(|b| same(b)) => return Ok(()),
+ Some(b) => (before.node(se.layer).and_then(|l| l.children().cloned()).unwrap_or_default(), b.group),
+ };
+ if art.iter().any(|n| holds_symbol(d, n, &se.symbol, &mut HashSet::new())) {
+ return Err(EngineError::Other("a symbol can't hold an instance of itself".into()));
+ }
+ let inv = se.xf.inverse();
+ let parts: Vec> = art
+ .iter()
+ .map(|n| {
+ let mut n = (**n).clone();
+ n.transform(inv, false);
+ Arc::new(n)
+ })
+ .collect();
+ // Once the layer's objects make a group, later edits give that group its members.
+ let (new_art, group) = if se.group {
+ let mut g = (*d.symbols[index].art).clone();
+ if let Some(ch) = g.children_mut() {
+ *ch = parts;
+ }
+ (g, true)
+ } else {
+ match <[Arc; 1]>::try_from(parts) {
+ Ok([one]) => (Arc::unwrap_or_clone(one), false),
+ Err(parts) => {
+ let id = d.alloc_id();
+ (Node::group(id, parts), true)
+ }
+ }
+ };
+ d.symbols[index].art = Arc::new(new_art);
+ follow_objects(d, &se.symbol, (&old, old_group), (&art, group));
+ super::brushsym::fit_instances_of(d, &se.symbol);
+ if let Some(e) = d.symbol_edit.as_mut() {
+ e.changed = true;
+ e.group = group;
+ }
+ Ok(())
+}
diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs
index 8cfdaf47f4..88f1b6a59a 100644
--- a/crates/engine/src/cmd/textedit.rs
+++ b/crates/engine/src/cmd/textedit.rs
@@ -39,7 +39,7 @@ pub fn specs() -> Vec {
"Character",
[],
None,
- "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
+ "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
has_doc,
set_range_style
),
@@ -48,7 +48,7 @@ pub fn specs() -> Vec {
"Touch Type",
[],
None,
- "{id, start: byte (a character of it), dx?: pt, dy?: pt, hScale?: %, vScale?: %, rotation?: deg} change one character (a ligature, one glyph for several characters, as a whole) as a Touch Type tool drag does, as one undo step: dx moves it along its line in reading order by changing the kerning of the character before it on the line and its own kerning, and the characters after it stay where they are (an error for the first character of a line and for a right-to-left character; limited to what kerning from -1000 to 10000 can give); dy raises it (baseline shift, along its own up axis when it is rotated); dx and dy are document points; hScale (including the object transform), vScale and rotation set its scales and rotation as text.setRangeStyle does. The kerning of the two characters also keeps the character and the ones after it where they were along the line when the font kerned them with their neighbors; a wider or narrower character moves the ones after it by the change in its width → {id, start, end} (the character's bytes)",
+ "{id, start: byte (a character of it), dx?: pt, dy?: pt, hScale?: %, vScale?: %, rotation?: deg} change one character (a ligature, one glyph for several characters, as a whole) as a Touch Type tool drag does, as one undo step: dx moves it along its line in reading order by changing the kerning of the character before it on the line and its own kerning, and the characters after it stay where they are (an error for the first character of a line and for a right-to-left character; limited to what kerning from -1000 to 10000 can give); dy raises it (baseline shift, up from its line whatever its rotation, also for the first character of a line and a right-to-left character); dx and dy are document points; hScale (including the object transform), vScale and rotation set its scales and rotation as text.setRangeStyle does. The kerning of the two characters also keeps the character and the ones after it where they were along the line when the font kerned them with their neighbors; a wider or narrower character moves the ones after it by the change in its width → {id, start, end} (the character's bytes)",
has_doc,
touch_type
),
@@ -186,6 +186,48 @@ pub(crate) fn set_plain_text(d: &mut vectorcraft_doc::Document, id: NodeId, text
Ok(())
}
+/// Replace the whole story of the type object `id` as [`set_plain_text`] replaces one type
+/// object's content: for a frame of threaded text, every frame's text. The new text goes into the
+/// thread's first frame and the other frames are emptied; the edit's reflow then pours it through
+/// them. → the story's last frame, which holds any text that does not fit.
+pub(crate) fn set_story_text(d: &mut vectorcraft_doc::Document, id: NodeId, text: &str) -> Result {
+ let story = d.story_of(id);
+ let (Some((&first, rest)), Some(&last)) = (story.split_first(), story.last()) else {
+ return Err(EngineError::NoNode(id));
+ };
+ if rest.is_empty() {
+ set_plain_text(d, id, text)?;
+ return Ok(id);
+ }
+ let frames: Vec = story
+ .iter()
+ .filter_map(|f| match d.node(*f).map(|n| &n.kind) {
+ Some(NodeKind::Text(t)) => Some((**t).clone()),
+ _ => None,
+ })
+ .collect();
+ let refs: Vec<&TextObject> = frames.iter().collect();
+ // The first frame takes the whole story first, so the replace keeps the story's first style
+ // and paragraph styles follow as for one type object.
+ let t = text_mut(d, first).ok_or(EngineError::NoNode(first))?;
+ t.runs = vectorcraft_text::thread::story(&refs);
+ t.set_paragraph_styles(vectorcraft_text::thread::story_paras(&refs, &[]));
+ set_plain_text(d, first, text)?;
+ // An emptied frame's paragraph takes the new text's last paragraph style, so it does not
+ // restyle that paragraph when the story is joined again.
+ let tail = match d.node(first).map(|n| &n.kind) {
+ Some(NodeKind::Text(t)) => t.paragraph_styles().last().cloned().unwrap_or_default(),
+ _ => Default::default(),
+ };
+ for f in rest {
+ let t = text_mut(d, *f).ok_or(EngineError::NoNode(*f))?;
+ t.runs.clear();
+ t.set_paragraph_styles(vec![tail.clone()]);
+ refresh_bounds(t);
+ }
+ Ok(last)
+}
+
/// The byte offset that `k` holds, read with [`index`].
fn byte_param(p: &Value, k: &str) -> Option {
p.get(k).and_then(Value::as_u64).map(index)
@@ -325,6 +367,7 @@ pub(crate) struct CharChange {
/// The language to set: a tag, or `None` for the default.
language: Option>,
font_axes: Option,
+ font_height_reference: Option,
}
/// `charDirection: "default"|"leftToRight"|"rightToLeft"` → the Character Direction to set (`None`
@@ -452,6 +495,20 @@ pub(crate) fn char_align_param(p: &Value, cmd: &str) -> Result Result > {
+ use vectorcraft_doc::FontHeightReference;
+ let Some(v) = p.get("fontHeightReference").filter(|v| !v.is_null()) else { return Ok(None) };
+ Ok(Some(match v.as_str() {
+ Some("emBox") => FontHeightReference::EmBox,
+ Some("capHeight") => FontHeightReference::CapHeight,
+ Some("xHeight") => FontHeightReference::XHeight,
+ Some("icfBox") => FontHeightReference::IcfBox,
+ _ => return Err(bad(cmd, "`fontHeightReference` must be \"emBox\", \"capHeight\", \"xHeight\" or \"icfBox\"")),
+ }))
+}
+
fn paint_param(p: &Value, k: &str, cmd: &str) -> Result > {
match p.get(k) {
None | Some(Value::Null) => Ok(None),
@@ -523,6 +580,7 @@ impl CharChange {
digits: digits_param(p, cmd)?,
language: language_param(p, cmd)?,
font_axes: font_axes_param(p, cmd)?,
+ font_height_reference: font_height_reference_param(p, cmd)?,
};
if c.size.is_some_and(|v| v <= 0.0) {
return Err(bad(cmd, "size must be positive"));
@@ -570,6 +628,7 @@ impl CharChange {
&& self.digits.is_none()
&& self.language.is_none()
&& self.font_axes.is_none()
+ && self.font_height_reference.is_none()
}
fn localize(&mut self, t: &TextObject, cmd: &str) -> Result<()> {
@@ -680,6 +739,9 @@ impl CharChange {
if let Some(v) = self.digits {
st.digits = v;
}
+ if let Some(v) = self.font_height_reference {
+ st.font_height_reference = v;
+ }
if let Some(v) = &self.language {
st.language.clone_from(v);
}
@@ -896,9 +958,8 @@ fn touch_type(s: &mut Session, p: &Value) -> Result {
});
};
// The baseline shift that raises the character `dy` document points. Baseline shift moves it
- // along its own up axis, turned with its rotation (the new one, when the call sets it), by a
- // length that the object transform, Shrink Text to Fit and a path effect such as Skew scale:
- // two layouts with the call's other changes and shifts one step apart, both within the range,
+ // up from its line, whatever its rotation, by a length that the object transform, Shrink Text
+ // to Fit and a path effect such as Skew scale: two layouts with the call's other changes and shifts one step apart, both within the range,
// measure that length. Neither shift is one that a run already has, so the character's run
// splits off alike in both.
let raise = if dy == 0.0 {
@@ -1216,7 +1277,11 @@ fn type_step(s: &mut Session, p: &Value) -> Result {
match step {
Step::Size => st.size = super::typecmd::local_type_value(t, st.size * points + inc, (0.1, 1296.0), false, C)?,
Step::Leading => {
- let leading = t.para_at(paras.get(i).copied().unwrap_or(0)).effective_leading(st);
+ // With Auto leading the step starts from the leading the lines are set with:
+ // the paragraph's Auto Leading share of the em size the font height reference
+ // gives the characters. An inline graphic keeps its size.
+ let em = if run.inline.is_some() { st.size } else { vectorcraft_text::FontDb::global().em_size(st, t.vertical) };
+ let leading = t.para_at(paras.get(i).copied().unwrap_or(0)).effective_leading(&CharStyle { size: em, ..st.clone() });
st.leading = Some(super::typecmd::local_type_value(t, leading * points + inc, (0.1, 5000.0), false, C)?);
}
Step::Tracking => st.tracking = (st.tracking + inc).clamp(-1000.0, 10000.0),
diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs
index 5995c490d8..ee8ab1d3c5 100644
--- a/crates/engine/src/cmd/textstyles.rs
+++ b/crates/engine/src/cmd/textstyles.rs
@@ -178,6 +178,7 @@ pub fn char_attrs(v: &CharStyle) -> Map {
("standardVerticalRoman", json!(v.standard_vertical_roman)),
("noBreak", json!(v.no_break)),
("digits", json!(v.digits)),
+ ("fontHeightReference", json!(v.font_height_reference)),
("language", json!(v.language)),
] {
m.insert(k.into(), x);
diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs
index 65febdf0bd..4a1200c256 100644
--- a/crates/engine/src/cmd/typecmd/area_tests.rs
+++ b/crates/engine/src/cmd/typecmd/area_tests.rs
@@ -1306,6 +1306,97 @@ fn digits_are_a_character_attribute_saved_only_when_set() {
assert_eq!(set, [("صفحة ".to_string(), Digits::Default), ("12".to_string(), Digits::Farsi)]);
}
+/// Font height reference (Character panel › Set Font Height Reference): a character attribute,
+/// saved only when not the em box; the type is laid out again at the em size it gives, so 20 pt
+/// type measuring a 0.7 em cap height grows by 1 / 0.7, and a leading step from Auto starts at
+/// 120% of that em size.
+#[test]
+fn font_height_reference_is_a_character_attribute_saved_only_when_not_the_em_box() {
+ use vectorcraft_doc::FontHeightReference as R;
+ use vectorcraft_text::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, height_font};
+ vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap());
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
+ let id =
+ s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hx Hx", "font": HEIGHT_FAMILY, "size": 20})).unwrap()["id"].as_u64().unwrap();
+ let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
+ NodeKind::Text(t) => t.clone(),
+ _ => panic!("text"),
+ };
+ let height = |s: &Session| text(s).cached_bounds.unwrap().height();
+ let em_box = height(&s);
+ assert_eq!(text(&s).runs[0].style.font_height_reference, R::EmBox);
+ s.execute("select.set", &json!({"ids": [id]})).unwrap();
+ for (key, want) in [("capHeight", R::CapHeight), ("xHeight", R::XHeight), ("icfBox", R::IcfBox), ("emBox", R::EmBox)] {
+ s.execute("text.setFormat", &json!({"fontHeightReference": key})).unwrap();
+ assert!(text(&s).runs.iter().all(|r| r.style.font_height_reference == want && r.style.size == 20.0));
+ let saved = serde_json::to_value(&text(&s).runs[0].style).unwrap();
+ assert_eq!(saved.get("fontHeightReference").and_then(|v| v.as_str()), (want != R::EmBox).then_some(key));
+ }
+ s.execute("text.setFormat", &json!({"fontHeightReference": "capHeight"})).unwrap();
+ let grown = height(&s) / em_box;
+ assert!((grown - 1000.0 / f64::from(HEIGHT_CAP)).abs() < 1e-6, "{grown}");
+ // A leading step from Auto starts at the leading the lines are set with: 120% of the em size
+ // (the paragraph's Auto Leading).
+ s.execute("type.step", &json!({"attribute": "leading"})).unwrap();
+ let stepped = text(&s).runs[0].style.leading.unwrap();
+ assert!((stepped - (1.2 * 20.0 * 1000.0 / f64::from(HEIGHT_CAP) + 2.0)).abs() < 1e-9, "{stepped}");
+ s.execute("edit.undo", &json!({})).unwrap();
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(text(&s).runs[0].style.font_height_reference, R::EmBox);
+ assert!((height(&s) - em_box).abs() < 1e-9);
+ let err = s.execute("text.setFormat", &json!({"fontHeightReference": "baseline"})).unwrap_err().to_string();
+ assert!(err.contains("`fontHeightReference` must be"), "{err}");
+ // Characters selected with the Type tool: only the range takes it.
+ s.execute("text.setRangeStyle", &json!({"id": id, "start": 3, "end": 5, "fontHeightReference": "xHeight"})).unwrap();
+ let set: Vec<_> = text(&s).runs.iter().map(|r| (r.text.clone(), r.style.font_height_reference)).collect();
+ assert_eq!(set, [("Hx ".to_string(), R::EmBox), ("Hx".to_string(), R::XHeight)]);
+}
+
+/// A leading step from Auto starts at the leading each paragraph's lines are set with, its
+/// Auto Leading share of the em size: 20 pt type in paragraphs at 120% and 150% steps from 24 pt
+/// and from 30 pt.
+#[test]
+fn a_leading_step_from_auto_starts_at_each_paragraphs_auto_leading() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
+ let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab\nCd", "size": 20})).unwrap()["id"].as_u64().unwrap();
+ s.execute("text.setFormat", &json!({"id": id, "start": 3, "end": 5, "autoLeading": 150})).unwrap();
+ s.execute("select.set", &json!({"ids": [id]})).unwrap();
+ s.execute("type.step", &json!({"attribute": "leading"})).unwrap();
+ let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind else {
+ panic!("text");
+ };
+ let leading: Vec<_> = t.runs.iter().map(|r| (r.text.as_str(), r.style.leading)).collect();
+ assert_eq!(leading, [("Ab\n", Some(26.0)), ("Cd", Some(32.0))]);
+}
+
+/// An inline graphic keeps its size whatever the font height reference, so a leading step from
+/// Auto starts at 120% of that size: 20 pt Cap Height type steps from 120% of 20 / 0.7 pt and
+/// the graphic in it from 24 pt.
+#[test]
+fn a_leading_step_from_auto_starts_at_an_inline_graphics_own_size() {
+ use vectorcraft_text::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, height_font};
+ vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap());
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
+ s.execute("shape.ellipse", &json!({"x": 300, "y": 300, "width": 10, "height": 10})).unwrap();
+ s.execute("symbol.new", &json!({"name": "Dot"})).unwrap();
+ s.execute("edit.clear", &json!({})).unwrap();
+ let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hx", "font": HEIGHT_FAMILY, "size": 20})).unwrap()["id"].as_u64().unwrap();
+ s.execute("text.insertInline", &json!({"id": id, "at": 2, "symbol": "Dot"})).unwrap();
+ s.execute("select.set", &json!({"ids": [id]})).unwrap();
+ s.execute("text.setFormat", &json!({"fontHeightReference": "capHeight"})).unwrap();
+ s.execute("type.step", &json!({"attribute": "leading"})).unwrap();
+ let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind else {
+ panic!("text");
+ };
+ let leading: Vec<_> = t.runs.iter().map(|r| (r.inline.is_some(), r.style.leading.unwrap())).collect();
+ let text = 1.2 * 20.0 * 1000.0 / f64::from(HEIGHT_CAP) + 2.0;
+ assert_eq!(leading.len(), 2, "{leading:?}");
+ assert!(leading.iter().all(|&(inline, l)| (l - if inline { 26.0 } else { text }).abs() < 1e-9), "{leading:?}");
+}
+
/// The Indic digits (#4942): each set by its id through text.setFormat and text.setRangeStyle,
/// saved under it, kept by save and reopen and by character styles; the text stays as typed.
#[test]
diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs
index 116149ec78..9e589e8839 100644
--- a/crates/engine/src/cmd/variablecmds.rs
+++ b/crates/engine/src/cmd/variablecmds.rs
@@ -18,7 +18,7 @@ use vectorcraft_doc::{DataSet, DataValue, NodeId, NodeKind, Variable, VariableKi
use super::edit::selected_roots;
use super::fileio::{absolute_path, read_file_head, write_file};
-use super::textedit::set_plain_text;
+use super::textedit::set_story_text;
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selection, links, str_param};
mod csv;
@@ -160,6 +160,9 @@ fn rename(s: &mut Session, p: &Value) -> Result {
let from = var_name(p, C)?;
let to = named(p.get("newName").and_then(Value::as_str), "newName", C)?;
let st = s.doc()?;
+ if st.doc.variables.variable(&from).is_none() {
+ return Err(bad(C, format!("no variable named `{from}`")));
+ }
if st.doc.variables.variable(&to).is_some() {
return Err(bad(C, format!("variable `{to}` already exists")));
}
@@ -357,6 +360,9 @@ fn dataset_rename(s: &mut Session, p: &Value) -> Result {
let from = var_name(p, C)?;
let to = named(p.get("newName").and_then(Value::as_str), "newName", C)?;
let st = s.doc()?;
+ if st.doc.variables.dataset(&from).is_none() {
+ return Err(bad(C, format!("no dataset named `{from}`")));
+ }
if st.doc.variables.dataset(&to).is_some() {
return Err(bad(C, format!("dataset `{to}` already exists")));
}
@@ -487,16 +493,20 @@ fn apply_dataset(s: &mut Session, name: &str) -> Result {
};
// Locked art, art in a locked layer or group, and text whose object is gone, can't be
// rewritten: skipped and counted, like the rest. Hidden art is rewritten, in a hidden
- // layer or group too, and stays hidden unless a visibility value shows it.
- if !d.dataset_target(id) {
+ // layer or group too, and stays hidden unless a visibility value shows it. A text value
+ // rewrites the whole story of threaded text, so it skips when any frame of it is locked.
+ let target = if kind == VariableKind::Text { d.story_target(id) } else { d.dataset_target(id) };
+ if !target {
skipped += 1;
continue;
}
let done = match (kind, &value) {
// The Type tool's own whole-range replace, so a dataset's text is styled and
- // laid out exactly as typing it would be.
- (VariableKind::Text, DataValue::Text(text)) => set_plain_text(d, id, text).is_ok_and(|()| {
- typed.push(id);
+ // laid out exactly as typing it would be. A frame of threaded text has its whole
+ // story replaced, the value capture reads from it; the story's last frame is the
+ // one that overflows.
+ (VariableKind::Text, DataValue::Text(text)) => set_story_text(d, id, text).is_ok_and(|last| {
+ typed.push(last);
true
}),
(VariableKind::Visibility, DataValue::Visible(show)) => d.node_mut(id).is_some_and(|n| {
@@ -641,7 +651,7 @@ pub fn specs() -> Vec {
"Lock Variables",
["Window", "Variables"],
None,
- "{locked?: bool} lock or unlock the variables (default: toggle); saved with the document; a change is one undo step. While locked, variable.define, variable.delete, variable.rename, variable.make…Dynamic and a variable.loadLibrary that would delete or define a variable are refused; binding, unbinding and the dataset commands still run → {locked}",
+ "{locked?: bool} lock or unlock the variables (default: toggle); saved with the document; a change is one undo step. While locked, variable.define, variable.delete, variable.rename, variable.make…Dynamic and a variable.loadLibrary that would delete or define a variable are refused; binding, unbinding and the dataset commands still run, except a dataset.import whose header would define a variable → {locked}",
has_doc,
lock
),
@@ -670,7 +680,7 @@ pub fn specs() -> Vec {
"Capture Data Set",
["Window", "Variables"],
None,
- "{name?} record what the bound objects hold right now as a new dataset (Data Set 1…), and make it the active one",
+ "{name?} record what the bound objects hold right now as a new dataset (Data Set 1…), and make it the active one; a frame of threaded text holds its whole story, every frame's text in thread order",
has_doc,
dataset_capture
),
@@ -706,7 +716,7 @@ pub fn specs() -> Vec {
"Select Data Set",
["Window", "Variables"],
None,
- "{name} apply a dataset in one undo step, deselecting every selected object left hidden or locked (the key object too) → {applied, skipped, overflow?: [id…] (area type and type on a path whose text it rewrote and that no longer fits; left out when all fits), warning? (when no object is bound to a variable that the dataset has a value for, so nothing was applied)}",
+ "{name} apply a dataset in one undo step, deselecting every selected object left hidden or locked (the key object too); a text value bound to a frame of threaded text replaces the whole story → {applied, skipped, overflow?: [id…] (area type and type on a path whose text it rewrote and that no longer fits, the story's last frame for threaded text; left out when all fits), warning? (when no object is bound to a variable that the dataset has a value for, so nothing was applied)}",
has_doc,
dataset_select
),
diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs
index 2c3d66ee63..4a628d6ef3 100644
--- a/crates/engine/src/command_sets.rs
+++ b/crates/engine/src/command_sets.rs
@@ -2,10 +2,10 @@ use super::{NodeId, Value, cmd};
/// The commands that act on the active artboard (#693), which the app passes as their `artboard`:
/// Paste in Place, in Front and in Back paste onto it, Align to Artboard aligns to it, Distribute
-/// Objects and Distribute Spacing with Align to Artboard distribute objects across it, and All on
-/// Active Artboard selects on it. A `command.batch` given `artboard` passes it on to each of their
-/// steps that names none.
-pub const ON_ACTIVE_ARTBOARD: [&str; 7] = [
+/// Objects and Distribute Spacing with Align to Artboard distribute objects across it, All on
+/// Active Artboard selects on it, and Edit Symbol from the Symbols panel centers the symbol's art
+/// on it. A `command.batch` given `artboard` passes it on to each of their steps that names none.
+pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [
"edit.pasteInPlace",
"edit.pasteInFront",
"edit.pasteInBack",
@@ -13,6 +13,7 @@ pub const ON_ACTIVE_ARTBOARD: [&str; 7] = [
"object.distribute",
"object.distributeSpacing",
"select.allOnArtboard",
+ "symbol.edit",
];
/// The commands that resize the artboards the app passes (Object › Artboards): the app passes the
@@ -23,9 +24,9 @@ pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitTo
/// `(command, param)` pairs the journal records only so a replay reproduces the original run
/// (dates from the clock: `cmd::clock_date`; the artboards the app passes to the
-/// [`ON_ACTIVE_ARTBOARD`] and [`FIT_ACTIVE_ARTBOARD`] commands and to a batch); an action leaves
-/// them out ([`Session::journal_for_action`]).
-const REPLAY_ONLY: [(&str, &str); 14] = [
+/// [`ON_ACTIVE_ARTBOARD`] and [`FIT_ACTIVE_ARTBOARD`] commands and to a batch; the view's center
+/// the app passes to Edit Symbol); an action leaves them out ([`Session::journal_for_action`]).
+const REPLAY_ONLY: [(&str, &str); 16] = [
("file.new", "created"),
("document.save", "modified"),
("file.saveAs", "modified"),
@@ -39,6 +40,8 @@ const REPLAY_ONLY: [(&str, &str); 14] = [
("artboard.fitToArt", "indices"),
("artboard.fitToSelection", "index"),
("select.allOnArtboard", "artboard"),
+ ("symbol.edit", "artboard"),
+ ("symbol.edit", "viewCenter"),
("command.batch", "artboard"),
];
diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs
index 299f2f0004..30cf1e7e8d 100644
--- a/crates/engine/src/doc_state.rs
+++ b/crates/engine/src/doc_state.rs
@@ -34,6 +34,8 @@ pub struct DocState {
/// Select › Start Global Edit: the objects edited together until Stop Global Edit or Escape
/// ([`cmd::globaledit`]). Editing state: not saved, not undoable.
pub global_edit: Option,
+ /// What leaving symbol editing mode goes back to ([`cmd::symboledit`]).
+ pub(crate) symbol_edit_return: cmd::symboledit::Return,
pub interaction: Option,
/// Edits made while this is open are one undo step (a scrubbed numeric field).
pub undo_group: Option,
@@ -246,6 +248,7 @@ impl DocState {
variables_highlight: None,
isolation: None,
global_edit: None,
+ symbol_edit_return: Default::default(),
interaction: None,
undo_group: None,
last_transform: None,
diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs
index df707de3a2..fd2de6ec5b 100644
--- a/crates/engine/src/session/edit.rs
+++ b/crates/engine/src/session/edit.rs
@@ -37,6 +37,10 @@ impl Session {
if shaper_changed || dim_changed {
cmd::objects_on_path::refresh(&before, Arc::make_mut(&mut st.doc));
}
+ // Symbol editing: the symbol follows its art on the editing layer, before
+ // inline graphics follow their symbols.
+ let symbol_synced =
+ if st.doc.symbol_edit.is_some() { cmd::symboledit::sync(&before, Arc::make_mut(&mut st.doc)) } else { Ok(()) };
// Inline graphics in text follow their symbols.
cmd::inline::refresh(&before, Arc::make_mut(&mut st.doc));
// Text Wrap: area type follows its wrap objects; then threads re-flow.
@@ -60,7 +64,9 @@ impl Session {
if !st.doc.variables.bindings.is_empty() {
Arc::make_mut(&mut st.doc).prune_variable_bindings();
}
- if st.doc.too_deep(Some(&before)) {
+ if let Err(e) = symbol_synced {
+ Err(e)
+ } else if st.doc.too_deep(Some(&before)) {
// Deeper trees overflow the stack of what walks them.
Err(EngineError::Other(TOO_DEEP.into()))
} else if doc_sane(&st.doc, &st.selection) && objects_in_range(&st.doc, &spread) {
@@ -82,6 +88,21 @@ impl Session {
// The art on a locked artboard can't stay selected, however it got there, except
// the new art this edit made and new art still selected.
st.protect_locked_artboards(&before_sel.objects, &before_sel.new_art, Some(&*before));
+ // Symbol or opacity mask editing ended because the edit deleted its layer:
+ // isolation on the layer or inside it leaves too, out of symbol editing to what it
+ // was before.
+ let mode_layer = before.symbol_edit.as_ref().map(|e| e.layer).or(before.mask_edit.map(|m| m.layer));
+ if let Some(layer) = mode_layer
+ && st.doc.node(layer).is_none()
+ && st.isolation.is_some_and(|i| i == layer || st.doc.node(i).is_none())
+ {
+ if let Some(se) = &before.symbol_edit {
+ cmd::symboledit::go_back(st, se);
+ } else {
+ st.isolation = None;
+ st.active_layer = st.doc.default_layer();
+ }
+ }
st.revision += 1;
if st.interaction.is_none() {
let selection = match st.history.undo.last() {
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index c5baf054d1..2aab6da7df 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -158,6 +158,7 @@ mod swatchcmds;
mod swatches;
mod swatchlib;
mod symbolbounds;
+mod symboledit;
mod symbollib;
mod targeting;
mod textcombos;
diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs
index 90da1f7f8b..cd50516a76 100644
--- a/crates/engine/src/tests/brushsym.rs
+++ b/crates/engine/src/tests/brushsym.rs
@@ -1117,13 +1117,12 @@ fn place_and_break_link_round_trip_geometry() {
}
#[test]
-fn edit_then_update_redefines_all_instances() {
+fn break_link_then_update_redefines_all_instances() {
let mut s = session();
let (inst, name, _) = make_symbol(&mut s);
let other = NodeId(s.execute("symbol.place", &json!({"x": 300, "y": 200})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[inst]);
- let r = s.execute("symbol.edit", &json!({})).unwrap();
- assert_eq!(r["name"], name);
+ let r = s.execute("symbol.breakLink", &json!({})).unwrap();
let art = NodeId(r["ids"][0].as_u64().unwrap());
// Make the art twice as wide, then redefine.
s.execute("object.transform", &json!({"ids": [art.0], "matrix": [2, 0, 0, 1, -140, 0]})).ok();
diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs
index 410a828b9a..e7ddbc7c08 100644
--- a/crates/engine/src/tests/clipboard.rs
+++ b/crates/engine/src/tests/clipboard.rs
@@ -563,6 +563,75 @@ fn front_and_back_without_a_selection_use_the_current_layers_ends() {
assert_eq!(&l[i - 2..i], &below[..]);
}
+#[test]
+fn front_and_back_beside_a_compound_paths_member_go_beside_the_compound_path() {
+ let mut s = session();
+ let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
+ let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
+ sel(&mut s, &[a, b]);
+ let c = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
+ let members = |s: &Session| doc(s).node(c).unwrap().children().unwrap().iter().map(|n| n.id).collect::>();
+ let before = members(&s);
+ let layer = |s: &Session| doc(s).layers[0].children().unwrap().iter().map(|n| n.id).collect::>();
+ // A compound path and a group, each pasted with one of the compound path's members selected.
+ let other = rect(&mut s, 40.0, 0.0, 10.0, 10.0);
+ sel(&mut s, &[other]);
+ let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
+ for copied in [c, group] {
+ copy(&mut s, &[copied]);
+ sel(&mut s, &[before[0]]);
+ let above = ids_of(&s.execute("edit.pasteInFront", &json!({})).unwrap());
+ let l = layer(&s);
+ let i = l.iter().position(|id| *id == c).unwrap();
+ assert_eq!(&l[i + 1..i + 2], &above[..], "right above the compound path");
+ sel(&mut s, &[before[1]]);
+ let below = ids_of(&s.execute("edit.pasteInBack", &json!({})).unwrap());
+ let l = layer(&s);
+ let i = l.iter().position(|id| *id == c).unwrap();
+ assert_eq!(&l[i - 1..i], &below[..], "right below the compound path");
+ assert_eq!(members(&s), before, "the compound path keeps its own members");
+ }
+ // A path still goes in front of the member, inside the compound path.
+ let loose = rect(&mut s, 60.0, 0.0, 10.0, 10.0);
+ copy(&mut s, &[loose]);
+ sel(&mut s, &[before[0]]);
+ let path = ids_of(&s.execute("edit.pasteInFront", &json!({})).unwrap());
+ assert_eq!(members(&s), [before[0], path[0], before[1]]);
+}
+
+#[test]
+fn paste_in_back_of_a_clipping_path_keeps_it_the_clipping_path() {
+ let mut s = session();
+ let children = |s: &Session, g: NodeId| doc(s).node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect::>();
+ let loose = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
+ let other = rect(&mut s, 220.0, 0.0, 10.0, 10.0);
+ sel(&mut s, &[other]);
+ let group = id_of(&s.execute("object.group", &json!({})).unwrap());
+ // A path as the clipping path, and a compound path as the clipping path (a group pasted in back
+ // of a member goes beside the compound path).
+ let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
+ let mask = rect(&mut s, 10.0, 10.0, 50.0, 50.0);
+ sel(&mut s, &[art, mask]);
+ let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
+ let art2 = rect(&mut s, 0.0, 120.0, 100.0, 100.0);
+ let (a, b) = (rect(&mut s, 10.0, 130.0, 20.0, 20.0), rect(&mut s, 40.0, 130.0, 20.0, 20.0));
+ sel(&mut s, &[a, b]);
+ let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
+ sel(&mut s, &[art2, c]);
+ let g2 = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
+ for (g, clipping, target, copies) in [(g, mask, mask, vec![loose, group]), (g2, c, a, vec![group])] {
+ assert_eq!(children(&s, g)[0], clipping);
+ for copied in copies {
+ copy(&mut s, &[copied]);
+ sel(&mut s, &[target]);
+ let pasted = ids_of(&s.execute("edit.pasteInBack", &json!({})).unwrap());
+ let ch = children(&s, g);
+ assert_eq!(ch[0], clipping, "the clipping path stays the bottom child");
+ assert_eq!(&ch[1..2], &pasted[..], "right above the clipping path");
+ }
+ }
+}
+
#[test]
fn paste_on_all_artboards_keeps_the_offset_to_the_source_artboard() {
let mut s = Session::new();
diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs
index a580106d3c..aff7690c1d 100644
--- a/crates/engine/src/tests/dynamic_symbols.rs
+++ b/crates/engine/src/tests/dynamic_symbols.rs
@@ -144,8 +144,14 @@ fn break_link_bakes_the_changes_and_edit_symbol_shows_the_symbols_own_art() {
};
let art = NodeId(s.execute("symbol.breakLink", &json!({"ids": [inst.0]})).unwrap()["ids"][0].as_u64().unwrap());
assert_eq!(fills(&s, art), ["#0000ff", "#ff0000"]);
- let art = NodeId(s.execute("symbol.edit", &json!({"ids": [other.0]})).unwrap()["ids"][0].as_u64().unwrap());
- assert_eq!(fills(&s, art), ["#0000ff", "#0000ff"], "the symbol's art, without this instance's changes");
+ // Symbol editing mode shows the symbol's art, without this instance's changes.
+ s.execute("symbol.edit", &json!({"ids": [other.0]})).unwrap();
+ let st = s.doc().unwrap();
+ let layer = st.doc.symbol_edit.as_ref().unwrap().layer;
+ let parts: Vec =
+ st.doc.node(layer).unwrap().children().unwrap().iter().map(|c| c.appearance.fill_paint().color().unwrap().to_hex()).collect();
+ assert_eq!(parts, ["#0000ff", "#0000ff"], "the symbol's art, without this instance's changes");
+ assert_eq!(overrides(&s, other), 1, "the instance keeps its changes");
}
#[test]
diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs
index 5adffe77cf..666d317fe3 100644
--- a/crates/engine/src/tests/linked_stops.rs
+++ b/crates/engine/src/tests/linked_stops.rs
@@ -236,11 +236,39 @@ fn perceptual_spot_gradients_export_as_separation_shadings() {
assert!(pdf.contains("/C0[1]") && pdf.contains("/C1[0.4"), "white ink at 100% to 40%: {}", &pdf[at..(at + 200).min(pdf.len())]);
}
+#[test]
+fn perceptual_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() {
+ let (mut s, _) = setup();
+ run(&mut s, "swatch.new", json!({"name": "Leaf", "color": {"c": 1, "m": 0, "y": 1, "k": 0}, "spot": true}));
+ let ink_to_cyan = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": {"c": 1, "m": 0, "y": 0, "k": 0}}]});
+ let ink_to_leaf = json!({"stops": [{"offset": 0, "swatch": "Ink", "midpoint": 30}, {"offset": 1, "swatch": "Leaf", "tint": 50}]});
+ for (what, edit, space) in [
+ ("Ink → cyan", with(ink_to_cyan.clone(), json!({"method": "perceptual"})), "/DeviceN[/Cyan/Ink]/DeviceCMYK"),
+ ("Ink → Leaf 50 %", with(ink_to_leaf, json!({"method": "perceptual"})), "/DeviceN[/Ink/Leaf]/DeviceCMYK"),
+ ] {
+ run(&mut s, "paint.editGradient", edit);
+ let (pdf, warnings) = pdf_of(&s);
+ assert!(!pdf.contains("/Subtype/Image"), "{what}: no image");
+ assert!(pdf.contains("/ShadingType 2") && pdf.contains(space), "{what}: a DeviceN shading");
+ // The curve's stops: a stitching function of more than the two ends.
+ assert!(pdf.contains("/FunctionType 3"), "{what}: inks on the curve");
+ assert!(!warnings.iter().any(|w| w.contains("spot")), "{what}: {warnings:?}");
+ }
+ // The curve starts at the first stop's inks: no cyan, Ink at 100 %.
+ run(&mut s, "paint.editGradient", with(ink_to_cyan.clone(), json!({"method": "perceptual"})));
+ let (pdf, _) = pdf_of(&s);
+ assert!(pdf.contains("/C0[0 1]"), "the first stop's inks");
+ // A radial one too.
+ run(&mut s, "paint.editGradient", with(ink_to_cyan, json!({"method": "perceptual", "kind": "radial"})));
+ let (pdf, _) = pdf_of(&s);
+ assert!(!pdf.contains("/Subtype/Image") && pdf.contains("/ShadingType 3") && pdf.contains("/DeviceN[/Cyan/Ink]/DeviceCMYK"), "radial");
+}
+
#[test]
fn spot_gradients_drawn_as_images_warn() {
let (mut s, _) = setup();
let spot_warning = |w: &[String]| w.iter().any(|w| w.contains("spot colors in gradients exported as images"));
- let ink_to_cyan = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": {"c": 1, "m": 0, "y": 0, "k": 0}}]});
+ let ink_to_green = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#00ff00"}]});
// More stops than the export finds tints for: an image, as before.
let n = 4097;
let stops: Vec = (0..n)
@@ -250,7 +278,7 @@ fn spot_gradients_drawn_as_images_warn() {
})
.collect();
for (what, edit) in [
- ("Perceptual Ink → cyan", with(ink_to_cyan, json!({"method": "perceptual"}))),
+ ("Perceptual Ink → RGB green", with(ink_to_green, json!({"method": "perceptual"}))),
("dithered Classic Ink → paper", with(ink_to_white(100.0), json!({"dither": true, "method": "classic"}))),
("dithered Perceptual Ink → paper", with(ink_to_white(100.0), json!({"dither": true, "method": "perceptual"}))),
("Perceptual Ink and paper, 4,097 stops", json!({"stops": stops, "dither": false, "method": "perceptual"})),
diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs
index 32bff5b140..565405d58e 100644
--- a/crates/engine/src/tests/recolor.rs
+++ b/crates/engine/src/tests/recolor.rs
@@ -537,6 +537,58 @@ fn recolor_to_a_library_spot_colour_links_it_and_adds_the_swatch() {
assert_eq!(r["swatches"], json!(["Leaf"]));
}
+/// A row's `tint` gives the art linked to the row's spot color that share of its tint;
+/// randomize without a change keeps it on the row, and a tint that is not a number is refused.
+#[test]
+fn a_rows_tint_tints_the_spot_color_the_art_links_to() {
+ let mut s = session();
+ run(&mut s, "swatch.new", json!({"name": "Ink 101", "color": {"c": 0.0, "m": 1.0, "y": 0.0, "k": 0.0}, "spot": true}));
+ let data = run(&mut s, "swatch.library.save", json!({"names": ["Ink 101"], "name": "Inks"}))["data"].as_str().unwrap().to_string();
+ let lib = run(&mut s, "swatch.library.load", json!({"data": data, "name": "inks.vcswatches"}))["library"].as_str().unwrap().to_string();
+ run(&mut s, "swatch.delete", json!({"names": ["Ink 101"]}));
+ let red = rect(&mut s, json!("#e02010"));
+ select_all(&mut s);
+ let map = json!([{"from": ["rgb 224 32 16"], "to": "cmyk 0 100 0 0", "tint": 40}]);
+ run(&mut s, "recolor.apply", json!({"map": map, "limitTo": lib}));
+ match s.doc().unwrap().doc.node(red).unwrap().appearance.fill_paint() {
+ vectorcraft_color::Paint::Solid { color, swatch, tint } => {
+ assert_eq!(swatch.as_deref(), Some("Ink 101"), "linked to the spot color");
+ assert!((tint - 0.4).abs() < 1e-4, "at the row's tint: {tint}");
+ assert!(close(color, Color::cmyk(0.0, 1.0, 0.0, 0.0).tinted(0.4)), "{color:?}");
+ }
+ p => panic!("{p:?}"),
+ }
+ let r = run(&mut s, "recolor.randomize", json!({"map": map, "order": false, "saturationBrightness": false}));
+ assert_eq!(r["map"][0]["tint"], json!(40.0), "{r}");
+ let e = s.execute("recolor.apply", &json!({"map": [{"from": ["rgb 224 32 16"], "to": "#ff0000", "tint": "40"}]})).unwrap_err();
+ assert!(e.to_string().contains("`tint` must be a number"), "{e}");
+}
+
+/// Randomize order moves a row's tint with its new color; changing saturation and brightness
+/// drops the tint of every color it changes.
+#[test]
+fn randomize_moves_a_tint_with_its_color_and_drops_it_when_the_color_changes() {
+ let mut s = session();
+ let map = json!([
+ {"from": ["rgb 255 0 0"], "to": "cmyk 0 100 0 0", "tint": 40},
+ {"from": ["rgb 0 255 0"], "to": "rgb 0 255 0"},
+ {"from": ["rgb 0 0 255"], "to": "rgb 0 0 255"},
+ ]);
+ let mut moved = false;
+ for seed in 0..20 {
+ let r = run(&mut s, "recolor.randomize", json!({"map": map, "seed": seed}));
+ for row in r["map"].as_array().unwrap() {
+ let spot = row["to"] == json!("cmyk 0 100 0 0");
+ assert_eq!(row.get("tint").cloned(), spot.then(|| json!(40.0)), "seed {seed}: the tint goes with its color: {r}");
+ }
+ moved |= r["map"][0]["to"] != map[0]["to"];
+ }
+ assert!(moved, "some seed moves the tinted color to another row");
+ let sb = run(&mut s, "recolor.randomize", json!({"map": map, "order": false, "saturationBrightness": true}));
+ assert_ne!(sb["map"][0]["to"], map[0]["to"], "{sb}");
+ assert!(sb["map"][0].get("tint").is_none(), "a changed color has no tint: {sb}");
+}
+
#[test]
fn model_param_chooses_the_model_of_the_new_colour() {
// RGB art in a CMYK document: by default a CMYK replacement comes out RGB (#2170).
@@ -572,6 +624,40 @@ fn model_param_must_be_a_string_when_given() {
assert_eq!(fill(&s, art).to_hex(), "#1a1a1a", "nothing changed");
}
+/// A row's own `model` takes the place of the command's for that row's colors; a bad one fails
+/// before editing; `recolor.randomize` moves it with its new color.
+#[test]
+fn a_rows_model_applies_to_its_own_colors() {
+ let mut s = session();
+ let (a, b) = (rect(&mut s, json!("#ff00ff")), rect(&mut s, json!("#00ffff")));
+ select_all(&mut s);
+ let row = |from: &str, to: Value| json!({"from": [from], "to": to});
+ let mut first = row("#ff00ff", json!({"c": 0, "m": 1, "y": 0, "k": 0}));
+ first["model"] = json!("new");
+ let map = json!([first, row("#00ffff", json!({"c": 1, "m": 0, "y": 0, "k": 0}))]);
+ run(&mut s, "recolor.apply", json!({"map": map}));
+ assert_eq!(fill(&s, a), Color::cmyk(0.0, 1.0, 0.0, 0.0), "the row with `new` takes the CMYK color");
+ assert_eq!(fill(&s, b).model(), vectorcraft_color::cms::Model::Rgb, "the other row keeps RGB");
+ run(&mut s, "edit.undo", json!({}));
+ let mut keep = map.clone();
+ keep[0]["model"] = json!("keep");
+ run(&mut s, "recolor.apply", json!({"map": keep, "model": "new"}));
+ assert_eq!(fill(&s, a).model(), vectorcraft_color::cms::Model::Rgb, "the row's `keep` wins over the command's `new`");
+ assert_eq!(fill(&s, b), Color::cmyk(1.0, 0.0, 0.0, 0.0));
+ run(&mut s, "edit.undo", json!({}));
+ for bad in [json!("nope"), json!(42)] {
+ let mut m = map.clone();
+ m[0]["model"] = bad.clone();
+ assert!(s.execute("recolor.apply", &json!({"map": m})).is_err(), "{bad}");
+ }
+ assert_eq!(fill(&s, a).to_hex(), "#ff00ff", "nothing changed");
+ let r = run(&mut s, "recolor.randomize", json!({"map": map, "seed": 1}));
+ let out = r["map"].as_array().unwrap();
+ let moved = out.iter().find(|r| r.get("model").is_some()).expect("the model stays on a row");
+ assert_eq!((&moved["to"], &moved["model"]), (&json!("cmyk 0 100 0 0"), &json!("new")), "{r}");
+ assert_eq!(out.iter().filter(|r| r.get("model").is_some()).count(), 1, "{r}");
+}
+
/// Recolor Artwork's commands refuse a parameter of the wrong form, such as `limitTo: 5` or
/// `includeImages: "false"`, with an error that names it; the art keeps its color and no undo
/// step is recorded. A null counts as a value left out.
diff --git a/crates/engine/src/tests/symboledit.rs b/crates/engine/src/tests/symboledit.rs
new file mode 100644
index 0000000000..491d6cd830
--- /dev/null
+++ b/crates/engine/src/tests/symboledit.rs
@@ -0,0 +1,491 @@
+//! Symbol editing mode (`symbol.edit`, `symbol.exitEditing`).
+
+use serde_json::{Value, json};
+use vectorcraft_doc::NodeKind;
+use vectorcraft_geom::Rect;
+
+use crate::*;
+
+fn run(s: &mut Session, cmd: &str, p: Value) -> Value {
+ s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
+}
+
+fn id(v: &Value) -> NodeId {
+ NodeId(v["id"].as_u64().expect("an id"))
+}
+
+/// A 400 × 300 document with the 80 × 40 symbol "Box" made from a rectangle at (100, 50), its
+/// instance there and a second instance centered on (300, 200).
+fn two_instances() -> (Session, NodeId, NodeId) {
+ let mut s = Session::new();
+ run(&mut s, "file.new", json!({"width": 400, "height": 300}));
+ run(&mut s, "shape.rectangle", json!({"x": 100, "y": 50, "width": 80, "height": 40}));
+ let first = id(&run(&mut s, "symbol.new", json!({"name": "Box"})));
+ let second = id(&run(&mut s, "symbol.place", json!({"name": "Box", "x": 300, "y": 200})));
+ (s, first, second)
+}
+
+/// The bounds of `id` as the document measures them: an instance's by its symbol's art.
+fn bounds(s: &Session, id: NodeId) -> Rect {
+ s.doc().unwrap().doc.bounds_of(&[id], false).expect("bounds")
+}
+
+fn close(a: Rect, b: Rect) -> bool {
+ [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() < 1e-6)
+}
+
+fn is_instance(s: &Session, id: NodeId) -> bool {
+ s.doc().unwrap().doc.node(id).is_some_and(|n| matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Box"))
+}
+
+/// The objects on the editing layer.
+fn layer_art(s: &Session) -> Vec {
+ let st = s.doc().unwrap();
+ let layer = st.doc.symbol_edit.as_ref().expect("editing a symbol").layer;
+ st.doc.node(layer).and_then(|l| l.children()).map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default()
+}
+
+#[test]
+fn edit_symbol_edits_the_art_where_the_instance_shows_it_and_every_instance_follows() {
+ let (mut s, first, second) = two_instances();
+ run(&mut s, "select.set", json!({"ids": [first.0]}));
+ let r = run(&mut s, "symbol.edit", json!({}));
+ assert_eq!((r["name"].as_str(), r["id"].as_u64()), (Some("Box"), Some(first.0)));
+ let layer = NodeId(r["layer"].as_u64().unwrap());
+ let st = s.doc().unwrap();
+ assert_eq!(st.isolation, Some(layer));
+ assert_eq!(st.active_layer, Some(layer));
+ // The instance stays linked: editing the symbol doesn't expand it.
+ assert!(is_instance(&s, first) && is_instance(&s, second));
+ let art = layer_art(&s);
+ assert_eq!(art.len(), 1);
+ assert!(close(bounds(&s, art[0]), Rect::new(100.0, 50.0, 180.0, 90.0)), "{:?}", bounds(&s, art[0]));
+ assert_eq!(s.doc().unwrap().selection.objects, art);
+ // An edit of the art reaches both instances at once, each at its own place.
+ run(&mut s, "object.move", json!({"dx": 10, "dy": 0}));
+ assert!(close(bounds(&s, first), Rect::new(110.0, 50.0, 190.0, 90.0)), "{:?}", bounds(&s, first));
+ assert!(close(bounds(&s, second), Rect::new(270.0, 180.0, 350.0, 220.0)), "{:?}", bounds(&s, second));
+ // New art goes into the symbol.
+ run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 10, "height": 10}));
+ assert_eq!(layer_art(&s).len(), 2);
+ assert!(close(bounds(&s, second), Rect::new(260.0, 180.0, 350.0, 240.0)), "{:?}", bounds(&s, second));
+ let r = run(&mut s, "symbol.exitEditing", json!({}));
+ assert_eq!(r["name"], "Box");
+ let st = s.doc().unwrap();
+ assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none());
+ assert!(st.doc.node(layer).is_none(), "the editing layer is gone");
+ assert_eq!(st.selection.objects, vec![first]);
+ assert!(is_instance(&s, first));
+ assert!(close(bounds(&s, second), Rect::new(260.0, 180.0, 350.0, 240.0)), "{:?}", bounds(&s, second));
+}
+
+#[test]
+fn an_instance_transform_places_the_art_and_edits_go_back_through_it() {
+ let (mut s, first, second) = two_instances();
+ // The second instance twice as large: a 20 pt move there is a 10 pt move of the symbol's art.
+ run(&mut s, "select.set", json!({"ids": [second.0]}));
+ run(&mut s, "object.scale", json!({"sx": 200, "sy": 200, "origin": [300, 200]}));
+ let big = bounds(&s, second);
+ assert!(close(big, Rect::new(220.0, 160.0, 380.0, 240.0)), "{big:?}");
+ run(&mut s, "symbol.edit", json!({"id": second.0}));
+ let art = layer_art(&s);
+ assert!(close(bounds(&s, art[0]), big), "{:?}", bounds(&s, art[0]));
+ run(&mut s, "object.move", json!({"dx": 20, "dy": 0}));
+ assert!(close(bounds(&s, second), Rect::new(240.0, 160.0, 400.0, 240.0)), "{:?}", bounds(&s, second));
+ assert!(close(bounds(&s, first), Rect::new(110.0, 50.0, 190.0, 90.0)), "{:?}", bounds(&s, first));
+}
+
+#[test]
+fn the_symbols_panel_edits_a_symbol_without_an_instance_at_the_artboard_center() {
+ let (mut s, first, second) = two_instances();
+ run(&mut s, "edit.clear", json!({"ids": [first.0, second.0]}));
+ run(&mut s, "select.none", json!({}));
+ let r = run(&mut s, "symbol.edit", json!({"name": "Box"}));
+ assert!(r.get("id").is_none());
+ let art = layer_art(&s);
+ assert!(close(bounds(&s, art[0]), Rect::new(160.0, 130.0, 240.0, 170.0)), "{:?}", bounds(&s, art[0]));
+ run(&mut s, "object.move", json!({"dx": 0, "dy": 5}));
+ run(&mut s, "symbol.exitEditing", json!({}));
+ // No instance was added, and a new one shows the edited art.
+ let mut instances = 0;
+ s.doc().unwrap().doc.walk(|n| instances += usize::from(matches!(n.kind, NodeKind::SymbolInstance { .. })));
+ assert_eq!(instances, 0);
+ let placed = id(&run(&mut s, "symbol.place", json!({"name": "Box", "x": 200, "y": 150})));
+ assert!(close(bounds(&s, placed), Rect::new(160.0, 135.0, 240.0, 175.0)), "{:?}", bounds(&s, placed));
+ assert!(s.execute("symbol.edit", &json!({"name": "Nope"})).is_err());
+}
+
+#[test]
+fn the_symbols_panel_edits_a_symbol_at_the_center_of_the_active_artboard_or_the_view() {
+ let (mut s, _, _) = two_instances();
+ run(&mut s, "artboard.new", json!({"x": 500, "y": 0, "width": 200, "height": 100}));
+ run(&mut s, "select.none", json!({}));
+ run(&mut s, "symbol.edit", json!({"name": "Box", "artboard": 1}));
+ let art = layer_art(&s);
+ assert!(close(bounds(&s, art[0]), Rect::new(560.0, 30.0, 640.0, 70.0)), "{:?}", bounds(&s, art[0]));
+ run(&mut s, "symbol.exitEditing", json!({}));
+ // An artboard the document doesn't have: the first one.
+ run(&mut s, "symbol.edit", json!({"name": "Box", "artboard": 7, "viewCenter": [1000, 1000]}));
+ let art = layer_art(&s);
+ assert!(close(bounds(&s, art[0]), Rect::new(160.0, 130.0, 240.0, 170.0)), "{:?}", bounds(&s, art[0]));
+ run(&mut s, "symbol.exitEditing", json!({}));
+ // Without artboards, the view's center.
+ std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.clear();
+ run(&mut s, "symbol.edit", json!({"name": "Box", "viewCenter": [1000, 1000]}));
+ let art = layer_art(&s);
+ assert!(close(bounds(&s, art[0]), Rect::new(960.0, 980.0, 1040.0, 1020.0)), "{:?}", bounds(&s, art[0]));
+}
+
+#[test]
+fn leaving_without_an_edit_leaves_the_document_and_its_history_as_they_were() {
+ let (mut s, first, _) = two_instances();
+ let steps = s.doc().unwrap().history.undo.len();
+ let art = s.doc().unwrap().doc.symbols[0].art.clone();
+ run(&mut s, "symbol.edit", json!({"id": first.0}));
+ assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
+ run(&mut s, "object.exitIsolation", json!({}));
+ let st = s.doc().unwrap();
+ assert_eq!(st.history.undo.len(), steps);
+ assert!(std::sync::Arc::ptr_eq(&st.doc.symbols[0].art, &art));
+ assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none());
+ // Outside the mode, leaving it does nothing.
+ run(&mut s, "symbol.exitEditing", json!({}));
+ assert_eq!(s.doc().unwrap().history.undo.len(), steps);
+ // A step undone before editing can still be redone after leaving without an edit.
+ run(&mut s, "shape.rectangle", json!({"x": 300, "y": 20, "width": 10, "height": 10}));
+ run(&mut s, "edit.undo", json!({}));
+ run(&mut s, "symbol.edit", json!({"id": first.0}));
+ assert!(s.doc().unwrap().history.redo.is_empty());
+ run(&mut s, "symbol.exitEditing", json!({}));
+ assert_eq!(s.doc().unwrap().history.redo.len(), 1);
+ run(&mut s, "edit.redo", json!({}));
+ // Leaving after an edit that was undone adds a step, keeping the redo step that holds the
+ // editing layer apart from the document outside the mode.
+ run(&mut s, "symbol.edit", json!({"id": first.0}));
+ run(&mut s, "object.move", json!({"dx": 10, "dy": 0}));
+ run(&mut s, "edit.undo", json!({}));
+ let steps = s.doc().unwrap().history.undo.len();
+ run(&mut s, "symbol.exitEditing", json!({}));
+ let st = s.doc().unwrap();
+ assert_eq!(st.history.undo.len(), steps + 1);
+ assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none());
+}
+
+#[test]
+fn leaving_without_an_edit_keeps_the_current_symbol_picked_while_editing() {
+ let (mut s, first, _) = two_instances();
+ run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}));
+ run(&mut s, "symbol.new", json!({"name": "Small"}));
+ run(&mut s, "symbol.setCurrent", json!({"name": "Box"}));
+ let steps = s.doc().unwrap().history.undo.len();
+ run(&mut s, "symbol.edit", json!({"id": first.0}));
+ // A click in the Symbols panel while editing: not an undo step.
+ run(&mut s, "symbol.setCurrent", json!({"name": "Small"}));
+ run(&mut s, "symbol.exitEditing", json!({}));
+ let st = s.doc().unwrap();
+ assert_eq!(st.history.undo.len(), steps);
+ assert_eq!(st.doc.unknown.get("currentSymbol").and_then(Value::as_str), Some("Small"));
+}
+
+#[test]
+fn leaving_right_after_a_batch_that_only_entered_takes_its_step_back() {
+ let (mut s, first, _) = two_instances();
+ let steps = s.doc().unwrap().history.undo.len();
+ run(&mut s, "command.batch", json!({"commands": [{"command": "symbol.edit", "params": {"id": first.0}}]}));
+ assert!(s.doc().unwrap().doc.symbol_edit.is_some());
+ assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
+ run(&mut s, "symbol.exitEditing", json!({}));
+ let st = s.doc().unwrap();
+ assert_eq!(st.history.undo.len(), steps);
+ assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none());
+}
+
+#[test]
+fn leaving_right_after_a_batch_that_edited_and_entered_keeps_its_edits() {
+ let (mut s, first, second) = two_instances();
+ let steps = s.doc().unwrap().history.undo.len();
+ // A batch named like the entering step that moves an instance before entering: leaving keeps
+ // the move and adds a step of its own.
+ let moved = Rect::new(310.0, 180.0, 390.0, 220.0);
+ let commands = json!([
+ {"command": "select.set", "params": {"ids": [second.0]}},
+ {"command": "object.move", "params": {"dx": 50, "dy": 0}},
+ {"command": "symbol.edit", "params": {"id": first.0}},
+ ]);
+ run(&mut s, "command.batch", json!({"label": "Edit Symbol", "commands": commands}));
+ assert!(close(bounds(&s, second), moved), "{:?}", bounds(&s, second));
+ run(&mut s, "symbol.exitEditing", json!({}));
+ let st = s.doc().unwrap();
+ assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none());
+ assert_eq!(st.history.undo.len(), steps + 2);
+ assert!(close(bounds(&s, second), moved), "{:?}", bounds(&s, second));
+ // Undo takes back the exit, then the batch's move and entry together.
+ run(&mut s, "edit.undo", json!({}));
+ assert!(s.doc().unwrap().doc.symbol_edit.is_some());
+ run(&mut s, "edit.undo", json!({}));
+ let st = s.doc().unwrap();
+ assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none());
+ assert!(close(bounds(&s, second), Rect::new(260.0, 180.0, 340.0, 220.0)), "{:?}", bounds(&s, second));
+}
+
+#[test]
+fn redefining_the_symbol_being_edited_leaves_symbol_editing_mode_in_the_same_step() {
+ let (mut s, first, second) = two_instances();
+ let other = id(&run(&mut s, "shape.rectangle", json!({"x": 10, "y": 200, "width": 30, "height": 30})));
+ let layer = NodeId(run(&mut s, "symbol.edit", json!({"id": first.0}))["layer"].as_u64().unwrap());
+ // The art on the editing layer can't redefine the symbol.
+ let e = s.execute("symbol.update", &json!({"name": "Box"})).unwrap_err().to_string();
+ assert!(e.contains("can't hold an instance of itself"), "{e}");
+ let steps = s.doc().unwrap().history.undo.len();
+ run(&mut s, "symbol.update", json!({"name": "Box", "ids": [other.0]}));
+ let st = s.doc().unwrap();
+ assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none() && st.doc.node(layer).is_none());
+ assert_eq!(st.history.undo.len(), steps + 1);
+ // Every instance shows the new 30 × 30 art, and a later edit can't bring the old art back.
+ assert!(close(bounds(&s, second), Rect::new(285.0, 185.0, 315.0, 215.0)), "{:?}", bounds(&s, second));
+ run(&mut s, "shape.rectangle", json!({"x": 300, "y": 10, "width": 10, "height": 10}));
+ assert!(close(bounds(&s, second), Rect::new(285.0, 185.0, 315.0, 215.0)), "{:?}", bounds(&s, second));
+ // Undo goes back into the edit as it was.
+ run(&mut s, "edit.undo", json!({}));
+ run(&mut s, "edit.undo", json!({}));
+ let st = s.doc().unwrap();
+ assert_eq!(st.isolation, Some(layer));
+ assert!(st.doc.symbol_edit.is_some());
+}
+
+#[test]
+fn leaving_goes_back_to_the_isolation_before_and_undo_keeps_a_group_isolated_inside() {
+ let (mut s, first, _) = two_instances();
+ // The instance in an isolated group.
+ let other = id(&run(&mut s, "shape.rectangle", json!({"x": 10, "y": 200, "width": 20, "height": 20})));
+ run(&mut s, "select.set", json!({"ids": [first.0, other.0]}));
+ let group = id(&run(&mut s, "object.group", json!({})));
+ run(&mut s, "object.isolate", json!({"id": group.0}));
+ run(&mut s, "symbol.edit", json!({"id": first.0}));
+ run(&mut s, "symbol.exitEditing", json!({}));
+ assert_eq!(s.doc().unwrap().isolation, Some(group));
+ // A group isolated inside the symbol's art stays isolated through an undo.
+ let layer = NodeId(run(&mut s, "symbol.edit", json!({"id": first.0}))["layer"].as_u64().unwrap());
+ run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 10, "height": 10}));
+ let art: Vec = layer_art(&s).iter().map(|i| i.0).collect();
+ run(&mut s, "select.set", json!({ "ids": art }));
+ let inner = id(&run(&mut s, "object.group", json!({})));
+ run(&mut s, "object.isolate", json!({"id": inner.0}));
+ run(&mut s, "select.all", json!({}));
+ run(&mut s, "object.move", json!({"dx": 5, "dy": 0}));
+ run(&mut s, "edit.undo", json!({}));
+ assert_eq!(s.doc().unwrap().isolation, Some(inner));
+ run(&mut s, "object.exitIsolation", json!({}));
+ assert_eq!(s.doc().unwrap().isolation, Some(layer));
+ run(&mut s, "object.exitIsolation", json!({}));
+ assert_eq!(s.doc().unwrap().isolation, Some(group));
+ // Deleting the editing layer goes back there too.
+ let layer = NodeId(run(&mut s, "symbol.edit", json!({"id": first.0}))["layer"].as_u64().unwrap());
+ run(&mut s, "layer.delete", json!({"ids": [layer.0]}));
+ assert_eq!(s.doc().unwrap().isolation, Some(group));
+}
+
+#[test]
+fn leaving_after_a_save_keeps_the_document_saved() {
+ let (mut s, first, _) = two_instances();
+ for edit in [false, true] {
+ run(&mut s, "symbol.edit", json!({"id": first.0}));
+ if edit {
+ run(&mut s, "object.move", json!({"dx": 10, "dy": 0}));
+ }
+ // The save leaves the editing layer out of the file.
+ s.doc_mut().unwrap().mark_saved();
+ run(&mut s, "symbol.exitEditing", json!({}));
+ let st = s.doc().unwrap();
+ assert!(!st.is_dirty(), "edit: {edit}");
+ assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none(), "edit: {edit}");
+ }
+}
+
+#[test]
+fn deleting_the_editing_layer_leaves_symbol_editing_mode() {
+ let (mut s, first, _) = two_instances();
+ let layer = NodeId(run(&mut s, "symbol.edit", json!({"id": first.0}))["layer"].as_u64().unwrap());
+ run(&mut s, "layer.delete", json!({"ids": [layer.0]}));
+ let st = s.doc().unwrap();
+ assert!(st.doc.symbol_edit.is_none() && st.doc.node(layer).is_none());
+ assert_eq!(st.isolation, None);
+ assert!(st.active_layer.is_some_and(|l| st.doc.node(l).is_some()));
+ assert!(is_instance(&s, first));
+}
+
+#[test]
+fn undo_and_redo_restore_the_art_every_instance_shows_and_the_mode() {
+ let (mut s, first, second) = two_instances();
+ run(&mut s, "symbol.edit", json!({"id": first.0}));
+ let layer = s.doc().unwrap().doc.symbol_edit.as_ref().unwrap().layer;
+ run(&mut s, "object.move", json!({"dx": 10, "dy": 0}));
+ run(&mut s, "symbol.exitEditing", json!({}));
+ run(&mut s, "edit.undo", json!({}));
+ assert_eq!(s.doc().unwrap().isolation, Some(layer), "back in symbol editing mode");
+ run(&mut s, "edit.undo", json!({}));
+ assert!(close(bounds(&s, second), Rect::new(260.0, 180.0, 340.0, 220.0)), "{:?}", bounds(&s, second));
+ assert_eq!(s.doc().unwrap().isolation, Some(layer));
+ run(&mut s, "edit.undo", json!({}));
+ let st = s.doc().unwrap();
+ assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none());
+ run(&mut s, "edit.redo", json!({}));
+ run(&mut s, "edit.redo", json!({}));
+ assert!(close(bounds(&s, second), Rect::new(270.0, 180.0, 350.0, 220.0)), "{:?}", bounds(&s, second));
+ assert_eq!(s.doc().unwrap().isolation, Some(layer));
+}
+
+#[test]
+fn instances_of_one_symbol_only_and_no_instance_of_itself() {
+ let (mut s, first, _) = two_instances();
+ run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}));
+ let other = id(&run(&mut s, "symbol.new", json!({"name": "Small"})));
+ run(&mut s, "select.set", json!({"ids": [first.0, other.0]}));
+ let e = s.execute("symbol.edit", &json!({})).unwrap_err().to_string();
+ assert!(e.contains("select instances of one symbol"), "{e}");
+ let e = s.execute("symbol.edit", &json!({"ids": [first.0, other.0]})).unwrap_err().to_string();
+ assert!(e.contains("select instances of one symbol"), "{e}");
+ assert!(s.execute("symbol.edit", &json!({"ids": [first.0, 999_999]})).is_err());
+ assert!(s.doc().unwrap().doc.symbol_edit.is_none());
+ run(&mut s, "symbol.edit", json!({"id": first.0}));
+ let e = s.execute("symbol.place", &json!({"name": "Box"})).unwrap_err().to_string();
+ assert!(e.contains("can't hold an instance of itself"), "{e}");
+ assert_eq!(layer_art(&s).len(), 1);
+ // An instance of another symbol may go in.
+ run(&mut s, "symbol.place", json!({"name": "Small"}));
+ assert_eq!(layer_art(&s).len(), 2);
+}
+
+#[test]
+fn other_editing_modes_and_symbol_editing_do_not_overlap() {
+ let (mut s, first, second) = two_instances();
+ run(&mut s, "symbol.edit", json!({"id": first.0}));
+ assert!(s.execute("object.pattern.make", &json!({})).is_err());
+ assert!(s.execute("transparency.editOpacityMask", &json!({})).is_err());
+ // Editing another symbol from the panel ends this edit first.
+ run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}));
+ run(&mut s, "symbol.exitEditing", json!({}));
+ run(&mut s, "select.set", json!({"ids": [second.0]}));
+ run(&mut s, "symbol.edit", json!({}));
+ run(&mut s, "symbol.edit", json!({"name": "Box", "x": 50, "y": 50}));
+ assert_eq!(s.doc().unwrap().doc.symbol_edit.as_ref().unwrap().instance, None);
+ assert_eq!(s.doc().unwrap().doc.layers.iter().filter(|l| l.name.as_deref() == Some("Box")).count(), 1);
+}
+
+#[test]
+fn renaming_deleting_and_saving_while_a_symbol_is_edited() {
+ let (mut s, first, _) = two_instances();
+ run(&mut s, "symbol.edit", json!({"id": first.0}));
+ run(&mut s, "object.move", json!({"dx": 10, "dy": 0}));
+ let layer = s.doc().unwrap().doc.symbol_edit.as_ref().unwrap().layer;
+ // Saving leaves the editing layer out; the symbol already holds the edit.
+ let saved = s.doc().unwrap().doc.without_edit_modes().into_owned();
+ assert!(saved.symbol_edit.is_none() && saved.node(layer).is_none());
+ assert!(saved.symbols[0].art.geometric_bounds().is_some());
+ run(&mut s, "symbol.options", json!({"name": "Box", "newName": "Crate"}));
+ let st = s.doc().unwrap();
+ assert_eq!(st.doc.symbol_edit.as_ref().unwrap().symbol, "Crate");
+ assert_eq!(st.doc.node(layer).and_then(|l| l.name.clone()).as_deref(), Some("Crate"));
+ run(&mut s, "object.move", json!({"dx": 10, "dy": 0}));
+ // Deleting the symbol being edited leaves the mode in the same step.
+ run(&mut s, "symbol.delete", json!({"name": "Crate"}));
+ let st = s.doc().unwrap();
+ assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none() && st.doc.node(layer).is_none());
+ assert!(st.doc.symbols.is_empty());
+ run(&mut s, "edit.undo", json!({}));
+ assert_eq!(s.doc().unwrap().isolation, Some(layer));
+}
+
+/// Deleting several symbols, the one being edited among them, leaves the mode in the same step.
+#[test]
+fn deleting_several_symbols_with_the_edited_one_leaves_the_mode() {
+ let (mut s, first, _) = two_instances();
+ run(&mut s, "shape.rectangle", json!({"x": 10, "y": 200, "width": 20, "height": 20}));
+ run(&mut s, "symbol.new", json!({"name": "Dot"}));
+ run(&mut s, "symbol.edit", json!({"id": first.0}));
+ let layer = s.doc().unwrap().doc.symbol_edit.as_ref().unwrap().layer;
+ run(&mut s, "symbol.delete", json!({"names": ["Dot", "Box"]}));
+ let st = s.doc().unwrap();
+ assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none() && st.doc.node(layer).is_none());
+ assert!(st.doc.symbols.is_empty());
+}
+
+/// Editing a dynamic symbol keeps each instance's appearance changes to the objects its art still
+/// has, and drops the changes to an object the edit deleted.
+#[test]
+fn editing_a_dynamic_symbol_keeps_the_instances_changes_to_the_objects_still_there() {
+ let mut s = Session::new();
+ run(&mut s, "file.new", json!({"width": 400, "height": 300}));
+ let a = id(&run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})));
+ let b = id(&run(&mut s, "shape.rectangle", json!({"x": 60, "y": 10, "width": 40, "height": 40})));
+ let inst = id(&run(&mut s, "symbol.new", json!({"name": "Pair", "ids": [a.0, b.0], "type": "dynamic"})));
+ run(&mut s, "symbol.instance.setAppearance", json!({"id": inst.0, "path": [0], "fill": "#00ff00"}));
+ run(&mut s, "symbol.instance.setAppearance", json!({"id": inst.0, "path": [1], "fill": "#ff0000"}));
+ // Each change by the path it names and the color it paints.
+ let changes = |s: &Session| -> Vec<(Vec, String)> {
+ let n = s.doc().unwrap().doc.node(inst).unwrap().clone();
+ n.extras().symbol_overrides.iter().map(|o| (o.path.clone(), o.fill.as_ref().and_then(|p| p.color()).unwrap().to_hex())).collect()
+ };
+ let other = id(&run(&mut s, "symbol.place", json!({"name": "Pair", "x": 200, "y": 200})));
+ run(&mut s, "symbol.edit", json!({"id": other.0}));
+ let art = layer_art(&s);
+ assert_eq!(art.len(), 2);
+ // Deleting the first object: the change to the second follows it to the first place.
+ run(&mut s, "select.set", json!({"ids": [art[0].0]}));
+ run(&mut s, "edit.clear", json!({}));
+ assert_eq!(changes(&s), vec![(vec![0], "#ff0000".to_string())], "the change to the deleted object goes");
+ run(&mut s, "symbol.exitEditing", json!({}));
+ assert_eq!(changes(&s), vec![(vec![0], "#ff0000".to_string())]);
+ assert!(s.doc().unwrap().doc.node(inst).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })));
+}
+
+#[test]
+fn undo_back_into_an_earlier_edit_leaves_it_to_its_own_isolation() {
+ let (mut s, first, second) = two_instances();
+ let other = id(&run(&mut s, "shape.rectangle", json!({"x": 10, "y": 200, "width": 20, "height": 20})));
+ run(&mut s, "select.set", json!({"ids": [second.0, other.0]}));
+ let group = id(&run(&mut s, "object.group", json!({})));
+ // The first edit is entered with nothing isolated.
+ run(&mut s, "symbol.edit", json!({"id": first.0}));
+ run(&mut s, "object.move", json!({"dx": 10, "dy": 0}));
+ run(&mut s, "symbol.exitEditing", json!({}));
+ assert_eq!(s.doc().unwrap().isolation, None);
+ // The second edit is entered with the group isolated.
+ run(&mut s, "object.isolate", json!({"id": group.0}));
+ run(&mut s, "symbol.edit", json!({"id": second.0}));
+ run(&mut s, "edit.undo", json!({}));
+ assert_eq!(s.doc().unwrap().isolation, Some(group));
+ // Back in the first edit, leaving it goes back to what it was entered from.
+ run(&mut s, "edit.undo", json!({}));
+ assert!(s.doc().unwrap().doc.symbol_edit.is_some());
+ run(&mut s, "symbol.exitEditing", json!({}));
+ assert_eq!(s.doc().unwrap().isolation, None);
+}
+
+#[test]
+fn undoing_entry_with_a_group_isolated_inside_the_art_goes_back_to_before() {
+ let mut s = Session::new();
+ run(&mut s, "file.new", json!({"width": 400, "height": 300}));
+ let a = id(&run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})));
+ let b = id(&run(&mut s, "shape.rectangle", json!({"x": 40, "y": 10, "width": 20, "height": 20})));
+ run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
+ let inner = id(&run(&mut s, "object.group", json!({})));
+ let c = id(&run(&mut s, "shape.rectangle", json!({"x": 10, "y": 40, "width": 20, "height": 20})));
+ run(&mut s, "select.set", json!({"ids": [inner.0, c.0]}));
+ let instance = id(&run(&mut s, "symbol.new", json!({"name": "Pair"})));
+ let before = s.doc().unwrap().active_layer;
+ assert!(before.is_some());
+ run(&mut s, "symbol.edit", json!({"id": instance.0}));
+ let layer = s.doc().unwrap().doc.symbol_edit.as_ref().unwrap().layer;
+ let group = {
+ let st = s.doc().unwrap();
+ layer_art(&s).into_iter().find(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. }))).expect("a group")
+ };
+ run(&mut s, "object.isolate", json!({"id": group.0}));
+ assert_eq!(s.doc().unwrap().isolation, Some(group));
+ run(&mut s, "edit.undo", json!({}));
+ let st = s.doc().unwrap();
+ assert!(st.doc.symbol_edit.is_none() && st.doc.node(layer).is_none());
+ assert_eq!(st.isolation, None);
+ assert_eq!(st.active_layer, before);
+}
diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs
index 025cf6d30a..ed47cb1d57 100644
--- a/crates/engine/src/tests/textedit.rs
+++ b/crates/engine/src/tests/textedit.rs
@@ -325,6 +325,16 @@ fn type_commands_refuse_a_number_or_boolean_given_as_text() {
("text.setRangeStyle", json!({"id": id.0, "allCaps": 1}), "allCaps"),
("text.setRangeStyle", json!({"id": id.0, "noBreak": "true"}), "noBreak"),
("text.setRangeStyle", json!({"id": id.0, "size": 30, "tateChuYoko": 1}), "tateChuYoko"),
+ ("text.setFormat", json!({"ids": [id.0], "underline": "true"}), "underline"),
+ ("text.setFormat", json!({"ids": [id.0], "strikethrough": 1}), "strikethrough"),
+ ("text.setFormat", json!({"ids": [id.0], "allCaps": "false"}), "allCaps"),
+ ("text.setFormat", json!({"ids": [id.0], "proportionalMetrics": 1}), "proportionalMetrics"),
+ ("text.setFormat", json!({"ids": [id.0], "tateChuYoko": "true"}), "tateChuYoko"),
+ ("text.setFormat", json!({"ids": [id.0], "standardVerticalRoman": "true"}), "standardVerticalRoman"),
+ ("text.setFormat", json!({"ids": [id.0], "rotation": 10, "noBreak": 1}), "noBreak"),
+ ("text.setFormat", json!({"ids": [id.0], "hyphenate": "false"}), "hyphenate"),
+ ("text.setFormat", json!({"ids": [id.0], "hyphenateCapitalized": 0}), "hyphenateCapitalized"),
+ ("text.setFormat", json!({"ids": [id.0], "romanHangingPunctuation": "true"}), "romanHangingPunctuation"),
("text.getRange", json!({"id": id.0, "effective": "true"}), "effective"),
("type.opticalMarginAlignment", json!({"on": "true"}), "on"),
("type.systemLayout", json!({"on": "true"}), "on"),
@@ -338,12 +348,13 @@ fn type_commands_refuse_a_number_or_boolean_given_as_text() {
assert!(wrong.is_empty(), "not refused: {wrong:#?}");
let style = json!({"id": id.0, "size": 30, "underline": true, "tracking": null, "start": null, "noBreak": true});
s.execute("text.setRangeStyle", &style).unwrap();
+ s.execute("text.setFormat", &json!({"ids": [id.0], "strikethrough": true, "hyphenate": null})).unwrap();
s.execute("type.size.increase", &json!({"by": null})).unwrap();
s.execute("type.opticalMarginAlignment", &json!({"on": true})).unwrap();
s.execute("type.ruby", &json!({"text": "a", "size": null, "overhang": false})).unwrap();
let t = obj(&s, id);
let st = &t.runs[0].style;
- assert!(st.underline && st.no_break && t.optical_margin && st.size > 30.0, "{st:?}");
+ assert!(st.underline && st.strikethrough && st.no_break && t.optical_margin && st.size > 30.0, "{st:?}");
assert!(!t.ruby.is_empty() && t.ruby.iter().all(|r| !r.overhang && r.size_percent == 50.0), "{:?}", t.ruby);
}
@@ -507,7 +518,7 @@ fn touch_type_moves_one_character_in_centered_and_right_aligned_lines() {
}
}
-/// `dy` moves a rotated character that many document points along its own up axis, also in type
+/// `dy` moves a rotated character that many document points up from its line, also in type
/// scaled unevenly.
#[test]
fn touch_type_raises_a_rotated_character_in_unevenly_scaled_type() {
@@ -518,9 +529,66 @@ fn touch_type_raises_a_rotated_character_in_unevenly_scaled_type() {
let before = glyph_pens(&s, id);
s.execute("text.touchType", &json!({"id": id.0, "start": 1, "dy": 10})).unwrap();
let (x, y) = moved_by(&before, &glyph_pens(&s, id), 1);
- assert!(((x * x + y * y).sqrt() - 10.0).abs() < 1e-6, "({x}, {y})");
+ assert!(near((x, y), (0.0, -10.0)), "({x}, {y})");
}
+/// A character rotated near or at a quarter turn moves across its line and along it: in "ABCD"
+/// with the B at 85, 90 and 95 degrees, `dx` 10 and `dy` 4 move the B 10 pt right and 4 pt up and
+/// leave the C and D where they are, through baseline shift and kerning only, with Auto and
+/// Optical kerning and in type scaled unevenly. Undo, redo and the native format keep the place.
+#[test]
+fn touch_type_moves_a_character_turned_near_a_quarter_turn_across_its_line() {
+ for rotation in [85.0, 90.0, 95.0, -90.0] {
+ for (kerning, scaled) in [("auto", false), ("optical", false), ("auto", true)] {
+ let case = format!("{rotation}°, {kerning}, scaled {scaled}");
+ let mut s = session();
+ let id = NodeId(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "ABCD", "size": 40})).unwrap()["id"].as_u64().unwrap());
+ s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": kerning})).unwrap();
+ if scaled {
+ s.execute("object.transform", &json!({"ids": [id.0], "matrix": [2, 0, 0, 0.5, 0, 0]})).unwrap();
+ }
+ s.execute("text.touchType", &json!({"id": id.0, "start": 1, "rotation": rotation})).unwrap();
+ let before = glyph_pens(&s, id);
+ let runs_before = obj(&s, id).runs;
+ s.execute("text.touchType", &json!({"id": id.0, "start": 1, "dx": 10, "dy": 4})).unwrap();
+ let after = glyph_pens(&s, id);
+ assert!(near(moved_by(&before, &after, 1), (10.0, -4.0)), "{case}: {:?}", moved_by(&before, &after, 1));
+ for byte in [0, 2, 3] {
+ assert!(near(moved_by(&before, &after, byte), (0.0, 0.0)), "{case}, byte {byte}: {:?}", moved_by(&before, &after, byte));
+ }
+ // Only kerning and baseline shift change.
+ let t = obj(&s, id);
+ let style = |byte: usize| vectorcraft_text::edit::slice_runs(&t.runs, byte, byte + 1)[0].style.clone();
+ let plain = |mut st: CharStyle| {
+ st.kerning = None;
+ st.baseline_shift = 0.0;
+ st
+ };
+ for byte in 0..4 {
+ let was = vectorcraft_text::edit::slice_runs(&runs_before, byte, byte + 1)[0].style.clone();
+ assert_eq!(plain(style(byte)), plain(was), "{case}, byte {byte}");
+ }
+ let shift = style(1).baseline_shift;
+ assert!(shift > 0.0, "{case}: {shift}");
+ // A drag straight across the line is baseline shift alone.
+ let before = glyph_pens(&s, id);
+ s.execute("text.touchType", &json!({"id": id.0, "start": 1, "dy": -6})).unwrap();
+ assert!(near(moved_by(&before, &glyph_pens(&s, id), 1), (0.0, 6.0)), "{case}: {:?}", moved_by(&before, &glyph_pens(&s, id), 1));
+ s.execute("edit.undo", &json!({})).unwrap();
+ let moved = glyph_pens(&s, id);
+ assert!(near(moved_by(&after, &moved, 1), (0.0, 0.0)), "{case}: undone");
+ s.execute("edit.redo", &json!({})).unwrap();
+ s.execute("edit.undo", &json!({})).unwrap();
+ // The native format keeps both attributes and the place they give.
+ let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
+ let NodeKind::Text(reopened) = &back.node(id).unwrap().kind else { panic!("not text") };
+ assert_eq!(reopened.runs, obj(&s, id).runs, "{case}");
+ let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), reopened);
+ let pens: Vec<(usize, Point)> = lay.glyphs.iter().map(|g| (g.byte, reopened.xf * (g.xf * Point::ZERO))).collect();
+ assert!(near(moved_by(&moved, &pens, 1), (0.0, 0.0)), "{case}: reopened");
+ }
+ }
+}
/// `dy` moves a character that many document points in type scaled up 2000 times, where baseline
/// shift is limited to 0.648 pt of text space.
#[test]
diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs
index bdacd0e1bf..e1bfd3e2f2 100644
--- a/crates/engine/src/tests/variables.rs
+++ b/crates/engine/src/tests/variables.rs
@@ -114,6 +114,113 @@ fn applying_a_dataset_reports_the_area_type_it_overflows() {
assert_eq!((&v["name"], &v["overflow"]), (&json!("Long"), &json!([a.0])), "{v}");
}
+/// Area type threaded into a rectangle → (session, first frame, second frame, the story).
+fn threaded(second_height: u32) -> (Session, NodeId, NodeId, String) {
+ let mut s = session();
+ let story = "The quick brown fox jumps over the lazy dog and keeps running. ".repeat(3) + "\nSecond paragraph.\nThird.";
+ let r = s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "area": {"width": 150, "height": 60}})).unwrap();
+ let a = NodeId(r["id"].as_u64().unwrap());
+ let r = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": second_height})).unwrap();
+ let b = NodeId(r["id"].as_u64().unwrap());
+ s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
+ s.execute("text.thread.create", &json!({})).unwrap();
+ (s, a, b, story)
+}
+
+/// Whether `dataset.list` says the data set `name` matches the art.
+fn matches(s: &mut Session, name: &str) -> bool {
+ let sets = s.execute("dataset.list", &json!({})).unwrap();
+ let set = sets["datasets"].as_array().unwrap().iter().find(|d| d["name"] == name).unwrap().clone();
+ set["matches"].as_bool().unwrap()
+}
+
+#[test]
+fn a_text_value_on_a_frame_of_threaded_type_replaces_the_whole_story() {
+ let (mut s, a, b, story) = threaded(200);
+ assert!(!plain(&s, a).is_empty() && !plain(&s, b).is_empty());
+ s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap();
+ s.execute("variable.bind", &json!({"variable": "Name", "ids": [a.0]})).unwrap();
+ // A capture reads the whole story, every frame's text in thread order.
+ s.execute("dataset.capture", &json!({"name": "Orig"})).unwrap();
+ let orig = s.doc().unwrap().doc.variables.dataset("Orig").unwrap().values.get("Name").cloned();
+ assert_eq!(orig, Some(vectorcraft_doc::DataValue::Text(story.clone())));
+ s.execute("dataset.new", &json!({"name": "B", "values": {"Name": "Bob"}})).unwrap();
+
+ let v = s.execute("dataset.select", &json!({"name": "B"})).unwrap();
+ assert_eq!((v["applied"].as_u64(), v["skipped"].as_u64()), (Some(1), Some(0)));
+ assert_eq!((plain(&s, a), plain(&s, b)), ("Bob".to_string(), String::new()));
+ assert!(matches(&mut s, "B"));
+ // The captured row applied back gives the story back, every time.
+ for _ in 0..2 {
+ s.execute("dataset.select", &json!({"name": "Orig"})).unwrap();
+ assert_eq!(format!("{}{}", plain(&s, a), plain(&s, b)), story);
+ assert!(!plain(&s, b).is_empty());
+ assert!(matches(&mut s, "Orig"));
+ s.execute("dataset.select", &json!({"name": "B"})).unwrap();
+ assert_eq!(format!("{}{}", plain(&s, a), plain(&s, b)), "Bob");
+ }
+}
+
+#[test]
+fn a_text_value_on_a_later_frame_of_threaded_type_replaces_the_whole_story() {
+ let (mut s, a, b, story) = threaded(200);
+ s.execute("variable.define", &json!({"name": "Tail", "kind": "text"})).unwrap();
+ s.execute("variable.bind", &json!({"variable": "Tail", "ids": [b.0]})).unwrap();
+ s.execute("dataset.capture", &json!({"name": "Orig"})).unwrap();
+ s.execute("dataset.new", &json!({"name": "T", "values": {"Tail": "END"}})).unwrap();
+
+ let v = s.execute("dataset.select", &json!({"name": "T"})).unwrap();
+ assert_eq!(v["applied"].as_u64(), Some(1));
+ assert_eq!((plain(&s, a), plain(&s, b)), ("END".to_string(), String::new()));
+ assert!(matches(&mut s, "T"));
+ s.execute("dataset.select", &json!({"name": "Orig"})).unwrap();
+ assert_eq!(format!("{}{}", plain(&s, a), plain(&s, b)), story);
+ assert!(matches(&mut s, "Orig"));
+}
+
+#[test]
+fn a_story_with_a_locked_frame_is_neither_read_nor_rewritten() {
+ let (mut s, a, b, story) = threaded(200);
+ s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap();
+ s.execute("variable.bind", &json!({"variable": "Name", "ids": [a.0]})).unwrap();
+ s.execute("dataset.new", &json!({"name": "B", "values": {"Name": "Bob"}})).unwrap();
+ s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
+ s.execute("object.lock", &json!({})).unwrap();
+
+ let v = s.execute("dataset.select", &json!({"name": "B"})).unwrap();
+ assert_eq!((v["applied"].as_u64(), v["skipped"].as_u64()), (Some(0), Some(1)));
+ assert_eq!(format!("{}{}", plain(&s, a), plain(&s, b)), story);
+ assert!(s.doc().unwrap().doc.captured_values().is_empty());
+}
+
+#[test]
+fn two_text_variables_in_one_story_apply_in_definition_order() {
+ let (mut s, a, b, _) = threaded(200);
+ s.execute("variable.define", &json!({"name": "Head", "kind": "text"})).unwrap();
+ s.execute("variable.define", &json!({"name": "Tail", "kind": "text"})).unwrap();
+ s.execute("variable.bind", &json!({"variable": "Tail", "ids": [a.0]})).unwrap();
+ s.execute("variable.bind", &json!({"variable": "Head", "ids": [b.0]})).unwrap();
+ s.execute("dataset.new", &json!({"name": "R", "values": {"Head": "one", "Tail": "two"}})).unwrap();
+
+ let v = s.execute("dataset.select", &json!({"name": "R"})).unwrap();
+ assert_eq!(v["applied"].as_u64(), Some(2));
+ assert_eq!(format!("{}{}", plain(&s, a), plain(&s, b)), "two");
+}
+
+#[test]
+fn applying_a_dataset_to_threaded_type_reports_overflow_on_the_last_frame() {
+ let (mut s, a, b, _) = threaded(40);
+ s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap();
+ s.execute("variable.bind", &json!({"variable": "Name", "ids": [a.0]})).unwrap();
+ s.execute("dataset.new", &json!({"name": "Long", "values": {"Name": "word ".repeat(120)}})).unwrap();
+ s.execute("dataset.new", &json!({"name": "Short", "values": {"Name": "Ann"}})).unwrap();
+
+ let v = s.execute("dataset.select", &json!({"name": "Long"})).unwrap();
+ assert_eq!(&v["overflow"], &json!([b.0]), "{v}");
+ let v = s.execute("dataset.select", &json!({"name": "Short"})).unwrap();
+ assert!(v.get("overflow").is_none(), "{v}");
+}
+
#[test]
fn mismatched_and_missing_bindings_are_skipped_and_counted() {
let mut s = session();
@@ -409,7 +516,8 @@ fn make_dynamic_errors_name_the_command() {
}
/// Lock Variables refuses defining, deleting and renaming variables, Make … Dynamic included,
-/// while binding, unbinding and the dataset commands still run.
+/// while binding, unbinding and the dataset commands still run (an import that would define a
+/// variable is refused; see `locked_variables_refuse_header_cells_that_define_variables`).
#[test]
fn locked_variables_refuse_new_deleted_and_renamed_variables() {
let mut s = session();
@@ -453,6 +561,14 @@ fn locked_variables_refuse_new_deleted_and_renamed_variables() {
s.execute("variable.define", &json!({"name": "Other", "kind": "text"})).unwrap();
}
+/// `variable.lock`'s params text names the dataset command it refuses: an import whose header
+/// would define a variable.
+#[test]
+fn the_lock_params_text_names_the_refused_import() {
+ let params = cmd::find_command("variable.lock").unwrap().params;
+ assert!(params.contains("the dataset commands still run, except a dataset.import whose header would define a variable"), "{params}");
+}
+
/// Locking is an undo step only when it changes the state, and the lock is saved with the
/// document: a file saved locked opens locked, and a file without the key opens unlocked.
#[test]
@@ -652,6 +768,20 @@ fn renaming_carries_the_bindings_and_values_with_it() {
assert!(s.execute("dataset.rename", &json!({"name": "Title", "newName": "Taken"})).is_err());
}
+/// Renaming a name that does not exist onto one that does reports the missing name, the same
+/// error a rename to a free name gives.
+#[test]
+fn renaming_a_missing_name_onto_a_taken_one_reports_the_missing_name() {
+ let mut s = session();
+ s.execute("variable.define", &json!({"name": "A", "kind": "text"})).unwrap();
+ s.execute("dataset.new", &json!({"name": "A"})).unwrap();
+
+ let e = s.execute("variable.rename", &json!({"name": "Nope", "newName": "A"})).unwrap_err().to_string();
+ assert!(e.contains("no variable named `Nope`"), "{e}");
+ let e = s.execute("dataset.rename", &json!({"name": "Nope", "newName": "A"})).unwrap_err().to_string();
+ assert!(e.contains("no dataset named `Nope`"), "{e}");
+}
+
/// `dataset.set` is how a value changes after the row exists: replacing it must not need the
/// dataset to be deleted and rebuilt (which loses its place in the list and the active one).
#[test]
@@ -1632,6 +1762,37 @@ fn locked_variables_refuse_a_library_that_deletes_or_defines_variables() {
assert_eq!(vars.datasets.iter().map(|d| d.name.as_str()).collect::>(), ["B"]);
}
+/// A graph variable's data set applies its CSV as `graph.setData` does: a right-axis series the row's data no longer
+/// has is dropped, and a row with neither a label nor a value is not drawn as an empty slot.
+#[test]
+fn graph_variable_applies_csv_as_set_data() {
+ let mut s = session();
+ let create = json!({"type": "column", "x": 10, "y": 10, "width": 120, "height": 80, "csv": ",a,b\nQ1,10,1000\nQ2,5,500"});
+ let id = s.execute("graph.create", &create).unwrap()["id"].as_u64().unwrap();
+ let other = s.execute("graph.create", &create).unwrap()["id"].as_u64().unwrap();
+ for g in [id, other] {
+ s.execute("graph.setType", &json!({"id": g, "seriesIndexes": [1], "valueAxis": "right"})).unwrap();
+ }
+ s.execute("select.set", &json!({"ids": [id]})).unwrap();
+ s.execute("variable.makeGraphDynamic", &json!({})).unwrap();
+ let name = s.execute("variable.list", &json!({})).unwrap()["variables"][0]["name"].as_str().unwrap().to_string();
+ let spec = |s: &Session, g: u64| s.doc().unwrap().doc.node(NodeId(g)).unwrap().extras().graph.as_deref().unwrap().clone();
+ // A dropped empty row wider than the others (`,,`) adds no blank series, so the right axis keeps nothing.
+ for (row, csv) in [("Wide", ",a\nQ1,10\n,,\nQ2,5"), ("One", ",a\nQ1,10\nQ2,5"), ("Blank", ",a\nQ1,10\n,\nQ2,5")] {
+ s.execute("dataset.new", &json!({"name": row, "values": {name.clone(): csv}})).unwrap();
+ s.execute("dataset.select", &json!({"name": row})).unwrap();
+ s.execute("graph.setData", &json!({"id": other, "csv": csv})).unwrap();
+ let (merged, set) = (spec(&s, id), spec(&s, other));
+ assert_eq!(merged.right_series, set.right_series, "{row}");
+ assert_eq!(merged.categories, set.categories, "{row}");
+ assert_eq!(merged.cells(), set.cells(), "{row}");
+ assert!(merged.right_series.is_empty(), "{row}");
+ assert_eq!(merged.cells(), [[Some(10.0)], [Some(5.0)]], "{row}");
+ }
+ assert!(spec(&s, id).right_series.is_empty());
+ assert_eq!(spec(&s, id).categories, ["Q1", "Q2"]);
+}
+
#[test]
fn graph_variable_applies_csv_and_captures() {
let mut s = session();
diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs
index 38a60e2394..7202df9605 100644
--- a/crates/engine/tests/command_sweep.rs
+++ b/crates/engine/tests/command_sweep.rs
@@ -434,6 +434,11 @@ fn structured_junk() {
("addon.color.printFixes", json!({"inkLimit": 1e308, "overprintBlack": -1e308})),
("addon.color.printFixes", json!({"inkLimit": 1, "overprintBlack": 1, "removeWhiteOverprint": true, "scope": "document", "textOnly": true})),
("addon.color.printFixes", json!({"inkLimit": [300], "scope": 3, "ids": "x"})),
+ ("addon.color.nearestSwatch", json!({"library": 7, "count": u64::MAX, "color": [1e308, -1e308, "x"]})),
+ ("addon.color.nearestSwatch", json!({"library": "web-safe-216", "color": {"l": 1e30, "a": -1e30, "b": 0}, "count": 50})),
+ ("addon.color.nearestSwatch", json!({"library": "spectrum-gradients", "fill": "x", "ids": [u64::MAX]})),
+ ("addon.color.applyNearestSwatch", json!({"library": "web-safe-216", "fill": true, "stroke": true})),
+ ("addon.color.applyNearestSwatch", json!({"library": "nope", "ids": "x", "stroke": 3})),
("effect.apply", json!({"effect": "no.such.effect"})),
("effect.remove", json!({"index": 99})),
("effect.setParams", json!({"index": 0, "params": null})),
diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs
index e7a89d97c5..931963de39 100644
--- a/crates/engine/tests/import_fuzz.rs
+++ b/crates/engine/tests/import_fuzz.rs
@@ -2623,11 +2623,12 @@ fn ascii85(data: &[u8]) -> String {
const PATTERN: &str = "%AI3_BeginPattern: (Dots)\n(Dots) 0 0 6 6\n%_0 A\n%_0 Ae\n%_u\n%_0 0 m\n%_0 6 L\n%_6 6 L\n%_6 0 L\n%_n\n%_0 0 0 1 K\n%_1 J 1 w\n%_3 3 m\n%_3 3 L\n%_S\n%_U\n%_9 () XW\nE\n%AI3_EndPattern\n";
/// The swatches in editing data: process, spot (one the art doesn't use), global, a gradient that
-/// isn't defined and a pattern, a colour group, and versioned content read once.
-const PALETTE: &str = "%AI5_BeginPalette\n0 0 Pb\n%AI17_Begin_Content_if_version_gt:24 15\n1 1 1 1 ([Registration]) 0 Xs\n([Registration])\nPc\n\
+/// isn't defined and a pattern, a colour group, versioned content read once, and the None swatch
+/// and a swatch without a name, as version 7 files write them.
+const PALETTE: &str = "%AI5_BeginPalette\n0 0 Pb\nPn\nPc\n%AI17_Begin_Content_if_version_gt:24 15\n1 1 1 1 ([Registration]) 0 Xs\n([Registration])\nPc\n\
0 0 0 1 k\n(Black)\nPc\n0.1 0.9 0.8 0 (Unused ink) 0 x\n(Unused ink)\nPc\n0 0 0 1 0 0 0 (Black global) 0 1 Xk\n(Black global)\nPc\n\
Bb\n2 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(G)\nPc\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Dots)\nPc\n\
- %AI17_Alternate_Content\n0 0 0 1 k\n(Black)\nPc\n%AI17_End_Versioned_Content\n1 (Greys) 1 Pg\n0 0 0 0.5 k\n(K50)\nPc\nPB\n%AI5_EndPalette\n";
+ %AI17_Alternate_Content\n0 0 0 1 k\n(Black)\nPc\n%AI17_End_Versioned_Content\n1 (Greys) 1 Pg\n0 0 0 0.5 k\n(K50)\nPc\n0.75 g\nPc\nPB\n%AI5_EndPalette\n";
/// The editing data of a file with every sort of object the layers reader knows, and some it doesn't.
fn editing_text() -> String {
@@ -2697,8 +2698,9 @@ fn the_editing_fixture_reads_its_palette() {
let swatches: Vec<&str> = doc.swatches.iter().map(|s| s.name.as_str()).collect();
assert_eq!(swatches, ["[None]", "Black", "Unused ink", "Black global", "Dots"]);
assert!(doc.swatch("Unused ink").is_some_and(|s| s.spot && s.global));
- let groups: Vec<(&str, usize)> = doc.swatch_groups.iter().map(|g| (g.name.as_str(), g.swatches.len())).collect();
- assert_eq!(groups, [("Greys", 1)]);
+ let groups: Vec<(&str, Vec<&str>)> =
+ doc.swatch_groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|s| s.name.as_str()).collect())).collect();
+ assert_eq!(groups, [("Greys", vec!["K50", "Gray K=25"])], "the swatch without a name is named by its values");
}
/// The fuzzed editing data, as it is, reads its CMYK image with its ink amounts and its alpha
@@ -2954,6 +2956,40 @@ proptest! {
survive("mutated EPS editing data", || vectorcraft_eps::import(&bytes).ok().map(|r| r.document))?;
}
+ /// A `.ai` whose envelopes are damaged or hostile: any kind, warp style, options word,
+ /// Fidelity and grid size, corners out of range or repeated, the contents block cut short.
+ #[test]
+ fn ai_envelope_never_panics(
+ kind in prop::sample::select(vec![0i64, 1, 2, 3, 4, -1, 1 << 40]),
+ style in prop::sample::select(vec![0i64, 1, 8, 15, 16, -3, i64::MAX]),
+ word in prop::sample::select(vec![0i64, 1, 131073, 65536, 0x2_0007, 1 << 18, -1, i64::MAX]),
+ fidelity in prop::sample::select(vec!["50", "0", "100", "101", "-1", "1e308", "nan"]),
+ size in prop::sample::select(vec!["[1 1]", "[3 2]", "[0 0]", "[51 1]", "[100000 100000]", "[-1 2]", "[1e308 1]"]),
+ corner in prop::sample::select(vec!["10 10", "1e308 -1e308", "nan 0", "10 10 10 10", "0"]),
+ edit in 0i64..2,
+ cut in 0usize..2_000,
+ edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec!['0', '9', '-', ' ', '\n', '(', ')', '/', ':', ';', ',', '[', ']', '%', '_', 'X', 'u', 'U'])), 0..8),
+ ) {
+ use vectorcraft_testkit::ai;
+ let n = |x: &str, y: &str| format!("%_[0.5 1 {x} {y} {x} {y} 1 {x} {y} 1] /N X#\n");
+ let mesh = format!(
+ "%_/Mesh X!\n%_2 /Version X#\n%_/Cartesian /Type X#\n%_{size} /Size X#\n%_/Data X#\n%_[0 0] /P X#\n{}{}{}%_[{corner}] /N X#\n%_/E X#\n%_[0 0] /P X#\n%_/E X#\n%_/End X!\n",
+ n("10", "10"),
+ n("10", "90"),
+ n("90", "90")
+ );
+ let content = "%_u\n%_1 0 0 1 0 0 Xa\n%_10 10 m\n%_10 90 L\n%_90 90 L\n%_90 10 L\n%_f\n%_U\n";
+ let keys = format!(
+ "%_{word} /Int (AIDeformOptionsKey) ,\n%_{fidelity} /Int (AIDeformFidelityKey) ,\n%_{edit} /Bool (AIDeformEditModeKey) ,\n%_{style} /Int (DeformStyle) ,\n%_0.5 /Real (DeformValue) ,\n%_1 /Bool (Rotate) ,\n"
+ );
+ let art = format!(
+ "%_u\n{mesh}%_U\n%_/ArtDictionary :\n{keys}%_X=\n{content}%_X+\n%_ (AIDeformArtKey) ,\n%_{kind} /Int (AIDeformStyle) ,\n%_;\n%_\nu\n1 0 0 1 0 0 Xa\n12 12 m\n12 88 L\n88 88 L\nf\nU\n(Adobe Deform Plugin) 1 0 0 XP\n0 0 1 1 0 0 Xa\n0 0 m\n5 5 L\nf\n"
+ );
+ let data = mutate_text(&ai::editing_data(100.0, 100.0, &ai::layer("L", &art)), cut, &edits);
+ let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat();
+ 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 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', 'k', 'x'])), 0..12), damage in prop::collection::vec((0usize..4_000, any::()), 0..4)) {
@@ -2980,6 +3016,101 @@ proptest! {
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat();
survive("mutated .ai variable library", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?;
}
+
+ /// A `.ai` whose Objects on Path record and group are damaged or hostile.
+ #[test]
+ fn ai_objects_on_path_never_panics(cut in 0usize..4_000, edits in prop::collection::vec((0usize..4_000, prop::sample::select(vec!['0', '1', '9', '-', '.', 'e', ' ', '\n', '(', ')', '/', ':', ';', ',', '%', '_', 'u', 'U'])), 0..12)) {
+ let text = mutate_text(&on_path_data(&ON_PATH_IDS, &ON_PATH_IDS, 4, "4", "0.5", "", ["0", "1", "2"], true, 0), cut, &edits);
+ let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat();
+ // Trusted, so that the layers read are built whatever the empty page shows.
+ survive("mutated .ai Objects on Path", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?;
+ }
+
+ /// Objects on Path records of any shape: ids in any order, repeated or missing, any number of
+ /// objects, pivots and angles out of range or not finite, spacings, order tags that disagree,
+ /// groups nested or cut short, and versioned content left open.
+ #[test]
+ fn ai_objects_on_path_records_never_panic(
+ listed in prop::collection::vec(prop::sample::select(ON_PATH_IDS.to_vec()), 0..7),
+ drawn in prop::collection::vec(prop::sample::select(ON_PATH_IDS.to_vec()), 0..7),
+ members in 0usize..7,
+ pivot in prop::sample::select(vec!["0", "4", "8", "9", "-1", "2.5", "1e400"]),
+ rotation in prop::sample::select(vec!["0", "0.5235987755982988", "-3.2", "1e400", "-1e400", "1e300"]),
+ spacing in prop::sample::select(vec!["", "%_56.5 /Real (Spacing) ,\n", "%_0 /Bool (IsEquiSpaced) ,\n", "%_1 /Bool (Flip) ,\n"]),
+ tags in prop::array::uniform3(prop::sample::select(vec!["0", "1", "2", "-1", "7", "(x)", "1e400"])),
+ versioned in any::(),
+ nest in 0usize..3,
+ cut in 0usize..2_000,
+ ) {
+ let data = on_path_data(&listed, &drawn, members, pivot, rotation, spacing, tags, versioned, nest);
+ let cut_at = data.len().saturating_sub(cut);
+ let cut_at = (0..=cut_at).rev().find(|i| data.is_char_boundary(*i)).unwrap_or(0);
+ for data in [data.as_str(), &data[..cut_at]] {
+ let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(data)].concat();
+ survive("hostile Objects on Path", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?;
+ }
+ }
+}
+
+/// The data [`ai_objects_on_path_never_panics`] damages, as it is, opens with its Objects on Path group.
+#[test]
+fn the_objects_on_path_fuzz_data_opens_live() {
+ let text = on_path_data(&ON_PATH_IDS, &ON_PATH_IDS, 4, "4", "0.5", "", ["0", "1", "2"], true, 0);
+ let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat();
+ // Trusted: the empty page it is read beside isn't compared with its art.
+ let (doc, warnings, _) = vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0);
+ let g = doc.layers.first().and_then(|l| l.children()).and_then(|c| c.first()).unwrap_or_else(|| panic!("{warnings:?}"));
+ assert!(g.extras().objects_on_path.is_some(), "{g:?}");
+}
+
+/// The ids of the objects of an Objects on Path group in the fuzz cases.
+const ON_PATH_IDS: [&str; 5] = ["f-0001", "f-0002", "f-0003", "f-0004", "f-0005"];
+
+/// Editing data with an Objects on Path record naming `listed` for `members` objects (Pivot
+/// `pivot`, Rotation `rotation`, then the entries `more`) and a group of a path and squares whose
+/// dictionaries give the ids `drawn` (the first the path's, the others with the order tags `tags`
+/// in turn), inside `nest` more groups, in versioned content with a copy after it when `versioned`
+/// is set.
+#[allow(clippy::too_many_arguments)]
+fn on_path_data(
+ listed: &[&str],
+ drawn: &[&str],
+ members: usize,
+ pivot: &str,
+ rotation: &str,
+ more: &str,
+ tags: [&str; 3],
+ versioned: bool,
+ nest: usize,
+) -> String {
+ use vectorcraft_testkit::ai;
+ let options = ai::on_path_options(members, 0, 0.0, more)
+ .replace("%_0 /Int (PivotPosition)", &format!("%_{pivot} /Int (PivotPosition)"))
+ .replace("%_0 /Real (Rotation)", &format!("%_{rotation} /Real (Rotation)"));
+ let record = ai::on_path_record("Adobe Align On Path", listed, &options); // brand-ok: the record's name in the files
+ let mut group = String::from("0 Ae\nu\n/ConstraintGroup :\n128 /GroupType ,\n;\n0 0 1 0 0 0 1 XA\n20 20 m\n100 80 L\n180 20 L\nS\n");
+ for (i, id) in drawn.iter().enumerate() {
+ if i == 0 {
+ group += &ai::on_path_member(id, None, 0.0);
+ } else {
+ let x = 10.0 + 30.0 * i as f64;
+ let tag = tags.get(i - 1).map_or_else(|| (i - 1).to_string(), |t| t.to_string());
+ group += &format!(
+ "0 1 1 0 1 0 0 Xa\n{}f\n%_/ArtDictionary :\n%_{tag} /Int (ConstraintArtOrderId) ,\n%_({id}) /String (Persistent ID) ,\n%_({rotation}) /String (BBAccumRotation) ,\n%_;\n%_\n",
+ ai::rect(x, 40.0, x + 10.0, 46.0)
+ );
+ }
+ }
+ group += "U\n";
+ for _ in 0..nest {
+ group = format!("0 Ae\nu\n{group}U\n");
+ }
+ let art = if versioned {
+ format!("%AI17_Begin_Content_if_version_gt:24 14\n{group}%AI17_Alternate_Content\n{group}%AI17_End_Versioned_Content\n")
+ } else {
+ group
+ };
+ ai::editing_data(200.0, 100.0, &format!("{record}{}", ai::layer("L", &art)))
}
/// A `.ai` in PostScript form as other apps write it: the procsets that define its operators named,
@@ -3011,6 +3142,22 @@ proptest! {
}
}
+/// An operand of a layer's options (`Lb`): a flag, a colour index or component, a percentage, or
+/// anything else.
+fn arb_layer_operand() -> impl Strategy {
+ prop_oneof![Just("0".to_string()), Just("1".to_string()), (-2i32..300).prop_map(|v| v.to_string()), arb_num()]
+}
+
+/// A coordinate of a guide path: the ends of the canvas around the template box's centre (100 50),
+/// the edges of the artboards, near them, or anything else.
+fn arb_guide_coord() -> impl Strategy {
+ prop_oneof![
+ prop::sample::select(vec!["-8091.5", "8291.5", "-8141.5", "8241.5", "0", "50", "100", "200", "-8091.505", "8291.5001", "1e308"])
+ .prop_map(str::to_string),
+ arb_num(),
+ ]
+}
+
/// The operators, operands and section comments of hostile editing data.
fn arb_ai_token() -> impl Strategy {
prop_oneof![
@@ -3037,6 +3184,9 @@ fn arb_ai_token() -> impl Strategy {
"b",
"W",
"(b) *",
+ "(N) *",
+ "(S) *",
+ "-8091.5 50 m 8291.5 50 L (N) *",
"u",
"U",
"*u",
@@ -3214,6 +3364,12 @@ fn arb_ai_token() -> impl Strategy {
"[1 1] /P X#",
"(Adobe Path Blends) 1 0 92 XP",
"(Adobe Path Blends) 1 0 999999 XP",
+ "(Adobe Deform Plugin) 1 0 0 XP",
+ "%_/ArtDictionary :\n%_131073 /Int (AIDeformOptionsKey) ,\n%_X=\n",
+ "%_X+\n%_ (AIDeformArtKey) ,\n%_2 /Int (AIDeformStyle) ,\n%_;\n",
+ "%_1 /Int (AIDeformStyle) ,\n%_9 /Int (DeformStyle) ,\n%_1e308 /Real (DeformValue) ,\n%_;\n",
+ "%_1 /Bool (AIDeformEditModeKey) ,",
+ "[1e308 1e308] /Size X#",
"\n%44434241010000000000000000000000\n",
"\n%0200000041000000000000000000000000000000\n",
"\n%4G\n",
@@ -3297,6 +3453,42 @@ proptest! {
survive("hostile editing data in an EPS of its art's box", || vectorcraft_engine::cmd::fileio::load("x.eps", &boxed).ok().map(|l| l.doc))?;
}
+ /// Layer options (`Lb`) of any number of operands with any values, and guide paths (`(N) *`,
+ /// `(S) *`) of any points, among them ones across the whole canvas or from edge to edge of
+ /// artboards that overlap or are the same, on layers and sublayers.
+ #[test]
+ fn ai_layer_options_and_ruler_guides_never_panic(
+ options in prop::collection::vec(arb_layer_operand(), 0..17),
+ guides in prop::collection::vec((prop::collection::vec((arb_guide_coord(), arb_guide_coord()), 0..5), any::(), any::()), 0..12),
+ boards in prop::collection::vec(prop::sample::select(vec![[0.0, 100.0, 200.0, 0.0], [0.0, 100.0, 100.0, 0.0], [50.0, 100.0, 200.0, 0.0]]), 0..4),
+ ) {
+ use vectorcraft_testkit::ai;
+ let board = |b: &[f64; 4]| {
+ format!(
+ "%_/Dictionary :\n%_{} {} /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} {} /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n",
+ b[0], b[1], b[2], b[3]
+ )
+ };
+ let array: String = boards.iter().map(board).collect();
+ let document = format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n{array}%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n");
+ let paths: Vec = guides
+ .iter()
+ .map(|(points, ruler, sub)| {
+ let ops: String = points.iter().enumerate().map(|(i, (x, y))| format!("{x} {y} {}\n", if i == 0 { "m" } else { "L" })).collect();
+ let path = format!("{ops}({}) *\n", if *ruler { "N" } else { "S" });
+ if *sub { format!("%AI5_BeginLayer\n{} Lb\n(Sub) Ln\n{path}LB\n%AI5_EndLayer--\n", options.join(" ")) } else { path }
+ })
+ .collect();
+ let body = format!("{document}%AI5_BeginLayer\n{} Lb\n(L) Ln\n{}\nLB\n%AI5_EndLayer--\n", options.join(" "), paths.concat());
+ let data = ai::editing_data(200.0, 100.0, &body).replacen("%%EndComments", "%AI3_TemplateBox: 100 50 100 50\n%%EndComments", 1);
+ survive("layer options and ruler guides", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?;
+ survive("layer options and ruler guides in units of 10 points", || {
+ Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(2000.0, 1000.0), vec![], false, false, 10.0).0)
+ })?;
+ let eps = ai::eps(data.as_bytes(), ai::page_ps());
+ survive("layer options and ruler guides in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?;
+ }
+
/// The testkit's sample damaged, as it is and compressed, in EPS, `.ai` and PDF files.
#[test]
fn ai_mutated_sample_never_panics(cut in 0usize..4_000, edits in prop::collection::vec((0usize..4_000, any::()), 0..12)) {
diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs
index 50fcec2416..c32bf22177 100644
--- a/crates/eps/src/import/ai.rs
+++ b/crates/eps/src/import/ai.rs
@@ -18,6 +18,7 @@
//! did before (the printed page, or the PDF), with a warning saying why.
mod blend;
+mod envelope;
mod frames;
mod lex;
mod mesh;
@@ -32,6 +33,7 @@ use std::io::Read as _;
use super::lex::find;
use crate::ps;
+pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN;
pub(crate) use frames::text_frames;
pub use read::{IMAGE_TOO_LARGE, PaletteSwatches, Structure, artboards, palette, read, variables};
pub(crate) use read::{join_and, slot_frame, slot_of};
diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs
new file mode 100644
index 0000000000..33fae9eab3
--- /dev/null
+++ b/crates/eps/src/import/ai/envelope.rs
@@ -0,0 +1,361 @@
+//! Envelopes from the editing data (`(Adobe Deform Plugin) 1 0 0 XP`), read as live envelopes.
+//!
+//! What an envelope is and does is Illustrator's public documentation: Make with Warp, Make with
+//! Mesh (rows and columns) and Make with Top Object
+//! (),
+//! Edit Contents
+//! (),
+//! Envelope Options
+//! ()
+//! and the warp styles with their bend and distortions
+//! ().
+//!
+//! An envelope is written in three parts. On `%_` lines, a group holding the mesh that shapes it,
+//! then its `/ArtDictionary`: Envelope Options as a bit word (`AIDeformOptionsKey`), Fidelity
+//! (`AIDeformFidelityKey`), Edit Contents (`AIDeformEditModeKey`), a warp's style (`DeformStyle`,
+//! numbered as Effect › Warp lists them), bend and distortions (`DeformValue`, `DeformHoriz`,
+//! `DeformVert`, fractions) and orientation (`Rotate`), the contents (`X=` … `X+`, then
+//! `(AIDeformArtKey)`) and the kind (`AIDeformStyle`: 1 a warp, 2 a mesh, 3 a top object). Then the
+//! distorted art on plain lines, and the plugin's `XP`. While the contents are edited, the group
+//! holds the contents and the dictionary the mesh. A top object's outline is the edge of its
+//! one-patch mesh. An envelope whose parts don't read, or that doesn't come out as drawn, keeps its
+//! drawn art.
+
+use std::collections::BTreeMap;
+use std::sync::Arc;
+
+use kurbo::{BezPath, Point, Rect, Vec2};
+use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, default_fidelity};
+use vectorcraft_doc::{Document, ImageBlob, LayerColor, Node, NodeId, NodeKind, PatternDef};
+use vectorcraft_geom::PathData;
+
+use super::obj::Obj;
+use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, compare_scale, differ, differ_in_colour};
+
+/// The plugin that writes envelopes.
+pub(super) const PLUGIN: &str = "Adobe Deform Plugin"; // brand-ok: the plugin name the files use
+/// The note for an envelope that keeps its drawn art.
+pub(crate) const DRAWN: &str = "an envelope VectorCraft couldn't read as a live envelope comes in as its drawn art";
+/// The most envelopes waiting for their drawn art at once.
+pub(super) const MAX_PENDING: usize = 64;
+/// The most envelopes one import draws to check; more keep their drawn art.
+pub(super) const MAX_CHECKED: usize = 256;
+/// The most rows or columns of a mesh read (Make with Mesh's own limit).
+const MAX_GRID: u32 = 50;
+/// The bits of the options word that are read: Distort Appearance, Distort Pattern Fills, Distort
+/// Linear Gradients, Anti-Alias (set: off) and Preserve Shape Using (set: Clipping Mask).
+const KNOWN_BITS: i64 = 0b111 | 1 << 16 | 1 << 17;
+/// More of the inked pixels than this differing, each with all its neighbours, and the envelope
+/// doesn't come out as drawn.
+const MAX_SOLID: f64 = 0.03;
+/// More of the inked pixels than this differing at all, and the envelope doesn't come out as drawn.
+const MAX_ANY: f64 = 0.1;
+
+/// The whole number of entry `key`: `None` when it is missing, `Some(None)` when it isn't one.
+fn whole(o: &Obj, key: &str) -> Option> {
+ o.get(key)?;
+ let n = o.nums(key);
+ Some(match n.as_slice() {
+ [v] if v.is_finite() && v.fract() == 0.0 && v.abs() < 1e12 => Some(*v as i64),
+ _ => None,
+ })
+}
+
+/// A switch (`0` or `1`), off when missing.
+fn switch(o: &Obj, key: &str) -> Option {
+ match whole(o, key) {
+ None | Some(Some(0)) => Some(false),
+ Some(Some(1)) => Some(true),
+ _ => None,
+ }
+}
+
+/// Envelope Options and Fidelity.
+pub(super) fn options(o: &Obj) -> Option<(EnvelopeOptions, f64)> {
+ let word = whole(o, "AIDeformOptionsKey")??;
+ if word < 0 || word & !KNOWN_BITS != 0 {
+ return None;
+ }
+ let fidelity = match whole(o, "AIDeformFidelityKey") {
+ None => default_fidelity(),
+ Some(Some(f)) if (0..=100).contains(&f) => f as f64,
+ Some(_) => return None,
+ };
+ let bit = |n: u32| word & (1 << n) != 0;
+ let options = EnvelopeOptions {
+ anti_alias: !bit(16),
+ preserve_shape: if bit(17) { PreserveShape::ClippingMask } else { PreserveShape::Transparency },
+ distort_appearance: bit(0),
+ distort_pattern_fills: bit(1),
+ distort_linear_gradients: bit(2),
+ };
+ Some((options, fidelity))
+}
+
+/// A warp: its style, bend, distortions and orientation.
+fn warp(o: &Obj) -> Option {
+ let style = whole(o, "DeformStyle")??;
+ let id = super::style::warp_style(style)?;
+ let percent = |key: &str| -> Option {
+ if o.get(key).is_none() {
+ return Some(0.0);
+ }
+ match o.nums(key).as_slice() {
+ [v] if v.is_finite() && (-1.0..=1.0).contains(v) => Some(v * 100.0),
+ _ => None,
+ }
+ };
+ o.get("DeformValue")?;
+ let vertical = switch(o, "Rotate")?;
+ Some(EnvelopeKind::Warp {
+ style: id.into(),
+ bend: percent("DeformValue")?,
+ h: percent("DeformHoriz")?,
+ v: percent("DeformVert")?,
+ horizontal: !vertical,
+ })
+}
+
+/// The gradient mesh `n` is, or the one its plain groups hold alone.
+fn only_mesh(n: &Node) -> Option<&GradientMesh> {
+ match &n.kind {
+ NodeKind::Mesh(m) => Some(m),
+ NodeKind::Group { children, clip: false } => match children.as_slice() {
+ [c] => only_mesh(c),
+ _ => None,
+ },
+ _ => None,
+ }
+}
+
+/// A grid point and its handles.
+type GridPoint = (Point, [Vec2; 4]);
+
+/// The points of mesh `m` as a `rows`×`cols` grid with its first row at the top and its first
+/// column at the left (y down), as an envelope's mesh lays them out; `None` for a grid out of range
+/// or with points that aren't finite.
+fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec)> {
+ let (mut rows, mut cols) = (m.rows, m.cols);
+ if rows == 0 || cols == 0 || rows > MAX_GRID || cols > MAX_GRID {
+ return None;
+ }
+ let len = (rows as usize + 1) * (cols as usize + 1);
+ if m.points.len() != len {
+ return None;
+ }
+ let finite = |v: Vec2| v.x.is_finite() && v.y.is_finite();
+ if !m.points.iter().all(|q| finite(q.p.to_vec2()) && q.handles.iter().all(|h| finite(*h))) {
+ return None;
+ }
+ let mut pts: Vec = m.points.iter().map(|q| (q.p, q.handles)).collect();
+ let at = |pts: &[GridPoint], cols: u32, r: u32, c: u32| pts.get((r * (cols + 1) + c) as usize).map_or(Point::ZERO, |q| q.0);
+ let remap = |h: [Vec2; 4], slots: [usize; 4]| slots.map(|s| h.get(s).copied().unwrap_or(Vec2::ZERO));
+ // Columns that run down the page: the grid goes the other way round.
+ let along = at(&pts, cols, 0, cols) - at(&pts, cols, 0, 0);
+ if along.y.abs() > along.x.abs() {
+ let mut t = Vec::with_capacity(len);
+ for r in 0..=cols {
+ for c in 0..=rows {
+ let (p, h) = pts.get((c * (cols + 1) + r) as usize).copied()?;
+ // The new next column is the old next row.
+ let mut slots = [0; 4];
+ (slots[H_RIGHT], slots[H_LEFT], slots[H_DOWN], slots[H_UP]) = (H_DOWN, H_UP, H_RIGHT, H_LEFT);
+ t.push((p, remap(h, slots)));
+ }
+ }
+ (rows, cols) = (cols, rows);
+ pts = t;
+ }
+ if (at(&pts, cols, 0, cols) - at(&pts, cols, 0, 0)).x < 0.0 {
+ for row in pts.chunks_mut(cols as usize + 1) {
+ row.reverse();
+ for (_, h) in row.iter_mut() {
+ h.swap(H_RIGHT, H_LEFT);
+ }
+ }
+ }
+ if (at(&pts, cols, rows, 0) - at(&pts, cols, 0, 0)).y < 0.0 {
+ let mut flipped: Vec = pts.chunks(cols as usize + 1).rev().flatten().copied().collect();
+ for (_, h) in &mut flipped {
+ h.swap(H_DOWN, H_UP);
+ }
+ pts = flipped;
+ }
+ Some((rows, cols, pts))
+}
+
+/// The outline of an upright grid: its edge, clockwise from the top left corner.
+fn outline(rows: u32, cols: u32, pts: &[GridPoint]) -> Option {
+ let at = |r: u32, c: u32| pts.get((r * (cols + 1) + c) as usize).copied();
+ // Each edge: from a point by one of its handles to the next point by one of its handles.
+ type Edge = ((u32, u32), usize, (u32, u32), usize);
+ let mut ring: Vec = vec![];
+ ring.extend((0..cols).map(|c| ((0, c), H_RIGHT, (0, c + 1), H_LEFT)));
+ ring.extend((0..rows).map(|r| ((r, cols), H_DOWN, (r + 1, cols), H_UP)));
+ ring.extend((1..=cols).rev().map(|c| ((rows, c), H_LEFT, (rows, c - 1), H_RIGHT)));
+ ring.extend((1..=rows).rev().map(|r| ((r, 0), H_UP, (r - 1, 0), H_DOWN)));
+ let mut bp = BezPath::new();
+ bp.move_to(at(0, 0)?.0);
+ for ((ar, ac), out, (br, bc), into) in ring {
+ let ((a, ha), (b, hb)) = (at(ar, ac)?, at(br, bc)?);
+ bp.curve_to(a + *ha.get(out)?, b + *hb.get(into)?, b);
+ }
+ bp.close_path();
+ Some(PathData::from_bezpath(&bp))
+}
+
+/// Has group `n` nothing of its own: no name, lock, transparency, appearance or other properties,
+/// shown?
+fn plain_group(n: &Node) -> bool {
+ let plain = Node::new(n.id, NodeKind::Group { children: vec![], clip: false });
+ matches!(n.kind, NodeKind::Group { clip: false, .. })
+ && (&n.name, n.visible, n.locked, n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape)
+ == (&plain.name, plain.visible, plain.locked, plain.opacity, plain.blend, plain.isolate, plain.knockout, plain.knockout_shape)
+ && n.appearance == plain.appearance
+ && n.extras() == plain.extras()
+}
+
+/// `nodes` without the plain group the editing data puts round an envelope's contents.
+fn unwrapped(mut nodes: Vec) -> Vec> {
+ if nodes.len() == 1
+ && let Some(n) = nodes.first()
+ && plain_group(n)
+ && let Some(n) = nodes.pop()
+ && let NodeKind::Group { children, .. } = n.kind
+ {
+ return children;
+ }
+ nodes.into_iter().map(Arc::new).collect()
+}
+
+/// The live envelope of dictionary `o`, the group on `%_` lines before it (`before`) and the art
+/// in its `AIDeformArtKey` block (`inner`); `None` where they don't make one.
+pub(super) fn live(o: &Obj, before: Option, inner: Vec) -> Option {
+ let editing = switch(o, "AIDeformEditModeKey")?;
+ let (options, fidelity) = options(o)?;
+ let before = before?;
+ // While the contents are edited, they are the group before the dictionary and the mesh is in it.
+ let (content, shape): (Vec>, Option<&GradientMesh>) = if editing {
+ let NodeKind::Group { children, clip: false } = &before.kind else { return None };
+ let shape = match inner.as_slice() {
+ [n] => only_mesh(n),
+ _ => None,
+ };
+ (children.clone(), shape)
+ } else {
+ let shape = only_mesh(&before);
+ (unwrapped(inner), shape)
+ };
+ if content.is_empty() {
+ return None;
+ }
+ let kind = match whole(o, "AIDeformStyle")?? {
+ 1 => warp(o)?,
+ 2 => {
+ let (rows, cols, pts) = upright(shape?)?;
+ let (points, handles) = pts.into_iter().unzip();
+ EnvelopeKind::Mesh { rows, cols, points, handles }
+ }
+ 3 => {
+ let (rows, cols, pts) = upright(shape?)?;
+ EnvelopeKind::TopObject { path: outline(rows, cols, &pts)? }
+ }
+ _ => return None,
+ };
+ Some(NodeKind::Envelope { content, kind: Box::new(kind), fidelity, editing, options, frame: Box::default() })
+}
+
+/// What the import's documents hold that art refers to: the patterns and image blobs.
+pub(super) struct Shared<'a> {
+ pub(super) patterns: &'a [PatternDef],
+ pub(super) images: &'a BTreeMap,
+}
+
+/// A document of `node` alone, on a layer with id `layer`, with the patterns and images it shows.
+fn alone(node: &Node, layer: NodeId, shared: &Shared<'_>) -> Document {
+ let mut doc = Document::new(1.0, 1.0);
+ let mut l = Node::layer(layer, "", LayerColor::Preset(0));
+ if let Some(c) = l.children_mut() {
+ c.push(Arc::new(node.clone()));
+ }
+ doc.layers = vec![Arc::new(l)];
+ doc.patterns = shared.patterns.to_vec();
+ let mut keys = vec![];
+ doc.visit_images(|_, im| keys.push(im.key.clone()));
+ for k in keys {
+ if let Some(blob) = shared.images.get(&k) {
+ doc.images.insert(k, blob.clone());
+ }
+ }
+ doc
+}
+
+/// How `live` and `drawn`, drawn over `region` at `scale`, differ: the pixels that differ in
+/// lightness or colour, those whose neighbours all differ too (where one draws something the other
+/// doesn't, not an edge drawn a little apart), and the pixels either inks. `None` when they can't
+/// be drawn.
+fn differing(live: &Document, drawn: &Document, region: Rect, scale: f64) -> Option<(usize, usize, usize)> {
+ let x = vectorcraft_render::Renderer::new().render_region(live, region, scale, false);
+ let y = vectorcraft_render::Renderer::new().render_region(drawn, region, scale, false);
+ if x.width == 0 || x.height == 0 || x.width != y.width || x.height != y.height {
+ return None;
+ }
+ let (w, h) = (x.width as usize, x.height as usize);
+ let (xs, ys) = (x.pixels.as_chunks::<4>().0, y.pixels.as_chunks::<4>().0);
+ let differs: Vec = xs.iter().zip(ys).map(|(p, q)| differ(p, q) || differ_in_colour(p, q)).collect();
+ let inked = xs.iter().zip(ys).filter(|(p, q)| p[3] > 8 || q[3] > 8).count();
+ let at = |i: usize, j: usize| differs.get(j * w + i).copied().unwrap_or(false);
+ let any = differs.iter().filter(|d| **d).count();
+ let solid = (1..h.saturating_sub(1))
+ .flat_map(|j| (1..w.saturating_sub(1)).map(move |i| (i, j)))
+ .filter(|&(i, j)| (j - 1..=j + 1).all(|n| (i - 1..=i + 1).all(|m| at(m, n))))
+ .count();
+ Some((any, solid, inked))
+}
+
+/// The differences from their drawn art that the live envelopes of one import may add up to, as
+/// shares of the page drawn as the page check draws it: half of what that check allows
+/// ([`MAX_DIFFERENCE`], [`MAX_SOLID_DIFFERENCE`]), so live envelopes never make the file open from
+/// its PDF part instead.
+#[derive(Debug, Default)]
+pub(super) struct Spent {
+ any: f64,
+ solid: f64,
+}
+
+/// Do `live` and `drawn` draw alike: few of the pixels either inks differ, and fewer still where a
+/// whole patch differs; and, on `page` (when the file has one), do they differ little enough that
+/// with the differences in `spent` the page check still takes the layers' art (it is added to
+/// `spent` when they do)? Both are drawn on `layer`, a layer id no other node has.
+pub(super) fn drawn_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, page: Option, spent: &mut Spent) -> bool {
+ let (Some(a), Some(b)) = (live.visual_bounds(), drawn.visual_bounds()) else { return false };
+ let region = a.union(b).inflate(2.0, 2.0);
+ if !(region.is_finite() && region.width() > 0.0 && region.height() > 0.0) || region.width().max(region.height()) > 1e6 {
+ return false;
+ }
+ let (x, y) = (alone(live, layer, shared), alone(drawn, layer, shared));
+ let Some((any, solid, inked)) = differing(&x, &y, region, compare_scale(region)) else { return false };
+ if inked == 0 {
+ return false;
+ }
+ let share = |n: usize| n as f64 / inked as f64;
+ if share(solid) > MAX_SOLID || share(any) > MAX_ANY {
+ return false;
+ }
+ let Some(page) = page.filter(|p| p.is_finite() && p.width() > 0.0 && p.height() > 0.0) else { return true };
+ // Only what is on the page counts, drawn as the page check draws it (about 400 pixels along the
+ // page's longer side).
+ let on_page = region.intersect(page);
+ let scale = compare_scale(page);
+ if on_page.width() * scale < 1.0 || on_page.height() * scale < 1.0 {
+ return true;
+ }
+ let Some((any, solid, _)) = differing(&x, &y, on_page, scale) else { return false };
+ let pixels = (page.width() * scale * page.height() * scale).max(1.0);
+ let (any, solid) = (spent.any + any as f64 / pixels, spent.solid + solid as f64 / pixels);
+ if any > MAX_DIFFERENCE / 2.0 || solid > MAX_SOLID_DIFFERENCE / 2.0 {
+ return false;
+ }
+ *spent = Spent { any, solid };
+ true
+}
diff --git a/crates/eps/src/import/ai/palette.rs b/crates/eps/src/import/ai/palette.rs
index 43955d5fc3..9a4ba72ebc 100644
--- a/crates/eps/src/import/ai/palette.rs
+++ b/crates/eps/src/import/ai/palette.rs
@@ -2,10 +2,13 @@
//! `%AI5_EndPalette`, as written in files users sent.
//!
//! - `0 0 Pb` starts the swatches and `PB` ends them.
-//! - Each swatch is its paint, then `(name) Pc`. The paint is a colour operator (`g`, `k`, `Xa`: a
-//! process colour; `x`, `Xx`: a spot colour; `Xk`: a global process colour), a gradient
-//! (`Bb` … `flag (gradient) … Bg` … `BB`) or a pattern (`(pattern) … p`). `Xs` and `Xz` paint
-//! with Registration, which every document has.
+//! - Each swatch is its paint, then an optional `(name)`, then `Pc`. The paint is a colour operator
+//! (`g`, `k`, `Xa`: a process colour; `x`, `Xx`: a spot colour; `Xk`: a global process colour), a
+//! gradient (`Bb` … `flag (gradient) … Bg` … `BB`) or a pattern (`(pattern) … p`). `Xs` and `Xz`
+//! paint with Registration, which every document has.
+//! - A swatch without a name (version 7 files write none) is named by its spot colour, gradient or
+//! pattern, or by its values as [`color_name`] gives them. `Pn` (the None swatch) and a `Pc` with
+//! no paint before it add nothing: the document has `[None]` already.
//! - `flag (name) count Pg` starts a colour group: the swatches up to the next `Pg` or `PB` are
//! its own.
//! - Newer files write the swatches between `%AI17_Begin_Content_if_version_gt` and
@@ -13,9 +16,14 @@
//! the first are read, the others skipped.
//!
//! Anything else in the section (an operator it doesn't know) is left alone: the swatches around
-//! it still come in.
+//! it still come in, and a paint before it makes no swatch.
+//!
+//! "AI7 spec": Adobe Illustrator File Format Specification, version 7.0 (1998), listed by PRONOM at
+//! https://www.nationalarchives.gov.uk/PRONOM/fmt/423; §11 documents the palette operators, and its
+//! example writes the swatches without names.
use vectorcraft_color::Color;
+use vectorcraft_doc::swatches::color_name;
use super::lex::{Lexer, Tok};
use super::obj::V;
@@ -55,9 +63,6 @@ impl Palette {
pub fn is_empty(&self) -> bool {
self.swatches.is_empty() && self.groups.iter().all(|(_, s)| s.is_empty())
}
- fn len(&self) -> usize {
- self.swatches.len() + self.groups.iter().map(|(_, s)| s.len()).sum::()
- }
}
/// The palette of `data`: what follows `%AI5_BeginPalette`, up to its end.
@@ -65,8 +70,10 @@ pub(super) fn palette(data: &[u8]) -> Palette {
let mut lex = Lexer::new(data);
let mut out = Palette::default();
let mut vals: Vec = Vec::new();
- // The paint of the swatch being read.
- let mut cell: Option = None;
+ // The paint of the swatch being read, with the name it gets when `Pc` gives none.
+ let mut cell: Option = None;
+ // How many swatches have been read.
+ let mut count = 0usize;
// Inside a gradient's `Bb` … `BB`.
let mut in_gradient = false;
// How deep in versioned content, and the depth of the block whose later alternatives (which
@@ -111,19 +118,20 @@ pub(super) fn palette(data: &[u8]) -> Palette {
}
"Bg" if in_gradient => {
if let Some(name) = last_text(&vals) {
- cell = Some(Cell::Gradient(name));
+ cell = Some(Entry { cell: Cell::Gradient(name.clone()), name });
}
}
"BB" => in_gradient = false,
- "p" => cell = first_text(&vals).map(Cell::Pattern),
+ "p" => cell = first_text(&vals).map(|name| Entry { cell: Cell::Pattern(name.clone()), name }),
"Xs" | "Xz" | "XS" | "XZ" => cell = None,
"g" | "k" | "x" | "Xa" | "Xx" | "Xk" => {
cell = paint::color_op(w, &vals).and_then(|(p, named)| match named {
- Some(Named { color, spot, .. }) => Some(Cell::Color { color, global: true, spot }),
- None => p.color().map(|color| Cell::Color { color, global: false, spot: false }),
+ Some(Named { name, color, spot, .. }) => Some(Entry { name, cell: Cell::Color { color, global: true, spot } }),
+ None => p.color().map(|color| Entry { name: color_name(color), cell: Cell::Color { color, global: false, spot: false } }),
});
}
"Pg" => {
+ cell = None;
// Capped as swatches are: a file of many `Pg` would make as many empty groups.
if let Some(name) = first_text(&vals)
&& out.groups.len() < MAX_SWATCHES
@@ -132,19 +140,27 @@ pub(super) fn palette(data: &[u8]) -> Palette {
}
}
"Pc" => {
- if let (Some(name), Some(c)) = (last_text(&vals), cell.take())
- && !name.starts_with('[')
- && out.len() < MAX_SWATCHES
+ // The name before `Pc`, or the one the paint gives; `[Registration]` and the other
+ // built-in swatches every document has are left out.
+ let name = last_text(&vals);
+ if let Some(mut e) = cell.take()
+ && !name.as_ref().is_some_and(|n| n.starts_with('['))
+ && count < MAX_SWATCHES
{
- let e = Entry { name, cell: c };
+ if let Some(name) = name {
+ e.name = name;
+ }
+ count += 1;
match out.groups.last_mut() {
Some((_, g)) => g.push(e),
None => out.swatches.push(e),
}
}
- cell = None;
}
- _ => {}
+ // A gradient's other operators (its focal point, its matrices) are part of its paint.
+ _ if in_gradient => {}
+ // Anything else ends the paint before it, which no `Pc` then makes a swatch of.
+ _ => cell = None,
}
vals.clear();
}
@@ -235,4 +251,71 @@ mod tests {
let p = palette(b"0 0 Pb\n1 2 3 Zz\n(Odd)\nPc\n(no paint) Pc\n0 0 0 1 k\n(Black)\nPc\nPB\n");
assert_eq!(p.swatches.iter().map(|e| e.name.as_str()).collect::>(), ["Black"]);
}
+
+ /// An operator it doesn't know after a paint ends that paint: the `Pc` after it makes no swatch.
+ #[test]
+ fn a_paint_before_an_unknown_operator_makes_no_swatch() {
+ let p = palette(b"0 0 Pb\n0 1 1 0 k\nZz\n(Odd)\nPc\n0.5 g\n1 (Group) 1 Pg\nPc\n0 0 0 1 k\n(Black)\nPc\nPB\n");
+ assert_eq!(p.swatches.iter().map(|e| e.name.as_str()).collect::>(), Vec::<&str>::new());
+ let groups: Vec<(&str, Vec<&str>)> = p.groups.iter().map(|(n, s)| (n.as_str(), s.iter().map(|e| e.name.as_str()).collect())).collect();
+ assert_eq!(groups, [("Group", vec!["Black"])]);
+ }
+
+ /// The palette of the AI7 spec's example (§11): `Pn`, then each swatch's paint and `Pc` with no
+ /// name, then a last `Pc`. Each swatch is named by its spot colour or gradient, or by its values;
+ /// `1 g` is white (§5.4.1).
+ #[test]
+ fn swatches_without_names_are_named_by_their_paint() {
+ let p = palette(
+ b"0 0 Pb\nPn\nPc\n1 g\nPc\n0 g\nPc\n0 0 0 0 k\nPc\n0.75 g\nPc\n\
+ Bb\n2 (B&W) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\nPc\n0.25 0 0 0 k\nPc\n\
+ 0 1 1 0 (Spot A) 0 x\nPc\n0.75 g\nPc\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\nPc\nPc\nPB\n",
+ );
+ assert!(p.groups.is_empty());
+ assert_eq!(
+ p.swatches,
+ vec![
+ color("Gray K=0", Color::gray(0.0), false, false),
+ color("Gray K=100", Color::gray(1.0), false, false),
+ color("C=0 M=0 Y=0 K=0", Color::cmyk(0.0, 0.0, 0.0, 0.0), false, false),
+ color("Gray K=25", Color::gray(0.25), false, false),
+ Entry { name: "B&W".into(), cell: Cell::Gradient("B&W".into()) },
+ color("C=25 M=0 Y=0 K=0", Color::cmyk(0.25, 0.0, 0.0, 0.0), false, false),
+ color("Spot A", Color::cmyk(0.0, 1.0, 1.0, 0.0), true, true),
+ color("Gray K=25", Color::gray(0.25), false, false),
+ Entry { name: "Dots".into(), cell: Cell::Pattern("Dots".into()) },
+ ]
+ );
+ // RGB and global process colours too.
+ let p = palette(b"0 0 Pb\n0 0 0 0 1 0.5 0 Xa\nPc\n0 0.5 1 0 1 0.5 0 (Brand) 0 1 Xk\nPc\nPB\n");
+ assert_eq!(p.swatches.iter().map(|e| e.name.as_str()).collect::>(), ["R=255 G=128 B=0", "Brand"]);
+ }
+
+ /// Named and unnamed swatches in one palette: the named ones keep their names, and built-in
+ /// swatches are still left out.
+ #[test]
+ fn named_swatches_keep_their_names_beside_unnamed_ones() {
+ let p = palette(
+ b"0 0 Pb\n1 1 1 1 ([Registration]) 0 Xs\n([Registration])\nPc\n0 0 0 1 k\n(Black)\nPc\n0 0 0 0.5 k\nPc\n\
+ 1 (Greys) 1 Pg\n0.4 g\n(Mid)\nPc\n0.4 g\nPc\nPB\n",
+ );
+ assert_eq!(p.swatches.iter().map(|e| e.name.as_str()).collect::>(), ["Black", "C=0 M=0 Y=0 K=50"]);
+ let groups: Vec<(&str, Vec<&str>)> = p.groups.iter().map(|(n, s)| (n.as_str(), s.iter().map(|e| e.name.as_str()).collect())).collect();
+ assert_eq!(groups, [("Greys", vec!["Mid", "Gray K=60"])]);
+ }
+
+ /// No more than `MAX_SWATCHES` swatches, counted across the colour groups.
+ #[test]
+ fn swatches_are_capped_across_groups() {
+ let mut data = b"0 0 Pb\n".to_vec();
+ for i in 0..MAX_SWATCHES / 1000 + 1 {
+ data.extend(format!("1 (G{i}) 1 Pg\n").as_bytes());
+ data.extend("0.5 g\nPc\n".repeat(1000).as_bytes());
+ }
+ data.extend(b"PB\n");
+ let p = palette(&data);
+ assert_eq!(p.groups.len(), MAX_SWATCHES / 1000 + 1);
+ assert_eq!(p.swatches.len() + p.groups.iter().map(|(_, s)| s.len()).sum::(), MAX_SWATCHES);
+ assert!(p.groups.last().is_some_and(|(_, s)| s.is_empty()));
+ }
}
diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs
index 8e7753dd77..cad61b7442 100644
--- a/crates/eps/src/import/ai/read.rs
+++ b/crates/eps/src/import/ai/read.rs
@@ -1,9 +1,12 @@
//! The reader: runs the editing data's operators into a document.
//!
//! - Art space has y up; the first artboard's top left corner is the document's origin.
-//! - Layers: `%AI5_BeginLayer`, `visible preview unlocked printing dimmed … colorIndex r g b …
-//! dimPercent … Lb` (ten operands in the legacy format, without the one before the colour
-//! index), `(name) Ln`, its art, `LB`.
+//! - Layers: `%AI5_BeginLayer`, `visible preview unlocked printing dimmed … colorIndex r g b
+//! template dimPercent … Lb` (ten operands in the legacy format, without the one before the
+//! colour index; see `Reader::layer_attrs`), `(name) Ln`, its art, `LB`.
+//! - Ruler guides: a straight `(N) *` guide path, directly on a layer, that runs across the whole
+//! canvas (16,383 points around the template box's centre) or from edge to edge of one artboard
+//! is a ruler guide on that layer ([`Document::guides`]); other guide paths stay paths.
//! - Groups `u` … `U`, compound paths `*u` … `*U`, clipping groups `q` … `Q` (the path painted
//! with `W` clips); a group's transparency and name follow its end.
//! - Paths: `m`, `l`/`L`, `c`/`C`, `v`/`V`, `y`/`Y`, painted by `N n F f S s B b` (lower case
@@ -15,6 +18,8 @@
//! app wrote) the bounding box.
//! - Variables: the variable library, XML nodes of the `/Document` dictionary, isn't read; a note
//! gives how many variables and data sets it has ([`VariableLibrary`]).
+//! - Objects on Path: a group whose objects' dictionaries carry ids, and a record of the
+//! `/Document` dictionary naming them, read by [`on_path`].
//! - Images: `%AI5_BeginRaster`, the colour space `XN`, `[matrix] bounds w h bits type alpha …`
//! and the samples after `XI`. 8-bit CMYK samples keep their ink amounts in a CMYK TIFF, and
//! an alpha channel that hides part of such an image becomes its opacity mask; other samples
@@ -70,6 +75,7 @@ mod art;
mod containers;
mod directives;
mod document;
+mod on_path;
mod ops;
mod types;
@@ -78,7 +84,7 @@ use art::preview_png;
pub use document::{PaletteSwatches, VariableLibrary, artboards, palette, variables};
pub(crate) use document::{slot_frame, slot_of};
pub use types::IMAGE_TOO_LARGE;
-use types::{BLEND_BUDGET, FLIP, Frame, GState, Kind, PatternHead, Place, Raster};
+use types::{BLEND_BUDGET, FLIP, Frame, GState, Kind, PatternHead, PendingEnvelope, Place, Raster};
#[cfg(test)]
pub use types::{NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED};
pub(super) use types::{blend_mode, blend_name};
@@ -115,6 +121,9 @@ pub struct Structure {
/// move, in its pixels, that places them there (the corner of the box they are written with,
/// in place of the canvas point of art space's origin).
pub placed_elsewhere: Vec<(NodeId, Affine)>,
+ /// The live envelopes read from the editing data, by id, with the drawn art each took the place
+ /// of: the importer puts that art back when the layers with the envelopes don't draw as the page.
+ pub envelopes_drawn: Vec<(NodeId, Node)>,
pub warnings: Vec,
}
@@ -145,6 +154,8 @@ struct Reader<'a> {
artboards: Vec<(String, Rect)>,
/// The variables and data sets of the `/Document` dictionary's variable library.
variables: VariableLibrary,
+ /// The Objects on Path records of the `/Document` dictionary and the ids of the objects.
+ on_path: on_path::OnPath,
gradients: HashMap,
gradient_def: Option,
instance: Option,
@@ -192,6 +203,17 @@ struct Reader<'a> {
blend_record: Option<(usize, Vec)>,
/// How many more objects blends may lay out in this import ([`super::blend::live_blend`]).
blend_budget: usize,
+ /// The group on `%_` lines an envelope's dictionary just took (see [`Reader::drop_envelope_art`]).
+ envelope_art: Option,
+ /// Envelopes waiting for their drawn art, innermost last.
+ envelopes: Vec,
+ /// How many more envelopes this import may draw to check ([`super::envelope::drawn_alike`]).
+ envelope_checks: usize,
+ /// How far the live envelopes read so far draw from their drawn art ([`super::envelope::Spent`]).
+ envelope_spent: super::envelope::Spent,
+ /// The live envelopes made so far and the drawn art each took the place of
+ /// ([`Structure::envelopes_drawn`]).
+ envelopes_drawn: Vec<(NodeId, Node)>,
/// A group just ended, its state (`Xy`, `Xd`, `XW`) not yet read.
group_ended: bool,
/// A gradient mesh just ended (`/End X!`), its own state (`Xy`) not yet read: also after its
@@ -206,6 +228,9 @@ struct Reader<'a> {
clip_fills: HashSet,
/// Groups closed as an object's drawn look (`9 () XW`).
looks: HashSet,
+ /// Straight `(N) *` guide paths painted directly on a layer, by id: their two points in art
+ /// space. [`Reader::finish`] makes the ruler guides among them guides of their layer.
+ ruler_guides: HashMap,
/// Legacy compound member groups, even when followed by the generic `9 () XW` marker.
compound_groups: HashSet,
/// Groups of a text object and its look (see [`Self::style_marker`]), which aren't a look.
@@ -274,6 +299,7 @@ impl<'a> Reader<'a> {
cropmarks: None,
artboards: Vec::new(),
variables: VariableLibrary::default(),
+ on_path: on_path::OnPath::default(),
gradients: HashMap::new(),
gradient_def: None,
instance: None,
@@ -306,8 +332,14 @@ impl<'a> Reader<'a> {
blend_roles: HashMap::new(),
blend_record: None,
blend_budget: BLEND_BUDGET,
+ envelope_art: None,
+ envelopes: Vec::new(),
+ envelope_checks: super::envelope::MAX_CHECKED,
+ envelope_spent: super::envelope::Spent::default(),
+ envelopes_drawn: Vec::new(),
clip_fills: HashSet::new(),
looks: HashSet::new(),
+ ruler_guides: HashMap::new(),
compound_groups: HashSet::new(),
text_looks: HashSet::new(),
group_ended: false,
diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs
index 3f60ebe11e..a32ea81daa 100644
--- a/crates/eps/src/import/ai/read/art.rs
+++ b/crates/eps/src/import/ai/read/art.rs
@@ -1,11 +1,12 @@
use super::containers::close;
use super::document::TEXT_SLOT;
use super::types::{
- FLIP, IMAGE_TOO_LARGE, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, Place,
+ FLIP, Frame, IMAGE_TOO_LARGE, Kind, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, MAX_SIDE, NON_NATIVE_ART,
+ NON_NATIVE_ART_UNREAD, Place,
};
use super::{
Affine, Appearance, AppearanceItem, Arc, BezPath, CANVAS_CENTRE, FillLayer, ImageBlob, ImageObject, Inks, Instance, LinkInfo, Node, NodeId,
- NodeKind, Obj, OpacityMask, Paint, PathData, Point, Reader, Rect, StrokeLayer, V, ps,
+ NodeKind, Obj, OpacityMask, Paint, PathData, PathEl, Point, Reader, Rect, StrokeLayer, V, ps,
};
impl<'a> Reader<'a> {
@@ -162,6 +163,10 @@ impl<'a> Reader<'a> {
if op.chars().next().is_some_and(|c| c.is_ascii_lowercase()) {
close(&mut bp);
}
+ let line = match bp.elements() {
+ [PathEl::MoveTo(a), PathEl::LineTo(b)] => Some((*a, *b)),
+ _ => None,
+ };
let to_doc = self.space();
let path = PathData::from_bezpath(&(to_doc * bp));
let gs = self.gs.clone();
@@ -191,6 +196,19 @@ impl<'a> Reader<'a> {
}
let kind = NodeKind::Path { path, rule: gs.rule, live: None, clipping: clip, guide };
let mut node = self.new_node(kind, &gs);
+ // A ruler guide is written as a straight `(N) *` guide path on its layer.
+ if guide
+ && op == "N"
+ && !hidden
+ && !gs.hidden
+ && !clip
+ && self.pattern.is_none()
+ && matches!(self.frames.last(), Some(Frame { kind: Kind::Layer(_), .. }))
+ && let Some((a, b)) = line
+ && [a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite())
+ {
+ self.ruler_guides.insert(node.id, (a, b));
+ }
node.appearance = Appearance { items, ..Appearance::default() }.into();
node.opacity = gs.opacity;
node.blend = gs.blend;
diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs
index 39f398a2e2..8d69d8114e 100644
--- a/crates/eps/src/import/ai/read/containers.rs
+++ b/crates/eps/src/import/ai/read/containers.rs
@@ -1,6 +1,6 @@
use super::document::slot_of;
use super::ops::{paints_apart, path_rule};
-use super::types::{Frame, GState, Kind, MAX_DEPTH, MAX_NODES};
+use super::types::{Frame, GState, Kind, MAX_DEPTH, MAX_NODES, PendingEnvelope};
use super::{AppearanceItem, Arc, BezPath, BlendMode, FillRule, HashSet, LayerColor, Node, NodeId, NodeKind, Obj, Paint, PathEl, Rc, Reader, V, obj};
impl<'a> Reader<'a> {
@@ -222,7 +222,7 @@ impl<'a> Reader<'a> {
let color = a.color.unwrap_or(LayerColor::Preset(0));
let mut layer = Node::new(
self.doc.alloc_id(),
- NodeKind::Layer { color, template: false, printable: a.printable, children, clip, preview: a.preview, dim_images: a.dim },
+ NodeKind::Layer { color, template: a.template, printable: a.printable, children, clip, preview: a.preview, dim_images: a.dim },
);
layer.name = Some(a.name.clone());
layer.visible = a.visible;
@@ -324,17 +324,30 @@ impl<'a> Reader<'a> {
"ArtDictionary" => {
let envelope = o.get("AIDeformOptionsKey").is_some();
self.art_dictionary(&o);
+ let before = self.envelope_art.take();
if envelope {
let mut slots = vec![];
for child in &children {
envelope_text_slots(child, &mut slots);
}
+ let typed = !slots.is_empty() || before.as_ref().is_some_and(has_text_slot);
for mut slot in slots {
// The editing data keeps the source text inside the envelope's options;
// its visible result is the outlined art the PDF page carries.
slot.visible = false;
self.add(slot, false)?;
}
+ // An envelope of type keeps its drawn art and its type, hidden, as above: the
+ // type is filled in after reading, which the envelope can't wait for.
+ if typed {
+ return Ok(());
+ }
+ if self.envelopes.len() >= crate::import::ai::envelope::MAX_PENDING {
+ self.warn(crate::import::ai::envelope::DRAWN);
+ } else {
+ let siblings = self.frames.last().map_or(0, |f| f.children.len());
+ self.envelopes.push(PendingEnvelope { obj: *o, before, inner: children, depth: self.frames.len(), siblings });
+ }
}
}
"Document" => self.document(&o),
@@ -467,7 +480,8 @@ impl<'a> Reader<'a> {
/// envelope's dictionary. It holds the mesh that shapes the envelope, or, while the envelope's
/// contents are being edited, those contents (the mesh then is in the dictionary); either way the
/// distorted art follows on plain lines. The source text in the contents stays, hidden, as the
- /// dictionary's does. Whether it was dropped.
+ /// dictionary's does. The group is kept in [`Reader::envelope_art`] for the envelope to be made
+ /// of. Whether it was dropped.
pub(super) fn drop_envelope_art(&mut self) -> bool {
let Some(n) = self.last_object() else { return false };
let id = n.id;
@@ -483,6 +497,7 @@ impl<'a> Reader<'a> {
slot.visible = false;
f.children.push(slot);
}
+ self.envelope_art = Some(group);
}
self.hidden_ids.remove(&id);
self.after_object = false;
@@ -543,6 +558,87 @@ impl<'a> Reader<'a> {
// The blend's own state block follows its record, as a group's follows its end.
self.after_object = true;
}
+
+ /// An envelope's plugin `XP`: the envelope whose dictionary was read last in this container
+ /// and its drawn art, the one object read since, become one live envelope, or, where they
+ /// can't, the drawn art stays (see [`crate::import::ai::envelope`]). Envelopes left waiting
+ /// in containers that closed keep their drawn art.
+ pub(super) fn end_envelope(&mut self) {
+ let depth = self.frames.len();
+ while self.envelopes.last().is_some_and(|p| p.depth > depth) {
+ self.envelopes.pop();
+ self.warn(crate::import::ai::envelope::DRAWN);
+ }
+ if self.envelopes.last().is_none_or(|p| p.depth != depth) {
+ return;
+ }
+ let Some(p) = self.envelopes.pop() else { return };
+ let drawn = self.frames.last().filter(|f| f.children.len() == p.siblings + 1).and_then(|f| f.children.last());
+ let Some(drawn) = drawn else {
+ self.warn(crate::import::ai::envelope::DRAWN);
+ return;
+ };
+ let live = (self.envelope_checks > 0).then(|| crate::import::ai::envelope::live(&p.obj, p.before, p.inner)).flatten();
+ let Some(kind) = live else {
+ self.warn(crate::import::ai::envelope::DRAWN);
+ return;
+ };
+ // Objects the reader couldn't read come in as the page's art in their place: the envelope's
+ // drawn art stays round them.
+ let mut ids = HashSet::new();
+ fn collect(n: &Node, ids: &mut HashSet) {
+ ids.insert(n.id);
+ for c in n.children().into_iter().flatten() {
+ collect(c, ids);
+ }
+ }
+ collect(drawn, &mut ids);
+ if let NodeKind::Envelope { content, .. } = &kind {
+ content.iter().for_each(|c| collect(c, &mut ids));
+ }
+ if self.unread.iter().any(|(id, _)| ids.contains(id)) {
+ self.warn(crate::import::ai::envelope::DRAWN);
+ return;
+ }
+ self.envelope_checks -= 1;
+ // The drawn art's own properties (name, visibility, lock, transparency, appearance, mask,
+ // attributes) become the envelope's.
+ let mut envelope = drawn.clone();
+ (envelope.id, envelope.kind) = (self.doc.alloc_id(), kind);
+ let layer = self.doc.alloc_id();
+ let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images };
+ let mut shown = envelope.clone();
+ (shown.visible, shown.opacity) = (true, 1.0);
+ let mut plain = drawn.clone();
+ (plain.visible, plain.opacity) = (true, 1.0);
+ let page = self.page_in_doc();
+ if !crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent) {
+ self.warn(crate::import::ai::envelope::DRAWN);
+ return;
+ }
+ // The contents are the envelope's own now, not a copy on `%_` lines.
+ fn forget(n: &Node, hidden: &mut HashSet) {
+ hidden.remove(&n.id);
+ for c in n.children().into_iter().flatten() {
+ forget(c, hidden);
+ }
+ }
+ forget(&envelope, &mut self.hidden_ids);
+ if let Some(f) = self.frames.last_mut()
+ && let Some(slot) = f.children.last_mut()
+ {
+ let id = envelope.id;
+ let drawn = std::mem::replace(slot, envelope);
+ self.envelopes_drawn.push((id, drawn));
+ }
+ }
+}
+
+/// Does `node` hold a text slot?
+fn has_text_slot(node: &Node) -> bool {
+ let mut slots = vec![];
+ envelope_text_slots(node, &mut slots);
+ !slots.is_empty()
}
/// The source text inside an envelope options dictionary, carried through its containing metadata.
diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs
index eeaf108543..0874ec0959 100644
--- a/crates/eps/src/import/ai/read/document.rs
+++ b/crates/eps/src/import/ai/read/document.rs
@@ -1,8 +1,11 @@
use super::art::{element_name, elements, join_and, sane};
use super::containers::drop_commented_copies;
use super::types::{FLIP, Kind, MAX_DEPTH};
-use super::{Affine, Artboard, ColorMode, Document, NodeKind, Obj, OpacityMask, Paint, Point, Reader, Rect, Structure, Swatch, Unit, V, obj};
-use vectorcraft_doc::{ImageBlob, PatternDef};
+use super::{
+ Affine, Arc, Artboard, CANVAS_CENTRE, ColorMode, Document, Node, NodeId, NodeKind, Obj, OpacityMask, Paint, Point, Reader, Rect, Structure,
+ Swatch, Unit, V, obj,
+};
+use vectorcraft_doc::{Guide, ImageBlob, PatternDef};
/// `%AI5_RulerUnits` → [`Unit`] (Illustrator 7 spec table 3; centimeters is 4; pixels is 6 in later files).
fn ruler_unit(v: u8) -> Option {
@@ -221,6 +224,7 @@ impl<'a> Reader<'a> {
/// An object's dictionary: its name (`AIArtName`, or the XML id `AI10_ArtUID`), and the
/// opacity mask it may carry.
pub(super) fn art_dictionary(&mut self, o: &Obj) {
+ self.constraint_art(o);
// A blend's key object or spine.
if let Some(kind) = o.text("ShapeBlendPathType")
&& let Some(id) = self.last_object().map(|n| n.id)
@@ -231,7 +235,7 @@ impl<'a> Reader<'a> {
// An envelope (a distortion, `AIDeformStyle` / `DeformValue`) is written on `%_` lines as
// a group holding the mesh that shapes it (or its contents, while they are being edited);
// the distorted art the file's PDF part draws follows on plain lines. That group isn't
- // art, so it goes (#2405).
+ // art, so it goes (#2405), kept aside for the live envelope ([`Reader::end_envelope`]).
if (o.get("AIDeformStyle").is_some() || o.get("DeformValue").is_some()) && self.drop_envelope_art() {
return;
}
@@ -275,10 +279,11 @@ impl<'a> Reader<'a> {
}
}
- /// The `/Document` dictionary: the artboards, and how many variables and data sets its variable
- /// library has.
+ /// The `/Document` dictionary: the artboards, how many variables and data sets its variable
+ /// library has, and its Objects on Path records.
pub(super) fn document(&mut self, o: &Obj) {
variable_library(o, 0, &mut self.variables);
+ self.constraint_data(o);
let Some(list) = find_entry(o, "ArtboardArray", 0) else { return };
for (i, ab) in list.items().enumerate().take(1000) {
let (p1, p2) = (ab.nums("PositionPoint1"), ab.nums("PositionPoint2"));
@@ -312,6 +317,12 @@ impl<'a> Reader<'a> {
self.artboards.first().map(|(_, r)| *r).or(self.cropmarks).or_else(|| self.sized_board())
}
+ /// The page the art is compared with in the document's space, once the art has started.
+ pub(super) fn page_in_doc(&self) -> Option |