mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-21 01:44:57 +01:00
Merge branch 'fix/trace-seam-fills-clip' of github.com:dotCooCoo/vectorcraft into fix/trace-seam-fills-clip
This commit is contained in:
commit
f3d4b0b726
360 files changed
+26446
-2730
No files matched your search
Generated
+144
-17
@@ -508,6 +508,12 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bit_field"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
@@ -981,7 +987,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e#8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e"
|
||||
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
@@ -991,7 +997,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e#8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
@@ -1033,6 +1039,36 @@ dependencies = [
|
||||
"writeable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
dependencies = [
|
||||
"craft-jpeg",
|
||||
"exr",
|
||||
"flate2",
|
||||
"half",
|
||||
"image",
|
||||
"image-webp",
|
||||
"jpeg-encoder",
|
||||
"png 0.18.1",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
"zune-core 0.5.3",
|
||||
"zune-jpeg 0.5.15",
|
||||
"zune-jpegxl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
@@ -1090,12 +1126,23 @@ dependencies = [
|
||||
"unicode-normalization",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2)",
|
||||
"flate2",
|
||||
"kurbo 0.13.1",
|
||||
"roxmltree 0.21.2",
|
||||
@@ -1105,6 +1152,15 @@ dependencies = [
|
||||
"vectorcraft-pathops 0.18.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
@@ -1203,6 +1259,15 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.3"
|
||||
@@ -1715,6 +1780,22 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "exr"
|
||||
version = "1.74.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6"
|
||||
dependencies = [
|
||||
"bit_field",
|
||||
"half",
|
||||
"lebe",
|
||||
"miniz_oxide 0.8.9",
|
||||
"multiversion",
|
||||
"rayon-core",
|
||||
"smallvec",
|
||||
"zune-inflate",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
@@ -2747,6 +2828,7 @@ dependencies = [
|
||||
"moxcms",
|
||||
"num-traits",
|
||||
"png 0.18.1",
|
||||
"qoi",
|
||||
"tiff",
|
||||
"zune-core 0.5.3",
|
||||
"zune-jpeg 0.5.15",
|
||||
@@ -3200,6 +3282,12 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
|
||||
|
||||
[[package]]
|
||||
name = "lebe"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
@@ -3399,6 +3487,28 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076"
|
||||
dependencies = [
|
||||
"multiversion-macros",
|
||||
"target-features",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion-macros"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"target-features",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion_no_op"
|
||||
version = "1.0.0"
|
||||
@@ -4349,21 +4459,21 @@ dependencies = [
|
||||
"unarray",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "psd"
|
||||
version = "0.3.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a25f9b8cfffd65d911baf31a033239f7a0facb755faa2481575b70db5dc9195"
|
||||
dependencies = [
|
||||
"thiserror 1.0.69",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pxfm"
|
||||
version = "0.1.30"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
|
||||
|
||||
[[package]]
|
||||
name = "qoi"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-error"
|
||||
version = "1.2.3"
|
||||
@@ -5734,6 +5844,12 @@ dependencies = [
|
||||
"xattr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "target-features"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5"
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
@@ -6546,6 +6662,7 @@ dependencies = [
|
||||
"chrono",
|
||||
"craft-docpath",
|
||||
"craft-proof",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"hayro-jpeg2000",
|
||||
@@ -6558,7 +6675,6 @@ dependencies = [
|
||||
"log",
|
||||
"proptest",
|
||||
"rayon",
|
||||
"roxmltree 0.21.2",
|
||||
"rustix 1.1.6",
|
||||
"ruzstd",
|
||||
"same-file",
|
||||
@@ -6734,6 +6850,7 @@ dependencies = [
|
||||
"aes",
|
||||
"chrono",
|
||||
"craft-pdf",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
"image",
|
||||
@@ -6744,7 +6861,6 @@ dependencies = [
|
||||
"md-5",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-graphics",
|
||||
"roxmltree 0.21.2",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
@@ -6785,16 +6901,16 @@ dependencies = [
|
||||
name = "vectorcraft-render"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-psd",
|
||||
"craft-tiff",
|
||||
"flate2",
|
||||
"gif 0.14.2",
|
||||
"image",
|
||||
"jpeg-encoder",
|
||||
"log",
|
||||
"png 0.18.1",
|
||||
"proptest",
|
||||
"psd",
|
||||
"serde_json",
|
||||
"tiff",
|
||||
"unicode-general-category",
|
||||
"vectorcraft-brush",
|
||||
"vectorcraft-color",
|
||||
@@ -6917,6 +7033,7 @@ dependencies = [
|
||||
name = "vectorcraft-trace"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
"serde",
|
||||
@@ -6930,6 +7047,7 @@ name = "vectorcraft-ui-egui"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"chrono",
|
||||
"craft-keymap",
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
@@ -8370,6 +8488,15 @@ version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
|
||||
|
||||
[[package]]
|
||||
name = "zune-inflate"
|
||||
version = "0.2.54"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02"
|
||||
dependencies = [
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zune-jpeg"
|
||||
version = "0.4.21"
|
||||
|
||||
+6
-1
@@ -30,9 +30,14 @@ craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
|
||||
@@ -252,11 +252,12 @@ speaks English, German, Japanese, Korean, Vietnamese, Traditional and Simplified
|
||||
The scores are self-assessed from our code against public documentation;
|
||||
[target-app-parity.md](docs/target-app-parity.md#how-this-was-measured-2026-10-10) explains how far to trust them.
|
||||
|
||||
All 57 approximated Photoshop-style raster filters are available. The Effect Gallery includes filter thumbnails and an in-dialog preview.
|
||||
|
||||
**What's missing:**
|
||||
- reliable exchange of .ai files (layer structure in real files; the editing copy a save writes keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), leaves out other objects' effects other than geometry effects, and writes live objects as their art);
|
||||
- an interaction-fidelity pass covering every tool's modifiers and small behaviours;
|
||||
- 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials);
|
||||
- filter thumbnails and a preview area inside the Effect Gallery (the gallery itself and all 57 Photoshop-style raster filters, approximated, are in);
|
||||
- CJK composition for vertical type (vertical type itself has initial support, with a Japanese interface);
|
||||
- scripting, and the rest of Variables (image and graph kinds, dataset import);
|
||||
- generative AI features.
|
||||
|
||||
+3
-2
@@ -102,14 +102,14 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta
|
||||
| Arabic | `ar` | none (no right-to-left interface) | 0% |
|
||||
| French | `fr` | full | 100% |
|
||||
| Portuguese (Brazil) | `pt-br` | full | 100% |
|
||||
| Indonesian | `id` | none | 0% |
|
||||
| Indonesian | `id` | 6,947 catalog rows; status and error messages partial | most dialogs and tooltips |
|
||||
| Japanese | `ja` | full | 100% |
|
||||
| German | `de` | full | 98% |
|
||||
| Korean | `ko` | full | 100% |
|
||||
| Bosnian | `bs` | full (AI-assisted, native review pending) | 100% |
|
||||
| Vietnamese | `vi` | full | 100% |
|
||||
|
||||
Also shipped: Traditional Chinese (partial, 80%), Bulgarian, Finnish, Greek, Hungarian, Italian, Polish, Russian, Swedish, Ukrainian and Georgian (full), Catalan (full; AI-drafted, native review welcome), Czech (catalog complete; render-site gaps reduced; native review pending).
|
||||
Also shipped: Traditional Chinese (partial, 80%), Bulgarian, Finnish, Greek, Hungarian, Italian, Polish, Russian, Swedish, Ukrainian, Georgian, Dutch, Danish and Turkish (full), Catalan (full; AI-drafted, native review welcome), Czech (catalog complete; render-site gaps reduced; native review pending).
|
||||
The Georgian catalog has had a native speaker's review; no other catalog has. Details: [localization-parity.md](docs/localization-parity.md).
|
||||
|
||||
## Upcoming
|
||||
@@ -133,6 +133,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
|
||||
- 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
|
||||
@@ -155,6 +155,12 @@ fn copied_file(paths: Vec<PathBuf>, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
copied_file_within(paths, mimes, MAX_BYTES)
|
||||
}
|
||||
|
||||
/// Whether a paste of one of `mimes` can take a copied file: one of them is not text.
|
||||
#[cfg_attr(windows, allow(dead_code))]
|
||||
fn takes_files(mimes: &[&'static str]) -> bool {
|
||||
mimes.iter().any(|&m| m != TEXT)
|
||||
}
|
||||
|
||||
/// [`copied_file`] with a file of more than `limit` bytes skipped.
|
||||
fn copied_file_within(paths: Vec<PathBuf>, mimes: &[&'static str], limit: usize) -> Option<Flavour> {
|
||||
paths.into_iter().find_map(|path| {
|
||||
@@ -727,7 +733,7 @@ mod portable {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use super::{BITMAP, ClipboardRead, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, text_of};
|
||||
use super::{BITMAP, ClipboardRead, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, takes_files, text_of};
|
||||
|
||||
/// What our last write put on the clipboard.
|
||||
#[derive(Clone)]
|
||||
@@ -741,7 +747,7 @@ mod portable {
|
||||
}
|
||||
|
||||
/// A read of arboard's clipboard.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Request {
|
||||
Text,
|
||||
Image,
|
||||
@@ -813,6 +819,19 @@ mod portable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a paste of one of `mimes` can take what `cb` holds: text that is not empty when one
|
||||
/// of `mimes` is text (`text` reads it), else files copied in a file manager when one of `mimes`
|
||||
/// is not text (`files` reads the list). The list is read only when the text doesn't do, and no
|
||||
/// copied file is opened: Paste checks the files themselves.
|
||||
fn arboard_has<B>(
|
||||
mimes: &[&'static str],
|
||||
cb: &mut B,
|
||||
text: impl FnOnce(&mut B) -> Result<String, String>,
|
||||
files: impl FnOnce(&mut B) -> Vec<PathBuf>,
|
||||
) -> bool {
|
||||
(mimes.contains(&TEXT) && text(cb).is_ok_and(|t| !t.is_empty())) || (takes_files(mimes) && !files(cb).is_empty())
|
||||
}
|
||||
|
||||
/// `request` read on `reads`' worker, waiting `wait` at most.
|
||||
#[cfg(test)]
|
||||
fn read_within(reads: &mut super::loads::Loads<Request, Answer>, request: Request, wait: Duration) -> Answer {
|
||||
@@ -1441,10 +1460,11 @@ mod portable {
|
||||
read
|
||||
}
|
||||
|
||||
/// Text, on macOS vector art or a bitmap (by the pasteboard's types), and on the Wayland
|
||||
/// core protocol copied files, SVG, text or PNG (by the types offered, nothing read).
|
||||
/// Text or files copied in a file manager (their list read, no file opened:
|
||||
/// [`arboard_has`]), on macOS vector art or a bitmap (by the pasteboard's types), and on the
|
||||
/// Wayland core protocol copied files, SVG, text or PNG (by the types offered, nothing read).
|
||||
/// arboard has no cheap way to ask for a bitmap (reading one costs as much as pasting it):
|
||||
/// the paste keys take it, the menu item waits for text.
|
||||
/// the paste keys take it, the menu item waits for text or copied files.
|
||||
fn has(&mut self, mimes: &[&'static str]) -> bool {
|
||||
#[cfg(target_os = "macos")]
|
||||
if super::mac::has(mimes) {
|
||||
@@ -1455,7 +1475,7 @@ mod portable {
|
||||
if let Backend::Wayland(wl) = cb {
|
||||
return wl.has(mimes);
|
||||
}
|
||||
mimes.contains(&TEXT) && cb.get_text().is_ok_and(|t| !t.is_empty())
|
||||
arboard_has(mimes, cb, Backend::get_text, Backend::file_list)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1619,6 +1639,40 @@ mod portable {
|
||||
assert!(Answer::Text(Ok("art.svg".into())).files().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_is_available_for_files_copied_in_a_file_manager() {
|
||||
use vectorcraft_engine::cmd::clipboard::{PASTE_ORDER, SVG};
|
||||
/// What the clipboard holds, and which reads [`arboard_has`] made.
|
||||
struct Held {
|
||||
text: Option<String>,
|
||||
files: Vec<PathBuf>,
|
||||
reads: Vec<Request>,
|
||||
}
|
||||
fn has(mimes: &[&'static str], text: Option<&str>, files: &[&str]) -> (bool, Vec<Request>) {
|
||||
let mut held = Held { text: text.map(String::from), files: files.iter().map(PathBuf::from).collect(), reads: vec![] };
|
||||
let text = |h: &mut Held| {
|
||||
h.reads.push(Request::Text);
|
||||
h.text.clone().ok_or_else(|| "no text".to_string())
|
||||
};
|
||||
let files = |h: &mut Held| {
|
||||
h.reads.push(Request::Files);
|
||||
h.files.clone()
|
||||
};
|
||||
let has = arboard_has(mimes, &mut held, text, files);
|
||||
(has, held.reads)
|
||||
}
|
||||
// Files a file manager copied, with no text: the Paste menu item is available.
|
||||
assert_eq!(has(&PASTE_ORDER, None, &["/tmp/art.svg"]), (true, vec![Request::Text, Request::Files]));
|
||||
assert_eq!(has(&PASTE_ORDER, Some(""), &["/tmp/art.svg"]), (true, vec![Request::Text, Request::Files]));
|
||||
assert_eq!(has(&[SVG], None, &["/tmp/art.svg"]), (true, vec![Request::Files]));
|
||||
// Text does, and the list is not read.
|
||||
assert_eq!(has(&PASTE_ORDER, Some("hello"), &[]), (true, vec![Request::Text]));
|
||||
// An empty list and no text: nothing to paste.
|
||||
assert_eq!(has(&PASTE_ORDER, None, &[]), (false, vec![Request::Text, Request::Files]));
|
||||
// A paste of text alone can't take copied files, and their list is not read.
|
||||
assert_eq!(has(&[TEXT], None, &["/tmp/art.svg"]), (false, vec![Request::Text]));
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn arboards_reads_run_on_its_reader_and_wait_by_kind() {
|
||||
@@ -1925,7 +1979,7 @@ mod wayland {
|
||||
use wayland_client::{Connection, Dispatch, Proxy, QueueHandle, WEnum};
|
||||
|
||||
use super::loads::{Asker, GONE, LOAD_WAIT, Loads, wait_for_answer};
|
||||
use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, uri_list_paths};
|
||||
use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, takes_files, uri_list_paths};
|
||||
|
||||
/// The types text is offered under and read from, best first: `text/plain;charset=utf-8` (GTK
|
||||
/// and Qt apps), `UTF8_STRING` (X11 apps through XWayland) and `text/plain`.
|
||||
@@ -2016,11 +2070,6 @@ mod wayland {
|
||||
Some(first)
|
||||
}
|
||||
|
||||
/// Whether a paste of one of `mimes` can take a copied file: one of them is not text.
|
||||
fn takes_files(mimes: &[&'static str]) -> bool {
|
||||
mimes.iter().any(|&m| m != TEXT)
|
||||
}
|
||||
|
||||
/// The first type among `offered` that lists copied files ([`FILE_LISTS`]), in any letter case.
|
||||
fn file_list_type(offered: &[String]) -> Option<&str> {
|
||||
FILE_LISTS.iter().find_map(|(list, _)| offered.iter().find(|o| o.eq_ignore_ascii_case(list))).map(String::as_str)
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! VectorCraft desktop app.
|
||||
//!
|
||||
//! Usage: `vectorcraft [--control <port> [--automation-read-root <dir>]... [--automation-write-root <dir>]...]
|
||||
//! [--in-window-menus] [--new-instance] [--safe-mode] [--] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`)
|
||||
//! [--in-window-menus] [--new-instance] [--safe-mode] [--present-mode <mode>] [--frame-latency <frames>] [--] [files…]`,
|
||||
//! `vectorcraft --version`, `vectorcraft --help` (or `-h`)
|
||||
//!
|
||||
//! Any other argument starting with '-' (not `-` alone) is an error; after `--`, every argument is
|
||||
//! a file.
|
||||
@@ -19,6 +20,9 @@
|
||||
//! `--automation-write-root` (or `VECTORCRAFT_AUTOMATION_READ_ROOT` / `_WRITE_ROOT`) confine the
|
||||
//! files its requests read and write (`vectorcraft_engine::file_access`); the person at the
|
||||
//! keyboard isn't confined.
|
||||
//!
|
||||
//! `--present-mode` and `--frame-latency` (or `VECTORCRAFT_PRESENT_MODE` / `_FRAME_LATENCY`) change
|
||||
//! how the window's frames reach the display (`presentation`).
|
||||
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
|
||||
|
||||
mod automation_args;
|
||||
@@ -59,6 +63,7 @@ mod portal_request;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd", test))]
|
||||
mod portal_save;
|
||||
mod prefs_dir;
|
||||
mod presentation;
|
||||
mod printing;
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
mod quit_windows;
|
||||
@@ -158,6 +163,14 @@ Options:
|
||||
--safe-mode Start without plug-ins: none loads or runs until
|
||||
VectorCraft starts normally (Help › Safe Mode); the
|
||||
files open in a new window, as with --new-instance
|
||||
--present-mode <mode> How frames reach the display: fifo (vsync),
|
||||
autovsync (the default; relaxed vsync where the
|
||||
driver offers it) or novsync
|
||||
(or VECTORCRAFT_PRESENT_MODE)
|
||||
--frame-latency <frames> Frames the display may queue, 1 to 3 (the default
|
||||
is 1) (or VECTORCRAFT_FRAME_LATENCY); with either
|
||||
one set, the files open in a new window, as with
|
||||
--new-instance
|
||||
--version Print the version and exit
|
||||
-h, --help Print this help and exit
|
||||
-- Treat every argument after it as a file
|
||||
@@ -177,13 +190,16 @@ struct CommandLine {
|
||||
safe_mode: bool,
|
||||
}
|
||||
|
||||
/// Reads the arguments after the program name. The automation roots and the control port go into
|
||||
/// `roots_args` and `control`. `Err` is the exit code when the process ends here: `--version` and
|
||||
/// `--help` print and succeed; a bad automation option or an unknown option prints an error and fails.
|
||||
/// Reads the arguments after the program name. The automation roots, the control port and the
|
||||
/// presentation overrides (with `VECTORCRAFT_PRESENT_MODE` and `VECTORCRAFT_FRAME_LATENCY` filling
|
||||
/// what the flags leave unset) go into `roots_args`, `control` and `presentation`. `Err` is the exit code
|
||||
/// when the process ends here: `--version` and `--help` print and succeed; a bad automation or
|
||||
/// presentation option or an unknown option prints an error and fails.
|
||||
fn read_command_line(
|
||||
mut args: impl Iterator<Item = String>,
|
||||
control: &mut automation_args::ControlArg,
|
||||
roots_args: &mut automation_args::AutomationArgs,
|
||||
presentation: &mut presentation::Overrides,
|
||||
) -> Result<CommandLine, std::process::ExitCode> {
|
||||
let mut files = Vec::new();
|
||||
let mut in_window_menus = std::env::var_os("VECTORCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0");
|
||||
@@ -196,7 +212,11 @@ fn read_command_line(
|
||||
files.extend(args.by_ref());
|
||||
break;
|
||||
}
|
||||
match roots_args.consume(&a, &mut args).and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) }) {
|
||||
match roots_args
|
||||
.consume(&a, &mut args)
|
||||
.and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) })
|
||||
.and_then(|taken| if taken { Ok(true) } else { presentation.consume(&a, &mut args) })
|
||||
{
|
||||
Ok(true) => continue,
|
||||
Ok(false) => {}
|
||||
Err(e) => {
|
||||
@@ -235,6 +255,14 @@ fn read_command_line(
|
||||
eprintln!("vectorcraft: unknown option {a}; see vectorcraft --help, or put -- before a file whose name starts with '-'");
|
||||
return Err(std::process::ExitCode::FAILURE);
|
||||
}
|
||||
// After the arguments: the flags, `--version` and `--help` win over a bad environment value.
|
||||
match presentation.with_env(std::env::var_os("VECTORCRAFT_PRESENT_MODE"), std::env::var_os("VECTORCRAFT_FRAME_LATENCY")) {
|
||||
Ok(overrides) => *presentation = overrides,
|
||||
Err(e) => {
|
||||
eprintln!("vectorcraft: {e}");
|
||||
return Err(std::process::ExitCode::FAILURE);
|
||||
}
|
||||
}
|
||||
Ok(CommandLine { files, in_window_menus, new_instance, safe_mode })
|
||||
}
|
||||
|
||||
@@ -253,8 +281,9 @@ fn main() -> std::process::ExitCode {
|
||||
let root_env = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty()).map(std::path::PathBuf::from);
|
||||
let mut roots_args =
|
||||
automation_args::AutomationArgs::new(root_env("VECTORCRAFT_AUTOMATION_READ_ROOT"), root_env("VECTORCRAFT_AUTOMATION_WRITE_ROOT"));
|
||||
let mut presentation = presentation::Overrides::default();
|
||||
let CommandLine { files, in_window_menus, new_instance, safe_mode: safe_mode_flag } =
|
||||
match read_command_line(std::env::args().skip(1), &mut control, &mut roots_args) {
|
||||
match read_command_line(std::env::args().skip(1), &mut control, &mut roots_args, &mut presentation) {
|
||||
Ok(command_line) => command_line,
|
||||
Err(code) => return code,
|
||||
};
|
||||
@@ -275,7 +304,8 @@ fn main() -> std::process::ExitCode {
|
||||
// Files opened from the file manager while VectorCraft runs open in its window (#4892). Before
|
||||
// the log file is attached: a launch that hands its files over leaves the running app's log be.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
match single_instance::start(control_port.is_some(), new_instance, safe_mode_flag, &files) {
|
||||
// A launch that sets the presentation runs as its own app: a running app keeps its own surface.
|
||||
match single_instance::start(control_port.is_some(), new_instance || presentation.is_set(), safe_mode_flag, &files) {
|
||||
single_instance::Start::Forwarded => return std::process::ExitCode::SUCCESS,
|
||||
single_instance::Start::Running(primary) => single_instance::hold(primary),
|
||||
}
|
||||
@@ -427,7 +457,10 @@ fn main() -> std::process::ExitCode {
|
||||
let mut options = options;
|
||||
// One frame queued, not two: the canvas is rasterized on the CPU and the GPU only
|
||||
// composites it, so the window answers the pointer a frame sooner (#444).
|
||||
options.wgpu_options.surface = eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY;
|
||||
// `--present-mode` and `--frame-latency` change it for a launch (`presentation`).
|
||||
options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY);
|
||||
// What the app asks for: the driver picks novsync's mode and may clamp the latency.
|
||||
log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation));
|
||||
// Only adapters that can show the window, in the order `gpu` gives (#306, #502).
|
||||
if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
|
||||
create.native_adapter_selector = Some(gpu::selector(power, displays, compositor, left_out.adapters.clone(), startup.clone()));
|
||||
@@ -458,6 +491,10 @@ fn main() -> std::process::ExitCode {
|
||||
}
|
||||
options
|
||||
};
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
if presentation != presentation::Overrides::default() {
|
||||
log::warn!("--present-mode and --frame-latency set the wgpu renderer's window surface: ignored without it");
|
||||
}
|
||||
#[cfg(feature = "wgpu")]
|
||||
gpu::watch_panics();
|
||||
#[cfg(feature = "wgpu")]
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
//! `--present-mode <mode>` (or `VECTORCRAFT_PRESENT_MODE`) and `--frame-latency <frames>` (or
|
||||
//! `VECTORCRAFT_FRAME_LATENCY`) set how the window's frames reach the display for one launch. The
|
||||
//! modes are `fifo` (vsync), `autovsync` (the default: wgpu picks relaxed vsync, which tears a late
|
||||
//! frame, else vsync, by what the driver offers) and `novsync` (wgpu picks Immediate, else Mailbox,
|
||||
//! else Fifo). A mode the driver may not offer is never requested. The latency is the number of
|
||||
//! frames the swap chain may queue, 1 to 3. Unset, the app keeps its own surface settings. A flag
|
||||
//! overrides its variable; a value that isn't one of these stops the app with a message, as
|
||||
//! `--control` does. A launch that sets either one runs as its own app, as with `--new-instance`.
|
||||
//! The surface the app asks for is logged at start-up.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
/// A present mode the command line or the environment can ask for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
Fifo,
|
||||
AutoVsync,
|
||||
NoVsync,
|
||||
}
|
||||
|
||||
/// The present mode and frame latency this launch asked for (`None`: the app's own setting).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Overrides {
|
||||
pub mode: Option<Mode>,
|
||||
pub latency: Option<u32>,
|
||||
}
|
||||
|
||||
/// A present mode named by `name` (the flag or the variable): `fifo`, `autovsync` or `novsync`, any case.
|
||||
fn mode(name: &str, value: Option<&str>) -> Result<Mode, String> {
|
||||
let need = format!("{name} needs fifo, autovsync or novsync");
|
||||
let Some(v) = value else { return Err(need) };
|
||||
match v.trim().to_ascii_lowercase().as_str() {
|
||||
"fifo" => Ok(Mode::Fifo),
|
||||
"autovsync" => Ok(Mode::AutoVsync),
|
||||
"novsync" => Ok(Mode::NoVsync),
|
||||
_ => Err(format!("{need}, not `{v}`")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame latency named by `name`: 1, 2 or 3.
|
||||
fn latency(name: &str, value: Option<&str>) -> Result<u32, String> {
|
||||
let need = format!("{name} needs 1, 2 or 3 frames");
|
||||
let Some(v) = value else { return Err(need) };
|
||||
v.trim().parse().ok().filter(|n| (1..=3).contains(n)).ok_or(format!("{need}, not `{v}`"))
|
||||
}
|
||||
|
||||
/// The value of `--flag <value>` or `--flag=<value>` when `arg` is that flag; `None` when it isn't.
|
||||
fn flag_value(flag: &str, arg: &str, args: &mut impl Iterator<Item = String>) -> Option<Option<String>> {
|
||||
match arg.strip_prefix(flag)? {
|
||||
"" => Some(args.next()),
|
||||
rest => rest.strip_prefix('=').map(|v| Some(v.to_owned())),
|
||||
}
|
||||
}
|
||||
|
||||
impl Overrides {
|
||||
/// Whether a flag or a variable set the present mode or the frame latency.
|
||||
pub fn is_set(&self) -> bool {
|
||||
*self != Self::default()
|
||||
}
|
||||
|
||||
/// Returns whether this argument is `--present-mode` or `--frame-latency`. The next argument is
|
||||
/// its value whatever it is, as with `--control`.
|
||||
pub fn consume(&mut self, arg: &str, args: &mut impl Iterator<Item = String>) -> Result<bool, String> {
|
||||
if let Some(value) = flag_value("--present-mode", arg, args) {
|
||||
if self.mode.is_some() {
|
||||
return Err("--present-mode given twice".into());
|
||||
}
|
||||
self.mode = Some(mode("--present-mode", value.as_deref())?);
|
||||
return Ok(true);
|
||||
}
|
||||
if let Some(value) = flag_value("--frame-latency", arg, args) {
|
||||
if self.latency.is_some() {
|
||||
return Err("--frame-latency given twice".into());
|
||||
}
|
||||
self.latency = Some(latency("--frame-latency", value.as_deref())?);
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Fills what the flags left unset from `VECTORCRAFT_PRESENT_MODE` and `VECTORCRAFT_FRAME_LATENCY`.
|
||||
/// Unset or empty is no override; a variable is not read when its flag was given.
|
||||
pub fn with_env(self, mode_var: Option<OsString>, latency_var: Option<OsString>) -> Result<Self, String> {
|
||||
let set = |v: Option<OsString>| v.filter(|v| !v.is_empty()).map(|v| v.to_string_lossy().into_owned());
|
||||
let mode = match (self.mode, set(mode_var)) {
|
||||
(Some(m), _) => Some(m),
|
||||
(None, Some(v)) => Some(mode("VECTORCRAFT_PRESENT_MODE", Some(&v))?),
|
||||
(None, None) => None,
|
||||
};
|
||||
let latency = match (self.latency, set(latency_var)) {
|
||||
(Some(n), _) => Some(n),
|
||||
(None, Some(v)) => Some(latency("VECTORCRAFT_FRAME_LATENCY", Some(&v))?),
|
||||
(None, None) => None,
|
||||
};
|
||||
Ok(Self { mode, latency })
|
||||
}
|
||||
|
||||
/// `surface` with the overrides applied.
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig) -> eframe::egui_wgpu::SurfaceConfig {
|
||||
use eframe::wgpu::PresentMode;
|
||||
let present_mode = match self.mode {
|
||||
Some(Mode::Fifo) => PresentMode::Fifo,
|
||||
Some(Mode::AutoVsync) => PresentMode::AutoVsync,
|
||||
Some(Mode::NoVsync) => PresentMode::AutoNoVsync,
|
||||
None => surface.present_mode,
|
||||
};
|
||||
eframe::egui_wgpu::SurfaceConfig { present_mode, desired_maximum_frame_latency: self.latency.or(surface.desired_maximum_frame_latency) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The present mode and frame latency `surface` asks for, for the start-up log:
|
||||
/// "autovsync, frame latency 1", with "(override)"
|
||||
/// after a value a flag or variable set.
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides) -> String {
|
||||
use eframe::wgpu::PresentMode;
|
||||
let mode = match surface.present_mode {
|
||||
PresentMode::AutoVsync => "autovsync",
|
||||
PresentMode::AutoNoVsync => "novsync",
|
||||
PresentMode::Fifo => "fifo",
|
||||
PresentMode::FifoRelaxed => "fiforelaxed",
|
||||
PresentMode::Immediate => "immediate",
|
||||
PresentMode::Mailbox => "mailbox",
|
||||
};
|
||||
let latency = surface.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string());
|
||||
let tag = |set: bool| if set { " (override)" } else { "" };
|
||||
format!("{mode}{}, frame latency {latency}{}", tag(overrides.mode.is_some()), tag(overrides.latency.is_some()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse(args: &[&str]) -> Result<Overrides, String> {
|
||||
let mut overrides = Overrides::default();
|
||||
let mut args = args.iter().map(|a| a.to_string());
|
||||
while let Some(a) = args.next() {
|
||||
assert!(overrides.consume(&a, &mut args)?, "{a}");
|
||||
}
|
||||
Ok(overrides)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_take_the_three_modes_and_latencies_from_1_to_3() {
|
||||
assert_eq!(parse(&[]), Ok(Overrides::default()));
|
||||
assert_eq!(parse(&["--present-mode", "fifo"]).map(|o| o.mode), Ok(Some(Mode::Fifo)));
|
||||
assert_eq!(parse(&["--present-mode=AutoVsync"]).map(|o| o.mode), Ok(Some(Mode::AutoVsync)));
|
||||
assert_eq!(parse(&["--present-mode", " novsync "]).map(|o| o.mode), Ok(Some(Mode::NoVsync)));
|
||||
for n in 1..=3 {
|
||||
assert_eq!(parse(&["--frame-latency", &n.to_string()]).map(|o| o.latency), Ok(Some(n)));
|
||||
}
|
||||
assert_eq!(parse(&["--frame-latency=2", "--present-mode", "fifo"]), Ok(Overrides { mode: Some(Mode::Fifo), latency: Some(2) }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_flag_values_are_errors() {
|
||||
let modes = "--present-mode needs fifo, autovsync or novsync";
|
||||
assert_eq!(parse(&["--present-mode"]), Err(modes.into()));
|
||||
for bad in ["mailbox", "immediate", "vsync", "fast", ""] {
|
||||
assert_eq!(parse(&["--present-mode", bad]), Err(format!("{modes}, not `{bad}`")));
|
||||
assert_eq!(parse(&[&format!("--present-mode={bad}")]), Err(format!("{modes}, not `{bad}`")));
|
||||
}
|
||||
assert_eq!(parse(&["--present-mode", "--frame-latency"]), Err(format!("{modes}, not `--frame-latency`")));
|
||||
let frames = "--frame-latency needs 1, 2 or 3 frames";
|
||||
assert_eq!(parse(&["--frame-latency"]), Err(frames.into()));
|
||||
for bad in ["0", "4", "-1", "one", "1.5", "99999999999", ""] {
|
||||
assert_eq!(parse(&["--frame-latency", bad]), Err(format!("{frames}, not `{bad}`")));
|
||||
}
|
||||
assert_eq!(parse(&["--present-mode", "fifo", "--present-mode=novsync"]), Err("--present-mode given twice".into()));
|
||||
assert_eq!(parse(&["--frame-latency=1", "--frame-latency", "2"]), Err("--frame-latency given twice".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_arguments_are_not_presentation_flags() {
|
||||
let mut overrides = Overrides::default();
|
||||
let mut args = ["fifo".to_owned()].into_iter();
|
||||
for other in ["--present-modes", "--present", "--frame-latency-2", "drawing.svg", "--control"] {
|
||||
assert!(!overrides.consume(other, &mut args).unwrap(), "{other}");
|
||||
}
|
||||
assert_eq!(args.next().as_deref(), Some("fifo"));
|
||||
assert_eq!(overrides, Overrides::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variables_fill_what_the_flags_leave_unset_and_bad_values_are_errors() {
|
||||
let none = Overrides::default();
|
||||
assert_eq!(none.with_env(None, None), Ok(none));
|
||||
assert_eq!(none.with_env(Some("".into()), Some("".into())), Ok(none));
|
||||
assert_eq!(none.with_env(Some("FIFO".into()), Some("2".into())), Ok(Overrides { mode: Some(Mode::Fifo), latency: Some(2) }));
|
||||
assert_eq!(
|
||||
none.with_env(Some("mailbox".into()), None),
|
||||
Err("VECTORCRAFT_PRESENT_MODE needs fifo, autovsync or novsync, not `mailbox`".into())
|
||||
);
|
||||
assert_eq!(none.with_env(None, Some("0".into())), Err("VECTORCRAFT_FRAME_LATENCY needs 1, 2 or 3 frames, not `0`".into()));
|
||||
// A flag wins, and its variable is not read, so a bad value there doesn't stop the app.
|
||||
let flags = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) };
|
||||
assert_eq!(flags.with_env(Some("bad".into()), Some("9".into())), Ok(flags));
|
||||
let mode_only = Overrides { mode: Some(Mode::AutoVsync), latency: None };
|
||||
assert_eq!(mode_only.with_env(Some("bad".into()), Some("1".into())), Ok(Overrides { mode: Some(Mode::AutoVsync), latency: Some(1) }));
|
||||
// Either value set makes the launch run as its own app.
|
||||
assert!(!none.is_set());
|
||||
assert!(mode_only.is_set());
|
||||
assert!(Overrides { mode: None, latency: Some(1) }.is_set());
|
||||
}
|
||||
|
||||
/// `--help` states the app's own surface as the default, so it changes with it.
|
||||
#[cfg(feature = "wgpu")]
|
||||
#[test]
|
||||
fn the_usage_names_the_app_surface_as_the_default() {
|
||||
let app = eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY;
|
||||
let usage = crate::USAGE.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
assert_eq!(app.present_mode, eframe::wgpu::PresentMode::AutoVsync, "the usage calls autovsync the default");
|
||||
assert!(usage.contains("autovsync (the default"), "{usage}");
|
||||
let Some(frames) = app.desired_maximum_frame_latency else { panic!("the usage gives a default frame latency") };
|
||||
assert!(usage.contains(&format!("(the default is {frames})")), "{usage}");
|
||||
}
|
||||
|
||||
#[cfg(feature = "wgpu")]
|
||||
#[test]
|
||||
fn overrides_change_only_what_they_set_on_the_app_surface() {
|
||||
use eframe::egui_wgpu::SurfaceConfig;
|
||||
use eframe::wgpu::PresentMode;
|
||||
let app = SurfaceConfig::LOW_LATENCY;
|
||||
// No override: the surface the app asks for is unchanged.
|
||||
assert_eq!(Overrides::default().apply(app), app);
|
||||
let latency = Overrides { mode: None, latency: Some(2) };
|
||||
let s = latency.apply(app);
|
||||
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoVsync, Some(2)));
|
||||
assert_eq!(describe(&s, &latency), "autovsync, frame latency 2 (override)");
|
||||
let fifo = Overrides { mode: Some(Mode::Fifo), latency: None };
|
||||
let s = fifo.apply(app);
|
||||
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::Fifo, app.desired_maximum_frame_latency));
|
||||
// Never a mode the driver may lack: no vsync lets wgpu fall back by support.
|
||||
let novsync = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) };
|
||||
let s = novsync.apply(app);
|
||||
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(3)));
|
||||
assert_eq!(describe(&s, &novsync), "novsync (override), frame latency 3 (override)");
|
||||
let unset = SurfaceConfig { present_mode: PresentMode::Fifo, desired_maximum_frame_latency: None };
|
||||
assert_eq!(describe(&unset, &Overrides::default()), "fifo, frame latency default");
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,17 @@ fn prints_usage(args: &[&str], env: &[(&str, &str)]) {
|
||||
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(out.stderr.is_empty(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(stdout.starts_with("Usage: vectorcraft "), "{args:?}: {stdout}");
|
||||
for flag in ["--control", "--automation-read-root", "--automation-write-root", "--in-window-menus", "--safe-mode", "--version", "--help"] {
|
||||
for flag in [
|
||||
"--control",
|
||||
"--automation-read-root",
|
||||
"--automation-write-root",
|
||||
"--in-window-menus",
|
||||
"--safe-mode",
|
||||
"--present-mode",
|
||||
"--frame-latency",
|
||||
"--version",
|
||||
"--help",
|
||||
] {
|
||||
assert!(stdout.contains(flag), "{args:?}: usage doesn't mention {flag}: {stdout}");
|
||||
}
|
||||
// Headless work is the CLI's: the usage says where to go.
|
||||
@@ -73,6 +83,32 @@ fn help_wins_over_a_bad_control_port_variable() {
|
||||
prints_usage(&["--help"], &[("VECTORCRAFT_CONTROL_PORT", "abc")]);
|
||||
}
|
||||
|
||||
/// A bad presentation variable stops the app with a message before it starts; `--help` and the
|
||||
/// matching flag win over it. A run that gets past it stops at the control port `run` makes fail.
|
||||
#[test]
|
||||
fn a_bad_presentation_variable_is_an_error_unless_help_or_its_flag_is_given() {
|
||||
for (var, value, need) in [
|
||||
("VECTORCRAFT_FRAME_LATENCY", "0", "needs 1, 2 or 3 frames, not `0`"),
|
||||
("VECTORCRAFT_PRESENT_MODE", "mailbox", "needs fifo, autovsync or novsync, not `mailbox`"),
|
||||
] {
|
||||
let out = run(&[], &[(var, value)]);
|
||||
assert!(!out.status.success(), "{var}");
|
||||
assert_eq!(String::from_utf8(out.stderr).unwrap(), format!("vectorcraft: {var} {need}\n"));
|
||||
prints_usage(&["--help"], &[(var, value)]);
|
||||
}
|
||||
for (args, env) in [
|
||||
(&["--frame-latency", "2"][..], ("VECTORCRAFT_FRAME_LATENCY", "0")),
|
||||
(&["--present-mode=fifo"], ("VECTORCRAFT_PRESENT_MODE", "mailbox")),
|
||||
(&[], ("VECTORCRAFT_FRAME_LATENCY", "3")),
|
||||
] {
|
||||
let stderr = String::from_utf8(run(args, &[env]).stderr).unwrap();
|
||||
assert!(stderr.contains("VECTORCRAFT_CONTROL_PORT") && !stderr.contains(env.0), "{args:?}: {stderr}");
|
||||
}
|
||||
let out = run(&["--frame-latency", "4"], &[]);
|
||||
assert!(!out.status.success());
|
||||
assert_eq!(String::from_utf8(out.stderr).unwrap(), "vectorcraft: --frame-latency needs 1, 2 or 3 frames, not `4`\n");
|
||||
}
|
||||
|
||||
/// An option the app doesn't know (a typo of `--safe-mode`) is an error, not a file to open with
|
||||
/// plug-ins; a later `--help` still wins.
|
||||
#[test]
|
||||
|
||||
@@ -3,7 +3,7 @@ name = "vectorcraft-cad"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "VectorCraft CAD interchange: a hand-written ASCII DXF writer (R12 to 2018) and an HP-GL/2 plot file reader and writer"
|
||||
description = "VectorCraft CAD interchange: DXF export through craft-dxf and an HP-GL/2 plot file reader and writer"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
+19
-4
@@ -1,4 +1,4 @@
|
||||
//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and a reader on
|
||||
//! CAD interchange: a DXF writer (versions R12 to 2018) on `craft_dxf::drawing` and a reader on
|
||||
//! `craft_dxf::model`, and an HP-GL/2 plot file reader and writer.
|
||||
//!
|
||||
//! [`export`] writes the visible art of a document into one DXF drawing: each layer becomes a DXF
|
||||
@@ -15,7 +15,7 @@
|
||||
//! [`hpgl::import`] reads an HP-GL plotter file, and [`hpgl::export`] writes one: see [`hpgl`].
|
||||
//!
|
||||
//! - `aci`: the 256-colour index palette and the nearest index of a colour.
|
||||
//! - `writer`: group codes, handles and the file's sections, tables and objects.
|
||||
//! - The ASCII file around those entities is written by `craft_dxf::drawing`.
|
||||
//! - `scene`: the document walk that turns objects into entities.
|
||||
//! - `import`: the reader, entities to art, blocks to symbols.
|
||||
//! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves.
|
||||
@@ -24,7 +24,6 @@ mod aci;
|
||||
pub mod hpgl;
|
||||
pub mod import;
|
||||
mod scene;
|
||||
mod writer;
|
||||
|
||||
use vectorcraft_doc::{Document, Unit};
|
||||
use vectorcraft_geom::Rect;
|
||||
@@ -136,11 +135,27 @@ impl DxfVersion {
|
||||
self >= Self::R2004
|
||||
}
|
||||
/// Text is UTF-8 (earlier versions escape what isn't ASCII as `\U+XXXX`).
|
||||
fn utf8(self) -> bool {
|
||||
pub fn utf8(self) -> bool {
|
||||
self >= Self::R2007
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DxfVersion> for craft_dxf::drawing::Format {
|
||||
fn from(v: DxfVersion) -> Self {
|
||||
match v {
|
||||
DxfVersion::R12 => Self::R12,
|
||||
DxfVersion::R13 => Self::R13,
|
||||
DxfVersion::R14 => Self::R14,
|
||||
DxfVersion::R2000 => Self::R2000,
|
||||
DxfVersion::R2004 => Self::R2004,
|
||||
DxfVersion::R2007 => Self::R2007,
|
||||
DxfVersion::R2010 => Self::R2010,
|
||||
DxfVersion::R2013 => Self::R2013,
|
||||
DxfVersion::R2018 => Self::R2018,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many colours entities may use: indexed colours of the 256-colour palette, or true colour
|
||||
/// (with the nearest index for apps that read only the index).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
|
||||
@@ -14,8 +14,8 @@ use vectorcraft_effects::stroke;
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Vec2};
|
||||
|
||||
use crate::aci::nearest_aci;
|
||||
use crate::writer::{Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, fixed};
|
||||
use crate::{CAP_HEIGHT, ColorDepth, DxfImage, DxfOptions, DxfOutput, MAX_NEST, Preserve, RasterFormat};
|
||||
use craft_dxf::drawing::{Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, STANDARD_STYLE, fixed};
|
||||
|
||||
/// Curves are flattened to within this distance (points) where DXF needs straight segments
|
||||
/// (hatch boundaries, R12 polylines).
|
||||
@@ -543,7 +543,7 @@ impl<'a> Scene<'a> {
|
||||
o,
|
||||
to_dxf: Affine::new([k, 0.0, 0.0, -k, -r.x0 * k, r.y1 * k]),
|
||||
k,
|
||||
e: Codes::new(o.version),
|
||||
e: Codes::new(o.version.into()),
|
||||
next: fixed::FIRST_FREE,
|
||||
layers: vec![],
|
||||
layer_names: Names::with(&["0", "Defpoints"]),
|
||||
@@ -551,7 +551,7 @@ impl<'a> Scene<'a> {
|
||||
flags: LayerFlags { off: false, locked: false, plot: true },
|
||||
linetypes: vec![],
|
||||
styles: vec![],
|
||||
style_names: Names::with(&[crate::writer::STANDARD_STYLE]),
|
||||
style_names: Names::with(&[STANDARD_STYLE]),
|
||||
images: vec![],
|
||||
files: vec![],
|
||||
by_key: HashMap::new(),
|
||||
@@ -579,7 +579,7 @@ impl<'a> Scene<'a> {
|
||||
let one = (self.o.scale - 1.0).abs() < 1e-12;
|
||||
let insunits = if one { crate::insunits_code(self.o.unit).unwrap_or(0) } else { 0 };
|
||||
let drawing = Drawing {
|
||||
version: self.o.version,
|
||||
version: self.o.version.into(),
|
||||
layers: self.layers,
|
||||
linetypes: self.linetypes,
|
||||
styles: self.styles,
|
||||
|
||||
@@ -1451,3 +1451,23 @@ fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() {
|
||||
assert!(entities(&out).is_empty());
|
||||
assert!(out.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", out.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_bytes_match_shared_writer_goldens() {
|
||||
use std::path::PathBuf;
|
||||
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data");
|
||||
let cases: [(&str, DxfVersion, Document); 2] =
|
||||
[("shapes_r12.dxf", DxfVersion::R12, shapes_doc()), ("shapes_r2018.dxf", DxfVersion::R2018, shapes_doc())];
|
||||
for (name, version, doc) in cases {
|
||||
let out = export(&doc, &DxfOptions { version, ..opts(&doc) }).unwrap();
|
||||
let got = std::str::from_utf8(&out.bytes).expect("UTF-8 DXF");
|
||||
let path = dir.join(name);
|
||||
if std::env::var_os("WRITE_DXF_GOLDENS").is_some() {
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(&path, got).unwrap();
|
||||
continue;
|
||||
}
|
||||
let expected = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
|
||||
assert_eq!(got, expected, "DXF bytes changed versus {}", path.display());
|
||||
}
|
||||
}
|
||||
@@ -1,674 +0,0 @@
|
||||
//! The ASCII DXF file: group codes, handles, and the sections, tables and objects around the
|
||||
//! entities. DXF R13 and later give every object a handle and subclass markers; R2000 and later
|
||||
//! add layouts and plot styles, which CAD apps expect to find.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use crate::DxfVersion;
|
||||
|
||||
/// An object handle (written in hex).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Handle(pub u32);
|
||||
|
||||
/// The handles of the fixed objects every drawing has. Entities and table entries count up from
|
||||
/// [`FIRST_FREE`].
|
||||
pub(crate) mod fixed {
|
||||
use super::Handle;
|
||||
pub const LAYER_TABLE: Handle = Handle(0x1);
|
||||
pub const LTYPE_TABLE: Handle = Handle(0x2);
|
||||
pub const APPID_TABLE: Handle = Handle(0x3);
|
||||
pub const DIMSTYLE_TABLE: Handle = Handle(0x4);
|
||||
pub const STYLE_TABLE: Handle = Handle(0x5);
|
||||
pub const UCS_TABLE: Handle = Handle(0x6);
|
||||
pub const VIEW_TABLE: Handle = Handle(0x7);
|
||||
pub const VPORT_TABLE: Handle = Handle(0x8);
|
||||
pub const BLOCK_RECORD_TABLE: Handle = Handle(0x9);
|
||||
pub const ROOT: Handle = Handle(0xA);
|
||||
pub const GROUPS: Handle = Handle(0xB);
|
||||
pub const LAYOUTS: Handle = Handle(0xC);
|
||||
pub const MODEL_RECORD: Handle = Handle(0xD);
|
||||
pub const PAPER_RECORD: Handle = Handle(0xE);
|
||||
pub const MODEL_BLOCK: Handle = Handle(0xF);
|
||||
pub const MODEL_END: Handle = Handle(0x10);
|
||||
pub const PAPER_BLOCK: Handle = Handle(0x11);
|
||||
pub const PAPER_END: Handle = Handle(0x12);
|
||||
pub const MODEL_LAYOUT: Handle = Handle(0x13);
|
||||
pub const PAPER_LAYOUT: Handle = Handle(0x14);
|
||||
pub const ACTIVE_VPORT: Handle = Handle(0x15);
|
||||
pub const ACAD_APPID: Handle = Handle(0x16);
|
||||
pub const STANDARD_DIMSTYLE: Handle = Handle(0x17);
|
||||
pub const IMAGE_DICT: Handle = Handle(0x18);
|
||||
pub const IMAGE_VARS: Handle = Handle(0x19);
|
||||
pub const PLOT_STYLES: Handle = Handle(0x1A);
|
||||
pub const PLOT_NORMAL: Handle = Handle(0x1B);
|
||||
pub const FIRST_FREE: u32 = 0x30;
|
||||
}
|
||||
|
||||
/// A number as DXF writes it: up to 6 decimals, no trailing zeros, 0 for anything not finite.
|
||||
pub(crate) fn num(v: f64) -> String {
|
||||
if !v.is_finite() {
|
||||
return "0".into();
|
||||
}
|
||||
let s = format!("{v:.6}");
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.');
|
||||
if s == "-0" || s.is_empty() { "0".into() } else { s.into() }
|
||||
}
|
||||
|
||||
/// Text as a DXF string value: one line, `^` escaped, and before DXF 2007 (which reads UTF-8)
|
||||
/// every character outside ASCII as `\U+XXXX`.
|
||||
pub(crate) fn text(s: &str, utf8: bool) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\r' | '\n' | '\t' => out.push(' '),
|
||||
c if c.is_control() => {}
|
||||
'^' => out.push_str("^ "),
|
||||
c if !utf8 && !c.is_ascii() => match u16::try_from(u32::from(c)) {
|
||||
Ok(u) => _ = write!(out, "\\U+{u:04X}"),
|
||||
Err(_) => out.push('?'),
|
||||
},
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Group-code/value pairs in the order they are written.
|
||||
pub(crate) struct Codes {
|
||||
pub v: DxfVersion,
|
||||
out: String,
|
||||
}
|
||||
|
||||
impl Codes {
|
||||
pub fn new(v: DxfVersion) -> Self {
|
||||
Self { v, out: String::new() }
|
||||
}
|
||||
|
||||
pub fn into_string(self) -> String {
|
||||
self.out
|
||||
}
|
||||
|
||||
pub fn append(&mut self, other: &str) {
|
||||
self.out.push_str(other);
|
||||
}
|
||||
|
||||
/// A value written as it is (names and keywords the writer itself chose).
|
||||
pub fn raw(&mut self, code: u16, value: &str) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{value}");
|
||||
}
|
||||
|
||||
/// Text from the document, encoded for the version (see [`text`]).
|
||||
pub fn str(&mut self, code: u16, value: &str) {
|
||||
let t = text(value, self.v.utf8());
|
||||
self.raw(code, &t);
|
||||
}
|
||||
|
||||
pub fn int(&mut self, code: u16, value: i64) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{value}");
|
||||
}
|
||||
|
||||
pub fn num(&mut self, code: u16, value: f64) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{}", num(value));
|
||||
}
|
||||
|
||||
pub fn handle(&mut self, code: u16, h: Handle) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{:X}", h.0);
|
||||
}
|
||||
|
||||
/// A 2D point at `code` (x), `code + 10` (y).
|
||||
pub fn xy(&mut self, code: u16, x: f64, y: f64) {
|
||||
self.num(code, x);
|
||||
self.num(code + 10, y);
|
||||
}
|
||||
|
||||
/// A 3D point at `code`, `code + 10`, `code + 20` (z = 0).
|
||||
pub fn xyz(&mut self, code: u16, x: f64, y: f64) {
|
||||
self.xy(code, x, y);
|
||||
self.num(code + 20, 0.0);
|
||||
}
|
||||
|
||||
/// The extrusion direction of planar entities: the z axis.
|
||||
pub fn normal(&mut self) {
|
||||
self.num(210, 0.0);
|
||||
self.num(220, 0.0);
|
||||
self.num(230, 1.0);
|
||||
}
|
||||
|
||||
/// The start of an object: its type, and from R13 its handle, owner and first subclass.
|
||||
fn object(&mut self, kind: &str, h: Handle, owner: Handle, subclass: &str) {
|
||||
self.raw(0, kind);
|
||||
if self.v.handles() {
|
||||
self.handle(if kind == "DIMSTYLE" { 105 } else { 5 }, h);
|
||||
self.handle(330, owner);
|
||||
self.raw(100, subclass);
|
||||
}
|
||||
}
|
||||
|
||||
/// A table entry: the shared record subclass, then the table's own (from R13).
|
||||
fn record(&mut self, kind: &str, h: Handle, table: Handle, subclass: &str) {
|
||||
self.object(kind, h, table, "AcDbSymbolTableRecord");
|
||||
if self.v.handles() {
|
||||
self.raw(100, subclass);
|
||||
}
|
||||
}
|
||||
|
||||
fn section(&mut self, name: &str) {
|
||||
self.raw(0, "SECTION");
|
||||
self.raw(2, name);
|
||||
}
|
||||
|
||||
fn end_section(&mut self) {
|
||||
self.raw(0, "ENDSEC");
|
||||
}
|
||||
|
||||
fn table(&mut self, name: &str, h: Handle, count: usize) {
|
||||
self.raw(0, "TABLE");
|
||||
self.raw(2, name);
|
||||
if self.v.handles() {
|
||||
self.handle(5, h);
|
||||
self.raw(330, "0");
|
||||
self.raw(100, "AcDbSymbolTable");
|
||||
}
|
||||
self.int(70, count as i64);
|
||||
if name == "DIMSTYLE" && self.v.r2000() {
|
||||
self.raw(100, "AcDbDimStyleTable");
|
||||
}
|
||||
}
|
||||
|
||||
fn end_table(&mut self) {
|
||||
self.raw(0, "ENDTAB");
|
||||
}
|
||||
}
|
||||
|
||||
/// How an entity is drawn: its colour index, true colour, lineweight, linetype and transparency.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct EntityStyle {
|
||||
pub aci: u8,
|
||||
/// `0xRRGGBB` (DXF 2004 and later).
|
||||
pub rgb: Option<u32>,
|
||||
/// Hundredths of a millimetre (DXF 2000 and later).
|
||||
pub lineweight: Option<i32>,
|
||||
pub linetype: Option<String>,
|
||||
/// Opacity 0–255 (DXF 2004 and later; opaque is left out).
|
||||
pub alpha: Option<u8>,
|
||||
}
|
||||
|
||||
impl Codes {
|
||||
/// The start of an entity of `kind` owned by `owner` (model space, or a polyline for its
|
||||
/// vertices) on `layer` with its style, ending with `subclass` (none when empty).
|
||||
pub fn entity(&mut self, kind: &str, h: Handle, owner: Handle, layer: &str, style: &EntityStyle, subclass: &str) {
|
||||
self.object(kind, h, owner, "AcDbEntity");
|
||||
self.str(8, layer);
|
||||
if let Some(lt) = &style.linetype {
|
||||
self.str(6, lt);
|
||||
}
|
||||
self.int(62, i64::from(style.aci.max(1)));
|
||||
if self.v.r2000()
|
||||
&& let Some(lw) = style.lineweight
|
||||
{
|
||||
self.int(370, i64::from(lw));
|
||||
}
|
||||
if self.v.true_color() {
|
||||
if let Some(rgb) = style.rgb {
|
||||
self.int(420, i64::from(rgb));
|
||||
}
|
||||
if let Some(a) = style.alpha {
|
||||
self.int(440, 0x0200_0000 | i64::from(a));
|
||||
}
|
||||
}
|
||||
if self.v.handles() && !subclass.is_empty() {
|
||||
self.raw(100, subclass);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A DXF layer.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Layer {
|
||||
pub name: String,
|
||||
pub aci: u8,
|
||||
/// Switched off (a hidden layer).
|
||||
pub off: bool,
|
||||
pub locked: bool,
|
||||
/// Plotted (printable).
|
||||
pub plot: bool,
|
||||
}
|
||||
|
||||
/// A dash pattern: dash, gap, dash… lengths in drawing units.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct LineType {
|
||||
pub name: String,
|
||||
pub pattern: Vec<f64>,
|
||||
}
|
||||
|
||||
/// A placed image file and the image entities that show it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ImageDef {
|
||||
pub name: String,
|
||||
pub size: (u32, u32),
|
||||
pub handle: Handle,
|
||||
/// `(reactor, image entity)` per image entity.
|
||||
pub reactors: Vec<(Handle, Handle)>,
|
||||
}
|
||||
|
||||
/// Everything around the entities, collected while they were written.
|
||||
pub(crate) struct Drawing {
|
||||
pub version: DxfVersion,
|
||||
pub layers: Vec<Layer>,
|
||||
pub linetypes: Vec<LineType>,
|
||||
/// Text styles: (style name, font family).
|
||||
pub styles: Vec<(String, String)>,
|
||||
pub images: Vec<ImageDef>,
|
||||
/// The entities' group codes.
|
||||
pub entities: String,
|
||||
/// `[x0, y0, x1, y1]` of everything written (drawing units).
|
||||
pub extents: [f64; 4],
|
||||
/// The export region (drawing units).
|
||||
pub limits: [f64; 4],
|
||||
/// `$INSUNITS`.
|
||||
pub insunits: u8,
|
||||
pub metric: bool,
|
||||
/// The next free handle.
|
||||
pub next: u32,
|
||||
}
|
||||
|
||||
/// The text style every drawing has.
|
||||
pub(crate) const STANDARD_STYLE: &str = "Standard";
|
||||
|
||||
impl Drawing {
|
||||
/// The whole file.
|
||||
pub fn write(self) -> String {
|
||||
let v = self.version;
|
||||
let mut c = Codes::new(v);
|
||||
// Table entries get the handles after the entities'.
|
||||
let mut next = self.next;
|
||||
let mut take = |n: usize| {
|
||||
let start = next;
|
||||
next = next.saturating_add(u32::try_from(n).unwrap_or(u32::MAX));
|
||||
start
|
||||
};
|
||||
let ltype_base = take(3 + self.linetypes.len());
|
||||
let layer_base = take(1 + self.layers.len());
|
||||
let style_base = take(1 + self.styles.len());
|
||||
self.header(&mut c, next);
|
||||
if v.handles() {
|
||||
self.classes(&mut c);
|
||||
}
|
||||
c.section("TABLES");
|
||||
self.vport(&mut c);
|
||||
self.ltypes(&mut c, ltype_base);
|
||||
self.layer_table(&mut c, layer_base);
|
||||
self.style_table(&mut c, style_base);
|
||||
if v.handles() {
|
||||
for (name, h) in [("VIEW", fixed::VIEW_TABLE), ("UCS", fixed::UCS_TABLE)] {
|
||||
c.table(name, h, 0);
|
||||
c.end_table();
|
||||
}
|
||||
c.table("APPID", fixed::APPID_TABLE, 1);
|
||||
c.record("APPID", fixed::ACAD_APPID, fixed::APPID_TABLE, "AcDbRegAppTableRecord");
|
||||
c.raw(2, "ACAD");
|
||||
c.int(70, 0);
|
||||
c.end_table();
|
||||
c.table("DIMSTYLE", fixed::DIMSTYLE_TABLE, 1);
|
||||
c.record("DIMSTYLE", fixed::STANDARD_DIMSTYLE, fixed::DIMSTYLE_TABLE, "AcDbDimStyleTableRecord");
|
||||
c.raw(2, "Standard");
|
||||
c.int(70, 0);
|
||||
c.end_table();
|
||||
c.table("BLOCK_RECORD", fixed::BLOCK_RECORD_TABLE, 2);
|
||||
for (name, h, layout) in
|
||||
[("*Model_Space", fixed::MODEL_RECORD, fixed::MODEL_LAYOUT), ("*Paper_Space", fixed::PAPER_RECORD, fixed::PAPER_LAYOUT)]
|
||||
{
|
||||
c.record("BLOCK_RECORD", h, fixed::BLOCK_RECORD_TABLE, "AcDbBlockTableRecord");
|
||||
c.raw(2, name);
|
||||
if v.r2000() {
|
||||
c.handle(340, layout);
|
||||
c.int(70, 0);
|
||||
c.int(280, 1);
|
||||
c.int(281, 0);
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
c.end_section();
|
||||
if v.handles() {
|
||||
c.section("BLOCKS");
|
||||
for (name, record, begin, end) in [
|
||||
("*Model_Space", fixed::MODEL_RECORD, fixed::MODEL_BLOCK, fixed::MODEL_END),
|
||||
("*Paper_Space", fixed::PAPER_RECORD, fixed::PAPER_BLOCK, fixed::PAPER_END),
|
||||
] {
|
||||
c.object("BLOCK", begin, record, "AcDbEntity");
|
||||
c.raw(8, "0");
|
||||
c.raw(100, "AcDbBlockBegin");
|
||||
c.raw(2, name);
|
||||
c.int(70, 0);
|
||||
c.xyz(10, 0.0, 0.0);
|
||||
c.raw(3, name);
|
||||
c.raw(1, "");
|
||||
c.object("ENDBLK", end, record, "AcDbEntity");
|
||||
c.raw(8, "0");
|
||||
c.raw(100, "AcDbBlockEnd");
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
c.section("ENTITIES");
|
||||
c.append(&self.entities);
|
||||
c.end_section();
|
||||
if v.handles() {
|
||||
self.objects(&mut c);
|
||||
}
|
||||
c.raw(0, "EOF");
|
||||
c.into_string()
|
||||
}
|
||||
|
||||
fn header(&self, c: &mut Codes, handseed: u32) {
|
||||
let v = self.version;
|
||||
let var = |c: &mut Codes, name: &str| c.raw(9, name);
|
||||
c.section("HEADER");
|
||||
var(c, "$ACADVER");
|
||||
c.raw(1, v.acadver());
|
||||
var(c, "$DWGCODEPAGE");
|
||||
c.raw(3, "ANSI_1252");
|
||||
var(c, "$INSBASE");
|
||||
c.xyz(10, 0.0, 0.0);
|
||||
let [x0, y0, x1, y1] = self.extents;
|
||||
var(c, "$EXTMIN");
|
||||
c.xyz(10, x0, y0);
|
||||
var(c, "$EXTMAX");
|
||||
c.xyz(10, x1, y1);
|
||||
let [lx0, ly0, lx1, ly1] = self.limits;
|
||||
var(c, "$LIMMIN");
|
||||
c.xy(10, lx0, ly0);
|
||||
var(c, "$LIMMAX");
|
||||
c.xy(10, lx1, ly1);
|
||||
if v.r2000() {
|
||||
var(c, "$LWDISPLAY");
|
||||
c.int(290, 1);
|
||||
var(c, "$INSUNITS");
|
||||
c.int(70, i64::from(self.insunits));
|
||||
var(c, "$MEASUREMENT");
|
||||
c.int(70, i64::from(self.metric));
|
||||
}
|
||||
if v.handles() {
|
||||
var(c, "$HANDSEED");
|
||||
c.handle(5, Handle(handseed));
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
|
||||
fn classes(&self, c: &mut Codes) {
|
||||
let mut classes: Vec<(&str, &str, &str, i64, bool)> = vec![];
|
||||
if self.version.r2000() {
|
||||
classes.extend([
|
||||
("ACDBDICTIONARYWDFLT", "AcDbDictionaryWithDefault", "ObjectDBX Classes", 0, false),
|
||||
("ACDBPLACEHOLDER", "AcDbPlaceHolder", "ObjectDBX Classes", 0, false),
|
||||
("LAYOUT", "AcDbLayout", "ObjectDBX Classes", 0, false),
|
||||
]);
|
||||
}
|
||||
if !self.images.is_empty() {
|
||||
classes.extend([
|
||||
("RASTERVARIABLES", "AcDbRasterVariables", "ISM", 0, false),
|
||||
("IMAGE", "AcDbRasterImage", "ISM", 2175, true),
|
||||
("IMAGEDEF", "AcDbRasterImageDef", "ISM", 0, false),
|
||||
("IMAGEDEF_REACTOR", "AcDbRasterImageDefReactor", "ISM", 1, false),
|
||||
]);
|
||||
}
|
||||
c.section("CLASSES");
|
||||
for (name, cpp, app, flags, entity) in classes {
|
||||
c.raw(0, "CLASS");
|
||||
c.raw(1, name);
|
||||
c.raw(2, cpp);
|
||||
c.raw(3, app);
|
||||
c.int(90, flags);
|
||||
if self.version.true_color() {
|
||||
c.int(91, 0);
|
||||
}
|
||||
c.int(280, 0);
|
||||
c.int(281, i64::from(entity));
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
|
||||
/// The active viewport, zoomed to the drawing's extents.
|
||||
fn vport(&self, c: &mut Codes) {
|
||||
let [x0, y0, x1, y1] = self.extents;
|
||||
c.table("VPORT", fixed::VPORT_TABLE, 1);
|
||||
c.record("VPORT", fixed::ACTIVE_VPORT, fixed::VPORT_TABLE, "AcDbViewportTableRecord");
|
||||
c.raw(2, if self.version.handles() { "*Active" } else { "*ACTIVE" });
|
||||
c.int(70, 0);
|
||||
c.xy(10, 0.0, 0.0);
|
||||
c.xy(11, 1.0, 1.0);
|
||||
c.xy(12, (x0 + x1) / 2.0, (y0 + y1) / 2.0);
|
||||
c.xy(13, 0.0, 0.0);
|
||||
c.xy(14, 1.0, 1.0);
|
||||
c.xy(15, 10.0, 10.0);
|
||||
// The view direction looks down the z axis: (0, 0, 1), each code once.
|
||||
c.xy(16, 0.0, 0.0);
|
||||
c.num(36, 1.0);
|
||||
c.xyz(17, 0.0, 0.0);
|
||||
let (w, h) = ((x1 - x0).abs(), (y1 - y0).abs());
|
||||
// The view's height, with a margin; its width follows from the aspect ratio.
|
||||
c.num(40, (h.max(w / 1.5) * 1.1).max(1.0));
|
||||
c.num(41, 1.5);
|
||||
c.num(42, 50.0);
|
||||
c.num(43, 0.0);
|
||||
c.num(44, 0.0);
|
||||
c.num(50, 0.0);
|
||||
c.num(51, 0.0);
|
||||
for (code, value) in [(71, 0), (72, 1000), (73, 1), (74, 3), (75, 0), (76, 0), (77, 0), (78, 0)] {
|
||||
c.int(code, value);
|
||||
}
|
||||
if self.version.r2000() {
|
||||
c.int(281, 0);
|
||||
c.int(65, 0);
|
||||
c.num(146, 0.0);
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn ltypes(&self, c: &mut Codes, base: u32) {
|
||||
c.table("LTYPE", fixed::LTYPE_TABLE, 3 + self.linetypes.len());
|
||||
let solid = [("ByBlock", ""), ("ByLayer", ""), ("Continuous", "Solid line")];
|
||||
let rows = solid.iter().map(|(n, d)| (*n, *d, &[][..])).chain(self.linetypes.iter().map(|l| (l.name.as_str(), "", l.pattern.as_slice())));
|
||||
for (i, (name, desc, pattern)) in rows.enumerate() {
|
||||
c.record("LTYPE", Handle(base.saturating_add(i as u32)), fixed::LTYPE_TABLE, "AcDbLinetypeTableRecord");
|
||||
c.str(2, name);
|
||||
c.int(70, 0);
|
||||
c.str(3, if pattern.is_empty() { desc } else { "Dashed" });
|
||||
c.int(72, 65);
|
||||
c.int(73, pattern.len() as i64);
|
||||
c.num(40, pattern.iter().map(|v| v.abs()).sum());
|
||||
for v in pattern {
|
||||
c.num(49, *v);
|
||||
if self.version.handles() {
|
||||
c.int(74, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn layer_table(&self, c: &mut Codes, base: u32) {
|
||||
let zero = Layer { name: "0".into(), aci: 7, off: false, locked: false, plot: true };
|
||||
c.table("LAYER", fixed::LAYER_TABLE, 1 + self.layers.len());
|
||||
for (i, l) in std::iter::once(&zero).chain(&self.layers).enumerate() {
|
||||
c.record("LAYER", Handle(base.saturating_add(i as u32)), fixed::LAYER_TABLE, "AcDbLayerTableRecord");
|
||||
c.str(2, &l.name);
|
||||
c.int(70, if l.locked { 4 } else { 0 });
|
||||
// A negative colour switches the layer off.
|
||||
let aci = i64::from(l.aci.max(1));
|
||||
c.int(62, if l.off { -aci } else { aci });
|
||||
c.raw(6, "Continuous");
|
||||
if self.version.r2000() {
|
||||
c.int(290, i64::from(l.plot));
|
||||
c.int(370, -3);
|
||||
c.handle(390, fixed::PLOT_NORMAL);
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn style_table(&self, c: &mut Codes, base: u32) {
|
||||
c.table("STYLE", fixed::STYLE_TABLE, 1 + self.styles.len());
|
||||
let standard = (STANDARD_STYLE.to_string(), String::new());
|
||||
for (i, (name, family)) in std::iter::once(&standard).chain(&self.styles).enumerate() {
|
||||
c.record("STYLE", Handle(base.saturating_add(i as u32)), fixed::STYLE_TABLE, "AcDbTextStyleTableRecord");
|
||||
c.str(2, name);
|
||||
c.int(70, 0);
|
||||
c.num(40, 0.0);
|
||||
c.num(41, 1.0);
|
||||
c.num(50, 0.0);
|
||||
c.int(71, 0);
|
||||
c.num(42, 2.5);
|
||||
// The font file; from 2000 the family name too, which is how CAD apps find a TrueType font.
|
||||
if family.is_empty() {
|
||||
c.raw(3, "txt");
|
||||
} else {
|
||||
c.str(3, &format!("{family}.ttf"));
|
||||
}
|
||||
c.raw(4, "");
|
||||
if self.version.r2000() && !family.is_empty() {
|
||||
c.raw(1001, "ACAD");
|
||||
c.str(1000, family);
|
||||
c.int(1071, 0);
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn objects(&self, c: &mut Codes) {
|
||||
let v = self.version;
|
||||
let images = !self.images.is_empty();
|
||||
c.section("OBJECTS");
|
||||
let dict = |c: &mut Codes, h: Handle, owner: Handle, entries: &[(&str, Handle)]| {
|
||||
c.object("DICTIONARY", h, owner, "AcDbDictionary");
|
||||
c.int(281, 1);
|
||||
for (name, e) in entries {
|
||||
c.str(3, name);
|
||||
c.handle(350, *e);
|
||||
}
|
||||
};
|
||||
let mut root = vec![("ACAD_GROUP", fixed::GROUPS)];
|
||||
if images {
|
||||
root.extend([("ACAD_IMAGE_DICT", fixed::IMAGE_DICT), ("ACAD_IMAGE_VARS", fixed::IMAGE_VARS)]);
|
||||
}
|
||||
if v.r2000() {
|
||||
root.extend([("ACAD_LAYOUT", fixed::LAYOUTS), ("ACAD_PLOTSTYLENAME", fixed::PLOT_STYLES)]);
|
||||
}
|
||||
dict(c, fixed::ROOT, Handle(0), &root);
|
||||
dict(c, fixed::GROUPS, fixed::ROOT, &[]);
|
||||
if v.r2000() {
|
||||
dict(c, fixed::LAYOUTS, fixed::ROOT, &[("Layout1", fixed::PAPER_LAYOUT), ("Model", fixed::MODEL_LAYOUT)]);
|
||||
c.object("ACDBDICTIONARYWDFLT", fixed::PLOT_STYLES, fixed::ROOT, "AcDbDictionary");
|
||||
c.int(281, 1);
|
||||
c.raw(3, "Normal");
|
||||
c.handle(350, fixed::PLOT_NORMAL);
|
||||
c.raw(100, "AcDbDictionaryWithDefault");
|
||||
c.handle(340, fixed::PLOT_NORMAL);
|
||||
// A placeholder has no data and no subclass marker of its own.
|
||||
c.raw(0, "ACDBPLACEHOLDER");
|
||||
c.handle(5, fixed::PLOT_NORMAL);
|
||||
c.handle(330, fixed::PLOT_STYLES);
|
||||
self.layout(c, fixed::MODEL_LAYOUT, "Model", 0, fixed::MODEL_RECORD);
|
||||
self.layout(c, fixed::PAPER_LAYOUT, "Layout1", 1, fixed::PAPER_RECORD);
|
||||
}
|
||||
if images {
|
||||
c.object("RASTERVARIABLES", fixed::IMAGE_VARS, fixed::ROOT, "AcDbRasterVariables");
|
||||
c.int(90, 0);
|
||||
c.int(70, 0);
|
||||
c.int(71, 1);
|
||||
c.int(72, 0);
|
||||
let entries: Vec<(&str, Handle)> = self.images.iter().map(|i| (i.name.as_str(), i.handle)).collect();
|
||||
dict(c, fixed::IMAGE_DICT, fixed::ROOT, &entries);
|
||||
for img in &self.images {
|
||||
c.raw(0, "IMAGEDEF");
|
||||
c.handle(5, img.handle);
|
||||
c.raw(102, "{ACAD_REACTORS");
|
||||
c.handle(330, fixed::IMAGE_DICT);
|
||||
for (reactor, _) in &img.reactors {
|
||||
c.handle(330, *reactor);
|
||||
}
|
||||
c.raw(102, "}");
|
||||
c.handle(330, fixed::IMAGE_DICT);
|
||||
c.raw(100, "AcDbRasterImageDef");
|
||||
c.int(90, 0);
|
||||
c.str(1, &img.name);
|
||||
c.xy(10, f64::from(img.size.0), f64::from(img.size.1));
|
||||
c.xy(11, 1.0, 1.0);
|
||||
c.int(280, 1);
|
||||
c.int(281, 0);
|
||||
for (reactor, image) in &img.reactors {
|
||||
c.object("IMAGEDEF_REACTOR", *reactor, *image, "AcDbRasterImageDefReactor");
|
||||
c.int(90, 2);
|
||||
c.handle(330, *image);
|
||||
}
|
||||
}
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
|
||||
/// A layout (DXF 2000 and later): its plot settings, then the layout itself.
|
||||
fn layout(&self, c: &mut Codes, h: Handle, name: &str, tab: i64, record: Handle) {
|
||||
let [x0, y0, x1, y1] = self.extents;
|
||||
c.object("LAYOUT", h, fixed::LAYOUTS, "AcDbPlotSettings");
|
||||
c.raw(1, "");
|
||||
c.raw(2, "none_device");
|
||||
c.raw(4, "");
|
||||
c.raw(6, "");
|
||||
for code in 40..=49 {
|
||||
c.num(code, 0.0);
|
||||
}
|
||||
c.num(140, 0.0);
|
||||
c.num(141, 0.0);
|
||||
c.num(142, 1.0);
|
||||
c.num(143, 1.0);
|
||||
// Plot flags; 1024 marks the model space layout.
|
||||
c.int(70, if record == fixed::MODEL_RECORD { 688 | 1024 } else { 688 });
|
||||
c.int(72, 1);
|
||||
c.int(73, 0);
|
||||
c.int(74, 5);
|
||||
c.raw(7, "");
|
||||
c.int(75, 16);
|
||||
if self.version.true_color() {
|
||||
// Shade plot mode (as displayed), resolution level (normal) and custom DPI.
|
||||
c.int(76, 0);
|
||||
c.int(77, 2);
|
||||
c.int(78, 300);
|
||||
}
|
||||
c.num(147, 1.0);
|
||||
// The paper image origin is 148 (x) and 149 (y), not a point at 148 and 158.
|
||||
c.num(148, 0.0);
|
||||
c.num(149, 0.0);
|
||||
c.raw(100, "AcDbLayout");
|
||||
c.raw(1, name);
|
||||
c.int(70, 1);
|
||||
c.int(71, tab);
|
||||
let [lx0, ly0, lx1, ly1] = self.limits;
|
||||
c.xy(10, lx0, ly0);
|
||||
c.xy(11, lx1, ly1);
|
||||
c.xyz(12, 0.0, 0.0);
|
||||
c.xyz(14, x0, y0);
|
||||
c.xyz(15, x1, y1);
|
||||
c.num(146, 0.0);
|
||||
c.xyz(13, 0.0, 0.0);
|
||||
c.xyz(16, 1.0, 0.0);
|
||||
c.xyz(17, 0.0, 1.0);
|
||||
c.int(76, 1);
|
||||
c.handle(330, record);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn numbers_and_text_are_written_plainly() {
|
||||
assert_eq!(num(1.5), "1.5");
|
||||
assert_eq!(num(-0.0000001), "0");
|
||||
assert_eq!(num(2.0), "2");
|
||||
assert_eq!(num(f64::NAN), "0");
|
||||
assert_eq!(text("a^b\nc", true), "a^ b c");
|
||||
assert_eq!(text("Größe 😀", false), "Gr\\U+00F6\\U+00DFe ?");
|
||||
assert_eq!(text("Größe", true), "Größe");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
0
|
||||
SECTION
|
||||
2
|
||||
HEADER
|
||||
9
|
||||
$ACADVER
|
||||
1
|
||||
AC1009
|
||||
9
|
||||
$DWGCODEPAGE
|
||||
3
|
||||
ANSI_1252
|
||||
9
|
||||
$INSBASE
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
9
|
||||
$EXTMIN
|
||||
10
|
||||
10
|
||||
20
|
||||
20
|
||||
30
|
||||
0
|
||||
9
|
||||
$EXTMAX
|
||||
10
|
||||
180
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
9
|
||||
$LIMMIN
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
9
|
||||
$LIMMAX
|
||||
10
|
||||
200
|
||||
20
|
||||
100
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
SECTION
|
||||
2
|
||||
TABLES
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
VPORT
|
||||
70
|
||||
1
|
||||
0
|
||||
VPORT
|
||||
2
|
||||
*ACTIVE
|
||||
70
|
||||
0
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
11
|
||||
1
|
||||
21
|
||||
1
|
||||
12
|
||||
95
|
||||
22
|
||||
55
|
||||
13
|
||||
0
|
||||
23
|
||||
0
|
||||
14
|
||||
1
|
||||
24
|
||||
1
|
||||
15
|
||||
10
|
||||
25
|
||||
10
|
||||
16
|
||||
0
|
||||
26
|
||||
0
|
||||
36
|
||||
1
|
||||
17
|
||||
0
|
||||
27
|
||||
0
|
||||
37
|
||||
0
|
||||
40
|
||||
124.666667
|
||||
41
|
||||
1.5
|
||||
42
|
||||
50
|
||||
43
|
||||
0
|
||||
44
|
||||
0
|
||||
50
|
||||
0
|
||||
51
|
||||
0
|
||||
71
|
||||
0
|
||||
72
|
||||
1000
|
||||
73
|
||||
1
|
||||
74
|
||||
3
|
||||
75
|
||||
0
|
||||
76
|
||||
0
|
||||
77
|
||||
0
|
||||
78
|
||||
0
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
LTYPE
|
||||
70
|
||||
3
|
||||
0
|
||||
LTYPE
|
||||
2
|
||||
ByBlock
|
||||
70
|
||||
0
|
||||
3
|
||||
|
||||
72
|
||||
65
|
||||
73
|
||||
0
|
||||
40
|
||||
0
|
||||
0
|
||||
LTYPE
|
||||
2
|
||||
ByLayer
|
||||
70
|
||||
0
|
||||
3
|
||||
|
||||
72
|
||||
65
|
||||
73
|
||||
0
|
||||
40
|
||||
0
|
||||
0
|
||||
LTYPE
|
||||
2
|
||||
Continuous
|
||||
70
|
||||
0
|
||||
3
|
||||
Solid line
|
||||
72
|
||||
65
|
||||
73
|
||||
0
|
||||
40
|
||||
0
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
LAYER
|
||||
70
|
||||
2
|
||||
0
|
||||
LAYER
|
||||
2
|
||||
0
|
||||
70
|
||||
0
|
||||
62
|
||||
7
|
||||
6
|
||||
Continuous
|
||||
0
|
||||
LAYER
|
||||
2
|
||||
LAYER_1
|
||||
70
|
||||
0
|
||||
62
|
||||
171
|
||||
6
|
||||
Continuous
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
STYLE
|
||||
70
|
||||
1
|
||||
0
|
||||
STYLE
|
||||
2
|
||||
Standard
|
||||
70
|
||||
0
|
||||
40
|
||||
0
|
||||
41
|
||||
1
|
||||
50
|
||||
0
|
||||
71
|
||||
0
|
||||
42
|
||||
2.5
|
||||
3
|
||||
txt
|
||||
4
|
||||
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
SECTION
|
||||
2
|
||||
ENTITIES
|
||||
0
|
||||
POLYLINE
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
66
|
||||
1
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
70
|
||||
1
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
10
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
110
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
110
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
10
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
SEQEND
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
0
|
||||
POLYLINE
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
66
|
||||
1
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
70
|
||||
1
|
||||
40
|
||||
1
|
||||
41
|
||||
1
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
10
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
110
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
110
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
10
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
SEQEND
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
0
|
||||
POLYLINE
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
66
|
||||
1
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
70
|
||||
1
|
||||
40
|
||||
2
|
||||
41
|
||||
2
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
10
|
||||
120
|
||||
20
|
||||
50
|
||||
30
|
||||
0
|
||||
42
|
||||
-2.414214
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
10
|
||||
150
|
||||
20
|
||||
20
|
||||
30
|
||||
0
|
||||
42
|
||||
-0.414214
|
||||
0
|
||||
SEQEND
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
EOF
|
||||
File diff suppressed because it is too large.
Load diff
+17
-3
@@ -664,9 +664,6 @@ pub fn jpeg_with_icc(bytes: &[u8], icc: &[u8]) -> Option<Vec<u8>> {
|
||||
const CHUNK: usize = 0xFFFF - 2 - ICC_SEGMENT.len() - 2;
|
||||
let chunks: Vec<&[u8]> = icc.chunks(CHUNK).collect();
|
||||
let count = u8::try_from(chunks.len()).ok().filter(|n| *n > 0)?;
|
||||
if !bytes.starts_with(&[0xFF, 0xD8]) {
|
||||
return None;
|
||||
}
|
||||
let mut segments = Vec::with_capacity(icc.len() + 18 * chunks.len());
|
||||
for (i, chunk) in chunks.iter().enumerate() {
|
||||
let len = u16::try_from(chunk.len() + 2 + ICC_SEGMENT.len() + 2).ok()?;
|
||||
@@ -676,6 +673,23 @@ pub fn jpeg_with_icc(bytes: &[u8], icc: &[u8]) -> Option<Vec<u8>> {
|
||||
segments.extend_from_slice(&[u8::try_from(i + 1).ok()?, count]);
|
||||
segments.extend_from_slice(chunk);
|
||||
}
|
||||
with_icc_segments(bytes, segments)
|
||||
}
|
||||
|
||||
/// JPEG `bytes` without the ICC profile they carry: every `ICC_PROFILE` APP2 segment before the
|
||||
/// scan taken out, and the other segments and the scan as they are. `None` for bytes whose
|
||||
/// segments before the scan can't be read.
|
||||
pub fn jpeg_without_icc(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
with_icc_segments(bytes, vec![])
|
||||
}
|
||||
|
||||
/// JPEG `bytes` with every `ICC_PROFILE` APP2 segment before the scan taken out and `segments`
|
||||
/// written after the leading application segments; `None` when the bytes don't start a JPEG or
|
||||
/// their segments before the scan can't be read.
|
||||
fn with_icc_segments(bytes: &[u8], segments: Vec<u8>) -> Option<Vec<u8>> {
|
||||
if !bytes.starts_with(&[0xFF, 0xD8]) {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::with_capacity(bytes.len() + segments.len());
|
||||
out.extend_from_slice(&[0xFF, 0xD8]);
|
||||
let mut icc_segments = Some(segments);
|
||||
|
||||
+191
-21
@@ -266,6 +266,7 @@ pub fn hit_test_visible_skipping(doc: &Document, p: Point, opt: HitOptions, skip
|
||||
/// (`opt.scope`) or on a locked artboard. On a layer whose Preview is off it counts by its
|
||||
/// outline, as a click there hits it.
|
||||
pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: &[NodeId]) -> Option<NodeId> {
|
||||
let _walk = ArtWalk::open();
|
||||
let symbols = doc.symbol_boxes();
|
||||
let locks = doc.locked_artboards();
|
||||
selected.iter().rev().copied().find(|&id| {
|
||||
@@ -322,30 +323,31 @@ fn path_options(nodes: &[&Node], chain: &[NodeId], opt: HitOptions) -> Option<Hi
|
||||
/// The objects under `p` that [`Hit::top_object`] picks in `scope` (isolation mode), topmost
|
||||
/// first: what clicks there select, one below the other (Cmd/Ctrl-click selects behind).
|
||||
pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>) -> Vec<NodeId> {
|
||||
let _walk = ArtWalk::open();
|
||||
let opt = HitOptions { scope: scope.or(opt.scope), ..opt };
|
||||
// Normally one hit test per *object* suffices: layers and sublayers aren't selectable,
|
||||
// while a group (including a clipping group) is selected as one object. Repeatedly
|
||||
// searching the full tree for each hit made a stack of n overlapping paths O(n^2).
|
||||
// Isolation and Edit Contents change where selection groups begin; keep the original
|
||||
// traversal for those cases rather than change their Select Behind semantics.
|
||||
if opt.scope.is_some() {
|
||||
// Malformed files may contain non-layer roots; let the general traversal handle them.
|
||||
if opt.scope.is_some() || doc.layers.iter().any(|l| !l.is_layer()) {
|
||||
return objects_at_repeated(doc, p, opt, scope);
|
||||
}
|
||||
let mut tops = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
let symbols = doc.symbol_boxes();
|
||||
for layer in doc.layers.iter().rev() {
|
||||
// Malformed files may contain non-layer roots; let the general traversal handle them.
|
||||
if !layer.is_layer() {
|
||||
return objects_at_repeated(doc, p, opt, scope);
|
||||
}
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
}
|
||||
if !objects_at_layer(layer, p, opt, &symbols, &mut tops, &mut seen) {
|
||||
// An envelope in Edit Contents may expose objects *within* a top-level group.
|
||||
// The repeated traversal handles that mixed hierarchy precisely.
|
||||
return objects_at_repeated(doc, p, opt, scope);
|
||||
// The repeated traversal handles that mixed hierarchy precisely. The objects found
|
||||
// so far lie above the envelope and stay first; the repeated traversal finds the
|
||||
// rest with what is left of the limit of symbol art to walk.
|
||||
tops = objects_at_repeated_after(doc, p, opt, scope, tops);
|
||||
break;
|
||||
}
|
||||
}
|
||||
// The objects on a locked artboard can't be selected, as `hit_test_skipping` passes over them.
|
||||
@@ -409,7 +411,11 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox
|
||||
|
||||
/// The general selection order also handles isolation and nested Edit Contents.
|
||||
fn objects_at_repeated(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>) -> Vec<NodeId> {
|
||||
let mut tops: Vec<NodeId> = vec![];
|
||||
objects_at_repeated_after(doc, p, opt, scope, vec![])
|
||||
}
|
||||
|
||||
/// [`objects_at_repeated`] after `tops`, the topmost objects under `p` already found.
|
||||
fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>, mut tops: Vec<NodeId>) -> Vec<NodeId> {
|
||||
// Each round leaves out the objects found so far (and everything inside them).
|
||||
while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) {
|
||||
if tops.contains(&top) {
|
||||
@@ -429,6 +435,7 @@ pub const MAX_LOCKED_AT: usize = 20;
|
||||
/// out. While a pattern is edited only its tile layer is searched, and in isolation mode
|
||||
/// (`opt.scope`) only what is inside the isolated group or object.
|
||||
pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<NodeId> {
|
||||
let _walk = ArtWalk::open();
|
||||
let symbols = doc.symbol_boxes();
|
||||
let mut out = Vec::new();
|
||||
if let Some(scope) = opt.scope
|
||||
@@ -506,6 +513,7 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab
|
||||
/// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art
|
||||
/// ([`Node::geometric_bounds_with`]), and are also hit outside that box where their art paints.
|
||||
fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
|
||||
let _walk = ArtWalk::open();
|
||||
let finish = |mut h: Hit| {
|
||||
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
|
||||
h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count();
|
||||
@@ -1059,9 +1067,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds)
|
||||
}
|
||||
// A symbol instance is hit within its bounds, and outside them where its art paints
|
||||
// ([`instance_art_hit`]).
|
||||
// ([`instance_art_hit`]). In the art of another instance walked outside that instance's
|
||||
// bounds, it is hit only where its own art paints ([`ArtOnly`]).
|
||||
NodeKind::SymbolInstance { .. } => {
|
||||
if n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
|
||||
if !ArtOnly::on() && n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
|
||||
return Some(HitKind::Bounds);
|
||||
}
|
||||
instance_art_hit(n, p, opt, symbols)
|
||||
@@ -1113,10 +1122,12 @@ fn on_type_path(n: &Node, t: &crate::TextObject, p: Point, tol: f64) -> bool {
|
||||
stroke_contains(&path.to_bezpath(), 0.0, tol, p)
|
||||
}
|
||||
|
||||
/// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]).
|
||||
/// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]). In symbol art
|
||||
/// placed by [`FindPart`], each object visited takes one object of the [`ArtWalk`] limit, and
|
||||
/// nothing more is tested once the limit is used up.
|
||||
fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
|
||||
// Hidden art does not hit.
|
||||
if !n.visible {
|
||||
if !n.visible || ArtWalk::charged() && !ArtWalk::take(1) {
|
||||
return None;
|
||||
}
|
||||
// Nor art whose reach does not hold `p`, as in [`may_hit`]: a blend's steps far from `p` are
|
||||
@@ -1172,6 +1183,15 @@ impl<'a> InstanceArt<'a> {
|
||||
whole.or_else(|| self.map.as_ref()?.one_cell_with(n, &self.boxes))
|
||||
}
|
||||
|
||||
/// How many objects placing the whole art makes: the objects of the art with their opacity
|
||||
/// masks' art ([`Node::count_with_masks`]), or, through the guides, the most that
|
||||
/// [`crate::NineSliceMap::most_placed_with`] counts.
|
||||
fn size(&self) -> u64 {
|
||||
self.map
|
||||
.as_ref()
|
||||
.map_or_else(|| u64::try_from(self.art.count_with_masks()).unwrap_or(u64::MAX), |m| m.most_placed_with(&self.art, &self.boxes))
|
||||
}
|
||||
|
||||
/// Object `n` of the art placed on the canvas as it is drawn, clip groups included: moved by
|
||||
/// `whole` when an object around it is moved as one piece ([`Self::whole`]). `None` when
|
||||
/// placing it through the guides could make more than [`crate::MAX_SYMBOL_NODES`] objects, as
|
||||
@@ -1219,6 +1239,7 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
|
||||
/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or
|
||||
/// no editable object of its art is under `p`.
|
||||
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
|
||||
let _walk = ArtWalk::open();
|
||||
let art = InstanceArt::of(doc, inst)?;
|
||||
let symbols = doc.symbol_boxes();
|
||||
let mut path = vec![];
|
||||
@@ -1239,8 +1260,12 @@ struct FindPart<'a> {
|
||||
}
|
||||
|
||||
impl FindPart<'_> {
|
||||
/// What a click at `p` hits on object `n` of the art, placed. [`hit_any`] takes `n` and each
|
||||
/// object it visits inside `n` from the [`ArtWalk`] limit.
|
||||
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>, opt: HitOptions) -> Option<HitKind> {
|
||||
self.art.place(n, whole).and_then(|n| hit_any(&n, self.p, opt, self.symbols))
|
||||
let placed = self.art.place(n, whole)?;
|
||||
let _charged = ArtWalk::charge();
|
||||
hit_any(&placed, self.p, opt, self.symbols)
|
||||
}
|
||||
|
||||
fn skips_guide(&self, n: &Node) -> bool {
|
||||
@@ -1250,7 +1275,7 @@ impl FindPart<'_> {
|
||||
/// What a click at `p` hits on object `n` of the art, with `path` the child indices that lead
|
||||
/// to what it hits. `outline`: the view is in Outline, or a layer around `n` has Preview off.
|
||||
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>, outline: bool) -> Option<HitKind> {
|
||||
if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) {
|
||||
if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) || ArtWalk::used_up() {
|
||||
return None;
|
||||
}
|
||||
let outline = outline || previews_off(n);
|
||||
@@ -1259,6 +1284,9 @@ impl FindPart<'_> {
|
||||
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
|
||||
return self.hit(n, whole, opt);
|
||||
}
|
||||
if !ArtWalk::take(1) {
|
||||
return None;
|
||||
}
|
||||
let whole = self.art.whole(n, whole);
|
||||
if n.clips()
|
||||
&& let Some(first) = children.first()
|
||||
@@ -1298,17 +1326,146 @@ impl FindPart<'_> {
|
||||
/// Outline, [`HitOptions::outline`]): its strokes, and the art that the live geometry effects of a
|
||||
/// clipping path in it show past the art's box. `None` for an instance of a missing symbol, of a
|
||||
/// symbol that holds an instance of itself or nests too deep ([`SymbolBoxes::art`]), and of art past
|
||||
/// the 9-slice object limit ([`InstanceArt::of`]).
|
||||
/// the 9-slice object limit ([`InstanceArt::of`]), when `p` is outside the instance's reach
|
||||
/// ([`Node::reach_bounds_with`]), and once the click has visited as many objects of symbol art as
|
||||
/// [`ArtWalk`] allows.
|
||||
fn instance_art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return None };
|
||||
if opt.outline || symbols.art(symbol).is_none() {
|
||||
if opt.outline || symbols.art(symbol).is_none() || !n.reach_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
|
||||
return None;
|
||||
}
|
||||
let _walk = ArtWalk::open();
|
||||
if ArtWalk::used_up() {
|
||||
return None;
|
||||
}
|
||||
let art = InstanceArt::of(symbols.document(), n)?;
|
||||
#[cfg(test)]
|
||||
ARTS_WALKED.with(|c| c.set(c.get() + 1));
|
||||
let opt = HitOptions { clip_outlines: false, ..opt };
|
||||
let _art_only = ArtOnly::set();
|
||||
FindPart { art: &art, p, opt, symbols, whole_instance: true }.find(&art.art, &mut vec![], None, false)
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Whether a symbol instance's art is being walked outside the instance's box ([`ArtOnly`]).
|
||||
static ART_ONLY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// While a guard lives, a symbol instance is hit ([`hit_leaf`]) and touched by a marquee
|
||||
/// ([`marquee_with`]) only where its own art is, by the same rule at every level, and not anywhere
|
||||
/// in its box. [`instance_art_hit`] and the marquee's walk of an instance's art hold one: they walk
|
||||
/// the art outside the instance's box, where the box of an instance nested in the art can reach
|
||||
/// past it over empty space.
|
||||
struct ArtOnly {
|
||||
was: bool,
|
||||
}
|
||||
|
||||
impl ArtOnly {
|
||||
fn set() -> Self {
|
||||
Self { was: ART_ONLY.replace(true) }
|
||||
}
|
||||
|
||||
fn on() -> bool {
|
||||
ART_ONLY.get()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ArtOnly {
|
||||
fn drop(&mut self) {
|
||||
ART_ONLY.set(self.was);
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// How many more objects of symbol art the click or marquee under way may visit ([`ArtWalk`]),
|
||||
/// `None` outside one.
|
||||
static ART_WALK_LEFT: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
|
||||
/// Whether [`hit_any`] is testing symbol art that [`FindPart`] placed ([`ArtWalk::charge`]).
|
||||
static ART_WALK_CHARGED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The number of objects [`ArtWalk::open`] allows on this thread in place of
|
||||
/// [`crate::MAX_SYMBOL_NODES`].
|
||||
static ART_WALK_LIMIT: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
|
||||
/// How many symbol instances' art clicks and marquees walked on this thread.
|
||||
static ARTS_WALKED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The objects of symbol art that one click or one marquee may visit: [`crate::MAX_SYMBOL_NODES`]
|
||||
/// in all, the art of the instances nested in that art included, at every level. The first
|
||||
/// [`ArtWalk::open`] of a click or a marquee sets the limit, and the walks opened while its guard
|
||||
/// lives share it. Once the limit is used up, an instance is no longer hit or touched outside its
|
||||
/// box; inside its box it still is.
|
||||
struct ArtWalk {
|
||||
outermost: bool,
|
||||
}
|
||||
|
||||
impl ArtWalk {
|
||||
fn open() -> Self {
|
||||
let walk = Self { outermost: ART_WALK_LEFT.get().is_none() };
|
||||
walk.restart();
|
||||
walk
|
||||
}
|
||||
|
||||
/// For the outermost guard, sets what is left back to the whole limit.
|
||||
fn restart(&self) {
|
||||
if self.outermost {
|
||||
#[cfg(test)]
|
||||
let limit = ART_WALK_LIMIT.get().unwrap_or(crate::MAX_SYMBOL_NODES);
|
||||
#[cfg(not(test))]
|
||||
let limit = crate::MAX_SYMBOL_NODES;
|
||||
ART_WALK_LEFT.set(Some(limit));
|
||||
}
|
||||
}
|
||||
|
||||
/// Is nothing left?
|
||||
fn used_up() -> bool {
|
||||
ART_WALK_LEFT.get() == Some(0)
|
||||
}
|
||||
|
||||
/// Takes `n` objects from what is left. `false` when fewer are left, and nothing is left after.
|
||||
fn take(n: u64) -> bool {
|
||||
let Some(left) = ART_WALK_LEFT.get() else { return true };
|
||||
let rest = left.checked_sub(n);
|
||||
ART_WALK_LEFT.set(Some(rest.unwrap_or(0)));
|
||||
rest.is_some()
|
||||
}
|
||||
|
||||
/// While the guard lives, each object [`hit_any`] visits takes one object from what is left:
|
||||
/// [`FindPart`] holds one while it tests a placed object of symbol art, so that the members of an
|
||||
/// Intertwine group, and the objects of groups nested deeper than
|
||||
/// [`crate::symbol_overrides::MAX_PATH_DEPTH`], count toward the limit.
|
||||
fn charge() -> ArtWalkCharge {
|
||||
ArtWalkCharge { was: ART_WALK_CHARGED.replace(true) }
|
||||
}
|
||||
|
||||
/// Does [`hit_any`] take the objects it visits from what is left ([`Self::charge`])?
|
||||
fn charged() -> bool {
|
||||
ART_WALK_CHARGED.get()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ArtWalk {
|
||||
fn drop(&mut self) {
|
||||
if self.outermost {
|
||||
ART_WALK_LEFT.set(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The guard of [`ArtWalk::charge`].
|
||||
struct ArtWalkCharge {
|
||||
was: bool,
|
||||
}
|
||||
|
||||
impl Drop for ArtWalkCharge {
|
||||
fn drop(&mut self) {
|
||||
ART_WALK_CHARGED.set(self.was);
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `n` below a layer whose Preview is off, so that the canvas draws it in outline? As for clicks
|
||||
/// ([`path_options`]), the Preview of the isolated container `scope` and of the layers around it
|
||||
/// does not count.
|
||||
@@ -1502,6 +1659,7 @@ fn previews_off(n: &Node) -> bool {
|
||||
}
|
||||
|
||||
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool, outline: bool) -> Vec<NodeId> {
|
||||
let _walk = ArtWalk::open();
|
||||
let mut out = Vec::new();
|
||||
// The objects the marquee may touch ([`Top`]).
|
||||
let tops: Vec<Top> = match scope.and_then(|s| doc.node(s)) {
|
||||
@@ -1613,8 +1771,9 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)),
|
||||
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)),
|
||||
// A symbol instance is touched by its box, and outside it where the live geometry
|
||||
// effects of a clipping path in its art show the art.
|
||||
NodeKind::SymbolInstance { .. } => box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds),
|
||||
// effects of a clipping path in its art show the art. In the art of another instance
|
||||
// walked outside that instance's box, it is touched only by its own art ([`ArtOnly`]).
|
||||
NodeKind::SymbolInstance { .. } => !ArtOnly::on() && box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds),
|
||||
_ => box_touches(n, s, r),
|
||||
}
|
||||
}
|
||||
@@ -1628,15 +1787,26 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
}
|
||||
/// Does the marquee `r` touch the art of symbol instance `n` placed as the canvas draws it, as
|
||||
/// it touches a group of that art? Only for art whose clipping paths have live geometry effects
|
||||
/// ([`SymbolBoxes::art`]), and only when `r` meets the instance's reach
|
||||
/// ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's box.
|
||||
/// ([`SymbolBoxes::art`]), or for any art while [`ArtOnly`] is on, and only when `r` meets the
|
||||
/// instance's reach ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's
|
||||
/// box. Not once the marquee has placed as many objects of symbol art as [`ArtWalk`] allows.
|
||||
fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool) -> bool {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return false };
|
||||
let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
|
||||
if s.art(symbol).is_none_or(|a| a.reshaped.is_none()) || !n.reach_bounds_with(s).is_some_and(meets) {
|
||||
if s.art(symbol).is_none_or(|a| a.reshaped.is_none() && !ArtOnly::on()) || !n.reach_bounds_with(s).is_some_and(meets) {
|
||||
return false;
|
||||
}
|
||||
let _walk = ArtWalk::open();
|
||||
if ArtWalk::used_up() {
|
||||
return false;
|
||||
}
|
||||
let Some(art) = InstanceArt::of(s.document(), n) else { return false };
|
||||
if !ArtWalk::take(art.size()) {
|
||||
return false;
|
||||
}
|
||||
#[cfg(test)]
|
||||
ARTS_WALKED.with(|c| c.set(c.get() + 1));
|
||||
let _art_only = ArtOnly::set();
|
||||
art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, whole_compounds, false))
|
||||
}
|
||||
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool, out: &mut Vec<NodeId>) {
|
||||
|
||||
@@ -1452,6 +1452,76 @@ fn objects_at_edit_contents_uses_general_order() {
|
||||
assert_eq!(objects_at(&d, p, opt, None), vec![b, a]);
|
||||
}
|
||||
|
||||
/// Select Behind keeps one limit of symbol art to walk when it falls back to the general
|
||||
/// traversal, for an envelope in Edit Contents and for a root that is not a layer: the fallback
|
||||
/// walks no more art than what the first pass left, and keeps what the first pass found.
|
||||
#[test]
|
||||
fn select_behind_keeps_one_art_limit_when_it_falls_back() {
|
||||
// 60 instances of `Clipped` with the rectangle hidden, which a click at (150, 50) walks the art
|
||||
// of and misses: each walk takes 3 objects of the 100.
|
||||
let stack = |d: &mut Document, count: usize| {
|
||||
let l = d.layers[0].id;
|
||||
for _ in 0..count {
|
||||
let inst = instance_of(d, "Clipped");
|
||||
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
}
|
||||
};
|
||||
// An envelope in Edit Contents at the bottom of the layer, its contents under (150, 50).
|
||||
let envelope = |d: &mut Document| {
|
||||
let inner = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(120.0, 20.0, 180.0, 80.0)), Appearance::default_art()));
|
||||
let (a, b) = (d.alloc_id(), d.alloc_id());
|
||||
let e = Node::new(
|
||||
d.alloc_id(),
|
||||
NodeKind::Envelope {
|
||||
content: vec![inner(a), inner(b)],
|
||||
kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }),
|
||||
fidelity: 100.0,
|
||||
editing: true,
|
||||
options: Default::default(),
|
||||
frame: Box::new(vectorcraft_geom::Affine::IDENTITY),
|
||||
},
|
||||
);
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, e).unwrap();
|
||||
(a, b)
|
||||
};
|
||||
let p = Point::new(150.0, 50.0);
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
clipped_symbol(&mut d, false);
|
||||
let (a, b) = envelope(&mut d);
|
||||
stack(&mut d, 60);
|
||||
let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None));
|
||||
assert_eq!(behind, vec![b, a]);
|
||||
assert!(arts <= 34, "envelope in Edit Contents: {arts} instances' art walked");
|
||||
// An instance that the first pass hits by its art, the limit then used up, stays in the list:
|
||||
// `Shown` is `Clipped` with its rectangle shown, below 32 instances of `Clipped`.
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
clipped_symbol(&mut d, false);
|
||||
let (a, b) = envelope(&mut d);
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(test_move());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
group_symbol(&mut d, "Shown", vec![Arc::new(clip)]);
|
||||
let hit = instance_of(&mut d, "Shown");
|
||||
let hit_id = hit.id;
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(hit)).unwrap();
|
||||
stack(&mut d, 32);
|
||||
let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None));
|
||||
assert_eq!(behind, vec![hit_id, b, a], "hit before the fallback");
|
||||
assert!(arts <= 34, "hit before the fallback: {arts} instances' art walked");
|
||||
// A root that is not a layer, below the layer.
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
clipped_symbol(&mut d, false);
|
||||
stack(&mut d, 60);
|
||||
let root = Arc::new(Node::group(d.alloc_id(), vec![]));
|
||||
d.layers.insert(0, root);
|
||||
let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None));
|
||||
assert!(behind.is_empty());
|
||||
assert!(arts <= 34, "root that is not a layer: {arts} instances' art walked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_and_hidden_skip() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
@@ -1961,6 +2031,216 @@ fn a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box() {
|
||||
assert_eq!(at(108.0, HitOptions { outline: true, ..HitOptions::default() }), None, "Outline view");
|
||||
}
|
||||
|
||||
/// Outside a symbol instance's box, an instance nested in its art counts where its own art is, not
|
||||
/// anywhere in its box: a click or a marquee on empty space in the nested box, where a moved
|
||||
/// clipping path shows the art past the outer box, selects nothing, and on art drawn there it
|
||||
/// selects the outer instance.
|
||||
#[test]
|
||||
fn a_nested_symbol_instances_box_past_the_outer_box_is_not_a_hit() {
|
||||
set_clip_region(moved_clip_region);
|
||||
// `Two` draws squares at the corners of 0..200 × 0..100, and with `middle` one at 140..160 ×
|
||||
// 40..60. The outer symbol clips an instance of it to 0..100 × 0..100, which `test.move` moves
|
||||
// to 100..200: the outer box is 0..100, the nested box 0..200.
|
||||
let build = |middle: bool| {
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let square = |d: &mut Document, r: Rect| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art()));
|
||||
let mut squares = vec![square(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0)), square(&mut d, Rect::new(190.0, 90.0, 200.0, 100.0))];
|
||||
if middle {
|
||||
squares.push(square(&mut d, Rect::new(140.0, 40.0, 160.0, 60.0)));
|
||||
}
|
||||
group_symbol(&mut d, "Two", squares);
|
||||
let (mut mask, _) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(test_move());
|
||||
let nested = instance_of(&mut d, "Two");
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), nested]);
|
||||
clip.set_clips(true);
|
||||
group_symbol(&mut d, "Outer", vec![Arc::new(clip)]);
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Outer".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
(d, inst)
|
||||
};
|
||||
let at = |d: &Document, x: f64, y: f64| hit_test(d, Point::new(x, y), HitOptions::default()).map(|h| h.leaf);
|
||||
let inside = Rect::new(145.0, 45.0, 155.0, 55.0);
|
||||
let (d, inst) = build(false);
|
||||
assert_eq!(at(&d, 150.0, 50.0), None, "empty space in the nested box");
|
||||
assert!(marquee(&d, inside, None, false).is_empty(), "marquee on empty space in the nested box");
|
||||
assert_eq!(at(&d, 195.0, 95.0), Some(inst), "on the nested art past the outer box");
|
||||
assert_eq!(at(&d, 50.0, 50.0), Some(inst), "in the outer box");
|
||||
let (d, inst) = build(true);
|
||||
assert_eq!(at(&d, 150.0, 50.0), Some(inst), "on the nested art");
|
||||
// Across the middle square's left edge.
|
||||
assert_eq!(marquee(&d, Rect::new(135.0, 45.0, 145.0, 55.0), None, false), [inst], "marquee on the nested art");
|
||||
}
|
||||
|
||||
/// Adds the symbol `Clipped`: a clip group whose clipping path's region `test.move` moves to
|
||||
/// 100..200 × 0..100, past the 0..100 box, over a 0..200 × 0..100 rectangle shown when `shown`.
|
||||
/// A click at (150, 50) hits an instance of it on the rectangle, or, with the rectangle hidden,
|
||||
/// walks its art and finds nothing.
|
||||
fn clipped_symbol(d: &mut Document, shown: bool) {
|
||||
set_clip_region(moved_clip_region);
|
||||
let (mut mask, mut art) = half_clipped(d);
|
||||
mask.appearance.effects.push(test_move());
|
||||
art.visible = shown;
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(clip)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "Clipped".into(), art: Arc::new(root) });
|
||||
}
|
||||
|
||||
/// A symbol named `name` whose art is a group of `members`.
|
||||
fn group_symbol(d: &mut Document, name: &str, members: Vec<Arc<Node>>) {
|
||||
let root = Node::group(d.alloc_id(), members);
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: name.into(), art: Arc::new(root) });
|
||||
}
|
||||
|
||||
/// An instance of the symbol named `symbol`, not moved.
|
||||
fn instance_of(d: &mut Document, symbol: &str) -> Arc<Node> {
|
||||
Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY }))
|
||||
}
|
||||
|
||||
/// 30 small squares at the origin, which a click at (150, 50) passes by.
|
||||
fn far_squares(d: &mut Document) -> Vec<Arc<Node>> {
|
||||
(0..30).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()))).collect()
|
||||
}
|
||||
|
||||
/// Runs `f` with [`ArtWalk`] allowing `limit` objects, and returns its result with how many
|
||||
/// leaves [`hit_leaf`] tested and how many instances' art was walked meanwhile.
|
||||
fn with_art_limit<R>(limit: u64, f: impl FnOnce() -> R) -> (R, usize, usize) {
|
||||
ART_WALK_LIMIT.with(|c| c.set(Some(limit)));
|
||||
LEAVES_TESTED.with(|c| c.set(0));
|
||||
ARTS_WALKED.with(|c| c.set(0));
|
||||
let r = f();
|
||||
ART_WALK_LIMIT.with(|c| c.set(None));
|
||||
(r, LEAVES_TESTED.with(std::cell::Cell::get), ARTS_WALKED.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
/// One click visits at most the art walk's limit of objects in a chain of nested symbol
|
||||
/// instances, though each level's art alone is well within it. A click on the art of an
|
||||
/// instance nested in another is still found.
|
||||
#[test]
|
||||
fn a_click_walks_a_chain_of_nested_symbol_instances_within_one_limit() {
|
||||
// Level 0 is `Clipped`; each level above holds an instance of the level below and 30 squares:
|
||||
// 32 objects to visit at each level.
|
||||
let chain = |shown: bool| {
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
clipped_symbol(&mut d, shown);
|
||||
for level in 1..12 {
|
||||
let below = if level == 1 { "Clipped".to_string() } else { format!("Level {}", level - 1) };
|
||||
let mut members = vec![instance_of(&mut d, &below)];
|
||||
members.extend(far_squares(&mut d));
|
||||
group_symbol(&mut d, &format!("Level {level}"), members);
|
||||
}
|
||||
let inst = instance_of(&mut d, "Level 11");
|
||||
let id = inst.id;
|
||||
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
(d, id)
|
||||
};
|
||||
let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), HitOptions::default()).map(|h| h.leaf);
|
||||
// Without one limit for the click, the miss walks the art of all 12 levels.
|
||||
let (d, inst) = chain(false);
|
||||
let (hit, _, arts) = with_art_limit(100, || at(&d, 150.0));
|
||||
assert_eq!(hit, None);
|
||||
assert!(arts <= 4, "{arts} levels walked");
|
||||
assert_eq!(with_art_limit(100, || at(&d, 50.0)).0, Some(inst), "in the box");
|
||||
// Past the limit, a click that the art would take finds only the box.
|
||||
let (d, inst) = chain(true);
|
||||
assert_eq!(with_art_limit(100, || at(&d, 150.0)).0, None, "past the limit");
|
||||
assert_eq!(at(&d, 150.0), Some(inst), "within the limit");
|
||||
// Two levels: a click on the inner instance's art is found within the limit.
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
clipped_symbol(&mut d, true);
|
||||
let inner = instance_of(&mut d, "Clipped");
|
||||
group_symbol(&mut d, "Outer", vec![inner]);
|
||||
let inst = instance_of(&mut d, "Outer");
|
||||
let id = inst.id;
|
||||
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
assert_eq!(with_art_limit(100, || at(&d, 150.0)).0, Some(id), "nested");
|
||||
}
|
||||
|
||||
/// One click, and one marquee, visit at most the art walk's limit of objects in art that repeats
|
||||
/// one nested instance many times, though the art of each instance alone is well within it. A
|
||||
/// click on one of the nested instances' art is still found.
|
||||
#[test]
|
||||
fn a_click_and_a_marquee_walk_repeated_nested_symbol_instances_within_one_limit() {
|
||||
// 50 instances of `Clipped` in one symbol's art, its rectangle shown when `shown`.
|
||||
let repeated = |shown: bool| {
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
clipped_symbol(&mut d, shown);
|
||||
let members = (0..50).map(|_| instance_of(&mut d, "Clipped")).collect();
|
||||
group_symbol(&mut d, "Repeated", members);
|
||||
let inst = instance_of(&mut d, "Repeated");
|
||||
let id = inst.id;
|
||||
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
(d, id)
|
||||
};
|
||||
let (d, inst) = repeated(false);
|
||||
// Without one limit for the click, the miss walks the art of all 51 instances. The outer art
|
||||
// takes 1 object of the 100, and each nested instance with its art 4.
|
||||
let (hit, _, arts) = with_art_limit(100, || hit_test(&d, Point::new(150.0, 50.0), HitOptions::default()).map(|h| h.leaf));
|
||||
assert_eq!(hit, None);
|
||||
assert!(arts <= 26, "{arts} instances' art walked");
|
||||
// Select Behind over 60 instances of `Clipped` on the layer shares one limit too: each walk
|
||||
// takes 3 objects of the 100.
|
||||
let mut stack = Document::new(600.0, 400.0);
|
||||
let l = stack.layers[0].id;
|
||||
clipped_symbol(&mut stack, false);
|
||||
for _ in 0..60 {
|
||||
let inst = instance_of(&mut stack, "Clipped");
|
||||
stack.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
}
|
||||
let (behind, _, arts) = with_art_limit(100, || objects_at(&stack, Point::new(150.0, 50.0), HitOptions::default(), None));
|
||||
assert!(behind.is_empty());
|
||||
assert!(arts <= 34, "Select Behind: {arts} instances' art walked");
|
||||
// Without one limit for the marquee, it places the art of all 51 instances, inside the moved
|
||||
// region (within each instance's reach and outside its box). Placing the outer art takes 51
|
||||
// objects of the 100, and each nested art 4.
|
||||
let inside = Rect::new(140.0, 40.0, 160.0, 60.0);
|
||||
let (touched, _, arts) = with_art_limit(100, || marquee(&d, inside, None, false));
|
||||
assert!(touched.is_empty());
|
||||
assert!(arts <= 14, "{arts} instances' art placed");
|
||||
assert_eq!(with_art_limit(100, || marquee(&d, Rect::new(40.0, 40.0, 60.0, 60.0), None, false)).0, [inst], "in the box");
|
||||
// A click and a marquee on the nested instances' art are found within the limit.
|
||||
let (d, inst) = repeated(true);
|
||||
assert_eq!(with_art_limit(100, || hit_test(&d, Point::new(150.0, 50.0), HitOptions::default()).map(|h| h.leaf)).0, Some(inst), "click");
|
||||
let edge = Rect::new(140.0, -5.0, 160.0, 5.0);
|
||||
assert_eq!(with_art_limit(100, || marquee(&d, edge, None, false)).0, [inst], "marquee across the art's edge");
|
||||
}
|
||||
|
||||
/// The members of an Intertwine group in symbol art count toward the art walk's limit of objects
|
||||
/// for a click, as the members of a plain group do. A click on a member's path past the instance's
|
||||
/// box is still found within the limit.
|
||||
#[test]
|
||||
fn a_click_counts_the_members_of_an_intertwine_group_in_symbol_art_toward_one_limit() {
|
||||
set_clip_region(moved_clip_region);
|
||||
// A clip group whose clipping region `test.move` moves to 100..200 × 0..100, past the 0..100
|
||||
// box, over an Intertwine group of 200 squares at 140..160 × 40..60.
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, _) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(test_move());
|
||||
let squares = (0..200)
|
||||
.map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(140.0, 40.0, 160.0, 60.0)), Appearance::default_art())))
|
||||
.collect();
|
||||
let woven = Arc::new(Node::new(d.alloc_id(), NodeKind::Intertwine { children: squares }));
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), woven]);
|
||||
clip.set_clips(true);
|
||||
group_symbol(&mut d, "Woven", vec![Arc::new(clip)]);
|
||||
let inst = instance_of(&mut d, "Woven");
|
||||
let id = inst.id;
|
||||
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
let opt = HitOptions { path_only: true, ..HitOptions::default() };
|
||||
let at = |x: f64| hit_test(&d, Point::new(x, 50.0), opt).map(|h| h.leaf);
|
||||
// Inside the squares and away from their paths, every member is tested and none is hit.
|
||||
let (hit, leaves, _) = with_art_limit(100, || at(150.0));
|
||||
assert_eq!(hit, None);
|
||||
assert!(leaves <= 100, "{leaves} leaves tested");
|
||||
assert_eq!(with_art_limit(100, || at(140.0)).0, Some(id), "on the squares' paths");
|
||||
}
|
||||
|
||||
/// In a dynamic symbol's art that placing through its 9-slice guides could make more than
|
||||
/// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the
|
||||
/// canvas draws nothing of it. At the art's natural size the same art is picked.
|
||||
|
||||
+31
-3
@@ -281,7 +281,13 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
|
||||
});
|
||||
}
|
||||
b += match &n.kind {
|
||||
NodeKind::Path { path, live, .. } => path_bytes(path) + boxed(live),
|
||||
NodeKind::Path { path, live, .. } => {
|
||||
let was = other.and_then(|o| match &o.kind {
|
||||
NodeKind::Path { path, .. } => Some(path),
|
||||
_ => None,
|
||||
});
|
||||
path_bytes_besides(path, was) + boxed(live)
|
||||
}
|
||||
NodeKind::Layer { children, .. }
|
||||
| NodeKind::Group { children, .. }
|
||||
| NodeKind::Compound { children, .. }
|
||||
@@ -298,8 +304,30 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
|
||||
}
|
||||
|
||||
fn path_bytes(p: &PathData) -> usize {
|
||||
let anchors: usize =
|
||||
p.subpaths.iter().map(|s| if s.anchors.capacity() == 0 { 0 } else { ALLOC + s.anchors.capacity() * size_of::<Anchor>() }).sum();
|
||||
path_bytes_besides(p, None)
|
||||
}
|
||||
|
||||
/// [`path_bytes`] without the anchor chunks that `other` (another version of the path) holds too:
|
||||
/// a version made by changing one anchor shares every chunk but the one it changed.
|
||||
fn path_bytes_besides(p: &PathData, other: Option<&PathData>) -> usize {
|
||||
let mut shared: Vec<usize> =
|
||||
other.map(|o| o.subpaths.iter().flat_map(|s| s.anchors.chunk_allocations()).map(|(id, _)| id).collect()).unwrap_or_default();
|
||||
shared.sort_unstable();
|
||||
let chunk = ALLOC + ARC + size_of::<Vec<Anchor>>() + ALLOC;
|
||||
let anchors: usize = p
|
||||
.subpaths
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let table = s.anchors.table_bytes();
|
||||
let own: usize = s
|
||||
.anchors
|
||||
.chunk_allocations()
|
||||
.filter(|(id, _)| shared.binary_search(id).is_err())
|
||||
.map(|(_, capacity)| chunk + capacity * size_of::<Anchor>())
|
||||
.sum();
|
||||
if table == 0 { own } else { ALLOC + table + own }
|
||||
})
|
||||
.sum();
|
||||
anchors + if p.subpaths.capacity() == 0 { 0 } else { ALLOC + p.subpaths.capacity() * size_of::<SubPath>() }
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,11 @@ pub trait ColorVisitor {
|
||||
fn color(&mut self, c: Color) -> Color;
|
||||
/// The key of embedded image `key` recoloured, `None` when it stays as it is.
|
||||
fn image(&mut self, key: &str) -> Option<String>;
|
||||
/// Whether the pass recolors child `n` of a container: false leaves `n` and everything inside
|
||||
/// it as they are.
|
||||
fn enters(&mut self, _n: &Node) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// What a recolouring pass reaches: fills (including colorized image fills and gradient-mesh
|
||||
@@ -82,6 +87,9 @@ pub fn recolor_node(n: &mut Node, reach: Reach, v: &mut dyn ColorVisitor) -> usi
|
||||
}
|
||||
_ => {
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
if !v.enters(c) {
|
||||
continue;
|
||||
}
|
||||
let mut m = (**c).clone();
|
||||
let k = recolor_node(&mut m, reach, v);
|
||||
if k > 0 {
|
||||
|
||||
@@ -18,8 +18,8 @@ mod wrap;
|
||||
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
|
||||
use char_style::yes;
|
||||
pub use char_style::{
|
||||
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics,
|
||||
WARICHU_LINES, WARICHU_SCALE, WarichuAlign,
|
||||
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_DIACRITIC_POSITION, MAX_TSUME,
|
||||
MAX_WARICHU_GAP, ScriptMetrics, WARICHU_LINES, WARICHU_SCALE, WarichuAlign,
|
||||
};
|
||||
pub use composite::{
|
||||
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass,
|
||||
|
||||
@@ -48,8 +48,10 @@ pub struct CharStyle {
|
||||
/// of the character's ink, inside its own width, that is taken away, 0 to [`MAX_TSUME`]. 50
|
||||
/// halves that space and 100 sets the ink edge to edge; the glyph itself is not scaled. A
|
||||
/// cluster takes the value of its first character. Tracking, kerning and Insert Aki are added
|
||||
/// after it. Horizontal type only.
|
||||
/// after it. In vertical type an upright character is measured above and below its ink, inside
|
||||
/// its cell down the column.
|
||||
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
|
||||
/// <https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html>
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub tsume: f64,
|
||||
/// Use glyph shapes for automatic pair spacing; false uses font metrics.
|
||||
@@ -180,6 +182,18 @@ pub struct CharStyle {
|
||||
/// these characters are drawn in, whatever digits were typed.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub digits: Digits,
|
||||
/// Adjust Horizontal Diacritic Position (Character panel, Middle Eastern options): the font's
|
||||
/// mark glyphs among these characters (GDEF class 3, such as Arabic harakat and Hebrew points)
|
||||
/// move right by a positive value and left by a negative one, relative to their letters, in
|
||||
/// 1/1000 em of the size, from -[`MAX_DIACRITIC_POSITION`] to [`MAX_DIACRITIC_POSITION`].
|
||||
/// Saved only when not 0.
|
||||
/// <https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=549>
|
||||
#[serde(default, rename = "diacriticHorizontal", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub diacritic_horizontal: f64,
|
||||
/// Adjust Vertical Diacritic Position: the mark glyphs move up by a positive value and down by
|
||||
/// a negative one, as [`Self::diacritic_horizontal`] moves them across.
|
||||
#[serde(default, rename = "diacriticVertical", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub diacritic_vertical: f64,
|
||||
/// 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")]
|
||||
@@ -553,6 +567,10 @@ pub const MAX_AKI: f64 = 1000.0;
|
||||
/// The largest Tsume ([`CharStyle::tsume`]), in percent: all the blank space beside the ink.
|
||||
pub const MAX_TSUME: f64 = 100.0;
|
||||
|
||||
/// The largest Adjust Horizontal or Vertical Diacritic Position either way
|
||||
/// ([`CharStyle::diacritic_horizontal`]), in 1/1000 em: one em.
|
||||
pub const MAX_DIACRITIC_POSITION: f64 = 1000.0;
|
||||
|
||||
/// The number of lines a warichu block may be stacked on ([`CharStyle::warichu_lines`]).
|
||||
pub const WARICHU_LINES: std::ops::RangeInclusive<u8> = 1..=6;
|
||||
|
||||
@@ -684,6 +702,8 @@ impl Default for CharStyle {
|
||||
warichu_align: WarichuAlign::Auto,
|
||||
small_caps: None,
|
||||
digits: Digits::Default,
|
||||
diacritic_horizontal: 0.0,
|
||||
diacritic_vertical: 0.0,
|
||||
font_height_reference: FontHeightReference::EmBox,
|
||||
no_break: false,
|
||||
language: None,
|
||||
@@ -707,7 +727,8 @@ impl CharStyle {
|
||||
/// same way. The Warichu Settings Lines and Scale
|
||||
/// are kept to [`WARICHU_LINES`] and [`WARICHU_SCALE`]; a gap or scale that is not a number becomes its default. The gap is kept to 0 to
|
||||
/// [`crate::MAX_COORD`], as the baseline shift is, since a scaled type object holds it in its
|
||||
/// own units.
|
||||
/// own units. The Adjust Horizontal and Vertical Diacritic Positions are kept within
|
||||
/// [`MAX_DIACRITIC_POSITION`] either way, and one that is not a number becomes 0.
|
||||
pub fn keep_dimensions_in_range(&mut self) {
|
||||
let default = Self::default();
|
||||
let within = |v: f64, or: f64| if v > 0.0 { v.min(crate::MAX_COORD) } else { or };
|
||||
@@ -723,6 +744,9 @@ impl CharStyle {
|
||||
self.aki_left = aki(self.aki_left);
|
||||
self.aki_right = aki(self.aki_right);
|
||||
self.tsume = if self.tsume.is_nan() { 0.0 } else { self.tsume.clamp(0.0, MAX_TSUME) };
|
||||
let diacritic = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(-MAX_DIACRITIC_POSITION, MAX_DIACRITIC_POSITION) };
|
||||
self.diacritic_horizontal = diacritic(self.diacritic_horizontal);
|
||||
self.diacritic_vertical = diacritic(self.diacritic_vertical);
|
||||
self.warichu_lines = self.warichu_lines.clamp(*WARICHU_LINES.start(), *WARICHU_LINES.end());
|
||||
self.warichu_gap = if self.warichu_gap.is_nan() { default.warichu_gap } else { self.warichu_gap.clamp(0.0, crate::MAX_COORD) };
|
||||
self.warichu_scale =
|
||||
|
||||
@@ -511,6 +511,8 @@ impl crate::Document {
|
||||
st.aki_left = num("akiLeft").unwrap_or(st.aki_left);
|
||||
st.aki_right = num("akiRight").unwrap_or(st.aki_right);
|
||||
st.tsume = num("tsume").unwrap_or(st.tsume);
|
||||
st.diacritic_horizontal = num("diacriticHorizontal").unwrap_or(st.diacritic_horizontal);
|
||||
st.diacritic_vertical = num("diacriticVertical").unwrap_or(st.diacritic_vertical);
|
||||
st.warichu_gap = num("warichuGap").unwrap_or(st.warichu_gap);
|
||||
st.warichu_scale = num("warichuScale").unwrap_or(st.warichu_scale);
|
||||
st.keep_dimensions_in_range();
|
||||
@@ -537,6 +539,8 @@ impl crate::Document {
|
||||
("akiLeft", Some(st.aki_left)),
|
||||
("akiRight", Some(st.aki_right)),
|
||||
("tsume", Some(st.tsume)),
|
||||
("diacriticHorizontal", Some(st.diacritic_horizontal)),
|
||||
("diacriticVertical", Some(st.diacritic_vertical)),
|
||||
("leading", st.leading),
|
||||
];
|
||||
for (k, v) in kept {
|
||||
|
||||
@@ -17,22 +17,52 @@ pub enum Justify {
|
||||
JustifyAll,
|
||||
}
|
||||
|
||||
/// Paragraph composer (Paragraph panel menu): how lines are broken.
|
||||
/// Paragraph composer (Paragraph panel menu): how lines are broken, and whether complex scripts
|
||||
/// (Indic, Arabic, Hebrew) are shaped. `SingleLine` and `EveryLine` are the Middle Eastern & South
|
||||
/// Asian composers: they shape complex scripts with the font's layout tables, as all type is set
|
||||
/// here, and are what documents saved before the four composers existed use. The `Standard`
|
||||
/// composers break lines the same way but set a complex script glyph by glyph as the font maps its
|
||||
/// characters, with no conjuncts, marks placed or joining forms: what fonts that keep a script's
|
||||
/// glyphs on Latin character codes (legacy ANSI Indic fonts) need.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Composer {
|
||||
/// Break each line as soon as it is full.
|
||||
/// Middle Eastern & South Asian Single-line Composer: break each line as soon as it is full.
|
||||
SingleLine,
|
||||
/// Total fit over the whole paragraph (Illustrator's default): justified lines get even word
|
||||
/// spacing, ragged lines an even rag.
|
||||
/// Middle Eastern & South Asian Every-line Composer: total fit over the whole paragraph
|
||||
/// (Illustrator's default): justified lines get even word spacing, ragged lines an even rag.
|
||||
#[default]
|
||||
EveryLine,
|
||||
/// Standard Single-line Composer: [`Composer::SingleLine`]'s breaks, complex scripts not shaped.
|
||||
StandardSingleLine,
|
||||
/// Standard Every-line Composer: [`Composer::EveryLine`]'s breaks, complex scripts not shaped.
|
||||
StandardEveryLine,
|
||||
}
|
||||
|
||||
impl Composer {
|
||||
fn is_default(&self) -> bool {
|
||||
*self == Self::default()
|
||||
}
|
||||
|
||||
/// Does this composer break lines one at a time (as opposed to a total fit)?
|
||||
pub fn is_single_line(self) -> bool {
|
||||
matches!(self, Self::SingleLine | Self::StandardSingleLine)
|
||||
}
|
||||
|
||||
/// Does this composer shape complex scripts ([`Composer::SingleLine`], [`Composer::EveryLine`])?
|
||||
pub fn shapes_complex_scripts(self) -> bool {
|
||||
matches!(self, Self::SingleLine | Self::EveryLine)
|
||||
}
|
||||
|
||||
/// The same shaping with the other line breaking (`single_line`: one line at a time).
|
||||
pub fn with_breaking(self, single_line: bool) -> Self {
|
||||
match (single_line, self.shapes_complex_scripts()) {
|
||||
(true, true) => Self::SingleLine,
|
||||
(true, false) => Self::StandardSingleLine,
|
||||
(false, true) => Self::EveryLine,
|
||||
(false, false) => Self::StandardEveryLine,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A paragraph's hyphenation options (Paragraph panel menu › Hyphenation…): which words automatic
|
||||
|
||||
@@ -129,6 +129,42 @@ fn insert_aki_is_saved_only_when_set() {
|
||||
assert_eq!((d.char_styles[0].attrs["akiLeft"].as_f64(), d.char_styles[0].attrs["akiRight"].as_f64()), (Some(MAX_AKI), Some(0.0)));
|
||||
}
|
||||
|
||||
/// Adjust Horizontal and Vertical Diacritic Position are 0 by default and saved only when not 0,
|
||||
/// each on its own; styles written before them read as 0, and a value out of range from a file is
|
||||
/// kept within one em either way.
|
||||
#[test]
|
||||
fn diacritic_positions_are_saved_only_when_set() {
|
||||
let st = CharStyle::default();
|
||||
assert_eq!((st.diacritic_horizontal, st.diacritic_vertical), (0.0, 0.0));
|
||||
let saved = serde_json::to_value(&st).unwrap();
|
||||
assert!(saved.get("diacriticHorizontal").is_none() && saved.get("diacriticVertical").is_none());
|
||||
for set in [
|
||||
CharStyle { diacritic_horizontal: -250.0, ..CharStyle::default() },
|
||||
CharStyle { diacritic_vertical: 500.0, ..CharStyle::default() },
|
||||
CharStyle { diacritic_horizontal: 12.5, diacritic_vertical: -1000.0, ..CharStyle::default() },
|
||||
] {
|
||||
let saved = serde_json::to_value(&set).unwrap();
|
||||
assert_eq!(saved.get("diacriticHorizontal").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.diacritic_horizontal);
|
||||
assert_eq!(saved.get("diacriticVertical").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.diacritic_vertical);
|
||||
assert_eq!(saved.get("diacriticHorizontal").is_some(), set.diacritic_horizontal != 0.0);
|
||||
assert_eq!(saved.get("diacriticVertical").is_some(), set.diacritic_vertical != 0.0);
|
||||
assert_eq!(serde_json::from_value::<CharStyle>(saved).unwrap(), set);
|
||||
}
|
||||
let mut damaged = CharStyle { diacritic_horizontal: -4000.0, diacritic_vertical: 4000.0, ..CharStyle::default() };
|
||||
damaged.keep_dimensions_in_range();
|
||||
assert_eq!((damaged.diacritic_horizontal, damaged.diacritic_vertical), (-MAX_DIACRITIC_POSITION, MAX_DIACRITIC_POSITION));
|
||||
let mut damaged = CharStyle { diacritic_horizontal: f64::NAN, diacritic_vertical: f64::NEG_INFINITY, ..CharStyle::default() };
|
||||
damaged.keep_dimensions_in_range();
|
||||
assert_eq!((damaged.diacritic_horizontal, damaged.diacritic_vertical), (0.0, -MAX_DIACRITIC_POSITION));
|
||||
// A character style from a file is kept in range the same way.
|
||||
let mut d = crate::Document::new(100.0, 100.0);
|
||||
let attrs = serde_json::json!({"diacriticHorizontal": 5000, "diacriticVertical": -5000});
|
||||
d.char_styles.push(TextStyleDef { name: "Moved".into(), attrs: attrs.as_object().cloned().unwrap_or_default() });
|
||||
d.keep_type_values_in_range();
|
||||
let kept = |key: &str| d.char_styles[0].attrs[key].as_f64();
|
||||
assert_eq!((kept("diacriticHorizontal"), kept("diacriticVertical")), (Some(MAX_DIACRITIC_POSITION), Some(-MAX_DIACRITIC_POSITION)));
|
||||
}
|
||||
|
||||
/// Tsume is 0 by default and saved only when not 0; styles written before it read as 0, and a
|
||||
/// value out of range from a file, in a run or a character style, is kept from 0 to 100.
|
||||
#[test]
|
||||
|
||||
@@ -117,6 +117,11 @@ thread_local! {
|
||||
/// The objects of symbol art that [`bake_document`] has baked for instances inside the art of
|
||||
/// other instances, counted against [`crate::SYMBOL_ART_MAX_NODES`].
|
||||
static NESTED_NODES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
/// The objects in the baked art of the instances inside the art of other instances that
|
||||
/// [`bake_node`] baked for one export and then left as they are, counted with
|
||||
/// [`NESTED_NODES`] against [`crate::SYMBOL_ART_MAX_NODES`] before more art is baked. Never
|
||||
/// given back.
|
||||
static NESTED_DROPPED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
/// While [`bake_document_placing_symbols`] bakes: the symbols whose instances become their
|
||||
/// placed art ([`placed_symbol_art`]).
|
||||
static PLACING: std::cell::RefCell<Option<Rc<Placing>>> = const { std::cell::RefCell::new(None) };
|
||||
@@ -369,17 +374,29 @@ fn bake_object(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
};
|
||||
// Instances baked inside the art of others stop at the depth limit, or once their art
|
||||
// passes the objects one export bakes that way: an instance of a symbol whose art holds
|
||||
// instances of itself is kept as it is there.
|
||||
// instances of itself is kept as it is there. The symbol's art is held in the count while
|
||||
// it bakes, so the instances inside it bake only within what is left; the art it bakes to,
|
||||
// with what its effects add, then takes its place in the count. When that art does not
|
||||
// fit, the instance stays as it is, and the art baked for it, with the art dropped for the
|
||||
// instances inside it, still counts against the instances after it.
|
||||
let instance = matches!(n.kind, NodeKind::SymbolInstance { .. });
|
||||
if instance && INSTANCE_DEPTH.with(|c| c.get()) > 0 {
|
||||
let nested = instance && INSTANCE_DEPTH.with(|c| c.get()) > 0;
|
||||
let before = NESTED_NODES.with(|c| c.get());
|
||||
if nested {
|
||||
let count = symbol.as_ref().map_or(0, |a| a.count() as u64);
|
||||
let spent = NESTED_NODES.with(|c| c.get()).saturating_add(count);
|
||||
if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || spent > crate::SYMBOL_ART_MAX_NODES {
|
||||
let spent = before.saturating_add(count);
|
||||
let dropped = NESTED_DROPPED.with(|c| c.get());
|
||||
if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || spent.saturating_add(dropped) > crate::SYMBOL_ART_MAX_NODES {
|
||||
return None;
|
||||
}
|
||||
NESTED_NODES.with(|c| c.set(spent));
|
||||
}
|
||||
let m = reshape(Some(d), n, symbol.as_ref())?;
|
||||
let Some(m) = reshape(Some(d), n, symbol.as_ref()) else {
|
||||
if nested {
|
||||
NESTED_NODES.with(|c| c.set(before));
|
||||
}
|
||||
return None;
|
||||
};
|
||||
if instance {
|
||||
INSTANCE_DEPTH.with(|c| c.set(c.get() + 1));
|
||||
}
|
||||
@@ -387,7 +404,17 @@ fn bake_object(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
if instance {
|
||||
INSTANCE_DEPTH.with(|c| c.set(c.get() - 1));
|
||||
}
|
||||
return Some(baked.unwrap_or(m));
|
||||
let baked = baked.unwrap_or(m);
|
||||
if nested {
|
||||
let spent = before.saturating_add(baked.count() as u64);
|
||||
if spent.saturating_add(NESTED_DROPPED.with(|c| c.get())) > crate::SYMBOL_ART_MAX_NODES {
|
||||
NESTED_NODES.with(|c| c.set(before));
|
||||
NESTED_DROPPED.with(|c| c.set(c.get().saturating_add(baked.count() as u64)));
|
||||
return None;
|
||||
}
|
||||
NESTED_NODES.with(|c| c.set(spent));
|
||||
}
|
||||
return Some(baked);
|
||||
}
|
||||
// Symbol instances whose art draws live effects, when the caller asks for them: the art
|
||||
// placed, then baked. When the baked art passes the export's budget, or would draw too deep
|
||||
@@ -1068,6 +1095,7 @@ fn bake(doc: &Document, placing: Option<(bool, u64, WrittenLayers)>) -> Option<D
|
||||
}
|
||||
let mut d = placed.into_owned();
|
||||
NESTED_NODES.with(|c| c.set(0));
|
||||
NESTED_DROPPED.with(|c| c.set(0));
|
||||
let layers = d.layers.clone();
|
||||
d.layers = layers.iter().map(|l| bake_node(&mut d, l).map(Arc::new).unwrap_or_else(|| l.clone())).collect();
|
||||
Some(d)
|
||||
|
||||
@@ -1525,3 +1525,125 @@ fn placing_symbols_counts_art_dropped_for_depth_against_later_baked_art() {
|
||||
let room = bake(&d, Some((true, a + e + f, ALL))).unwrap();
|
||||
assert!(!is_instance(&room, 900) && !is_instance(&room, 901));
|
||||
}
|
||||
|
||||
/// Instance `id` of `symbol` with a geometry effect, so baking it reshapes its art.
|
||||
fn offset_instance(id: u64, symbol: &str) -> Node {
|
||||
let mut n = instance(id, symbol, vectorcraft_geom::Affine::IDENTITY);
|
||||
n.appearance.effects.push(fx("path.offsetPath", json!({"offset": 1.0})));
|
||||
n
|
||||
}
|
||||
|
||||
/// `n` baked as an instance inside another instance's art, with `spent` objects of nested symbol
|
||||
/// art already baked: the baked object, and the objects counted after it, art baked and dropped
|
||||
/// included.
|
||||
fn bake_nested(d: &mut Document, n: &Node, spent: u64) -> (Option<Node>, u64) {
|
||||
INSTANCE_DEPTH.with(|c| c.set(1));
|
||||
NESTED_NODES.with(|c| c.set(spent));
|
||||
NESTED_DROPPED.with(|c| c.set(0));
|
||||
let out = bake_node(d, n);
|
||||
INSTANCE_DEPTH.with(|c| c.set(0));
|
||||
(out, NESTED_NODES.with(|c| c.replace(0)).saturating_add(NESTED_DROPPED.with(|c| c.replace(0))))
|
||||
}
|
||||
|
||||
/// The object with id `id` in `n`'s subtree.
|
||||
fn find(n: &Node, id: u64) -> Option<&Node> {
|
||||
if n.id == NodeId(id) {
|
||||
return Some(n);
|
||||
}
|
||||
n.children().into_iter().flatten().find_map(|c| find(c, id))
|
||||
}
|
||||
|
||||
/// Is `n` an object other than a symbol instance?
|
||||
fn baked(n: Option<&Node>) -> bool {
|
||||
n.is_some_and(|n| !matches!(n.kind, NodeKind::SymbolInstance { .. }))
|
||||
}
|
||||
|
||||
/// An instance baked inside another instance's art counts the art it bakes to, the copies its
|
||||
/// symbol's effects make included: art that fits exactly takes the last of the budget, and art
|
||||
/// whose symbol fits but whose baked art does not leaves the instance as it is and still counts.
|
||||
#[test]
|
||||
fn nested_reshape_counts_baked_art() {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
add_symbol(&mut d, "Inner", gradient_copies(800));
|
||||
let n = offset_instance(900, "Inner");
|
||||
let source = d.symbols[0].art.count() as u64;
|
||||
let (all, spent) = bake_nested(&mut d, &n, 0);
|
||||
let baked = all.map_or(0, |m| m.count() as u64);
|
||||
assert!(baked > source + 1, "the copies are objects of their own: {baked} > {source} + 1");
|
||||
assert_eq!(spent, baked, "the baked art is counted in place of the symbol's art");
|
||||
let max = crate::SYMBOL_ART_MAX_NODES;
|
||||
let (exact, spent) = bake_nested(&mut d, &n, max - baked);
|
||||
assert!(exact.is_some(), "{baked} objects fit in {baked}");
|
||||
assert_eq!(spent, max);
|
||||
let (short, spent) = bake_nested(&mut d, &n, max - baked + 1);
|
||||
assert!(short.is_none(), "the symbol's {source} objects fit, the {baked} baked ones do not");
|
||||
assert_eq!(spent, max + 1, "the art baked for the instance left as it is still counts");
|
||||
}
|
||||
|
||||
/// An instance left as it is because its baked art does not fit still counts the art baked for
|
||||
/// it: an instance after it is left as it is too, before its art bakes.
|
||||
#[test]
|
||||
fn nested_reshape_refusal_keeps_its_work_counted() {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
add_symbol(&mut d, "Big", gradient_copies(800));
|
||||
add_symbol(&mut d, "Small", moved_square(810));
|
||||
let (big, small) = (offset_instance(900, "Big"), offset_instance(901, "Small"));
|
||||
let count = |d: &mut Document, n: &Node| bake_nested(d, n, 0).0.map_or(0, |m| m.count() as u64);
|
||||
let (b, s) = (count(&mut d, &big), count(&mut d, &small));
|
||||
assert!(s < b, "{s} < {b}");
|
||||
let first = crate::SYMBOL_ART_MAX_NODES - b + 1;
|
||||
let (refused, spent) = bake_nested(&mut d, &big, first);
|
||||
assert!(refused.is_none(), "the big art passes the budget");
|
||||
assert_eq!(spent, first + b, "the big art baked and dropped counts");
|
||||
let (later, after) = bake_nested(&mut d, &small, spent);
|
||||
assert!(later.is_none(), "the small art does not fit after the dropped art");
|
||||
assert_eq!(after, spent, "the small instance is refused before it bakes");
|
||||
}
|
||||
|
||||
/// Sibling instances inside other instances' art whose baked art each passes what is left: the
|
||||
/// first is baked and dropped, and its art counts, so the others are left as they are before
|
||||
/// their art bakes. With room for all of them, every one is baked.
|
||||
#[test]
|
||||
fn nested_reshape_refused_siblings_bake_once() {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
add_symbol(&mut d, "Big", gradient_copies(800));
|
||||
let one = offset_instance(900, "Big");
|
||||
let b = bake_nested(&mut d, &one, 0).0.map_or(0, |m| m.count() as u64);
|
||||
let siblings: Vec<Arc<Node>> = (0..16).map(|i| Arc::new(offset_instance(1000 + i, "Big"))).collect();
|
||||
let group = Node::group(NodeId(999), siblings);
|
||||
let first = crate::SYMBOL_ART_MAX_NODES - b + 1;
|
||||
let (refused, spent) = bake_nested(&mut d, &group, first);
|
||||
let refused = refused.unwrap_or_else(|| group.clone());
|
||||
assert!((0..16).all(|i| !baked(find(&refused, 1000 + i))), "no sibling fits: {refused:?}");
|
||||
assert_eq!(spent, first + b, "only the first sibling's art is baked and counted: {spent}");
|
||||
let (room, spent) = bake_nested(&mut d, &group, 0);
|
||||
let room = room.unwrap_or_else(|| panic!("the siblings are baked"));
|
||||
assert!((0..16).all(|i| baked(find(&room, 1000 + i))), "every sibling is baked");
|
||||
assert_eq!(spent, 16 * b);
|
||||
}
|
||||
|
||||
/// An instance inside another instance's art whose own art holds a reshaped instance counts that
|
||||
/// instance's baked art once: a budget of exactly the outer art's baked objects bakes both, and
|
||||
/// with one object less the art baked and dropped still counts.
|
||||
#[test]
|
||||
fn nested_reshape_counts_successful_descendants_once() {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
add_symbol(&mut d, "Inner", gradient_copies(800));
|
||||
let square = Node::path(NodeId(803), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
add_symbol(&mut d, "Outer", Node::group(NodeId(801), vec![Arc::new(offset_instance(802, "Inner")), Arc::new(square)]));
|
||||
let outer = offset_instance(900, "Outer");
|
||||
let (all, spent) = bake_nested(&mut d, &outer, 0);
|
||||
let all = all.unwrap_or_else(|| panic!("the outer instance is baked"));
|
||||
assert!(baked(find(&all, 802)), "the inner instance is baked: {all:?}");
|
||||
let total = all.count() as u64;
|
||||
assert_eq!(spent, total);
|
||||
let max = crate::SYMBOL_ART_MAX_NODES;
|
||||
let (exact, spent) = bake_nested(&mut d, &outer, max - total);
|
||||
let exact = exact.unwrap_or_else(|| panic!("{total} objects fit in {total}"));
|
||||
assert!(baked(find(&exact, 802)), "the inner instance is baked too");
|
||||
assert_eq!(spent, max);
|
||||
let (short, spent) = bake_nested(&mut d, &outer, max - total + 1);
|
||||
assert!(short.as_ref().is_none_or(|m| !baked(find(m, 802))), "with one object less, not both are baked");
|
||||
assert!(spent > max, "the art baked and dropped counts: {spent}");
|
||||
assert!(spent <= max - total + 1 + 2 * total, "at most the outer and the inner art are dropped: {spent}");
|
||||
}
|
||||
@@ -267,7 +267,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"distort.transform",
|
||||
"Transform…",
|
||||
DT,
|
||||
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, while the angles and light directions of pixel filters stay as they are; so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}",
|
||||
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale, a Drop Shadow's offset turns, reflects and scales, a pixel filter's lightDirection or strokeDirection turns and reflects to the nearest choice (at a tie, the one clockwise of it; VectorCraft's own rule), and Color Halftone's channel angles turn and reflect with the art (0 to 360); so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}",
|
||||
json!({"scaleH": 100.0, "scaleV": 100.0, "moveH": 0.0, "moveV": 0.0, "rotate": 0.0, "copies": 0, "reflectX": false, "reflectY": false, "reference": 4, "random": false, "objects": true, "patterns": false, "strokes": false}),
|
||||
),
|
||||
g(
|
||||
@@ -859,7 +859,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
crate::SVG_FILTER,
|
||||
"SVG Filter",
|
||||
&["Effect", "SVG Filters"],
|
||||
"{name: string (the filter's id), xml: string (one SVG <filter> element with an id and 1..64 primitives, at most 64 KB), scale: number 0.001..1000 (1; points per unit of the filter's user space), origin: [x, y] pt ([0, 0]; where the filter's user space starts in the document)} runs the SVG filter on the object's pixels, its lengths in points times scale, at the Document Raster Effects resolution or finer; svgFilter.apply applies one of the document's filters (svgFilter.list)",
|
||||
"{name: string (the filter's id), xml: string (one SVG <filter> element with an id and 1..64 primitives, at most 64 KB), scale: number 0.001..1000 (1; points per unit of the filter's user space), origin: [x, y] pt ([0, 0]; where the filter's user space starts in the document), axes?: [a, b, c, d] (absent or [1, 0, 0, 1]: the document's axes, and not null; the document directions of one unit along the filter's x axis [a, b] and y axis [c, d] before scale, each -1000..1000, with a·d - b·c at least 0.001 from 0; a turned, skewed or unevenly scaled user space, as SVG import gives a filtered element under a rotate, skew or uneven scale; the filter's offsets, blurs and region run along these axes; moving, turning or skewing the object moves origin and leaves axes)} runs the SVG filter on the object's pixels, its lengths in points times scale, at the Document Raster Effects resolution or finer; svgFilter.apply applies one of the document's filters (svgFilter.list)",
|
||||
json!({"scale": 1.0, "origin": [0.0, 0.0]}),
|
||||
));
|
||||
v
|
||||
|
||||
@@ -853,7 +853,11 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
}
|
||||
if !fx.is_empty() {
|
||||
m = crate::reshape::outlined_members(doc, &m);
|
||||
members_as_drawn(doc, &mut m);
|
||||
{
|
||||
// The members' raster effects then follow the group's own Transform effects as well.
|
||||
let _later = crate::raster::LaterGroups::enter(&n.appearance.effects);
|
||||
members_as_drawn(doc, &mut m);
|
||||
}
|
||||
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
|
||||
// The group's own fills and strokes paint the members as a whole: their gradients follow
|
||||
// the effects as the members' do.
|
||||
|
||||
@@ -321,6 +321,22 @@ pub(crate) fn opaque_paint(paint: &Paint) -> (Paint, Option<Paint>) {
|
||||
(base, transparent.then_some(mask))
|
||||
}
|
||||
|
||||
/// [`opaque_paint`] for a surface of several faces under one opacity mask. A transparent gradient
|
||||
/// without a placement (or a freeform gradient without points) is first pinned to `bounds`, the
|
||||
/// faces' bounds together grown by 1 pt, so every face's color and the mask share one placement.
|
||||
/// An opaque gradient is returned as [`opaque_paint`] returns it.
|
||||
pub(crate) fn opaque_surface_paint(paint: &Paint, bounds: impl FnOnce() -> vectorcraft_geom::Rect) -> (Paint, Option<Paint>) {
|
||||
let (base, mask) = opaque_paint(paint);
|
||||
if mask.is_none() || !matches!(paint, Paint::Gradient(_)) {
|
||||
return (base, mask);
|
||||
}
|
||||
let mut pinned = paint.clone();
|
||||
if let Paint::Gradient(g) = &mut pinned {
|
||||
g.pin(bounds().inflate(1.0, 1.0));
|
||||
}
|
||||
opaque_paint(&pinned)
|
||||
}
|
||||
|
||||
fn composed_art(id: vectorcraft_doc::NodeId, path: &vectorcraft_geom::PathData, paint: &Paint, light: Ramp, seam: f64) -> vectorcraft_doc::Node {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::color::BlendMode;
|
||||
|
||||
+113
-2
@@ -29,6 +29,8 @@ mod sketch_ink;
|
||||
mod texture;
|
||||
mod video;
|
||||
|
||||
use std::f64::consts::{PI, TAU};
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
|
||||
@@ -332,6 +334,9 @@ pub struct PixelSpace {
|
||||
pub extent: f64,
|
||||
}
|
||||
|
||||
/// Color Halftone's screen angle parameters with their defaults (degrees).
|
||||
const SCREEN_ANGLES: [(&str, f64); 4] = [("channel1", 108.0), ("channel2", 162.0), ("channel3", 90.0), ("channel4", 45.0)];
|
||||
|
||||
/// Effect `id`'s parameters `p` (defaults merged in) as a [`PixelFx`]; `None` for other effects.
|
||||
pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
let quality = |levels: [(&str, u32); 3], default: u32| {
|
||||
@@ -565,8 +570,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
},
|
||||
"pixelate.colorHalftone" => PixelFx::ColorHalftone {
|
||||
max_radius: num(p, "maxRadius", 8.0).clamp(4.0, 127.0),
|
||||
angles: [("channel1", 108.0), ("channel2", 162.0), ("channel3", 90.0), ("channel4", 45.0)]
|
||||
.map(|(k, d)| num(p, k, d).clamp(-360.0, 360.0)),
|
||||
angles: SCREEN_ANGLES.map(|(k, d)| num(p, k, d).clamp(-360.0, 360.0)),
|
||||
},
|
||||
"pixelate.crystallize" => PixelFx::Crystallize { cell: num(p, "cellSize", 10.0).clamp(3.0, 300.0) },
|
||||
"pixelate.mezzotint" => PixelFx::Mezzotint { kind: Mezzotint::parse(text(p, "type", "fineDots")) },
|
||||
@@ -855,6 +859,113 @@ fn pick<T: Clone>(table: &[(&str, &str)], all: &[T], value: &str, default: T) ->
|
||||
table.iter().zip(all).find(|((_, v), _)| v.eq_ignore_ascii_case(value)).map_or(default, |(_, t)| t.clone())
|
||||
}
|
||||
|
||||
/// The shortest that a direction's unit vector may become under a Transform effect and still give
|
||||
/// a direction ([`turned_directions`]).
|
||||
const MIN_TURNED: f64 = 1e-9;
|
||||
|
||||
/// How close (radians) two directions' angles to a turned direction must be to count as equally
|
||||
/// near ([`nearest`]).
|
||||
const TIE: f64 = 1e-9;
|
||||
|
||||
/// The parameters of pixel filter `id` (params `p`, defaults not merged in) that set a direction
|
||||
/// on the page, as `a` turns them: `a` is the linear part of a Transform effect listed after the
|
||||
/// filter, which turns, reflects and scales what the filter paints. A light direction or stroke
|
||||
/// direction becomes the one nearest to where `a` takes it, the one clockwise of it when two are
|
||||
/// equally near ([`snapped`]); `later` is the map the filter still goes through when it is drawn,
|
||||
/// after `a`. Color Halftone's screen angles (degrees counterclockwise from the page's horizontal)
|
||||
/// turn with `a`, from 0 up to 360. A direction that `a` takes to no direction (a zero scale) stays
|
||||
/// as it is. Empty for filters with no such parameter.
|
||||
pub(crate) fn turned_directions(id: &str, p: &Value, a: Affine, later: Affine) -> Vec<(&'static str, Value)> {
|
||||
enum Kind {
|
||||
Light(&'static str),
|
||||
Stroke,
|
||||
Screens,
|
||||
}
|
||||
let kind = match id {
|
||||
"sketch.basRelief" => Kind::Light("bottom"),
|
||||
"artistic.underpainting" | "artistic.roughPastels" | "sketch.conteCrayon" | "sketch.plaster" | "texture.texturizer" => Kind::Light("top"),
|
||||
"brushStrokes.sprayedStrokes" | "sketch.graphicPen" => Kind::Stroke,
|
||||
"pixelate.colorHalftone" => Kind::Screens,
|
||||
_ => return Vec::new(),
|
||||
};
|
||||
let p = crate::merged_params(id, p);
|
||||
match kind {
|
||||
Kind::Light(default) => {
|
||||
let light = Light::parse(text(&p, "lightDirection", default));
|
||||
snapped(&Light::ALL, Light::toward, light, a, later, false)
|
||||
.and_then(|t| name_of(&LIGHT_DIRECTIONS, &Light::ALL, t))
|
||||
.map(|name| vec![("lightDirection", Value::from(name))])
|
||||
.unwrap_or_default()
|
||||
}
|
||||
Kind::Stroke => {
|
||||
let direction = StrokeDirection::parse(text(&p, "strokeDirection", "rightDiagonal"));
|
||||
snapped(&StrokeDirection::ALL, StrokeDirection::along, direction, a, later, true)
|
||||
.and_then(|t| name_of(&STROKE_DIRECTIONS, &StrokeDirection::ALL, t))
|
||||
.map(|name| vec![("strokeDirection", Value::from(name))])
|
||||
.unwrap_or_default()
|
||||
}
|
||||
// A screen at θ° runs along (cos θ, −sin θ) on the page (y down).
|
||||
Kind::Screens => SCREEN_ANGLES
|
||||
.iter()
|
||||
.filter_map(|&(key, default)| {
|
||||
let t = num(&p, key, default).clamp(-360.0, 360.0).to_radians();
|
||||
let v = mapped(a, Vec2::new(t.cos(), -t.sin()))?;
|
||||
let degrees = ((-v.y).atan2(v.x).to_degrees() * 1e6).round() / 1e6;
|
||||
Some((key, Value::from(degrees.rem_euclid(360.0) + 0.0)))
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the linear part of `a` takes direction `v`; `None` when it takes it to no direction.
|
||||
fn mapped(a: Affine, v: Vec2) -> Option<Vec2> {
|
||||
let w = (a * v.to_point()) - (a * Point::ORIGIN);
|
||||
(w.is_finite() && w.hypot() > MIN_TURNED).then_some(w)
|
||||
}
|
||||
|
||||
/// The entry of `all` to store for `from` (directions `dir`) once `a` turns it: the one nearest to
|
||||
/// where `a` takes it ([`nearest`]). When the stored entry is still to be mapped by `later` and
|
||||
/// rounded again as it is drawn, it is the entry nearest to that among those that `later` takes to
|
||||
/// the entry nearest to where `later` after `a` takes `from`, so that the drawn direction is
|
||||
/// rounded once. `None` when `a` takes `from` to no direction.
|
||||
fn snapped<T: Copy + PartialEq>(all: &[T], dir: fn(T) -> Vec2, from: T, a: Affine, later: Affine, axis: bool) -> Option<T> {
|
||||
let v = mapped(a, dir(from))?;
|
||||
let turned = nearest(all, dir, v, axis)?;
|
||||
if later == Affine::IDENTITY {
|
||||
return Some(turned);
|
||||
}
|
||||
let Some(target) = mapped(later * a, dir(from)).and_then(|w| nearest(all, dir, w, axis)) else { return Some(turned) };
|
||||
let fits: Vec<T> = all.iter().copied().filter(|&t| mapped(later, dir(t)).and_then(|w| nearest(all, dir, w, axis)) == Some(target)).collect();
|
||||
nearest(&fits, dir, v, axis).or(Some(turned))
|
||||
}
|
||||
|
||||
/// The entry of `all` whose direction (`dir`, page axes with y down) is nearest to `v` by angle,
|
||||
/// a direction and its opposite counting as the same with `axis`. Of two equally near, the one
|
||||
/// clockwise of `v` on the page.
|
||||
fn nearest<T: Copy>(all: &[T], dir: impl Fn(T) -> Vec2, v: Vec2, axis: bool) -> Option<T> {
|
||||
let period = if axis { PI } else { TAU };
|
||||
let at = v.atan2();
|
||||
let mut best: Option<(T, f64)> = None;
|
||||
for &t in all {
|
||||
// How far clockwise of `v` the entry lies, within half a period either way.
|
||||
let d = (dir(t).atan2() - at).rem_euclid(period);
|
||||
let d = if d > period / 2.0 { d - period } else { d };
|
||||
let better = match best {
|
||||
None => true,
|
||||
Some((_, b)) => d.abs() < b.abs() - TIE || (d.abs() <= b.abs() + TIE && d > b),
|
||||
};
|
||||
if better {
|
||||
best = Some((t, d));
|
||||
}
|
||||
}
|
||||
best.map(|(t, _)| t)
|
||||
}
|
||||
|
||||
/// The value in `table` of entry `t` of `all` (the same order).
|
||||
fn name_of<T: PartialEq>(table: &[(&'static str, &'static str)], all: &[T], t: T) -> Option<&'static str> {
|
||||
table.iter().zip(all).find(|(_, u)| **u == t).map(|((_, v), _)| *v)
|
||||
}
|
||||
|
||||
/// `data` as `w` × `h` RGBA pixels, `None` when it isn't that size (or is empty).
|
||||
fn pixels(data: &mut [u8], w: usize, h: usize) -> Option<&mut [[u8; 4]]> {
|
||||
let (px, rest) = data.as_chunks_mut::<4>();
|
||||
|
||||
@@ -43,7 +43,7 @@ pub enum StrokeDirection {
|
||||
}
|
||||
|
||||
impl StrokeDirection {
|
||||
const ALL: [StrokeDirection; 4] =
|
||||
pub(super) const ALL: [StrokeDirection; 4] =
|
||||
[StrokeDirection::RightDiagonal, StrokeDirection::Horizontal, StrokeDirection::LeftDiagonal, StrokeDirection::Vertical];
|
||||
|
||||
/// The direction of `value` (a [`STROKE_DIRECTIONS`] value, any case); Right Diagonal
|
||||
@@ -53,7 +53,7 @@ impl StrokeDirection {
|
||||
}
|
||||
|
||||
/// The unit vector along the strokes (document axes, y down).
|
||||
fn along(self) -> Vec2 {
|
||||
pub(super) fn along(self) -> Vec2 {
|
||||
match self {
|
||||
StrokeDirection::RightDiagonal => RIGHT,
|
||||
StrokeDirection::Horizontal => Vec2::new(1.0, 0.0),
|
||||
|
||||
@@ -137,7 +137,7 @@ pub enum Light {
|
||||
}
|
||||
|
||||
impl Light {
|
||||
const ALL: [Light; 8] =
|
||||
pub(super) const ALL: [Light; 8] =
|
||||
[Light::Bottom, Light::BottomLeft, Light::Left, Light::TopLeft, Light::Top, Light::TopRight, Light::Right, Light::BottomRight];
|
||||
|
||||
/// The direction of `value` (a [`LIGHT_DIRECTIONS`] value, any case); Top otherwise.
|
||||
|
||||
@@ -452,7 +452,7 @@ pub(crate) fn followed(effects: &[Effect]) -> Cow<'_, [Effect]> {
|
||||
let Some(a) = after.filter(|a| *a != Affine::IDENTITY && follows(&e.id)) else { continue };
|
||||
let list = out.get_or_insert_with(|| effects.to_vec());
|
||||
if let Some(e) = list.get_mut(i) {
|
||||
follow_transform(e, a);
|
||||
follow_transform(e, a, Affine::IDENTITY);
|
||||
}
|
||||
}
|
||||
out.map_or(Cow::Borrowed(effects), Cow::Owned)
|
||||
@@ -472,7 +472,7 @@ pub(crate) fn follow_one(effects: &mut [Effect], t: &Effect) -> bool {
|
||||
let Some(a) = transform_step(t).filter(|a| *a != Affine::IDENTITY) else { return false };
|
||||
let mut changed = false;
|
||||
for e in effects.iter_mut().filter(|e| follows(&e.id)) {
|
||||
follow_transform(e, a);
|
||||
follow_transform(e, a, Affine::IDENTITY);
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
@@ -519,7 +519,7 @@ pub(crate) fn follow_contents(effects: &mut [Effect], a: Affine, outer: Affine)
|
||||
let det = b.determinant();
|
||||
let c = if b == Affine::IDENTITY || !(det.is_finite() && det.abs() > 1e-12) { a } else { b.inverse() * a * b };
|
||||
if c.is_finite() {
|
||||
follow_transform(e, c);
|
||||
follow_transform(e, c, b);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
@@ -666,11 +666,44 @@ pub(crate) fn follows(id: &str) -> bool {
|
||||
crate::is_raster(id) && id != crate::SVG_FILTER && id != RASTERIZE
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The linear part of the Transform effects of the groups and layers whose members are being
|
||||
/// evaluated ([`LaterGroups`]), which those groups apply to the members' raster effects once
|
||||
/// the members are evaluated: the members' light and stroke directions are rounded for them as
|
||||
/// well ([`follow_transform`]).
|
||||
static LATER_GROUPS: std::cell::Cell<Affine> = const { std::cell::Cell::new(Affine::IDENTITY) };
|
||||
}
|
||||
|
||||
/// The Transform effects of a group or layer whose members are being evaluated before the group's
|
||||
/// own effects are applied to them, added to [`LATER_GROUPS`] until it is dropped.
|
||||
pub(crate) struct LaterGroups(Affine);
|
||||
|
||||
impl LaterGroups {
|
||||
/// Add the Transform effects of `owner`, a group's or layer's own effects ([`contents_step`]),
|
||||
/// to those the members will still go through.
|
||||
pub(crate) fn enter(owner: &[Effect]) -> Self {
|
||||
let was = LATER_GROUPS.with(|l| l.get());
|
||||
if let Some(step) = contents_step(owner) {
|
||||
LATER_GROUPS.with(|l| l.set(was * step));
|
||||
}
|
||||
LaterGroups(was)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for LaterGroups {
|
||||
fn drop(&mut self) {
|
||||
LATER_GROUPS.with(|l| l.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Make raster effect `e` follow `a`, the linear part of a Transform effect listed after it, as
|
||||
/// that effect transforms what `e` paints: its distances and raster sizes scale by `a`'s mean
|
||||
/// scale ([`crate::scale_effect`]), and a Drop Shadow's offset turns, reflects and scales with
|
||||
/// `a`. Effects that [`follows`] leaves out stay as they are.
|
||||
fn follow_transform(e: &mut Effect, a: Affine) {
|
||||
/// scale ([`crate::scale_effect`]), a Drop Shadow's offset turns, reflects and scales with `a`,
|
||||
/// and a pixel filter's light direction, stroke direction or screen angles turn and reflect with
|
||||
/// it ([`pixel::turned_directions`]; `later` is the map `e` still goes through when it is drawn,
|
||||
/// before the Transform effects of the groups around it in [`LATER_GROUPS`]). Effects that
|
||||
/// [`follows`] leaves out stay as they are.
|
||||
fn follow_transform(e: &mut Effect, a: Affine, later: Affine) {
|
||||
if !follows(&e.id) {
|
||||
return;
|
||||
}
|
||||
@@ -678,15 +711,22 @@ fn follow_transform(e: &mut Effect, a: Affine) {
|
||||
let p = merged_params(&e.id, &e.params);
|
||||
a * Point::new(num(&p, "x", 7.0), num(&p, "y", 7.0))
|
||||
});
|
||||
let turned = pixel::turned_directions(&e.id, &e.params, a, LATER_GROUPS.with(|l| l.get()) * later);
|
||||
if let Some(k) = vectorcraft_doc::Scaling::factor(a) {
|
||||
crate::scale_effect(e, k);
|
||||
}
|
||||
if let Some(o) = offset.filter(|o| o.x.is_finite() && o.y.is_finite()) {
|
||||
let mut set = |key: &str, value: Value| {
|
||||
if !e.params.is_object() {
|
||||
e.params = Value::Object(Map::new());
|
||||
}
|
||||
e.params["x"] = json!(o.x);
|
||||
e.params["y"] = json!(o.y);
|
||||
e.params[key] = value;
|
||||
};
|
||||
if let Some(o) = offset.filter(|o| o.x.is_finite() && o.y.is_finite()) {
|
||||
set("x", json!(o.x));
|
||||
set("y", json!(o.y));
|
||||
}
|
||||
for (key, value) in turned {
|
||||
set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -515,18 +515,62 @@ fn laid_out(t: &vectorcraft_doc::TextObject) -> (Vec<kurbo::BezPath>, kurbo::Bez
|
||||
/// gradient fitted across the whole layout, and the transform also scales its stroke weights and
|
||||
/// dashes and transforms its pattern tiles. Placed gradients keep their place in text space and
|
||||
/// move with the type.
|
||||
pub fn paint_type_piece(piece: &mut Node, style: &vectorcraft_doc::CharStyle, bounds: Rect, xf: Affine) {
|
||||
///
|
||||
/// When `xf` is not a similarity (it scales unevenly, shears or flattens), one weight can't give
|
||||
/// the stroke the thickness the canvas paints in each direction: `piece` keeps only the run's fill,
|
||||
/// and the returned path is the area the run's stroke paints around `piece` in text space
|
||||
/// ([`crate::stroke::outline_region`]: dashes, caps, joins and alignment), placed by `xf` and
|
||||
/// filled with the stroke's paint, to paint over `piece`. `None` under a similarity and for a run
|
||||
/// without a stroke.
|
||||
pub fn paint_type_piece(piece: &mut Node, style: &vectorcraft_doc::CharStyle, bounds: Rect, xf: Affine) -> Option<Node> {
|
||||
let scaling = vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() };
|
||||
let mut ap = style.appearance();
|
||||
ap.pin_gradients(bounds);
|
||||
let stroke = if is_similarity(xf) { None } else { filled_stroke(piece, &mut ap) };
|
||||
piece.appearance = ap.into();
|
||||
piece.transform(xf, vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() });
|
||||
piece.transform(xf, scaling);
|
||||
stroke.map(|mut s| {
|
||||
s.transform(xf, scaling);
|
||||
s
|
||||
})
|
||||
}
|
||||
|
||||
/// Does `xf` keep angles and scale every direction alike (a move, a rotation, a uniform scale or a
|
||||
/// reflection), without flattening?
|
||||
fn is_similarity(xf: Affine) -> bool {
|
||||
let [a, b, c, d, ..] = xf.as_coeffs();
|
||||
let (x, y) = (a.hypot(b), c.hypot(d));
|
||||
let tol = 1e-9 * x.max(y);
|
||||
x.is_finite() && y.is_finite() && x > 0.0 && y > 0.0 && (x - y).abs() <= tol && (a * c + b * d).abs() <= tol * x.max(y)
|
||||
}
|
||||
|
||||
/// Takes the stroke out of `ap`, the appearance of `piece` (a path or compound path in text space),
|
||||
/// and returns the area it paints there as a path filled with its paint, opacity, blend mode,
|
||||
/// effects and overprint, with `piece`'s id. `None` when `ap` has no stroke or it paints nothing.
|
||||
fn filled_stroke(piece: &Node, ap: &mut Appearance) -> Option<Node> {
|
||||
let i = ap.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(_)))?;
|
||||
let AppearanceItem::Stroke(st) = ap.items.remove(i) else { return None };
|
||||
let path = PathData::from_bezpath(&piece.stroke_path()?);
|
||||
let region = crate::stroke::outline_region(&path, FillRule::NonZero, &st);
|
||||
if region.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let fill = vectorcraft_doc::FillLayer {
|
||||
opacity: st.opacity,
|
||||
blend: st.blend,
|
||||
effects: st.effects.clone(),
|
||||
overprint: st.overprint,
|
||||
..vectorcraft_doc::FillLayer::new(st.paint.stroke_as_fill())
|
||||
};
|
||||
Some(Node::path(piece.id, region, Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() }))
|
||||
}
|
||||
|
||||
/// Type as glyph outlines in document space: one path per run with the run's fill and stroke,
|
||||
/// over its colour glyphs (images, art), and (when the object has its own fills/strokes) the whole
|
||||
/// outline with the object's items below the characters under them and the others over them, as
|
||||
/// the renderer paints them. Each run's path is placed by the type's transform, which also scales its stroke
|
||||
/// weights and dashes and transforms its pattern tiles; its unplaced gradients are first fixed to
|
||||
/// weights and dashes and transforms its pattern tiles (a transform that is not a similarity puts
|
||||
/// the run's stroke on a filled path over it, [`paint_type_piece`]); its unplaced gradients are first fixed to
|
||||
/// the layout's bounds in text space. The object's own unplaced gradients are fixed to the
|
||||
/// bounding box of those bounds in the document. The group is marked as type's outlines
|
||||
/// ([`vectorcraft_doc::NodeExtras::type_outlines`]).
|
||||
@@ -542,8 +586,9 @@ pub fn outline_text(n: &Node) -> Option<Node> {
|
||||
continue;
|
||||
}
|
||||
let mut piece = Node::path(n.id, PathData::from_bezpath(bp), Appearance::default());
|
||||
paint_type_piece(&mut piece, &run.style, bounds, t.xf);
|
||||
let stroke = paint_type_piece(&mut piece, &run.style, bounds, t.xf);
|
||||
children.push(Arc::new(piece));
|
||||
children.extend(stroke.map(Arc::new));
|
||||
}
|
||||
if !n.appearance.items.is_empty() && !all.elements().is_empty() {
|
||||
let (below, above) = n.appearance.split_contents();
|
||||
|
||||
@@ -171,7 +171,7 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
|
||||
}
|
||||
}
|
||||
}
|
||||
let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| paint_of(i).1 * s.opacity > 0.0));
|
||||
let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| crate::solids::shadow::casts(paint_of(i).1 * s.opacity)));
|
||||
return check_shadow(p, casting.map(|s| &s.path), b, options);
|
||||
}
|
||||
let (path, _) = object_profile(n, "Revolve")?;
|
||||
@@ -350,8 +350,8 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData {
|
||||
|
||||
/// The shadow of Revolve `fx` cast by the surface of `path` in `item`'s paint about the axis of
|
||||
/// `b`, revolved with `options`, as dark as `item` is opaque and in its blending mode; `None` with
|
||||
/// the shadow off, when `item` is fully transparent or when it casts nothing, and an error when
|
||||
/// the surface it is cast from is past the limits.
|
||||
/// the shadow off, when `item` is fully transparent or its opacity is not a finite number, or when
|
||||
/// it casts nothing, and an error when the surface it is cast from is past the limits.
|
||||
///
|
||||
/// `kept` holds the faces the surface drawn kept for its shadow ([`surface`]); without them the
|
||||
/// surface is swept again for its shadow alone.
|
||||
@@ -366,7 +366,7 @@ fn shadow_of(
|
||||
) -> Result<Option<Node>, String> {
|
||||
let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(None) };
|
||||
let (_, opacity, blend) = paint_of(item);
|
||||
if opacity <= 0.0 {
|
||||
if !crate::solids::shadow::casts(opacity) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
@@ -377,7 +377,7 @@ fn shadow_of(
|
||||
/// Does Revolve `fx` cast a shadow, so a surface in paint as opaque as `opacity` keeps the faces
|
||||
/// its shadow is cast from ([`surface`])?
|
||||
fn casts(fx: &Effect, opacity: f32) -> bool {
|
||||
opacity > 0.0 && crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)).is_some()
|
||||
crate::solids::shadow::casts(opacity) && crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)).is_some()
|
||||
}
|
||||
|
||||
/// Add the surface of `path` about the axis of `b` to `caster`: the faces it kept when it was
|
||||
@@ -420,9 +420,9 @@ fn group_shadow(
|
||||
for s in shapes {
|
||||
let kept = kept.next().flatten();
|
||||
let Some((_, opacity, blend)) = surface_item(&s.items).map(paint_of) else { continue };
|
||||
// A member whose surface is fully transparent casts nothing.
|
||||
// A member whose surface is fully transparent, or whose opacity is not a finite number, casts nothing.
|
||||
let ink = crate::solids::shadow::Ink { opacity: opacity * s.opacity, blend };
|
||||
if ink.opacity <= 0.0 {
|
||||
if !ink.casts() {
|
||||
continue;
|
||||
}
|
||||
let faces = cast_surface(&mut caster, &s.path, b, options, kept)?;
|
||||
@@ -1861,6 +1861,55 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A surface whose fill, or whose member, is at NaN or infinite opacity casts no shadow, as one
|
||||
/// at 0 % does, whether the shadow is cast from the surface drawn or swept for it alone; the
|
||||
/// member beside it still casts its part.
|
||||
#[test]
|
||||
fn a_surface_whose_opacity_is_not_a_finite_number_casts_no_shadow() {
|
||||
let fx = crate::new_effect(REVOLVE, &json!({"shadow": true})).unwrap();
|
||||
let group = |opacity: f32| {
|
||||
let mut other = profile_node();
|
||||
other.id = NodeId(2);
|
||||
other.transform(Affine::translate((120.0, 0.0)), false);
|
||||
other.opacity = opacity;
|
||||
let mut g = Node::group(NodeId(9), vec![Arc::new(profile_node()), Arc::new(other)]);
|
||||
g.appearance.effects.push(fx.clone());
|
||||
g
|
||||
};
|
||||
let group_shadows = |g: &Node| {
|
||||
let shapes = members(g, "").unwrap();
|
||||
let b = union_bounds(&shapes).unwrap();
|
||||
let options = shared_options(&shapes, fx_options(&fx)).unwrap();
|
||||
let kept: Vec<Option<SolidFaces>> = shapes
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap());
|
||||
let cast = casts(&fx, opacity * s.opacity);
|
||||
surface(None, g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2
|
||||
})
|
||||
.collect();
|
||||
[group_shadow(g.id, &fx, &shapes, b, options, kept).unwrap(), group_shadow(g.id, &fx, &shapes, b, options, vec![]).unwrap()]
|
||||
.map(|art| format!("{art:?}"))
|
||||
};
|
||||
let expected = group_shadows(&group(0.0));
|
||||
for bad in [f32::NAN, f32::INFINITY] {
|
||||
let mut n = profile_node();
|
||||
if let AppearanceItem::Fill(f) = &mut n.appearance.items[0] {
|
||||
f.opacity = bad;
|
||||
}
|
||||
let (path, _) = profile(&n).unwrap();
|
||||
let b = path.bounds().unwrap();
|
||||
let item = surface_item(&n.appearance.items).unwrap();
|
||||
assert!(!casts(&fx, bad), "{bad}: the surface keeps no faces for a shadow");
|
||||
let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap();
|
||||
assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap(), None, "{bad} drawn");
|
||||
assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap(), None, "{bad} alone");
|
||||
let shadows = group_shadows(&group(bad));
|
||||
assert!(!expected[0].is_empty() && expected[0] != "[]", "the opaque member casts");
|
||||
assert_eq!(shadows, expected, "{bad}: only the opaque member casts");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -324,8 +324,7 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
|
||||
reshape_members(n, before, &mut shapes);
|
||||
let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?;
|
||||
check_profiles(id, p, &shapes, b)?;
|
||||
check_solids(id, p, &shapes)?;
|
||||
return check_cast(id, p, &shapes);
|
||||
return check_solids(id, p, &shapes);
|
||||
}
|
||||
let (path, rule) = object_profile(n, label)?;
|
||||
let anchors = || format!("{label} requires a shape with at least two anchors");
|
||||
@@ -342,38 +341,68 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
|
||||
let b = path.bounds().ok_or_else(anchors)?;
|
||||
let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }];
|
||||
check_profiles(id, p, &shapes, b)?;
|
||||
check_solids(id, p, &shapes)?;
|
||||
check_cast(id, p, &shapes)
|
||||
check_solids(id, p, &shapes)
|
||||
}
|
||||
|
||||
/// With the shadow of 3D effect `id` with parameters `p` on, an error when the shadow of `shapes`
|
||||
/// is past the limits ([`cast_shadow`]). In wireframe mode no shadow is drawn, and none is checked.
|
||||
fn check_cast(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
|
||||
if wireframe::wireframe_params(id, p) {
|
||||
return Ok(());
|
||||
}
|
||||
cast_shadow(id, p, shapes).map(|_| ())
|
||||
/// Does 3D effect `id` with parameters `p` cast a shadow: is it Extrude & Bevel, Inflate or Rotate
|
||||
/// with Shadows on, shaded? In wireframe mode no shadow is drawn, and none is checked.
|
||||
fn casts_shadow(id: &str, p: &Value) -> bool {
|
||||
!is_classic_three_d(id) && shadow::options(p).is_some() && !wireframe::wireframe_params(id, p)
|
||||
}
|
||||
|
||||
/// Does `item` of a shape with opacity `member` paint anything, and so cast a shadow?
|
||||
fn visible(item: &AppearanceItem, member: f32) -> bool {
|
||||
paint_of(item, member).1 > 0.0
|
||||
}
|
||||
|
||||
/// Do the solids 3D effect `id` with parameters `p` builds from the profiles of `shapes` about `b`
|
||||
/// build? Only the profiles no solid of [`check_solids`] is built from are built here: every
|
||||
/// shape's for Rotate, and for Extrude & Bevel and Inflate the profile of a shape with no fill,
|
||||
/// whose solids are its strokes' outlines or none. A filled shape's profile is its fill's solid,
|
||||
/// which [`check_solids`] builds once, about the bounds the effect draws it about.
|
||||
/// build? Only the profiles no solid of [`check_solids`] is built from are built here: for Rotate
|
||||
/// every shape's, except with its shadow cast that of a shape with a visible fill, whose plane is
|
||||
/// the fill's; for Extrude & Bevel and Inflate the profile of a shape with no fill, whose solids
|
||||
/// are its strokes' outlines or none. A filled shape's profile is its fill's solid, which
|
||||
/// [`check_solids`] builds once, about the bounds the effect draws it about.
|
||||
fn check_profiles(id: &str, p: &Value, shapes: &[Profile], b: Rect) -> Result<(), String> {
|
||||
shapes
|
||||
.iter()
|
||||
.filter(|s| is_plane(id) || !s.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_))))
|
||||
.try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ()))
|
||||
let cast = casts_shadow(id, p);
|
||||
let fill = |s: &Profile| s.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_)) && (!is_plane(id) || visible(i, s.opacity)));
|
||||
shapes.iter().filter(|s| if is_plane(id) { !(cast && fill(s)) } else { !fill(s) }).try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ()))
|
||||
}
|
||||
|
||||
/// Do the solids 3D effect `id` with parameters `p` builds from the fills and strokes of `shapes`
|
||||
/// fit, each on its own and all of them together ([`built_solids`])? Rotate's planes are not
|
||||
/// counted.
|
||||
/// fit, each on its own and all of them together ([`built_solids`]), and with its shadow cast, does
|
||||
/// the shadow fit? The shadow is cast from the faces those same builds kept ([`cast_built`]), as
|
||||
/// [`art_for`] casts it: Extrude & Bevel and Inflate build each solid once, and Rotate builds the
|
||||
/// plane of each visible fill and stroke once. Rotate's planes are not counted, and without its
|
||||
/// shadow Rotate builds no plane here.
|
||||
fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
|
||||
let Some(b) = union_bounds(shapes).filter(|_| !is_plane(id)) else { return Ok(()) };
|
||||
let Some(b) = union_bounds(shapes) else { return Ok(()) };
|
||||
let cast = casts_shadow(id, p);
|
||||
if is_plane(id) {
|
||||
if !cast {
|
||||
return Ok(());
|
||||
}
|
||||
let mut built = vec![];
|
||||
for s in shapes {
|
||||
for item in &s.items {
|
||||
if !visible(item, s.opacity) {
|
||||
built.push(None);
|
||||
continue;
|
||||
}
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
built.push(facets_and_faces(ROTATE, &area, rule, b, p, true)?.1);
|
||||
}
|
||||
}
|
||||
return cast_built(id, p, shapes, built).map(|_| ());
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ()))
|
||||
if !cast {
|
||||
return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ()));
|
||||
}
|
||||
let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true)
|
||||
.map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces)))
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
cast_built(id, p, shapes, built).map(|_| ())
|
||||
}
|
||||
|
||||
/// [`profile`], or the error a command reports for object `n`: type with no outlines to build from
|
||||
@@ -596,7 +625,9 @@ pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> {
|
||||
/// blend mode (so overlapping facets don't add up their transparency). Under colored lights a solid
|
||||
/// color with smooth facets is one composite of all its facets ([`composites_facets`]) unless
|
||||
/// `faces`: then each facet is a face of its own, as in a gradient, so the faces can go in one order
|
||||
/// with the faces of other solids.
|
||||
/// with the faces of other solids. Under colored lights a gradient with transparent stops is drawn
|
||||
/// opaque under one mask of its transparency, placed once on all the facets when it has no
|
||||
/// placement of its own ([`crate::lighting::opaque_surface_paint`]).
|
||||
fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool, faces: bool) -> Node {
|
||||
if !faces && composites_facets(&facets, paint, colored) {
|
||||
let mut group = crate::lighting::solid_surface(n.id, &facets, paint);
|
||||
@@ -605,7 +636,7 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
|
||||
return group;
|
||||
}
|
||||
// Preserve existing white-light paints and alpha composition exactly.
|
||||
let (opaque, mask) = if colored { crate::lighting::opaque_paint(paint) } else { (paint.clone(), None) };
|
||||
let (opaque, mask) = if colored { crate::lighting::opaque_surface_paint(paint, || facets_bounds(&facets)) } else { (paint.clone(), None) };
|
||||
let paint = &opaque;
|
||||
let children = facets
|
||||
.into_iter()
|
||||
@@ -642,6 +673,11 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
|
||||
group
|
||||
}
|
||||
|
||||
/// The bounds of every facet of `facets` together (`Rect::ZERO` when none has any).
|
||||
pub(crate) fn facets_bounds(facets: &[Facet]) -> Rect {
|
||||
facets.iter().filter_map(|f| f.path().bounds()).reduce(|a, c| a.union(c)).unwrap_or(Rect::ZERO)
|
||||
}
|
||||
|
||||
/// The width of the stroke of a facet's own paint that closes the seams between `face` and its
|
||||
/// neighbors. No wider than the facet is thick: seen at a grazing angle a facet can be thinner than
|
||||
/// the stroke, and its stroke would then paint over its neighbors.
|
||||
@@ -733,7 +769,8 @@ thread_local! {
|
||||
/// surfaces count too.
|
||||
pub(crate) static SOLIDS_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// How many Extrude & Bevel (Classic included) and Inflate solids [`facets`] and
|
||||
/// [`built_solids`] have built on this thread, for the tests.
|
||||
/// [`built_solids`] have built on this thread, for the tests. The solids built to cast a shadow
|
||||
/// ([`cast_shadow`]) count too.
|
||||
static SOLID_GEOMETRY_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
@@ -1435,7 +1472,7 @@ fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) ->
|
||||
return Some((vec![], wireframe::wire_surfaces(n.id, fx, shapes)?));
|
||||
}
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let cast = !is_classic_three_d(&fx.id) && shadow::options(&p).is_some();
|
||||
let cast = casts_shadow(&fx.id, &p);
|
||||
let (art, built) = surfaces_for(doc, n, fx, shapes, cast)?;
|
||||
// A shadow past the limits draws the source path, as a solid past them does; commands report
|
||||
// the error ([`validate_solid_in`]).
|
||||
@@ -1474,8 +1511,8 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
let view = view_options(p);
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
// The faces each solid of visible art added, with its member's scopes and its ink (opacity
|
||||
// and blending mode), in order. A fully transparent fill or stroke (or member) casts nothing
|
||||
// and does not place the plane.
|
||||
// and blending mode), in order. A fill or stroke (or member) that is fully transparent, or whose
|
||||
// opacity is not a finite number, casts nothing and does not place the plane ([`shadow::Ink::casts`]).
|
||||
let mut cast: Vec<shadow::Cast> = vec![];
|
||||
let ink = |item: &AppearanceItem, member: f32| {
|
||||
let (_, opacity, blend) = paint_of(item, member);
|
||||
@@ -1483,7 +1520,7 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
};
|
||||
if id == ROTATE {
|
||||
for s in shapes {
|
||||
for item in s.items.iter().filter(|i| ink(i, s.opacity).opacity > 0.0) {
|
||||
for item in s.items.iter().filter(|i| ink(i, s.opacity).casts()) {
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
@@ -1497,21 +1534,25 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
// Inflate's eye is placed for every shape together, as the solids are.
|
||||
let added: Vec<Result<std::ops::Range<usize>, String>> = if id == INFLATE {
|
||||
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect();
|
||||
let casts: Vec<bool> = inks.iter().map(|i| i.opacity > 0.0).collect();
|
||||
let casts: Vec<bool> = inks.iter().map(|i| i.casts()).collect();
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + shapes.len()));
|
||||
#[cfg(test)]
|
||||
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + casts.iter().filter(|c| **c).count()));
|
||||
caster.inflate(&shapes, &casts, bounds, inflate_options(p), view)
|
||||
} else {
|
||||
let mut added = vec![];
|
||||
for ((_, _, area, rule, _, _), ink) in parts.iter().zip(&inks) {
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + usize::from(ink.opacity > 0.0)));
|
||||
added.push(if ink.opacity > 0.0 { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) });
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + usize::from(ink.casts())));
|
||||
#[cfg(test)]
|
||||
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + usize::from(ink.casts())));
|
||||
added.push(if ink.casts() { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) });
|
||||
}
|
||||
added
|
||||
};
|
||||
for (((item, _, _, _, scopes, _), ink), faces) in parts.iter().zip(inks).zip(added) {
|
||||
if ink.opacity <= 0.0 {
|
||||
if !ink.casts() {
|
||||
continue;
|
||||
}
|
||||
// A stroke whose own solid is past the limits is left out; past the shadow's limit for
|
||||
@@ -1529,16 +1570,14 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
|
||||
/// [`cast_shadow`] from `built`, the faces the solids drawn kept ([`surfaces_for`] with its shadow
|
||||
/// cast), one entry for each solid in the order they are built: for Rotate each fill and stroke of
|
||||
/// each shape, otherwise each part ([`solid_parts`]). A stroke's solid left out of the art (past its
|
||||
/// own limits) kept no faces. Its Extrude & Bevel solid is built for the shadow alone, as
|
||||
/// [`cast_shadow`] builds it, and when an Inflate solid of visible art kept no faces the whole
|
||||
/// shadow is cast as [`cast_shadow`] casts it, since Inflate's solids share one eye.
|
||||
/// each shape, otherwise each part ([`solid_parts`]). No solid is built here: an entry with no faces
|
||||
/// (a stroke's solid left out of the art, past its own limits) casts nothing, as it draws nothing.
|
||||
/// Only `built` of another length than the solids is cast as [`cast_shadow`] casts it.
|
||||
fn cast_built<'a>(id: &str, p: &Value, shapes: &'a [Profile], built: Vec<Option<SolidFaces>>) -> Result<Option<Cast<'a>>, String> {
|
||||
if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE {
|
||||
return Ok(None);
|
||||
}
|
||||
let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) };
|
||||
let view = view_options(p);
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
let mut cast: Vec<shadow::Cast> = vec![];
|
||||
let ink = |item: &AppearanceItem, member: f32| {
|
||||
@@ -1552,42 +1591,25 @@ fn cast_built<'a>(id: &str, p: &Value, shapes: &'a [Profile], built: Vec<Option<
|
||||
}
|
||||
for ((s, item), kept) in items.into_iter().zip(built) {
|
||||
let ink = ink(item, s.opacity);
|
||||
if ink.opacity <= 0.0 {
|
||||
if !ink.casts() {
|
||||
continue;
|
||||
}
|
||||
let faces = match kept {
|
||||
Some(kept) => caster.add_solid(kept)?,
|
||||
None => {
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
caster.plane(&area, rule, b, view)?
|
||||
}
|
||||
};
|
||||
cast.push((s.scopes.as_slice(), ink, faces));
|
||||
let Some(kept) = kept else { continue };
|
||||
cast.push((s.scopes.as_slice(), ink, caster.add_solid(kept)?));
|
||||
}
|
||||
return Ok(Some((caster, settings, cast)));
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
let inks: Vec<shadow::Ink> = parts.iter().map(|(item, member, ..)| ink(item, *member)).collect();
|
||||
if parts.len() != built.len() || (id == INFLATE && inks.iter().zip(&built).any(|(ink, kept)| ink.opacity > 0.0 && kept.is_none())) {
|
||||
let (parts, _) = solid_parts(shapes, b);
|
||||
if parts.len() != built.len() {
|
||||
return cast_shadow(id, p, shapes);
|
||||
}
|
||||
for (((item, _, area, rule, scopes, _), ink), kept) in parts.iter().zip(inks).zip(built) {
|
||||
if ink.opacity <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let faces = match kept {
|
||||
Some(kept) => caster.add_solid(kept),
|
||||
None => {
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
caster.extrude(area, *rule, bounds, extrude_options(p), view)
|
||||
}
|
||||
};
|
||||
for ((item, member, _, _, scopes, _), kept) in parts.iter().zip(built) {
|
||||
let ink = ink(item, *member);
|
||||
// A fully transparent solid, or a stroke's solid left out of the art, casts nothing.
|
||||
let Some(kept) = kept.filter(|_| ink.casts()) else { continue };
|
||||
// A stroke whose own solid is past the limits is left out; past the shadow's limit for all
|
||||
// the solids together, the shadow is refused.
|
||||
let faces = match faces {
|
||||
let faces = match caster.add_solid(kept) {
|
||||
Ok(faces) => faces,
|
||||
Err(e) if matches!(item, AppearanceItem::Stroke(_)) && e != vectorcraft_three_d::TOO_COMPLEX_SHADOW => continue,
|
||||
Err(e) => return Err(e),
|
||||
|
||||
@@ -231,14 +231,15 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 {
|
||||
/// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by
|
||||
/// its tone and highlight (with Preserve Spot Colors, a color linked to a swatch as [`linked_face`]
|
||||
/// draws it). A gradient with transparent stops is shaded opaque and then masked by
|
||||
/// its own transparency, so the shading follows the gradient's coverage.
|
||||
/// its own transparency, so the shading follows the gradient's coverage; without a placement of its
|
||||
/// own, it is placed once on all the faces ([`crate::lighting::opaque_surface_paint`]).
|
||||
pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node {
|
||||
let shading = classic_shading(p);
|
||||
let lights = lights(p);
|
||||
let shade = shading_color(p);
|
||||
let preserve = preserves_spot_colors(p);
|
||||
let wire = shading.surface == ClassicSurface::Wireframe;
|
||||
let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_paint(source) };
|
||||
let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(&facets)) };
|
||||
let paint = &paint;
|
||||
let children = facets
|
||||
.into_iter()
|
||||
|
||||
@@ -50,6 +50,19 @@ pub(crate) struct Ink {
|
||||
pub(crate) blend: BlendMode,
|
||||
}
|
||||
|
||||
impl Ink {
|
||||
/// Whether art in this ink casts part of a shadow ([`casts`]).
|
||||
pub(crate) fn casts(self) -> bool {
|
||||
casts(self.opacity)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether art at `opacity` casts part of a shadow: its opacity is a finite number above zero.
|
||||
/// Art at zero, negative, NaN or infinite opacity casts nothing.
|
||||
pub(crate) fn casts(opacity: f32) -> bool {
|
||||
opacity.is_finite() && opacity > 0.0
|
||||
}
|
||||
|
||||
/// The shadow of the faces in `caster` as a path of object `id`, cast by art in `ink`: filled
|
||||
/// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule;
|
||||
/// `None` when it casts nothing.
|
||||
|
||||
@@ -1082,7 +1082,8 @@ fn geometry_builds(check: impl FnOnce() -> Result<(), String>) -> (usize, Result
|
||||
|
||||
/// The check builds each solid the effect draws once, about the bounds it draws it about: one for
|
||||
/// a fill and one for each stroke, on an object, on a group's members and on an appearance item,
|
||||
/// with the shadow on or off.
|
||||
/// with the shadow on or off. With the shadow on, the shadow is cast from the faces those builds
|
||||
/// kept, so no solid is built again for it.
|
||||
#[test]
|
||||
fn the_check_builds_each_drawn_solid_once() {
|
||||
for id in [EXTRUDE, CLASSIC_EXTRUDE, INFLATE] {
|
||||
@@ -1098,6 +1099,11 @@ fn the_check_builds_each_drawn_solid_once() {
|
||||
assert_eq!(geometry_builds(|| validate_three_d_at(&n, id, &json!({}), (Some(0), 0))), (1, Ok(())), "{id}: on the fill");
|
||||
let shadow = json!({"shadow": true});
|
||||
assert_eq!(geometry_builds(|| validate_solid(&n, id, &shadow)), (2, Ok(())), "{id}: with the shadow on");
|
||||
let mut other = square_node();
|
||||
other.id = NodeId(2);
|
||||
let g = Node::group(NodeId(9999), vec![Arc::new(square_node()), Arc::new(other)]);
|
||||
assert_eq!(geometry_builds(|| validate_solid(&g, id, &shadow)), (4, Ok(())), "{id}: a group with the shadow on");
|
||||
assert_eq!(geometry_builds(|| validate_three_d_at(&n, id, &shadow, (Some(0), 0))), (1, Ok(())), "{id}: the fill with the shadow on");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1954,6 +1960,57 @@ fn classic_shading_keeps_a_gradients_transparency() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient without a placement and with a transparent stop, under colored lights or classic
|
||||
/// shading, is placed once for the whole surface: every face's color and the surface's opacity mask
|
||||
/// share one placement, so the color and transparency ramps line up across the faces. A gradient
|
||||
/// placed in the document keeps its placement.
|
||||
#[test]
|
||||
fn a_transparent_unplaced_gradient_has_one_placement_for_color_and_mask() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
// The source's stops carry an unusual midpoint, so its color and mask copies can be told from
|
||||
// the light ramps.
|
||||
const MARK: f32 = 0.37;
|
||||
let mut first = GradientStop::new(0.0, RED);
|
||||
first.midpoint = MARK;
|
||||
let mut end = GradientStop::new(1.0, Color::BLACK);
|
||||
end.opacity = 0.25;
|
||||
let unplaced = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![first, end]));
|
||||
let placed = GradientGeom { start: Point::new(90.0, 100.0), end: Point::new(230.0, 140.0), aspect: 1.0, focal: None };
|
||||
// The placement of each copy of the source gradient: its own, else its fit on the path it fills.
|
||||
fn placements(n: &Node, out: &mut Vec<GradientGeom>) {
|
||||
n.walk(&mut |c| {
|
||||
if let Some(mask) = &c.extras().mask {
|
||||
placements(&mask.art, out);
|
||||
}
|
||||
let bounds = c.path_data().and_then(|p| p.bounds()).unwrap_or(Rect::ZERO);
|
||||
for item in &c.appearance.items {
|
||||
if let Paint::Gradient(g) = paint_ref(item)
|
||||
&& g.gradient.stops.first().is_some_and(|s| s.midpoint == MARK)
|
||||
{
|
||||
out.push(g.resolve(bounds));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let lit = json!({"lights": [{"color": "#ff8080"}]});
|
||||
for (id, params) in [(EXTRUDE, lit.clone()), (INFLATE, lit.clone()), (ROTATE, lit), (CLASSIC_EXTRUDE, json!({}))] {
|
||||
for geom in [None, Some(placed)] {
|
||||
let mut n = square_node();
|
||||
n.appearance.items = vec![AppearanceItem::Fill(FillLayer::new(Paint::Gradient(Box::new(GradientPaint { geom, ..unplaced.clone() }))))];
|
||||
n.appearance.effects.push(fx(id, params.clone()));
|
||||
let art = solid_art(&n).unwrap_or_else(|| panic!("{id}"));
|
||||
let mut masks = 0;
|
||||
art.walk(&mut |c| masks += usize::from(c.extras().mask.is_some()));
|
||||
assert!(masks > 0, "{id}: the surface carries the gradient's transparency as a mask");
|
||||
let mut found = vec![];
|
||||
placements(&art, &mut found);
|
||||
assert!(found.len() > 2, "{id}: the faces' colors and the mask");
|
||||
let expected = geom.unwrap_or(found[0]);
|
||||
assert!(found.iter().all(|g| *g == expected), "{id} {geom:?}: {found:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group member in a gradient with transparent stops keeps the shared back-to-front order of
|
||||
/// every member's faces: its faces go in runs that carry its opacity mask, and the other member's
|
||||
/// faces are drawn between them where they are in front of some and behind others. Here a square
|
||||
|
||||
@@ -312,3 +312,125 @@ fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke's solid left out of the art (past its own limits) keeps no faces, and the shadow cast
|
||||
/// from the faces the solids kept leaves it out without building it: it casts nothing, as it draws
|
||||
/// nothing, and the fill's solid still casts.
|
||||
#[test]
|
||||
fn a_stroke_left_out_of_the_art_casts_no_shadow() {
|
||||
for id in [EXTRUDE, INFLATE] {
|
||||
let n = stroked_square(1, 0.0, 1.0);
|
||||
let (path, rule) = profile(&n).unwrap();
|
||||
let shapes = [Profile { path, rule, items: solid_paints(&n), opacity: 1.0, scopes: vec![] }];
|
||||
let p = crate::merged_params(id, &json!({"shadow": true}));
|
||||
let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap());
|
||||
let mut built: Vec<Option<SolidFaces>> =
|
||||
built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect();
|
||||
let stroke = parts.iter().position(|(item, ..)| matches!(item, AppearanceItem::Stroke(_))).unwrap();
|
||||
assert!(built.len() == 2 && built.iter().all(Option::is_some), "{id}");
|
||||
let (both, _, cast) = cast_built(id, &p, &shapes, built.clone()).unwrap().unwrap();
|
||||
assert_eq!(cast.len(), 2, "{id}: the fill and the stroke cast");
|
||||
built[stroke] = None;
|
||||
let start = SOLIDS_BUILT.with(std::cell::Cell::get);
|
||||
let (fill, _, cast) = cast_built(id, &p, &shapes, built).unwrap().unwrap();
|
||||
assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get), start, "{id}: no solid is built for the shadow");
|
||||
assert_eq!(cast.len(), 1, "{id}: the stroke left out casts nothing");
|
||||
assert!(!fill.is_empty() && fill.len() < both.len(), "{id}: only the fill's faces are cast");
|
||||
}
|
||||
}
|
||||
|
||||
/// A command accepts each shadowed object that draws with its shadow, and with Rotate builds the
|
||||
/// plane of each visible fill and stroke once for the shadow: a fully transparent one casts nothing.
|
||||
#[test]
|
||||
fn the_check_accepts_the_shadowed_objects_that_draw() {
|
||||
for id in [EXTRUDE, INFLATE, ROTATE] {
|
||||
for params in shadow_settings(id) {
|
||||
for n in shadowed(id, ¶ms) {
|
||||
let mut drawn = 0;
|
||||
art(&n, id).unwrap().walk(&mut |c| drawn += usize::from(shadow_opacity(c).is_some()));
|
||||
assert!(drawn > 0, "{id} {params}");
|
||||
assert_eq!(validate_solid(&n, id, ¶ms), Ok(()), "{id} {params}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let shadow = json!({"shadow": true});
|
||||
for (stroke, planes) in [(1.0, 2), (0.5, 2), (0.0, 1)] {
|
||||
let n = stroked_square(1, 0.0, stroke);
|
||||
let start = SOLIDS_BUILT.with(std::cell::Cell::get);
|
||||
assert_eq!(validate_solid(&n, ROTATE, &shadow), Ok(()), "{stroke}");
|
||||
assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get) - start, planes, "Rotate, a stroke at {stroke}");
|
||||
}
|
||||
}
|
||||
|
||||
/// In wireframe mode no shadow is drawn, so the check casts none: with Shadows on, Rotate builds no
|
||||
/// plane for a shadow, and Extrude & Bevel and Inflate build each solid once, as with the shadow off.
|
||||
#[test]
|
||||
fn the_check_casts_no_shadow_in_wireframe_mode() {
|
||||
let n = stroked_square(1, 0.0, 1.0);
|
||||
let wire = json!({"shadow": true, "render": {"mode": "wireframe"}});
|
||||
for (id, solids) in [(ROTATE, 0), (EXTRUDE, 2), (INFLATE, 2)] {
|
||||
let start = SOLIDS_BUILT.with(std::cell::Cell::get);
|
||||
assert_eq!(validate_solid(&n, id, &wire), Ok(()), "{id}");
|
||||
assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get) - start, solids, "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The opacity of each part of the shadow of `n` (its 3D effect's shadow on) and the shadow's art,
|
||||
/// as [`cast_shadow`] casts it from solids built for the shadow alone and as [`cast_built`] casts
|
||||
/// it from the faces the solids drawn kept.
|
||||
fn cast_parts(n: &Node) -> [(Vec<f32>, String); 2] {
|
||||
let (_, fx) = solid(&n.appearance.effects).unwrap();
|
||||
let shapes = if is_container(n) {
|
||||
members(n, "").unwrap()
|
||||
} else {
|
||||
let (path, rule) = profile(n).unwrap();
|
||||
vec![Profile { path, rule, items: solid_paint_sources(n).1, opacity: 1.0, scopes: vec![] }]
|
||||
};
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let (_, built) = surfaces_for(None, n, fx, &shapes, true).unwrap();
|
||||
[cast_shadow(&fx.id, &p, &shapes), cast_built(&fx.id, &p, &shapes, built)].map(|c| {
|
||||
let (caster, settings, cast) = c.unwrap().unwrap();
|
||||
let inks = cast.iter().map(|(_, ink, _)| ink.opacity).collect();
|
||||
(inks, format!("{:?}", shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes))))
|
||||
})
|
||||
}
|
||||
|
||||
/// A fill, a stroke or a member whose opacity is NaN or infinite casts no part of the shadow, as one
|
||||
/// at 0 % does, whether the shadow is cast from solids built for it or from the solids drawn; the
|
||||
/// art beside it still casts its part.
|
||||
#[test]
|
||||
fn art_whose_opacity_is_not_a_finite_number_casts_no_shadow() {
|
||||
// The art with opacity `opacity` in one place: a square's stroke, the fill of a group's second
|
||||
// member, and a group's second member.
|
||||
let objects = |opacity: f32| {
|
||||
let mut fill = square_node(2, 200.0);
|
||||
for item in &mut fill.appearance.items {
|
||||
if let AppearanceItem::Fill(f) = item {
|
||||
f.opacity = opacity;
|
||||
}
|
||||
}
|
||||
let mut member = square_node(2, 200.0);
|
||||
member.opacity = opacity;
|
||||
[
|
||||
stroked_square(1, 0.0, opacity),
|
||||
Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(fill)]),
|
||||
Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(member)]),
|
||||
]
|
||||
};
|
||||
for id in [EXTRUDE, INFLATE, ROTATE] {
|
||||
for bad in [f32::NAN, f32::INFINITY] {
|
||||
for (i, (mut n, mut clear)) in objects(bad).into_iter().zip(objects(0.0)).enumerate() {
|
||||
n.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap());
|
||||
clear.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap());
|
||||
let expected = cast_parts(&clear);
|
||||
for (k, (inks, shadow)) in cast_parts(&n).into_iter().enumerate() {
|
||||
assert_eq!(inks, vec![1.0], "{id} {bad} object {i} cast {k}: only the opaque art casts");
|
||||
assert_eq!(shadow, expected[k].1, "{id} {bad} object {i} cast {k}");
|
||||
}
|
||||
let mut opacities = vec![];
|
||||
art(&n, id).unwrap().walk(&mut |c| opacities.extend(shadow_opacity(c)));
|
||||
assert_eq!(opacities, vec![0.5], "{id} {bad} object {i}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Effect › SVG Filters (`svg.filter`): an SVG `<filter>` element applied as a live raster effect.
|
||||
//! The filter runs on the object's pixels as SVG 1.1 describes it
|
||||
//! (<https://www.w3.org/TR/SVG11/filters.html>), drawn by resvg. Its lengths are in points times
|
||||
//! the effect's `scale`, its user space starts at the effect's `origin`, its object bounding box is the box of the drawn pixels, and it runs at the
|
||||
//! the effect's `scale`, its user space starts at the effect's `origin`, its axes point as the effect's `axes` say (a turned or
|
||||
//! skewed user space), its object bounding box is the box of the drawn pixels, and it runs at the
|
||||
//! Document Raster Effects resolution when the view shows the object at a finer one.
|
||||
|
||||
use std::sync::Arc;
|
||||
@@ -1224,13 +1225,16 @@ fn region_length(v: Option<&str>, default: f64, user: bool) -> Length {
|
||||
}
|
||||
|
||||
/// An SVG filter effect: the filter's XML, how many points one of its units is, where its user
|
||||
/// space's origin lies in the document, and its region.
|
||||
/// space's origin lies in the document, which way its axes point, and its region.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SvgFilterFx {
|
||||
/// The filter as it is drawn and written ([`rebuilt`]).
|
||||
xml: Arc<str>,
|
||||
scale: f64,
|
||||
origin: Vec2,
|
||||
/// The directions of the user space's axes in the document, before `scale` ([`axes_param`]):
|
||||
/// the identity unless the user space is turned, skewed or scaled unevenly.
|
||||
axes: Affine,
|
||||
/// Its region (filter effects region): x, y, width, height.
|
||||
region: [Length; 4],
|
||||
/// Is the region in user space with a length measured against the object's box? It is then
|
||||
@@ -1250,11 +1254,92 @@ fn origin_param(p: &Value) -> Vec2 {
|
||||
Vec2::new(at(0), at(1))
|
||||
}
|
||||
|
||||
/// The largest magnitude of an entry of an SVG filter effect's `axes`.
|
||||
pub const MAX_AXIS: f64 = 1000.0;
|
||||
|
||||
/// The smallest magnitude of the determinant of an SVG filter effect's `axes`.
|
||||
pub const MIN_AXES_DET: f64 = 0.001;
|
||||
|
||||
/// The `axes` of an SVG filter effect's parameters `p`: `[a, b, c, d]`, the document directions
|
||||
/// of one unit along the filter's x axis (`[a, b]`) and its y axis (`[c, d]`), before `scale`.
|
||||
/// The identity when absent; `None` when it isn't four numbers from -[`MAX_AXIS`] to [`MAX_AXIS`]
|
||||
/// whose determinant is at least [`MIN_AXES_DET`] across ([`valid_axes`]).
|
||||
fn axes_param(p: &Value) -> Option<Affine> {
|
||||
match p.get("axes") {
|
||||
None | Some(Value::Null) => Some(Affine::IDENTITY),
|
||||
Some(v) => valid_axes(v),
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` as the linear map of an SVG filter effect's `axes` ([`axes_param`]), when it is one.
|
||||
pub fn valid_axes(v: &Value) -> Option<Affine> {
|
||||
let n: Vec<f64> = v.as_array()?.iter().map(Value::as_f64).collect::<Option<_>>()?;
|
||||
axes_of(<[f64; 4]>::try_from(n).ok()?)
|
||||
}
|
||||
|
||||
/// `[a, b, c, d]` as the linear map of an SVG filter effect's `axes`, when the effect takes it ([`valid_axes`]).
|
||||
fn axes_of([a, b, c, d]: [f64; 4]) -> Option<Affine> {
|
||||
let det = a * d - b * c;
|
||||
([a, b, c, d].iter().all(|v| v.is_finite() && v.abs() <= MAX_AXIS) && det.abs() >= MIN_AXES_DET).then(|| Affine::new([a, b, c, d, 0.0, 0.0]))
|
||||
}
|
||||
|
||||
/// A filter's user space as the SVG filter effect stores it ([`user_space`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct UserSpace {
|
||||
/// The effect's `scale`.
|
||||
pub scale: f64,
|
||||
/// The effect's `origin`.
|
||||
pub origin: [f64; 2],
|
||||
/// The effect's `axes`; `None` when the axes are the document's.
|
||||
pub axes: Option<[f64; 4]>,
|
||||
}
|
||||
|
||||
/// `ts`, a user space mapped to the document, as the SVG filter effect's `scale` (the square root
|
||||
/// of its area scale), `origin` and, when it turns, skews or scales unevenly, `axes`. `None` when
|
||||
/// it can't be stored: not finite, `scale` outside 0.001..1000, or `axes` the effect refuses
|
||||
/// ([`valid_axes`]).
|
||||
pub fn user_space(ts: Affine) -> Option<UserSpace> {
|
||||
let [a, b, c, d, e, f] = ts.as_coeffs();
|
||||
if ![a, b, c, d, e, f].iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let scale = ts.determinant().abs().sqrt();
|
||||
if !(0.001..=1000.0).contains(&scale) {
|
||||
return None;
|
||||
}
|
||||
let even = b == 0.0 && c == 0.0 && a > 0.0 && (a - d).abs() <= 1e-9 * a.max(1.0);
|
||||
if even {
|
||||
return Some(UserSpace { scale: a, origin: [e, f], axes: None });
|
||||
}
|
||||
let axes = [a, b, c, d].map(|v| v / scale);
|
||||
axes_of(axes)?;
|
||||
Some(UserSpace { scale, origin: [e, f], axes: Some(axes) })
|
||||
}
|
||||
|
||||
/// The longest a unit vector becomes under the linear part of `a` (its largest singular value).
|
||||
fn stretch(a: Affine) -> f64 {
|
||||
let [a, b, c, d, _, _] = a.as_coeffs();
|
||||
let sum = a * a + b * b + c * c + d * d;
|
||||
let det = a * d - b * c;
|
||||
(0.5 * (sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt())).sqrt()
|
||||
}
|
||||
|
||||
/// The share of a raster pixel, `space.px` points wide, that a pixel of the Document Raster Effects
|
||||
/// resolution is (at most 1).
|
||||
fn raster_resolution(space: &PixelSpace) -> f64 {
|
||||
if space.line.is_finite() && space.line > 0.0 && space.px.is_finite() && space.px > 0.0 { (space.px / space.line).min(1.0) } else { 1.0 }
|
||||
}
|
||||
|
||||
/// How many times the raster's pixels a turned filter's canvas may hold ([`SvgFilterFx::turned_canvas`]).
|
||||
const TURNED_ROOM: f64 = 4.0;
|
||||
|
||||
impl SvgFilterFx {
|
||||
/// The effect's parameters `p` (defaults merged in): `xml`, the `<filter>` element, `scale`
|
||||
/// and `origin`. `None` when `xml` isn't a filter [`check`] takes, however the effect came to
|
||||
/// hold it (an opened file, a script): the object is then drawn, printed and exported without it.
|
||||
/// The effect's parameters `p` (defaults merged in): `xml`, the `<filter>` element, `scale`,
|
||||
/// `origin` and `axes`. `None` when `xml` isn't a filter [`check`] takes, or `axes` isn't
|
||||
/// valid ([`axes_param`]), however the effect came to hold it (an opened file, a script): the
|
||||
/// object is then drawn, printed and exported without it.
|
||||
pub(crate) fn parse(p: &Value) -> Option<Self> {
|
||||
let axes = axes_param(p)?;
|
||||
let xml = checked(text(p, "xml", ""))?;
|
||||
let (wrapped, _) = wrap(&xml);
|
||||
let doc = roxmltree::Document::parse(&wrapped).ok()?;
|
||||
@@ -1273,7 +1358,17 @@ impl SvgFilterFx {
|
||||
let (window, blur) = (largest(&["radius", "kernelUnitLength"]), largest(&["stdDeviation"]));
|
||||
let box_units = f.attribute("primitiveUnits").is_some_and(|u| u.trim() == "objectBoundingBox");
|
||||
let scale = num(p, "scale", 1.0).clamp(1e-3, 1e3);
|
||||
Some(Self { xml, scale, origin: origin_param(p), region, measured, window, blur, box_units })
|
||||
Some(Self { xml, scale, origin: origin_param(p), axes, region, measured, window, blur, box_units })
|
||||
}
|
||||
|
||||
/// The filter's user space → the document: moved to `origin`, scaled by `scale`, along `axes`.
|
||||
pub fn to_doc(&self) -> Affine {
|
||||
Affine::translate(self.origin) * Affine::scale(self.scale) * self.axes
|
||||
}
|
||||
|
||||
/// The box of `bounds` (document units) in the filter's user space.
|
||||
fn user_box(&self, bounds: Rect) -> Rect {
|
||||
self.to_doc().inverse().transform_rect_bbox(bounds)
|
||||
}
|
||||
|
||||
/// The filter's region in its user space for an object whose box there is `b`: lengths in user
|
||||
@@ -1308,11 +1403,11 @@ impl SvgFilterFx {
|
||||
with_attributes(xml, &[("x", r.x0), ("y", r.y0), ("width", r.width()), ("height", r.height())])
|
||||
}
|
||||
|
||||
/// The filter as SVG output writes it (one unit a point, [`Self::in_points`]) for an object
|
||||
/// whose box in the document is `bounds`: in its SVG 1.1 form ([`svg11`]), `None` when SVG 1.1
|
||||
/// can't hold it ([`Self::writes_as_svg11`]).
|
||||
pub fn written_xml(&self, bounds: Rect) -> Option<String> {
|
||||
let out = self.with_region(&self.svg11_form()?, (bounds - self.origin).scale_from_origin(1.0 / self.scale))?;
|
||||
/// The filter as SVG output writes it, in its user space ([`Self::to_doc`]), for an object
|
||||
/// whose box in that user space is `user_box`: in its SVG 1.1 form ([`svg11`]), `None` when SVG
|
||||
/// 1.1 can't hold it ([`Self::writes_as_svg11`]).
|
||||
pub fn written_xml(&self, user_box: Rect) -> Option<String> {
|
||||
let out = self.with_region(&self.svg11_form()?, user_box)?;
|
||||
(written_len(&out) <= MAX_WRITTEN_XML).then_some(out)
|
||||
}
|
||||
|
||||
@@ -1345,10 +1440,11 @@ impl SvgFilterFx {
|
||||
if !(space.px.is_finite() && space.px > 0.0) {
|
||||
return 1.0;
|
||||
}
|
||||
let mut s: f64 = if space.line.is_finite() && space.line > 0.0 { (space.px / space.line).min(1.0) } else { 1.0 };
|
||||
// A length spans length × scale / px raster pixels, or a fraction of the box.
|
||||
let mut s = raster_resolution(space);
|
||||
// A length spans at most length × scale × the axes' stretch / px raster pixels, or a fraction of the box.
|
||||
let reach = self.scale * stretch(self.axes);
|
||||
for (length, most) in [(self.window, MAX_WINDOW_PX), (self.blur, MAX_BLUR_PX)] {
|
||||
let px = if self.box_units { length * box_px.max(0.0) } else { length * self.scale / space.px };
|
||||
let px = if self.box_units { length * box_px.max(0.0) } else { length * reach / space.px };
|
||||
if px * s > most {
|
||||
s = most / px;
|
||||
}
|
||||
@@ -1374,15 +1470,21 @@ impl SvgFilterFx {
|
||||
self.measured
|
||||
}
|
||||
|
||||
/// Does one unit of the filter's user space measure one point (its `scale` is 1)?
|
||||
pub fn in_points(&self) -> bool {
|
||||
self.scale == 1.0
|
||||
/// Is the filter's user space the document's, only moved: one unit a point, its axes the
|
||||
/// document's (`scale` 1, no `axes`)?
|
||||
pub fn moves_only(&self) -> bool {
|
||||
self.scale == 1.0 && self.axes == Affine::IDENTITY
|
||||
}
|
||||
|
||||
/// Can SVG import store the filter's user space ([`Self::to_doc`]) again ([`user_space`])? Its
|
||||
/// `scale` and `axes` together can scale it past what one of them holds alone.
|
||||
pub fn opens_again(&self) -> bool {
|
||||
user_space(self.to_doc()).is_some()
|
||||
}
|
||||
|
||||
/// How far beyond `bounds` (document units) the filter can draw: its region's reach past them.
|
||||
pub fn outset(&self, bounds: Rect) -> f64 {
|
||||
let b = (bounds - self.origin).scale_from_origin(1.0 / self.scale);
|
||||
let region = self.region_in(b).scale_from_origin(self.scale) + self.origin;
|
||||
let region = self.to_doc().transform_rect_bbox(self.region_in(self.user_box(bounds)));
|
||||
let reach = [bounds.x0 - region.x0, bounds.y0 - region.y0, region.x1 - bounds.x1, region.y1 - bounds.y1].into_iter().fold(0.0, f64::max);
|
||||
if reach.is_finite() { reach.min(MAX_OUTSET) } else { 0.0 }
|
||||
}
|
||||
@@ -1397,20 +1499,40 @@ impl SvgFilterFx {
|
||||
}
|
||||
// Art that draws no pixels still has a box: the whole raster stands for it.
|
||||
let (x0, y0, x1, y1) = drawn_box(data, w, h).unwrap_or((0, 0, w, h));
|
||||
let s = self.resolution(space, (x1 - x0).max(y1 - y0) as f64);
|
||||
let (sw, sh) = ((w as f64 * s).ceil().max(1.0) as u32, (h as f64 * s).ceil().max(1.0) as u32);
|
||||
let Some(png) = png_of(data, w, x0, y0, x1, y1).map(Arc::new) else { return };
|
||||
let k = self.scale;
|
||||
// Filter user space → the small canvas, and the image's pixels → filter user space.
|
||||
let outer = Affine::scale(s) * space.to_doc.inverse() * Affine::translate(self.origin) * Affine::scale(k);
|
||||
let place = Affine::scale(1.0 / k) * Affine::translate(-self.origin) * space.to_doc * Affine::translate(Vec2::new(x0 as f64, y0 as f64));
|
||||
let b = place.transform_rect_bbox(Rect::new(0.0, 0.0, (x1 - x0) as f64, (y1 - y0) as f64));
|
||||
let user = self.to_doc();
|
||||
// Filter user space → the small canvas, and the small canvas → the raster's pixels.
|
||||
let (sw, sh, outer, back) = if self.axes == Affine::IDENTITY {
|
||||
let s = self.resolution(space, (x1 - x0).max(y1 - y0) as f64);
|
||||
let (sw, sh) = ((w as f64 * s).ceil().max(1.0) as u32, (h as f64 * s).ceil().max(1.0) as u32);
|
||||
(sw, sh, Affine::scale(s) * space.to_doc.inverse() * user, Affine::scale(1.0 / s))
|
||||
} else {
|
||||
// The canvas measures the costly lengths in its own pixels.
|
||||
let drawn = Rect::new(x0 as f64, y0 as f64, x1 as f64, y1 as f64);
|
||||
let Some(canvas) = self.turned_canvas(w, h, raster_resolution(space), drawn, space) else { return };
|
||||
canvas
|
||||
};
|
||||
// The source as an image, its size, and the map from its pixels to filter user space. The
|
||||
// object's box in user space is the image's box there, which resvg measures the region and
|
||||
// a primitive's lengths in the object's box against. In a turned or skewed user space the
|
||||
// source is first drawn onto the canvas's pixels, whose rows and columns run along the user
|
||||
// space's axes, and cut to the pixels it draws there: the image then lies along those axes,
|
||||
// and its box is the box of the art in the user space, not of the raster's box turned into it.
|
||||
let source = if self.axes == Affine::IDENTITY {
|
||||
let place = user.inverse() * space.to_doc * Affine::translate(Vec2::new(x0 as f64, y0 as f64));
|
||||
png_of(data, w, x0, y0, x1, y1).map(|png| (png, x1 - x0, y1 - y0, place))
|
||||
} else {
|
||||
on_canvas(data, w, h, sw, sh, outer * user.inverse() * space.to_doc)
|
||||
.map(|(png, cx, cy, iw, ih)| (png, iw, ih, outer.inverse() * Affine::translate(Vec2::new(cx as f64, cy as f64))))
|
||||
};
|
||||
let Some((png, iw, ih, place)) = source else { return };
|
||||
let png = Arc::new(png);
|
||||
let b = place.transform_rect_bbox(Rect::new(0.0, 0.0, iw as f64, ih as f64));
|
||||
let Some(drawn) = self.drawn_xml(b).and_then(|xml| with_id(&xml, DRAWN_ID)) else { return };
|
||||
let svg = format!(
|
||||
"<svg xmlns=\"{SVG_NS}\" xmlns:xlink=\"{XLINK_NS}\" width=\"{sw}\" height=\"{sh}\" viewBox=\"0 0 {sw} {sh}\"><defs>{drawn}</defs><g transform=\"{}\"><g filter=\"url(#{DRAWN_ID})\"><image width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" transform=\"{}\" xlink:href=\"data:image/png;base64,{}\"/></g></g></svg>",
|
||||
matrix(outer),
|
||||
x1 - x0,
|
||||
y1 - y0,
|
||||
iw,
|
||||
ih,
|
||||
matrix(place),
|
||||
base64(&png)
|
||||
);
|
||||
@@ -1420,19 +1542,65 @@ impl SvgFilterFx {
|
||||
}
|
||||
let Some(mut small) = tiny_skia::Pixmap::new(sw, sh) else { return };
|
||||
resvg::render(&tree, tiny_skia::Transform::identity(), &mut small.as_mut());
|
||||
let out = if s < 1.0 {
|
||||
let out = if back == Affine::IDENTITY {
|
||||
small
|
||||
} else {
|
||||
let Some(mut full) = tiny_skia::Pixmap::new(w as u32, h as u32) else { return };
|
||||
let paint = tiny_skia::PixmapPaint { quality: tiny_skia::FilterQuality::Bilinear, ..Default::default() };
|
||||
let up = (1.0 / s) as f32;
|
||||
full.draw_pixmap(0, 0, small.as_ref(), &paint, tiny_skia::Transform::from_scale(up, up), None);
|
||||
let [a, b, c, d, e, f] = back.as_coeffs().map(|v| v as f32);
|
||||
full.draw_pixmap(0, 0, small.as_ref(), &paint, tiny_skia::Transform::from_row(a, b, c, d, e, f), None);
|
||||
full
|
||||
} else {
|
||||
small
|
||||
};
|
||||
if out.data().len() == data.len() {
|
||||
data.copy_from_slice(out.data());
|
||||
}
|
||||
}
|
||||
|
||||
/// The canvas a filter whose user space is turned, skewed or scaled unevenly runs on, for a
|
||||
/// `w` × `h` raster lying in the document as `space` says, at resolution `s`
|
||||
/// ([`raster_resolution`]), whose art draws within `drawn` (raster pixels): its axes are the user
|
||||
/// space's, so the filter's offsets, blurs and other lengths run along them as SVG 1.1 measures
|
||||
/// them, and it covers what the raster shows. Along each of its axes its pixels are about as
|
||||
/// large as the raster's at `s`, and coarser when it would hold more than [`TURNED_ROOM`] times
|
||||
/// as many pixels as the raster does at `s`, and when a morphology radius or kernel unit would
|
||||
/// span more than 32 of its pixels or a blur's standard deviation more than 512 (a length in the
|
||||
/// object's box measured against the art's box on the canvas). Returns its size, the map from
|
||||
/// user space to it, and the map from it to the raster's pixels; `None` when the spaces can't
|
||||
/// be measured.
|
||||
fn turned_canvas(&self, w: usize, h: usize, s: f64, drawn: Rect, space: &PixelSpace) -> Option<(u32, u32, Affine, Affine)> {
|
||||
let to_px = space.to_doc.inverse() * self.to_doc();
|
||||
let from_px = to_px.inverse();
|
||||
let ub = from_px.transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64));
|
||||
let most = ((w as f64 * s).ceil().max(1.0) * (h as f64 * s).ceil().max(1.0) * TURNED_ROOM).max(1.0);
|
||||
// Canvas pixels a unit along each axis of the user space: as many as the raster's at `s`.
|
||||
let [a, b, c, d, _, _] = to_px.as_coeffs();
|
||||
let (mut qx, mut qy) = (s * a.hypot(b), s * c.hypot(d));
|
||||
let pixels = ub.width() * qx * ub.height() * qy;
|
||||
if pixels > most {
|
||||
let k = (most / pixels).sqrt();
|
||||
(qx, qy) = (qx * k, qy * k);
|
||||
}
|
||||
// A length along an axis spans length × q canvas pixels, or length × the art's box on the
|
||||
// canvas along that axis: both shrink with q.
|
||||
let art = from_px.transform_rect_bbox(drawn);
|
||||
for (length, cap) in [(self.window, MAX_WINDOW_PX), (self.blur, MAX_BLUR_PX)] {
|
||||
let px = if self.box_units { length * (art.width() * qx).max(art.height() * qy) } else { length * qx.max(qy) };
|
||||
if px > cap {
|
||||
let k = cap / px;
|
||||
(qx, qy) = (qx * k, qy * k);
|
||||
}
|
||||
}
|
||||
if !(qx.is_finite() && qx > 0.0 && qy.is_finite() && qy > 0.0 && ub.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let (cw, ch) = ((ub.width() * qx).ceil().max(1.0), (ub.height() * qy).ceil().max(1.0));
|
||||
// Rounding up adds at most a row and a column.
|
||||
if cw * ch > most + cw + ch + 1.0 {
|
||||
return None;
|
||||
}
|
||||
let outer = Affine::scale_non_uniform(qx, qy) * Affine::translate(Vec2::new(-ub.x0, -ub.y0));
|
||||
Some((cw as u32, ch as u32, outer, to_px * outer.inverse()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The farthest a filter's region reaches beyond the object, in points.
|
||||
@@ -1450,6 +1618,22 @@ fn drawn_box(data: &[u8], w: usize, h: usize) -> Option<(usize, usize, usize, us
|
||||
(x1 > x0 && y1 > y0).then_some((x0, y0, x1, y1))
|
||||
}
|
||||
|
||||
/// The pixels of `data` (premultiplied RGBA8, `w` × `h`) drawn onto a `cw` × `ch` canvas through
|
||||
/// `to_canvas` (the raster's pixels → the canvas's), cut to the box of the canvas pixels that aren't
|
||||
/// transparent (the whole canvas when all are): a PNG of them, the box's corner on the canvas, and
|
||||
/// its size.
|
||||
fn on_canvas(data: &[u8], w: usize, h: usize, cw: u32, ch: u32, to_canvas: Affine) -> Option<(Vec<u8>, usize, usize, usize, usize)> {
|
||||
let size = tiny_skia::IntSize::from_wh(u32::try_from(w).ok()?, u32::try_from(h).ok()?)?;
|
||||
let raster = tiny_skia::Pixmap::from_vec(data.to_vec(), size)?;
|
||||
let mut canvas = tiny_skia::Pixmap::new(cw, ch)?;
|
||||
let paint = tiny_skia::PixmapPaint { quality: tiny_skia::FilterQuality::Bilinear, ..Default::default() };
|
||||
let [a, b, c, d, e, f] = to_canvas.as_coeffs().map(|v| v as f32);
|
||||
canvas.draw_pixmap(0, 0, raster.as_ref(), &paint, tiny_skia::Transform::from_row(a, b, c, d, e, f), None);
|
||||
let (cw, ch) = (cw as usize, ch as usize);
|
||||
let (x0, y0, x1, y1) = drawn_box(canvas.data(), cw, ch).unwrap_or((0, 0, cw, ch));
|
||||
Some((png_of(canvas.data(), cw, x0, y0, x1, y1)?, x0, y0, x1 - x0, y1 - y0))
|
||||
}
|
||||
|
||||
/// The pixels of `data` (premultiplied RGBA8, `w` wide) in columns x0..x1 and rows y0..y1, as a PNG.
|
||||
fn png_of(data: &[u8], w: usize, x0: usize, y0: usize, x1: usize, y1: usize) -> Option<Vec<u8>> {
|
||||
use image::ImageEncoder;
|
||||
|
||||
@@ -222,6 +222,154 @@ fn user_space_starts_at_the_origin() {
|
||||
assert!((filter(json!({ "xml": half, "origin": [-10.0, 0.0] })).outset(b) - 10.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
/// The opacity of `data` (`w` wide) after the filter `xml` with `params` runs on a blue square
|
||||
/// over 10..20 pt of a 40 pt raster one point a pixel, at each of `points`.
|
||||
fn turned_run(xml: &str, params: serde_json::Value, points: &[(usize, usize)]) -> Vec<u8> {
|
||||
let w = 40;
|
||||
let mut data = image(w, w, |x, y| if (10..20).contains(&x) && (10..20).contains(&y) { [0, 0, 255, 255] } else { [0; 4] });
|
||||
let mut p = params;
|
||||
p["xml"] = json!(xml);
|
||||
filter(p).apply(&mut data, w, w, &space(w, w, 1.0, 1.0));
|
||||
points.iter().map(|&(x, y)| at(&data, w, x, y)[3]).collect()
|
||||
}
|
||||
|
||||
const SHIFT_X: &str = r#"<filter id="Shift" x="-1" y="-1" width="3" height="3"><feOffset dx="4"/></filter>"#;
|
||||
|
||||
/// With `axes`, the filter runs in its turned or skewed user space: an offset along its x axis
|
||||
/// moves the art along that axis in the document (SVG 1.1 measures a primitive's lengths in the
|
||||
/// user space of the element the filter is on).
|
||||
#[test]
|
||||
fn a_turned_user_space_moves_the_art_along_its_own_axes() {
|
||||
// The square spans 10..20 pt; moved 4 pt along x it covers 14..24 across.
|
||||
let points = [(22, 15), (15, 22), (12, 11)];
|
||||
assert_eq!(turned_run(SHIFT_X, json!({}), &points), [255, 0, 0], "the document's axes: to the right");
|
||||
// Turned a quarter turn: the filter's x axis points down the page.
|
||||
let down = turned_run(SHIFT_X, json!({ "axes": [0.0, 1.0, -1.0, 0.0] }), &points);
|
||||
assert_eq!(down, [0, 255, 0], "moved down, not to the right");
|
||||
// Skewed: one unit along y is one across and one down, so dy 4 moves the art 4 pt each way.
|
||||
let shift_y = r#"<filter id="Shift" x="-1" y="-1" width="3" height="3"><feOffset dy="4"/></filter>"#;
|
||||
let skewed = turned_run(shift_y, json!({ "axes": [1.0, 0.0, 1.0, 1.0] }), &[(22, 22), (11, 22), (11, 11)]);
|
||||
assert!(skewed[0] > 200 && skewed[1] < 60 && skewed[2] < 60, "moved across and down: {skewed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn axes_the_effect_cannot_measure_are_not_drawn() {
|
||||
for axes in [json!([0, 0, 0, 0]), json!([1, 2]), json!([1, 0, 0, "1"]), json!([2000, 0, 0, 1]), json!([0.01, 0, 0, 0.01]), json!("turned")] {
|
||||
let e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": SHIFT_X, "axes": axes }), visible: true };
|
||||
assert!(raster_effects(&[e]).is_empty(), "{axes}: drawn without it");
|
||||
assert!(valid_axes(&axes).is_none(), "{axes}");
|
||||
}
|
||||
assert_eq!(valid_axes(&json!([0, 1, -1, 0])), Some(Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0])));
|
||||
}
|
||||
|
||||
/// A region measured against the object's box is measured against its box in the turned user
|
||||
/// space: a diamond turned an eighth of a turn is a square there, and a flood over 0..100% of it
|
||||
/// covers the diamond alone.
|
||||
#[test]
|
||||
fn a_turned_region_is_measured_against_the_box_in_its_user_space() {
|
||||
let w = 40;
|
||||
let diamond = |x: usize, y: usize| (x as f64 - 19.5).abs() + (y as f64 - 19.5).abs() <= 10.0;
|
||||
let mut data = image(w, w, |x, y| if diamond(x, y) { [0, 0, 255, 255] } else { [0; 4] });
|
||||
let flood = r##"<filter id="F" filterUnits="userSpaceOnUse" x="0%" y="0%" width="100%" height="100%"><feFlood flood-color="#ff0000"/></filter>"##;
|
||||
let h = std::f64::consts::FRAC_1_SQRT_2;
|
||||
filter(json!({ "xml": flood, "axes": [h, h, -h, h] })).apply(&mut data, w, w, &space(w, w, 1.0, 1.0));
|
||||
assert_eq!(at(&data, w, 20, 20), [255, 0, 0, 255], "inside the diamond");
|
||||
assert!(at(&data, w, 12, 12)[3] < 40, "outside the diamond, inside its box on the page: {:?}", at(&data, w, 12, 12));
|
||||
}
|
||||
|
||||
/// In a turned user space, a region in the object's bounding box (the default `filterUnits`) and a
|
||||
/// primitive's lengths in it (`primitiveUnits="objectBoundingBox"`) are measured against the
|
||||
/// object's box there: on a diamond turned an eighth of a turn, a flood over 0..100% of the box
|
||||
/// covers the diamond alone.
|
||||
#[test]
|
||||
fn a_turned_filter_measures_box_units_against_the_box_in_its_user_space() {
|
||||
let w = 40;
|
||||
let h = std::f64::consts::FRAC_1_SQRT_2;
|
||||
let region = r##"<filter id="F" x="0" y="0" width="1" height="1"><feFlood flood-color="#ff0000"/></filter>"##;
|
||||
let primitive = r##"<filter id="F" filterUnits="userSpaceOnUse" x="-1000" y="-1000" width="2000" height="2000" primitiveUnits="objectBoundingBox"><feFlood flood-color="#ff0000" x="0" y="0" width="1" height="1"/></filter>"##;
|
||||
for xml in [region, primitive] {
|
||||
let diamond = |x: usize, y: usize| (x as f64 - 19.5).abs() + (y as f64 - 19.5).abs() <= 10.0;
|
||||
let mut data = image(w, w, |x, y| if diamond(x, y) { [0, 0, 255, 255] } else { [0; 4] });
|
||||
filter(json!({ "xml": xml, "axes": [h, h, -h, h] })).apply(&mut data, w, w, &space(w, w, 1.0, 1.0));
|
||||
assert_eq!(at(&data, w, 20, 20), [255, 0, 0, 255], "{xml}: inside the diamond");
|
||||
assert!(at(&data, w, 12, 12)[3] < 40, "{xml}: outside the diamond, inside its box on the page: {:?}", at(&data, w, 12, 12));
|
||||
}
|
||||
}
|
||||
|
||||
/// SVG import stores a filter's user space again only when `scale` and `axes` together stay within
|
||||
/// what it holds: each alone can be valid while their product is not.
|
||||
#[test]
|
||||
fn a_user_space_opens_again_only_within_what_import_stores() {
|
||||
let opens = |scale: f64, axes: serde_json::Value| filter(json!({ "xml": SHIFT_X, "scale": scale, "axes": axes })).opens_again();
|
||||
assert!(opens(1000.0, json!(null)));
|
||||
assert!(opens(2.0, json!([0.0, 1.0, -1.0, 0.0])));
|
||||
assert!(!opens(1000.0, json!([2.0, 0.0, 0.0, 2.0])), "scale 2000 across");
|
||||
assert!(!opens(0.001, json!([0.5, 0.0, 0.0, 0.5])), "scale 0.0005 across");
|
||||
let space = user_space(Affine::new([0.0, 2.0, -2.0, 0.0, 5.0, 6.0])).unwrap();
|
||||
assert_eq!((space.scale, space.origin, space.axes), (2.0, [5.0, 6.0], Some([0.0, 1.0, -1.0, 0.0])));
|
||||
}
|
||||
|
||||
/// The region of a turned filter reaches as far as its turned box does.
|
||||
#[test]
|
||||
fn a_turned_region_reaches_along_the_turned_axes() {
|
||||
let b = Rect::new(0.0, 0.0, 50.0, 50.0);
|
||||
let user = r#"<filter id="u" filterUnits="userSpaceOnUse" x="-30" y="-5" width="100" height="100"><feOffset/></filter>"#;
|
||||
assert!((filter(json!({ "xml": user })).outset(b) - 45.0).abs() < 1e-9, "45 pt below the box");
|
||||
// A quarter turn: user y runs to the left of the page, so -5..95 of it lies 95 pt left of the box.
|
||||
assert!((filter(json!({ "xml": user, "axes": [0.0, 1.0, -1.0, 0.0] })).outset(b) - 95.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
/// A filter skewed as far as `axes` allows runs on a canvas no larger than four times the raster's
|
||||
/// pixels, however far the skew spreads the raster's box in its user space.
|
||||
#[test]
|
||||
fn a_skewed_filter_runs_within_its_pixel_budget() {
|
||||
let (w, h) = (64, 48);
|
||||
let f = filter(json!({ "xml": SHIFT_X, "axes": [1.0, 0.0, 999.0, 1.0] }));
|
||||
let all = Rect::new(0.0, 0.0, w as f64, h as f64);
|
||||
let (cw, ch, ..) = f.turned_canvas(w, h, 1.0, all, &space(w, h, 1.0, 1.0)).unwrap();
|
||||
let (cw, ch) = (f64::from(cw), f64::from(ch));
|
||||
assert!(cw * ch <= TURNED_ROOM * (w * h) as f64 + cw + ch + 1.0, "{cw} × {ch}");
|
||||
// It still draws.
|
||||
let mut data = image(w, h, |x, y| if (20..40).contains(&x) && (10..30).contains(&y) { [0, 0, 255, 255] } else { [0; 4] });
|
||||
f.apply(&mut data, w, h, &space(w, h, 1.0, 1.0));
|
||||
// A plain quarter turn keeps the raster's own pixel size.
|
||||
let turned = filter(json!({ "xml": SHIFT_X, "axes": [0.0, 1.0, -1.0, 0.0] }));
|
||||
let (cw, ch, outer, _) = turned.turned_canvas(w, h, 1.0, all, &space(w, h, 1.0, 1.0)).unwrap();
|
||||
assert_eq!((cw, ch), (48, 64));
|
||||
assert!((outer.determinant() - 1.0).abs() < 1e-9);
|
||||
// Stretched 100 times across and squeezed 100 times down: each canvas axis keeps the raster's
|
||||
// detail along it, not one column of it.
|
||||
let stretched = filter(json!({ "xml": SHIFT_X, "axes": [100.0, 0.0, 0.0, 0.01] }));
|
||||
let (cw, ch, ..) = stretched.turned_canvas(100, 100, 1.0, Rect::new(0.0, 0.0, 100.0, 100.0), &space(100, 100, 1.0, 1.0)).unwrap();
|
||||
assert_eq!((cw, ch), (100, 100));
|
||||
}
|
||||
|
||||
/// On a far skewed canvas, a radius or a standard deviation in the object's box spans no more
|
||||
/// canvas pixels than the caps allow: it is measured against the art's box on the canvas, which the
|
||||
/// skew spreads far wider than the art's box in the raster.
|
||||
#[test]
|
||||
fn a_skewed_filter_keeps_box_lengths_within_the_caps_on_its_canvas() {
|
||||
let (w, h) = (64, 48);
|
||||
let sp = space(w, h, 1.0, 1.0);
|
||||
let drawn = Rect::new(20.0, 10.0, 40.0, 30.0);
|
||||
for (xml, length, cap) in [
|
||||
("<filter id=\"m\" primitiveUnits=\"objectBoundingBox\"><feMorphology radius=\"1.5\"/></filter>", 1.5, MAX_WINDOW_PX),
|
||||
("<filter id=\"b\" primitiveUnits=\"objectBoundingBox\"><feGaussianBlur stdDeviation=\"20\"/></filter>", 20.0, MAX_BLUR_PX),
|
||||
] {
|
||||
let f = filter(json!({ "xml": xml, "axes": [1.0, 0.0, 999.0, 1.0] }));
|
||||
let (_, _, outer, _) = f.turned_canvas(w, h, 1.0, drawn, &sp).unwrap();
|
||||
// The art's box on the canvas: the drawn pixels taken into user space, then onto the canvas.
|
||||
let art = (outer * f.to_doc().inverse() * sp.to_doc).transform_rect_bbox(drawn);
|
||||
let px = length * art.width().max(art.height());
|
||||
assert!(px <= cap + 1e-6, "{xml}: {px} canvas pixels");
|
||||
}
|
||||
// A user-space radius spans no more than 32 canvas pixels along either axis.
|
||||
let f = filter(json!({ "xml": "<filter id=\"u\"><feMorphology radius=\"100\"/></filter>", "scale": 1000.0, "axes": [1.0, 0.0, 999.0, 1.0] }));
|
||||
let (_, _, outer, _) = f.turned_canvas(w, h, 1.0, drawn, &sp).unwrap();
|
||||
let [qx, _, _, qy, _, _] = outer.as_coeffs();
|
||||
assert!(100.0 * qx.max(qy) <= MAX_WINDOW_PX + 1e-6, "{qx} {qy}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_no_finer_than_the_raster_effects_resolution() {
|
||||
let w = 16;
|
||||
@@ -448,7 +596,8 @@ fn a_region_measured_against_the_box_is_written_out() {
|
||||
let far = r#"<filter id="r" filterUnits="userSpaceOnUse" x="-50%" y="0" width="200%" height="10"><feOffset/></filter>"#;
|
||||
let f = filter(json!({ "xml": far, "origin": [10.0, 0.0] }));
|
||||
assert_eq!(
|
||||
f.written_xml(Rect::new(10.0, 0.0, 30.0, 10.0)).as_deref(),
|
||||
// The object over 10..30 pt of the page: 0..20 of the user space that starts at the origin.
|
||||
f.written_xml(Rect::new(0.0, 0.0, 20.0, 10.0)).as_deref(),
|
||||
Some(r#"<filter id="r" filterUnits="userSpaceOnUse" x="-10" y="0" width="40" height="10"><feOffset/></filter>"#)
|
||||
);
|
||||
let plain = filter(json!({ "xml": RED_FLOOD }));
|
||||
|
||||
@@ -11,6 +11,7 @@ mod rasterfollow;
|
||||
mod scale;
|
||||
mod solidcontext;
|
||||
mod transformfx;
|
||||
mod typestroke;
|
||||
|
||||
fn fx(id: &str, params: Value) -> Effect {
|
||||
Effect { id: id.into(), params, visible: true }
|
||||
|
||||
@@ -7,7 +7,8 @@ use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId};
|
||||
use vectorcraft_geom::{Affine, Anchor, PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use crate::geometry::{Budget, MAX_EFFECT_LINES, apply_geometry_carrying_within};
|
||||
use crate::{Carry, GeomContext, RasterFx, apply_geometry_carrying, bake_document, expand_outlined, raster_effects};
|
||||
use crate::pixel::{Light, StrokeDirection};
|
||||
use crate::{Carry, GeomContext, PixelFx, RasterFx, apply_geometry_carrying, bake_document, expand_outlined, raster_effects};
|
||||
|
||||
fn fx(id: &str, params: Value) -> Effect {
|
||||
Effect { id: id.into(), params, visible: true }
|
||||
@@ -436,6 +437,230 @@ fn pixel_filter_sizes_scale_with_the_transform_after_them() {
|
||||
assert!(matches!(drawn.get(1), Some(RasterFx::Pixel(crate::PixelFx::PaintDaubs { size, .. })) if (size - 20.0).abs() < 1e-9), "{drawn:?}");
|
||||
}
|
||||
|
||||
/// The light direction of the first pixel filter `effects` draw, if it has one.
|
||||
fn drawn_light(effects: &[Effect]) -> Option<Light> {
|
||||
raster_effects(effects).into_iter().find_map(|r| match r {
|
||||
RasterFx::Pixel(
|
||||
PixelFx::Underpainting { light, .. }
|
||||
| PixelFx::RoughPastels { light, .. }
|
||||
| PixelFx::ConteCrayon { light, .. }
|
||||
| PixelFx::BasRelief { light, .. }
|
||||
| PixelFx::Plaster { light, .. }
|
||||
| PixelFx::Texturizer { light, .. },
|
||||
) => Some(light),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The stroke direction of the first pixel filter `effects` draw, if it has one.
|
||||
fn drawn_strokes(effects: &[Effect]) -> Option<StrokeDirection> {
|
||||
raster_effects(effects).into_iter().find_map(|r| match r {
|
||||
RasterFx::Pixel(PixelFx::SprayedStrokes { direction, .. } | PixelFx::GraphicPen { direction, .. }) => Some(direction),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The screen angles of the first Color Halftone `effects` draw.
|
||||
fn drawn_screens(effects: &[Effect]) -> [f64; 4] {
|
||||
match raster_effects(effects).into_iter().next() {
|
||||
Some(RasterFx::Pixel(PixelFx::ColorHalftone { angles, .. })) => angles,
|
||||
other => panic!("expected a Color Halftone, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A Bas Relief lit from `light`, then a Transform effect with `params`: the light it draws with.
|
||||
fn relief_then(light: &str, params: Value) -> Option<Light> {
|
||||
drawn_light(&[fx("sketch.basRelief", json!({ "lightDirection": light })), transform(params)])
|
||||
}
|
||||
|
||||
/// A light direction before a Transform effect turns and reflects with the art (y down on the
|
||||
/// page), to the nearest of the eight directions, the clockwise one at a tie.
|
||||
#[test]
|
||||
fn bas_relief_light_follows_rotation_and_reflection() {
|
||||
assert_eq!(relief_then("top", json!({"rotate": 90})), Some(Light::Left));
|
||||
assert_eq!(relief_then("top", json!({"reflectY": true})), Some(Light::Bottom));
|
||||
assert_eq!(relief_then("top", json!({"reflectX": true})), Some(Light::Top));
|
||||
assert_eq!(relief_then("left", json!({"reflectX": true})), Some(Light::Right));
|
||||
// 22.5° clockwise lies halfway between Top and Top Right; 22.5° counterclockwise halfway
|
||||
// between Top and Top Left.
|
||||
assert_eq!(relief_then("top", json!({"rotate": -22.5})), Some(Light::TopRight));
|
||||
assert_eq!(relief_then("top", json!({"rotate": 22.5})), Some(Light::Top));
|
||||
assert_eq!(relief_then("top", json!({"rotate": 30})), Some(Light::TopLeft));
|
||||
// A turn of 90° counterclockwise, from each direction.
|
||||
for (from, to) in [
|
||||
("bottom", Light::Right),
|
||||
("bottomLeft", Light::BottomRight),
|
||||
("left", Light::Bottom),
|
||||
("topLeft", Light::BottomLeft),
|
||||
("top", Light::Left),
|
||||
("topRight", Light::TopLeft),
|
||||
("right", Light::Top),
|
||||
("bottomRight", Light::TopRight),
|
||||
] {
|
||||
assert_eq!(relief_then(from, json!({"rotate": 90})), Some(to), "{from}");
|
||||
}
|
||||
// Every filter with a light direction, and Bas Relief's default light (Bottom).
|
||||
for id in ["artistic.underpainting", "artistic.roughPastels", "sketch.conteCrayon", "sketch.basRelief", "sketch.plaster", "texture.texturizer"] {
|
||||
let effects = [fx(id, json!({"lightDirection": "top"})), transform(json!({"rotate": 90}))];
|
||||
assert_eq!(drawn_light(&effects), Some(Light::Left), "{id}");
|
||||
}
|
||||
assert_eq!(drawn_light(&[fx("sketch.basRelief", json!({})), transform(json!({"rotate": 90}))]), Some(Light::Right));
|
||||
// The Transform effects after the filter turn it together, with one rounding at the end.
|
||||
let twice = [fx("sketch.basRelief", json!({"lightDirection": "top"})), transform(json!({"rotate": -22.5})), transform(json!({"rotate": -22.5}))];
|
||||
assert_eq!(drawn_light(&twice), Some(Light::TopRight));
|
||||
}
|
||||
|
||||
/// A stroke direction before a Transform effect turns and reflects with the art, to the nearest
|
||||
/// of the four, a stroke and its reverse being the same, the clockwise one at a tie.
|
||||
#[test]
|
||||
fn stroke_axis_follows_transform() {
|
||||
let strokes = |id: &str, way: Option<&str>, params: Value| {
|
||||
let p = way.map_or(json!({}), |w| json!({ "strokeDirection": w }));
|
||||
drawn_strokes(&[fx(id, p), transform(params)])
|
||||
};
|
||||
let sprayed = "brushStrokes.sprayedStrokes";
|
||||
let pen = "sketch.graphicPen";
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 90})), Some(StrokeDirection::Vertical));
|
||||
assert_eq!(strokes(sprayed, Some("vertical"), json!({"rotate": 90})), Some(StrokeDirection::Horizontal));
|
||||
assert_eq!(strokes(pen, Some("rightDiagonal"), json!({"rotate": 90})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(pen, Some("rightDiagonal"), json!({"reflectX": true})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(pen, Some("leftDiagonal"), json!({"reflectY": true})), Some(StrokeDirection::RightDiagonal));
|
||||
assert_eq!(strokes(pen, None, json!({"rotate": 90})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": -22.5})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 22.5})), Some(StrokeDirection::Horizontal));
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": -44})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 180})), Some(StrokeDirection::Horizontal));
|
||||
}
|
||||
|
||||
fn near4(a: [f64; 4], b: [f64; 4]) -> bool {
|
||||
a.iter().zip(b).all(|(p, q)| (p - q).abs() < 1e-6)
|
||||
}
|
||||
|
||||
/// Color Halftone's screen angles before a Transform effect turn and reflect with the art.
|
||||
#[test]
|
||||
fn halftone_channels_follow_rotation_and_reflection() {
|
||||
let screens = |p: Value, transforms: &[Value]| {
|
||||
let mut effects = vec![fx("pixelate.colorHalftone", p)];
|
||||
effects.extend(transforms.iter().cloned().map(transform));
|
||||
drawn_screens(&effects)
|
||||
};
|
||||
let defaults = screens(json!({}), &[json!({"rotate": 90})]);
|
||||
assert!(near4(defaults, [198.0, 252.0, 180.0, 135.0]), "{defaults:?}");
|
||||
let reflected = screens(json!({"channel1": 45, "channel2": 30, "channel3": 0, "channel4": 270}), &[json!({"reflectX": true})]);
|
||||
assert!(near4(reflected, [135.0, 150.0, 180.0, 270.0]), "{reflected:?}");
|
||||
let flipped = screens(json!({"channel1": 45, "channel2": 30, "channel3": 0, "channel4": 270}), &[json!({"reflectY": true})]);
|
||||
assert!(near4(flipped, [315.0, 330.0, 0.0, 90.0]), "{flipped:?}");
|
||||
// One Transform effect reflects, then turns; two apply in the order they are listed.
|
||||
let p = json!({"channel1": 10.5, "channel2": -30, "channel3": 0, "channel4": 359.25});
|
||||
let one = screens(p.clone(), &[json!({"rotate": 30, "reflectX": true})]);
|
||||
assert!(near4(one, [199.5, 240.0, 210.0, 210.75]), "{one:?}");
|
||||
let two = screens(p, &[json!({"rotate": 30}), json!({"reflectX": true})]);
|
||||
assert!(near4(two, [139.5, 180.0, 150.0, 150.75]), "{two:?}");
|
||||
}
|
||||
|
||||
/// Only the visible Transform effects listed after a filter that move the art once turn its
|
||||
/// direction; a hidden filter turns too, and a zero scale leaves it as it is.
|
||||
#[test]
|
||||
fn only_earlier_visible_single_map_effects_follow() {
|
||||
let relief = fx("sketch.basRelief", json!({"lightDirection": "top"}));
|
||||
assert_eq!(drawn_light(&[transform(json!({"rotate": 90})), relief.clone()]), Some(Light::Top));
|
||||
for params in [
|
||||
json!({"rotate": 90, "objects": false}),
|
||||
json!({"rotate": 90, "copies": 1}),
|
||||
json!({"rotate": 90, "random": true}),
|
||||
json!({"scaleH": 0, "scaleV": 0}),
|
||||
] {
|
||||
assert_eq!(drawn_light(&[relief.clone(), transform(params.clone())]), Some(Light::Top), "{params}");
|
||||
}
|
||||
let mut hidden = transform(json!({"rotate": 90}));
|
||||
hidden.visible = false;
|
||||
assert_eq!(drawn_light(&[relief.clone(), hidden]), Some(Light::Top));
|
||||
let zero = [fx("pixelate.colorHalftone", json!({"channel1": 20})), transform(json!({"scaleH": 0, "scaleV": 0}))];
|
||||
assert!(near4(drawn_screens(&zero), [20.0, 162.0, 90.0, 45.0]), "{:?}", drawn_screens(&zero));
|
||||
// A hidden filter kept when the Transform effect is applied draws turned once it is shown.
|
||||
let mut off = relief;
|
||||
off.visible = false;
|
||||
let kept = crate::raster::without_geometry(&[off, transform(json!({"rotate": 90}))]);
|
||||
assert_eq!(kept.len(), 1);
|
||||
let mut shown = kept[0].clone();
|
||||
shown.visible = true;
|
||||
assert_eq!(drawn_light(&[shown]), Some(Light::Left));
|
||||
}
|
||||
|
||||
/// The light direction of every Bas Relief drawn on `n` and the nodes under it, from the object's
|
||||
/// effects and from each fill's and stroke's.
|
||||
fn lights_in(n: &Node) -> Vec<Light> {
|
||||
let mut out = vec![];
|
||||
n.walk(&mut |m| {
|
||||
let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects()));
|
||||
for list in lists {
|
||||
out.extend(drawn_light(list));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// The canvas, a fill's own effects, a group's members and export turn the light the same way.
|
||||
#[test]
|
||||
fn nested_and_baked_directions_match_canvas() {
|
||||
let relief = || fx("sketch.basRelief", json!({"lightDirection": "top"}));
|
||||
let turn = || transform(json!({"rotate": 90}));
|
||||
// A fill's own Transform effect, and the object's Transform effect over its fill.
|
||||
let fill = fill_square(31, vec![relief(), turn()]);
|
||||
let item = fill.appearance.items.first().unwrap();
|
||||
assert_eq!(drawn_light(item.effects()), Some(Light::Left));
|
||||
let mut over = fill_square(32, vec![relief()]);
|
||||
over.appearance.effects = vec![turn()];
|
||||
let item = over.appearance.items.first().unwrap();
|
||||
assert_eq!(drawn_light(&crate::item_effects_in(&over.appearance.effects, item.effects())), Some(Light::Left));
|
||||
// A fill's own turn of 30° and the object's turn of 30° make 60°, rounded once: Top Left, not
|
||||
// Left (Top Left after the first turn, then Left after the second).
|
||||
let thirty = || transform(json!({"rotate": 30}));
|
||||
let mut both = fill_square(37, vec![relief(), thirty()]);
|
||||
both.appearance.effects = vec![thirty()];
|
||||
let item = both.appearance.items.first().unwrap();
|
||||
assert_eq!(drawn_light(&crate::item_effects_in(&both.appearance.effects, item.effects())), Some(Light::TopLeft));
|
||||
// A group's Transform effect over a member's own filter and its fill's.
|
||||
let g = group(33, vec![square(34, vec![relief()]), fill_square(35, vec![relief()])], vec![turn()]);
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
assert_eq!(lights_in(&art), vec![Light::Left; 2]);
|
||||
// Baked for export: the Transform effect is applied and the filter keeps the turned light.
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, square(36, vec![relief(), turn()])).unwrap();
|
||||
d.insert(Some(layer), 1, g).unwrap();
|
||||
let baked = bake_document(&d).unwrap();
|
||||
let b = baked.node(NodeId(36)).unwrap();
|
||||
assert!(!b.appearance.effects.iter().any(|e| e.id == "distort.transform"), "{:?}", b.appearance.effects);
|
||||
assert_eq!(drawn_light(&b.appearance.effects), Some(Light::Left));
|
||||
for id in [34, 35] {
|
||||
assert_eq!(lights_in(baked.node(NodeId(id)).unwrap()), vec![Light::Left], "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A member's light under two nested groups that each turn 30° turns 60° in all, rounded once:
|
||||
/// Top Left, not Left (Top Left after the inner group's turn, then Left after the outer one's).
|
||||
#[test]
|
||||
fn nested_group_turns_round_the_light_once() {
|
||||
let relief = || fx("sketch.basRelief", json!({"lightDirection": "top"}));
|
||||
let thirty = || transform(json!({"rotate": 30}));
|
||||
let inner = group(41, vec![square(42, vec![relief()]), fill_square(43, vec![relief()])], vec![thirty()]);
|
||||
let outer = group(40, vec![inner], vec![thirty()]);
|
||||
let art = crate::evaluate_container(None, &outer).unwrap();
|
||||
assert_eq!(lights_in(&art), vec![Light::TopLeft; 2]);
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, outer).unwrap();
|
||||
let baked = bake_document(&d).unwrap();
|
||||
for id in [42, 43] {
|
||||
assert_eq!(lights_in(baked.node(NodeId(id)).unwrap()), vec![Light::TopLeft], "{id}");
|
||||
}
|
||||
// Three groups make 90°: Left, not Bottom Left.
|
||||
let three = group(44, vec![group(45, vec![group(46, vec![square(47, vec![relief()])], vec![thirty()])], vec![thirty()])], vec![thirty()]);
|
||||
let art = crate::evaluate_container(None, &three).unwrap();
|
||||
assert_eq!(lights_in(&art), vec![Light::Left]);
|
||||
}
|
||||
|
||||
/// A Transform effect after a 3D effect that makes copies or moves at random holds back the shadow
|
||||
/// before the 3D effect, as it does without the 3D effect.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Character strokes of outlined type under the type's transform ([`paint_type_piece`]): a live
|
||||
//! stroke with a scaled weight under a similarity, otherwise the area the stroke paints in text
|
||||
//! space, placed by the transform and filled.
|
||||
|
||||
use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{Appearance, CharStyle, Dash, LineJoin, Node, NodeId, StrokeAlign};
|
||||
use vectorcraft_geom::{Affine, FillRule, Rect, shapes};
|
||||
|
||||
use crate::*;
|
||||
|
||||
const BOX: Rect = Rect::new(0.0, 0.0, 10.0, 10.0);
|
||||
|
||||
fn red() -> Color {
|
||||
Color::rgb(1.0, 0.0, 0.0)
|
||||
}
|
||||
|
||||
/// A black run with a red stroke of `width` and round joins.
|
||||
fn style(width: f64) -> CharStyle {
|
||||
CharStyle {
|
||||
fill: Paint::solid(Color::BLACK),
|
||||
stroke: Paint::solid(red()),
|
||||
stroke_width: width,
|
||||
stroke_join: LineJoin::Round,
|
||||
..CharStyle::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A 10 x 10 square in text space standing in for a glyph.
|
||||
fn square() -> Node {
|
||||
Node::path(NodeId(7), shapes::rectangle(BOX), Appearance::default())
|
||||
}
|
||||
|
||||
fn area(n: &Node) -> f64 {
|
||||
vectorcraft_pathops::area(n.path_data().unwrap(), FillRule::NonZero).abs()
|
||||
}
|
||||
|
||||
fn near(a: Rect, b: Rect) -> bool {
|
||||
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 0.05)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_uneven_scale_fills_the_stroke_the_canvas_paints() {
|
||||
let mut piece = square();
|
||||
let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, Affine::scale_non_uniform(3.0, 1.0)).expect("a filled stroke");
|
||||
assert!(piece.appearance.stroke().is_none(), "the piece keeps only its fill");
|
||||
assert_eq!(piece.appearance.fill_paint(), Paint::solid(Color::BLACK));
|
||||
assert_eq!(piece.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 30.0, 10.0));
|
||||
assert!(stroke.appearance.stroke().is_none());
|
||||
assert_eq!(stroke.appearance.fill_paint(), Paint::solid(red()));
|
||||
assert_eq!(stroke.id, NodeId(7));
|
||||
// 4 pt across in text space: 12 pt across the upright sides and 4 pt across the level ones.
|
||||
let b = stroke.geometric_bounds().unwrap();
|
||||
assert!(near(b, Rect::new(-6.0, -2.0, 36.0, 12.0)), "{b:?}");
|
||||
// The ring of a 10 pt square stroked 4 pt with round joins (180 + 4π outside, 36 inside), 3 times as wide.
|
||||
let ring = 180.0 + 4.0 * std::f64::consts::PI - 36.0;
|
||||
assert!((area(&stroke) - 3.0 * ring).abs() < 0.5, "{}", area(&stroke));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_similarity_keeps_the_live_stroke_with_a_scaled_weight() {
|
||||
for (xf, weight) in [
|
||||
(Affine::translate((5.0, 5.0)), 4.0),
|
||||
(Affine::scale(2.0), 8.0),
|
||||
(Affine::rotate(0.5) * Affine::scale(2.0), 8.0),
|
||||
(Affine::scale_non_uniform(-2.0, 2.0), 8.0),
|
||||
] {
|
||||
let mut piece = square();
|
||||
assert!(paint_type_piece(&mut piece, &style(4.0), BOX, xf).is_none(), "{xf:?}");
|
||||
let st = piece.appearance.stroke().expect("a live stroke");
|
||||
assert!((st.width - weight).abs() < 1e-9, "{xf:?}: {}", st.width);
|
||||
assert_eq!(st.join, LineJoin::Round);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shears_and_flattening_transforms_fill_the_stroke() {
|
||||
// A shear keeps the area.
|
||||
let mut piece = square();
|
||||
let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, Affine::skew(0.5, 0.0)).expect("a filled stroke");
|
||||
let ring = 180.0 + 4.0 * std::f64::consts::PI - 36.0;
|
||||
assert!((area(&stroke) - ring).abs() < 0.5, "{}", area(&stroke));
|
||||
// Flattened to a line or a point: no division by the determinant, nothing non-finite.
|
||||
for xf in [Affine::scale_non_uniform(2.0, 0.0), Affine::scale(0.0)] {
|
||||
let mut piece = square();
|
||||
let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, xf).expect("a filled stroke");
|
||||
assert!(piece.appearance.stroke().is_none());
|
||||
if let Some(b) = stroke.geometric_bounds() {
|
||||
assert!([b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && b.height().abs() < 1e-9, "{xf:?}: {b:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stroke_options_shape_the_filled_stroke_in_text_space() {
|
||||
let xf = Affine::scale_non_uniform(3.0, 1.0);
|
||||
let filled = |st: CharStyle| paint_type_piece(&mut square(), &st, BOX, xf);
|
||||
// No stroke, or no weight: nothing is filled.
|
||||
assert!(filled(style(0.0)).is_none());
|
||||
assert!(filled(CharStyle { stroke: Paint::None, ..style(4.0) }).is_none());
|
||||
// Inside and outside alignment are kept to their side of the square before it is scaled.
|
||||
let inside = filled(CharStyle { stroke_align: StrokeAlign::Inside, ..style(4.0) }).unwrap();
|
||||
assert!(near(inside.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 30.0, 10.0)));
|
||||
assert!((area(&inside) - 3.0 * (100.0 - 4.0)).abs() < 0.5, "{}", area(&inside));
|
||||
let outside = filled(CharStyle { stroke_align: StrokeAlign::Outside, ..style(4.0) }).unwrap();
|
||||
assert!(near(outside.geometric_bounds().unwrap(), Rect::new(-12.0, -4.0, 42.0, 14.0)), "{:?}", outside.geometric_bounds());
|
||||
// Dashes are laid out along the square in text space: half of each 10 pt is painted.
|
||||
let solid = area(&filled(style(1.0)).unwrap());
|
||||
let dash = Dash { pattern: vec![5.0, 5.0], ..Default::default() };
|
||||
let dashed = area(&filled(CharStyle { stroke_dash: Some(dash), ..style(1.0) }).unwrap());
|
||||
assert!(dashed < 0.7 * solid && dashed > 0.3 * solid, "{dashed} of {solid}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_on_the_stroke_stays_where_the_stroke_had_it() {
|
||||
let stops = vec![GradientStop::new(0.0, red()), GradientStop::new(1.0, Color::BLACK)];
|
||||
let ramp = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
let mut piece = square();
|
||||
let stroke = paint_type_piece(&mut piece, &CharStyle { stroke: ramp, ..style(4.0) }, BOX, Affine::scale_non_uniform(3.0, 1.0)).unwrap();
|
||||
let Paint::Gradient(g) = stroke.appearance.fill_paint() else { panic!("a gradient fill") };
|
||||
// Fitted across the stroke's box in text space (the square grown by half the weight), then scaled.
|
||||
let geom = g.geom.expect("placed");
|
||||
assert!((geom.start.x + 6.0).abs() < 1e-6 && (geom.end.x - 36.0).abs() < 1e-6, "{geom:?}");
|
||||
}
|
||||
@@ -53,7 +53,7 @@ heic-rs = { version = "=0.1.4", default-features = false, features = ["std"], op
|
||||
flate2 = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
# The XML parts of Word documents placed as type (place/docx.rs).
|
||||
roxmltree = "0.21"
|
||||
craft-xml = { workspace = true }
|
||||
# The compound file that holds a Word 97-2003 document placed as type (place/doc.rs).
|
||||
cfb = "0.15"
|
||||
kurbo = { workspace = true }
|
||||
|
||||
@@ -98,6 +98,8 @@ pub(crate) mod symboledit;
|
||||
pub mod symbollib;
|
||||
pub(crate) mod tabs;
|
||||
mod textedit;
|
||||
mod xmlattrs;
|
||||
|
||||
pub use textedit::effective_kerning;
|
||||
pub mod textstyles;
|
||||
pub(crate) mod textwrap;
|
||||
|
||||
@@ -9,8 +9,9 @@
|
||||
//! text. Each action is an `/action-N` block with a hexadecimal `/name`; each step is an `/event-N`
|
||||
//! block inside one, with its `/internalName` in parentheses, the `/localizedName` it is shown with
|
||||
//! as hexadecimal text, and `/isOn` 0 when it is left out of playback; each value a step was
|
||||
//! recorded with is a `/parameter-N` block inside it, which is counted, and whose hexadecimal
|
||||
//! `/value` is checked against its byte count. The set's `/actionCount`, an action's `/eventCount`
|
||||
//! recorded with is a `/parameter-N` block inside it, which is counted, whose `/key` (a number),
|
||||
//! `/type` (text in parentheses) and `/value` (a number, text in parentheses or hexadecimal text) are
|
||||
//! kept, and whose hexadecimal `/value` is checked against its byte count. The set's `/actionCount`, an action's `/eventCount`
|
||||
//! and a step's `/parameterCount` give how many actions, steps and recorded values follow.
|
||||
//! The layout follows the README of Inventsable's Redesigning-Illustrator-Actions-in-Scripting
|
||||
//! (https://github.com/Inventsable/Redesigning-Illustrator-Actions-in-Scripting), the forum post
|
||||
@@ -40,6 +41,8 @@ const MAX_STEPS: usize = 10_000;
|
||||
/// The most steps read in the set: a small text can hold hundreds of thousands of empty steps, and
|
||||
/// the answer holds an object for each.
|
||||
const MAX_SET_STEPS: usize = 100_000;
|
||||
/// The most recorded values kept in the set; the others are counted but not kept.
|
||||
const MAX_VALUES: usize = 100_000;
|
||||
/// The longest name kept (bytes).
|
||||
const MAX_NAME: usize = 1024;
|
||||
/// The most tokens listed as unread.
|
||||
@@ -56,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Read Action Set File",
|
||||
[],
|
||||
None,
|
||||
"{path? | data?: the file's text | dataBase64?, name?: the file's name (default: the path's)} read an action set another app saved as text (.aia, starting \"/version\") without changing anything → {set: the set's /name (else the file's name without its extension, else empty), version, actions: [{name, steps: [{name: the step's /internalName, label: its /localizedName, or null when it has none or it is blank, on: false when /isOn is 0, params: how many /parameter blocks it has, line}]}], unread: [{line, text}] (tokens that aren't read, at most 1000), truncated: true when a cap stopped the reading (8 MiB, 16 open blocks, 1,000 actions, 10,000 steps in an action, 100,000 steps in the set; names past 1,024 bytes are cut), when the text ends inside a block or a value or after a field's name, when /actionCount, /eventCount or a step's /parameterCount differs from the actions, steps or recorded values read (a negative count, one too large for a number and one that isn't a number always differ), or when a hexadecimal name, label or recorded /value isn't as many bytes as its count says}. Give exactly one of path, data and dataBase64. Text that doesn't start with /version and a number is an error",
|
||||
"{path? | data?: the file's text | dataBase64?, name?: the file's name (default: the path's)} read an action set another app saved as text (.aia, starting \"/version\") without changing anything → {set: the set's /name (else the file's name without its extension, else empty), version, actions: [{name, steps: [{name: the step's /internalName, label: its /localizedName, or null when it has none or it is blank, on: false when /isOn is 0, params: how many /parameter blocks it has, values: [{key: the block's /key, or null, type: its /type, or null, value: its /value when it is a number, or text that is UTF-8 (else null), bytes?: the text's length in bytes}] (the first 100,000 recorded values in the set), line}]}], unread: [{line, text}] (tokens that aren't read, at most 1000), truncated: true when a cap stopped the reading (8 MiB, 16 open blocks, 1,000 actions, 10,000 steps in an action, 100,000 steps in the set; names past 1,024 bytes are cut), when the text ends inside a block or a value or after a field's name, when /actionCount, /eventCount or a step's /parameterCount differs from the actions, steps or recorded values read (a negative count, one too large for a number and one that isn't a number always differ), or when a hexadecimal name, label or recorded /value isn't as many bytes as its count says}. Give exactly one of path, data and dataBase64. Text that doesn't start with /version and a number is an error",
|
||||
always,
|
||||
read
|
||||
)]
|
||||
@@ -73,12 +76,33 @@ pub struct AiaStep {
|
||||
pub on: Option<i64>,
|
||||
/// How many `/parameter-N` blocks it has.
|
||||
pub params: usize,
|
||||
/// Its `/parameter-N` blocks, in order, while the set keeps at most [`MAX_VALUES`].
|
||||
pub values: Vec<AiaValue>,
|
||||
/// Its `/parameterCount`, if it has one.
|
||||
pub declared: Option<i64>,
|
||||
/// The line its block opens on (from 1).
|
||||
pub line: usize,
|
||||
}
|
||||
|
||||
/// A value a step was recorded with: a `/parameter-N` block.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AiaValue {
|
||||
/// Its `/key`, if it has one that fits an `i64`.
|
||||
pub key: Option<i64>,
|
||||
/// Its `/type`, read as UTF-8 with replacement characters, if it has one.
|
||||
pub kind: Option<String>,
|
||||
/// Its `/value`, if it is a number that fits an `i64` or text.
|
||||
pub value: Option<AiaData>,
|
||||
}
|
||||
|
||||
/// A recorded `/value` that is kept.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum AiaData {
|
||||
Int(i64),
|
||||
/// The bytes of text in parentheses or of hexadecimal text.
|
||||
Text(Vec<u8>),
|
||||
}
|
||||
|
||||
/// An action: an `/action-N` block.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AiaAction {
|
||||
@@ -106,6 +130,8 @@ pub struct AiaSet {
|
||||
pub truncated: bool,
|
||||
/// How many steps were read in all the actions.
|
||||
steps: usize,
|
||||
/// How many recorded values were kept in all the steps.
|
||||
values: usize,
|
||||
}
|
||||
|
||||
/// A token of the text.
|
||||
@@ -252,7 +278,8 @@ fn hex_bytes(digits: &[u8]) -> Option<Vec<u8>> {
|
||||
enum Kind {
|
||||
Action,
|
||||
Step,
|
||||
Param,
|
||||
/// A recorded value, and whether it is kept.
|
||||
Param(bool),
|
||||
/// A block that isn't read, or one past a cap.
|
||||
Other,
|
||||
}
|
||||
@@ -315,12 +342,18 @@ fn open_block(set: &mut AiaSet, stack: &[Kind], name: &[u8], line: usize) -> Kin
|
||||
}
|
||||
},
|
||||
Some(Kind::Step) if numbered(name, b"parameter-") => {
|
||||
let mut kept = false;
|
||||
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
|
||||
s.params += 1;
|
||||
if set.values < MAX_VALUES {
|
||||
s.values.push(AiaValue::default());
|
||||
set.values += 1;
|
||||
kept = true;
|
||||
}
|
||||
}
|
||||
Kind::Param
|
||||
Kind::Param(kept)
|
||||
}
|
||||
Some(Kind::Param | Kind::Other) => Kind::Other,
|
||||
Some(Kind::Param(_) | Kind::Other) => Kind::Other,
|
||||
_ => {
|
||||
unread(set, line, format!("/{} {{", String::from_utf8_lossy(name)));
|
||||
Kind::Other
|
||||
@@ -355,12 +388,23 @@ fn set_hex(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>, bytes: Op
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark `set` truncated when the hexadecimal `/value` on `line` isn't as many bytes as its count
|
||||
/// says.
|
||||
fn check_value(set: &mut AiaSet, bytes: Option<Vec<u8>>, line: usize) {
|
||||
if bytes.is_none() {
|
||||
/// Set the field `name` of the recorded value open on `line` to `token`: its `/key`, `/type` or
|
||||
/// `/value`, when the value is `kept`. A hexadecimal `/value` that isn't as many bytes as its count
|
||||
/// says marks `set` truncated, kept or not.
|
||||
fn set_param(set: &mut AiaSet, kept: bool, name: Option<&[u8]>, token: Token, line: usize) {
|
||||
if name == Some(b"value".as_slice()) && matches!(token, Token::Hex(None)) {
|
||||
set.truncated = true;
|
||||
unread(set, line, BAD_HEX);
|
||||
return;
|
||||
}
|
||||
let value = set.actions.last_mut().and_then(|a| a.steps.last_mut()).and_then(|s| s.values.last_mut());
|
||||
let Some(v) = value.filter(|_| kept) else { return };
|
||||
match (name, token) {
|
||||
(Some(b"key"), Token::Int(key)) => v.key = key,
|
||||
(Some(b"type"), Token::Text(t)) => v.kind = Some(String::from_utf8_lossy(&t).into_owned()),
|
||||
(Some(b"value"), Token::Int(Some(n))) => v.value = Some(AiaData::Int(n)),
|
||||
(Some(b"value"), Token::Text(t) | Token::Hex(Some(t))) => v.value = Some(AiaData::Text(t)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -448,13 +492,13 @@ pub fn read_aia(bytes: &[u8]) -> std::result::Result<AiaSet, String> {
|
||||
unread(&mut set, line, "}");
|
||||
}
|
||||
}
|
||||
Token::Hex(bytes) if matches!(stack.last(), Some(Kind::Param)) => {
|
||||
if field(&mut pending).as_deref() == Some(b"value".as_slice()) {
|
||||
check_value(&mut set, bytes, line);
|
||||
}
|
||||
_ if matches!(stack.last(), Some(Kind::Param(_))) => {
|
||||
let kept = matches!(stack.last(), Some(Kind::Param(true)));
|
||||
let name = field(&mut pending);
|
||||
set_param(&mut set, kept, name.as_deref(), token, line);
|
||||
}
|
||||
// The other values inside a recorded value, or a block that isn't read.
|
||||
_ if matches!(stack.last(), Some(Kind::Param | Kind::Other)) => {
|
||||
// The values inside a block that isn't read.
|
||||
_ if matches!(stack.last(), Some(Kind::Other)) => {
|
||||
pending = None;
|
||||
}
|
||||
Token::Hex(bytes) => {
|
||||
@@ -521,6 +565,21 @@ pub fn read_aia(bytes: &[u8]) -> std::result::Result<AiaSet, String> {
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
/// A recorded value in `actionSet.read`'s answer: `{key, type, value, bytes?}`, the value a number,
|
||||
/// text that is UTF-8 (else null) with its length in bytes, or null.
|
||||
fn value_json(v: &AiaValue) -> Value {
|
||||
let mut out = json!({ "key": v.key, "type": v.kind, "value": null });
|
||||
match &v.value {
|
||||
Some(AiaData::Int(n)) => out["value"] = json!(n),
|
||||
Some(AiaData::Text(t)) => {
|
||||
out["value"] = json!(std::str::from_utf8(t).ok());
|
||||
out["bytes"] = json!(t.len());
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn read(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "actionSet.read";
|
||||
let (path, data, b64) = (text_param(p, "path", C)?, text_param(p, "data", C)?, text_param(p, "dataBase64", C)?);
|
||||
@@ -544,7 +603,8 @@ fn read(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let label = s.label.clone().filter(|l| !l.trim().is_empty());
|
||||
json!({ "name": s.name, "label": label, "on": s.on != Some(0), "params": s.params, "line": s.line })
|
||||
let values: Vec<Value> = s.values.iter().map(value_json).collect();
|
||||
json!({ "name": s.name, "label": label, "on": s.on != Some(0), "params": s.params, "values": values, "line": s.line })
|
||||
})
|
||||
.collect();
|
||||
json!({ "name": a.name, "steps": steps })
|
||||
|
||||
@@ -8,6 +8,7 @@ mod contour;
|
||||
mod cutting;
|
||||
mod document;
|
||||
mod image;
|
||||
mod packaging;
|
||||
mod pathtools;
|
||||
mod pen;
|
||||
mod select;
|
||||
@@ -15,6 +16,7 @@ mod shapes;
|
||||
mod typetools;
|
||||
|
||||
pub(crate) use image::{DecodedImages, refresh_color_masks};
|
||||
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
use super::CommandSpec;
|
||||
|
||||
@@ -27,6 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(cutting::specs());
|
||||
v.extend(document::specs());
|
||||
v.extend(image::specs());
|
||||
v.extend(packaging::specs());
|
||||
v.extend(pathtools::specs());
|
||||
v.extend(pen::specs());
|
||||
v.extend(select::specs());
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
//! Packaging Tools (`addon.packaging.*`), a built-in add-on for the dielines of boxes and other
|
||||
//! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line
|
||||
//! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each
|
||||
//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Its submenu
|
||||
//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's.
|
||||
|
||||
mod roles;
|
||||
|
||||
pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
use super::super::CommandSpec;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
roles::specs()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,454 @@
|
||||
//! Fold line roles (`addon.packaging.setRole`, `addon.packaging.roles`,
|
||||
//! `addon.packaging.setRoleSwatch`). A path, compound path or live shape has a role when its top
|
||||
//! stroke is painted with the swatch the document's role table gives that role, at any tint. The
|
||||
//! table lives in [`Document::unknown`] under [`ROLES_KEY`], `{cut, crease, partialCut,
|
||||
//! perforation}` each naming a swatch; a role it leaves out, or names with something other than a
|
||||
//! string, takes its default swatch, named after the role.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::super::super::overprint::edit_counted;
|
||||
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// Document unknown key: the role table, `{role id: swatch name}`.
|
||||
pub(crate) const ROLES_KEY: &str = "packagingRoles";
|
||||
|
||||
const SET_ROLE: &str = "addon.packaging.setRole";
|
||||
const ROLES: &str = "addon.packaging.roles";
|
||||
const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch";
|
||||
|
||||
/// What a fold line does when the blank is cut and folded.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Role {
|
||||
/// Separates the material.
|
||||
Cut,
|
||||
/// A fold.
|
||||
Crease,
|
||||
/// A fold cut part way through the board.
|
||||
PartialCut,
|
||||
/// A fold along a line of cuts.
|
||||
Perforation,
|
||||
}
|
||||
|
||||
impl Role {
|
||||
pub(crate) const ALL: [Role; 4] = [Role::Cut, Role::Crease, Role::PartialCut, Role::Perforation];
|
||||
|
||||
/// The role's id in params and in the role table.
|
||||
pub(crate) fn id(self) -> &'static str {
|
||||
match self {
|
||||
Role::Cut => "cut",
|
||||
Role::Crease => "crease",
|
||||
Role::PartialCut => "partialCut",
|
||||
Role::Perforation => "perforation",
|
||||
}
|
||||
}
|
||||
|
||||
/// The role's name, which is also its default swatch's name.
|
||||
pub(crate) fn name(self) -> &'static str {
|
||||
match self {
|
||||
Role::Cut => "Cut",
|
||||
Role::Crease => "Crease",
|
||||
Role::PartialCut => "Partial Cut",
|
||||
Role::Perforation => "Perforation",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_id(id: &str) -> Option<Role> {
|
||||
Role::ALL.into_iter().find(|r| r.id() == id)
|
||||
}
|
||||
|
||||
/// The color a missing role swatch is made with (VectorCraft's own values): Cut 100% magenta,
|
||||
/// Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan.
|
||||
fn color(self) -> Color {
|
||||
match self {
|
||||
Role::Cut => Color::cmyk(0.0, 1.0, 0.0, 0.0),
|
||||
Role::Crease => Color::cmyk(1.0, 0.0, 0.0, 0.0),
|
||||
Role::PartialCut => Color::cmyk(0.0, 0.0, 1.0, 0.0),
|
||||
Role::Perforation => Color::cmyk(0.5, 0.5, 0.0, 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
fn index(self) -> usize {
|
||||
Role::ALL.iter().position(|r| *r == self).unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// The swatch each role is carried by, in [`Role::ALL`] order.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct RoleTable([String; 4]);
|
||||
|
||||
impl RoleTable {
|
||||
/// The document's role table, with each missing or damaged entry at its default. When a damaged
|
||||
/// table names one swatch for two roles, the later role takes its default name instead, or
|
||||
/// "Crease 2" and so on when an earlier role has that.
|
||||
pub(crate) fn of(d: &Document) -> RoleTable {
|
||||
let stored = d.unknown.get(ROLES_KEY).and_then(Value::as_object);
|
||||
let mut names: Vec<String> = Vec::with_capacity(Role::ALL.len());
|
||||
for r in Role::ALL {
|
||||
let name = match stored.and_then(|m| m.get(r.id())).and_then(Value::as_str) {
|
||||
Some(name) if !name.is_empty() && !names.iter().any(|n| n == name) => name.to_string(),
|
||||
_ => {
|
||||
let base = r.name();
|
||||
std::iter::once(base.to_string())
|
||||
.chain((2..).map(|i| format!("{base} {i}")))
|
||||
.find(|n| !names.contains(n))
|
||||
.unwrap_or_else(|| base.to_string())
|
||||
}
|
||||
};
|
||||
names.push(name);
|
||||
}
|
||||
RoleTable(Role::ALL.map(|r| names.get(r.index()).cloned().unwrap_or_else(|| r.name().to_string())))
|
||||
}
|
||||
|
||||
/// The swatch of `role`.
|
||||
pub(crate) fn swatch(&self, role: Role) -> &str {
|
||||
self.0.get(role.index()).map_or("", String::as_str)
|
||||
}
|
||||
|
||||
/// The role swatch `name` carries.
|
||||
pub(crate) fn role_of_swatch(&self, name: &str) -> Option<Role> {
|
||||
Role::ALL.into_iter().find(|r| self.swatch(*r) == name)
|
||||
}
|
||||
|
||||
/// The role of object `n`: the role of the swatch its top stroke is painted with.
|
||||
pub(crate) fn role_of(&self, n: &Node) -> Option<Role> {
|
||||
if !can_carry(n) {
|
||||
return None;
|
||||
}
|
||||
match &n.appearance.stroke()?.paint {
|
||||
Paint::Solid { swatch: Some(name), .. } => self.role_of_swatch(name),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_value(&self) -> Value {
|
||||
Value::Object(Role::ALL.into_iter().map(|r| (r.id().to_string(), json!(self.swatch(r)))).collect::<Map<_, _>>())
|
||||
}
|
||||
}
|
||||
|
||||
/// Swatch `from` of `d` is now named `to`, and `global` says whether it is still a global color.
|
||||
/// A role it carried keeps it under the new name, as the strokes linked to it do; when it stopped
|
||||
/// being global, which unlinks those strokes, the role moves to a new name that `setRole` makes a
|
||||
/// swatch for. Another role that named `to` without such a swatch moves to a new name too, so no
|
||||
/// two roles share a swatch.
|
||||
pub(crate) fn role_swatch_edited(d: &mut Document, from: &str, to: &str, global: bool) {
|
||||
let before = RoleTable::of(d);
|
||||
let mut table = before.clone();
|
||||
for r in Role::ALL {
|
||||
let name = table.swatch(r).to_string();
|
||||
let moved = if name == from && global {
|
||||
Some(to.to_string())
|
||||
} else if name == from || (name == to && from != to) {
|
||||
Some(free_role_name(d, &table, r))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let (Some(new), Some(slot)) = (moved, table.0.get_mut(r.index())) {
|
||||
*slot = new;
|
||||
}
|
||||
}
|
||||
if table != before {
|
||||
d.unknown.insert(ROLES_KEY.to_string(), table.to_value());
|
||||
}
|
||||
}
|
||||
|
||||
/// Swatches `merged` of `d` were merged into swatch `kept`, and `linked` says whether their strokes
|
||||
/// now link to it (it is a global color). When `kept` carries no role, it takes the role of the
|
||||
/// first merged swatch that carried one, so the lines of that role keep it; a merged swatch's other
|
||||
/// role keeps its name, which the next `setRole` makes a swatch for.
|
||||
pub(crate) fn role_swatches_merged(d: &mut Document, merged: &[String], kept: &str, linked: bool) {
|
||||
let mut table = RoleTable::of(d);
|
||||
if !linked || table.role_of_swatch(kept).is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(role) = merged.iter().find_map(|m| table.role_of_swatch(m)) else { return };
|
||||
if let Some(slot) = table.0.get_mut(role.index()) {
|
||||
*slot = kept.to_string();
|
||||
}
|
||||
d.unknown.insert(ROLES_KEY.to_string(), table.to_value());
|
||||
}
|
||||
|
||||
/// A name for `role`'s swatch that no swatch, color group or other role of `table` uses: the
|
||||
/// role's name, else "Cut 2", "Cut 3"… The document holds finitely many names, so the search
|
||||
/// always ends at a free one.
|
||||
fn free_role_name(d: &Document, table: &RoleTable, role: Role) -> String {
|
||||
let free = |n: &str| !d.swatch_name_taken(n) && Role::ALL.into_iter().all(|r| r == role || table.swatch(r) != n);
|
||||
let base = role.name();
|
||||
if free(base) {
|
||||
return base.to_string();
|
||||
}
|
||||
(2usize..).map(|i| format!("{base} {i}")).find(|n| free(n)).unwrap_or_else(|| base.to_string())
|
||||
}
|
||||
|
||||
/// Whether `n` can carry a role: a path (a live shape too) that is neither a clipping path nor a
|
||||
/// guide, or a compound path.
|
||||
fn can_carry(n: &Node) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Path { clipping, guide, .. } => !clipping && !guide,
|
||||
NodeKind::Compound { .. } => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects under the outermost objects `roots` that can carry a role, through groups and clip
|
||||
/// groups, each once, and
|
||||
/// how many of `roots` and their members can't (text, images, symbol instances and other objects).
|
||||
/// With `editable`, objects that are locked or hidden, are in a locked or hidden group or layer, or
|
||||
/// are on a locked artboard are left out and counted as skipped.
|
||||
fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec<NodeId>, usize) {
|
||||
fn walk(n: &Node, out: &mut Vec<NodeId>, skipped: &mut usize) {
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } => {
|
||||
for c in children {
|
||||
// A group's clipping path draws no stroke: it is skipped.
|
||||
if matches!(c.kind, NodeKind::Path { clipping: true, .. }) {
|
||||
*skipped += 1;
|
||||
} else {
|
||||
walk(c, out, skipped);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ if can_carry(n) => out.push(n.id),
|
||||
_ => *skipped += 1,
|
||||
}
|
||||
}
|
||||
let (mut out, mut skipped) = (vec![], 0);
|
||||
// A path of a compound path is painted with the compound's appearance: the compound takes the
|
||||
// role. `roots` come from `checked_ids_or_selection`, which keeps only outermost objects, so a
|
||||
// group and its member are never both roots.
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let compound_of = |id: NodeId| d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
|
||||
for n in roots.iter().map(|id| compound_of(*id).unwrap_or(*id)).filter(|id| seen.insert(*id)).filter_map(|id| d.node(id)) {
|
||||
walk(n, &mut out, &mut skipped);
|
||||
}
|
||||
if editable {
|
||||
// Named directly or not, a locked or hidden object, or one in a locked or hidden group or
|
||||
// layer or on a locked artboard, stays as it is.
|
||||
let ok = d.editable();
|
||||
let before = out.len();
|
||||
out.retain(|id| ok(*id));
|
||||
skipped += before - out.len();
|
||||
}
|
||||
(out, skipped)
|
||||
}
|
||||
|
||||
/// Every object of the document that can carry a role, through layers and groups.
|
||||
fn document_targets(d: &Document) -> Vec<NodeId> {
|
||||
fn walk(n: &Node, out: &mut Vec<NodeId>) {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)),
|
||||
_ if can_carry(n) => out.push(n.id),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
d.layers.iter().for_each(|l| walk(l, &mut out));
|
||||
out
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"addon.packaging.setRole",
|
||||
"Make Fold Line",
|
||||
["Object", "Plug-ins", "Packaging Tools"],
|
||||
None,
|
||||
"{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}",
|
||||
has_selection,
|
||||
set_role
|
||||
),
|
||||
cmd!(
|
||||
query "addon.packaging.roles",
|
||||
"Fold Lines",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out",
|
||||
has_doc,
|
||||
roles
|
||||
),
|
||||
cmd!(
|
||||
"addon.packaging.setRoleSwatch",
|
||||
"Role Swatches…",
|
||||
["Object", "Plug-ins", "Packaging Tools"],
|
||||
None,
|
||||
"{role: cut|crease|partialCut|perforation, swatch: a global or spot color swatch's name} make the swatch carry the role, in the document's role table, as one undo step (none when it already does). Objects stroked with the role's old swatch keep their color and no longer have the role. Refused: a missing swatch, a gradient or pattern swatch, a process color that is not global, a tint swatch, [None], [Registration], and a swatch another role has → {role, swatch, changed}",
|
||||
has_doc,
|
||||
set_role_swatch
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The role `p` gives: `Some(None)` for `none` when `none` is allowed.
|
||||
fn role_param(p: &Value, cmd: &str, none: bool) -> Result<Option<Role>> {
|
||||
let id = text_param(p, "role", cmd)?.ok_or_else(|| bad(cmd, "missing `role`"))?;
|
||||
match Role::from_id(id) {
|
||||
Some(r) => Ok(Some(r)),
|
||||
None if none && id == "none" => Ok(None),
|
||||
None if none => Err(bad(cmd, format!("unknown role `{id}`: cut, crease, partialCut, perforation or none"))),
|
||||
None => Err(bad(cmd, format!("unknown role `{id}`: cut, crease, partialCut or perforation"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Why swatch `name` of `d` can't carry a role, if it can't.
|
||||
fn unfit_swatch(d: &Document, name: &str) -> Option<String> {
|
||||
if name == REGISTRATION || name == "[None]" {
|
||||
return Some(format!("`{name}` can't carry a role"));
|
||||
}
|
||||
let Some(sw) = d.swatch(name) else { return Some(format!("no swatch `{name}`")) };
|
||||
match &sw.paint {
|
||||
Paint::Solid { swatch: Some(_), .. } => Some(format!("`{name}` is a tint swatch: pick its base or another global or spot color")),
|
||||
Paint::Solid { .. } if sw.global => None,
|
||||
Paint::Solid { .. } => Some(format!("`{name}` is a process color: pick a global or spot color")),
|
||||
_ => Some(format!("`{name}` isn't a color swatch")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `role`'s swatch in `d`, made as a global spot swatch in the document's color mode when `d`
|
||||
/// lacks it → its paint at 100%. When a color group or a swatch that can't carry a role (a process
|
||||
/// color that is not global, a tint, a gradient) has the swatch's name, the swatch is made under a
|
||||
/// free name, which the role table then gives the role.
|
||||
fn role_paint(d: &mut Document, role: Role) -> Result<Paint> {
|
||||
let mut table = RoleTable::of(d);
|
||||
let current = table.swatch(role);
|
||||
let taken = match d.swatch(current) {
|
||||
Some(_) => unfit_swatch(d, current).is_some(),
|
||||
None => d.swatch_name_taken(current),
|
||||
};
|
||||
if taken {
|
||||
let free = free_role_name(d, &table, role);
|
||||
if let Some(slot) = table.0.get_mut(role.index()) {
|
||||
*slot = free;
|
||||
}
|
||||
d.unknown.insert(ROLES_KEY.to_string(), table.to_value());
|
||||
}
|
||||
let name = table.swatch(role);
|
||||
if d.swatch(name).is_none() {
|
||||
let model = d.color_mode.model();
|
||||
let color = role.color();
|
||||
let color = if color.model() == model {
|
||||
color
|
||||
} else {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
cms.convert(&color, model, cms.settings().intent)
|
||||
};
|
||||
d.swatches.push(Swatch { name: name.to_string(), paint: Paint::solid(color), global: true, spot: true });
|
||||
}
|
||||
if let Some(why) = unfit_swatch(d, name) {
|
||||
return Err(bad(SET_ROLE, format!("{why} (the {} role's swatch; addon.packaging.setRoleSwatch picks another)", role.name())));
|
||||
}
|
||||
d.tint_paint(name, 1.0).ok_or_else(|| bad(SET_ROLE, format!("`{name}` isn't a global or spot color")))
|
||||
}
|
||||
|
||||
/// Gives object `id` of `d` `role`'s `paint` (`None`: takes its role away) → whether it changed.
|
||||
fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Paint>, overprint: bool) -> bool {
|
||||
let Some(n) = d.node_mut(id) else { return false };
|
||||
let had = table.role_of(n);
|
||||
let mut a = (*n.appearance).clone();
|
||||
match paint {
|
||||
Some(paint) => {
|
||||
a.set_stroke(paint.clone());
|
||||
if let Some(st) = a.stroke_mut() {
|
||||
if st.width <= 0.0 {
|
||||
st.width = 1.0;
|
||||
}
|
||||
// A hidden stroke would carry the role without drawing or printing the line.
|
||||
st.visible = true;
|
||||
st.overprint = overprint;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if had.is_none() {
|
||||
return false;
|
||||
}
|
||||
if let Some(st) = a.stroke_mut() {
|
||||
if let Paint::Solid { color, .. } = st.paint {
|
||||
st.paint = Paint::solid(color);
|
||||
}
|
||||
st.overprint = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if a == *n.appearance {
|
||||
return false;
|
||||
}
|
||||
n.appearance = vectorcraft_doc::Shared::new(a);
|
||||
true
|
||||
}
|
||||
|
||||
fn set_role(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let role = role_param(p, SET_ROLE, true)?;
|
||||
let overprint = switch_or(p, "overprint", true, SET_ROLE)?;
|
||||
let roots = checked_ids_or_selection(s, p, SET_ROLE)?;
|
||||
let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true);
|
||||
if ids.is_empty() {
|
||||
return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role"));
|
||||
}
|
||||
let label = role.map_or("Remove Fold Line Role", |_| "Make Fold Line");
|
||||
let mut changed = 0;
|
||||
edit_counted(s, label, |d| {
|
||||
let before = (d.swatches.len(), d.unknown.get(ROLES_KEY).cloned());
|
||||
let paint = role.map(|r| role_paint(d, r)).transpose()?;
|
||||
// A role swatch made again (its strokes may still name it) is a change of its own.
|
||||
let made = (d.swatches.len(), d.unknown.get(ROLES_KEY).cloned()) != before;
|
||||
let table = RoleTable::of(d);
|
||||
changed = ids.iter().filter(|id| give_role(d, &table, **id, paint.as_ref(), overprint)).count();
|
||||
Ok(changed + usize::from(made))
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "changed": changed, "skipped": skipped }))
|
||||
}
|
||||
|
||||
fn roles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let given = p.get("ids").is_some_and(|v| !v.is_null());
|
||||
let roots = checked_ids_or_selection(s, p, ROLES)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let (scope, ids) = match (given, roots.is_empty()) {
|
||||
(true, _) => ("ids", role_targets(d, &roots, false).0),
|
||||
(false, false) => ("selection", role_targets(d, &roots, false).0),
|
||||
(false, true) => ("document", document_targets(d)),
|
||||
};
|
||||
let table = RoleTable::of(d);
|
||||
let mut counts = [0usize; 4];
|
||||
for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) {
|
||||
if let Some(c) = counts.get_mut(r.index()) {
|
||||
*c += 1;
|
||||
}
|
||||
}
|
||||
let rows: Vec<Value> = Role::ALL
|
||||
.into_iter()
|
||||
.zip(counts)
|
||||
.map(|(r, count)| {
|
||||
let swatch = table.swatch(r);
|
||||
json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count })
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() }))
|
||||
}
|
||||
|
||||
fn set_role_swatch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let Some(role) = role_param(p, SET_ROLE_SWATCH, false)? else { return Err(bad(SET_ROLE_SWATCH, "missing `role`")) };
|
||||
let name = text_param(p, "swatch", SET_ROLE_SWATCH)?.ok_or_else(|| bad(SET_ROLE_SWATCH, "missing `swatch`"))?;
|
||||
let d = &s.doc()?.doc;
|
||||
if let Some(why) = unfit_swatch(d, name) {
|
||||
return Err(bad(SET_ROLE_SWATCH, why));
|
||||
}
|
||||
let mut table = RoleTable::of(d);
|
||||
if let Some(other) = Role::ALL.into_iter().find(|r| *r != role && table.swatch(*r) == name) {
|
||||
return Err(bad(SET_ROLE_SWATCH, format!("`{name}` already carries the {} role", other.name())));
|
||||
}
|
||||
if let Some(slot) = table.0.get_mut(role.index()) {
|
||||
*slot = name.to_string();
|
||||
}
|
||||
let value = table.to_value();
|
||||
let changed = RoleTable::of(d) != table;
|
||||
if changed {
|
||||
s.edit("Role Swatches", |d, _| {
|
||||
d.unknown.insert(ROLES_KEY.to_string(), value);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "role": role.id(), "swatch": name, "changed": changed }))
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
//! Tests for Packaging Tools: fold line roles, their swatches and the role table.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, Node, NodeKind};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn session(mode: &str) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400, "colorMode": mode})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64) -> NodeId {
|
||||
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 40, "height": 40})).unwrap())
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).cloned().unwrap()
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn set_role(s: &mut Session, p: Value) -> Value {
|
||||
s.execute("addon.packaging.setRole", &p).unwrap()
|
||||
}
|
||||
|
||||
fn err(s: &mut Session, cmd: &str, p: Value) -> String {
|
||||
s.execute(cmd, &p).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
fn b64(v: &Value) -> Vec<u8> {
|
||||
vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap()
|
||||
}
|
||||
|
||||
/// The `roles` query's counts, in role order.
|
||||
fn counts(s: &mut Session, p: Value) -> Vec<u64> {
|
||||
let r = s.execute("addon.packaging.roles", &p).unwrap();
|
||||
r["roles"].as_array().unwrap().iter().map(|r| r["count"].as_u64().unwrap()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_role_makes_the_spot_swatch_and_links_the_top_stroke() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_none());
|
||||
let before = steps(&s);
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)));
|
||||
assert_eq!(steps(&s), before + 1, "one undo step");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let sw = d.swatch("Cut").unwrap();
|
||||
assert!(sw.global && sw.spot, "{sw:?}");
|
||||
assert_eq!(sw.paint, Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), "100% magenta in a CMYK document");
|
||||
let st = node(&s, a).appearance.stroke().cloned().unwrap();
|
||||
assert!(matches!(&st.paint, Paint::Solid { swatch: Some(n), tint, .. } if n == "Cut" && *tint == 1.0), "{:?}", st.paint);
|
||||
assert!(st.overprint, "role strokes overprint by default");
|
||||
// Again: nothing changes, and no undo step is recorded.
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert_eq!(r["changed"].as_u64(), Some(0));
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
// Undo takes the swatch away with the role.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_role_gets_its_own_swatch_color_in_the_document_s_mode() {
|
||||
let mut s = session("rgb");
|
||||
for (i, role) in ["cut", "crease", "partialCut", "perforation"].into_iter().enumerate() {
|
||||
let id = rect(&mut s, 20.0 + 60.0 * i as f64);
|
||||
set_role(&mut s, json!({"role": role, "ids": [id.0]}));
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let colors: Vec<Color> = ["Cut", "Crease", "Partial Cut", "Perforation"].iter().map(|n| d.swatch(n).unwrap().paint.color().unwrap()).collect();
|
||||
assert!(colors.iter().all(|c| matches!(c, Color::Rgb { .. })), "an RGB document's swatches are RGB: {colors:?}");
|
||||
assert_eq!(colors.iter().map(|c| c.to_hex()).collect::<BTreeSet<_>>().len(), 4, "four colors: {colors:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_without_a_stroke_gets_one_and_overprint_can_be_left_off() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.edit("strip", |d, _| {
|
||||
let n = d.node_mut(a).unwrap();
|
||||
n.appearance.items.retain(AppearanceItem::is_fill);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(node(&s, a).appearance.stroke().is_none());
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [a.0], "overprint": false}));
|
||||
let st = node(&s, a).appearance.stroke().cloned().unwrap();
|
||||
assert_eq!(st.width, 1.0, "a 1 pt stroke");
|
||||
assert!(!st.overprint);
|
||||
assert!(matches!(&st.paint, Paint::Solid { swatch: Some(n), .. } if n == "Crease"));
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0], "overprint": "yes"})).contains("overprint"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn none_takes_the_role_away_and_keeps_the_color() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "perforation", "ids": [a.0]}));
|
||||
let shown = node(&s, a).appearance.stroke().unwrap().paint.color().unwrap();
|
||||
let before = steps(&s);
|
||||
let r = set_role(&mut s, json!({"role": "none", "ids": [a.0, b.0]}));
|
||||
assert_eq!(r["changed"].as_u64(), Some(1), "the plain rectangle has no role to take away");
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
let st = node(&s, a).appearance.stroke().cloned().unwrap();
|
||||
assert_eq!(st.paint, Paint::solid(shown));
|
||||
assert!(!st.overprint);
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [0, 0, 0, 0]);
|
||||
// Nothing left with a role: no undo step.
|
||||
set_role(&mut s, json!({"role": "none", "ids": [a.0, b.0]}));
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_roles_and_targets_are_refused() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "fold", "ids": [a.0]})).contains("unknown role"));
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"ids": [a.0]})).contains("role"));
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": 3, "ids": [a.0]})).contains("role"));
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("addon.packaging.setRole", &json!({"role": "cut"})).is_err(), "nothing selected");
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Lid", "size": 20})).unwrap());
|
||||
let before = steps(&s);
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [t.0]})).contains("select a path"));
|
||||
assert_eq!(steps(&s), before);
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_none(), "a refused run makes no swatch");
|
||||
// Text beside a path is skipped and counted.
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, t.0]}));
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_are_walked_and_their_locked_and_hidden_members_left_out() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b, c) = (rect(&mut s, 20.0), rect(&mut s, 100.0), rect(&mut s, 180.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap();
|
||||
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
s.edit("lock", |d, _| {
|
||||
d.node_mut(b).unwrap().locked = true;
|
||||
d.node_mut(c).unwrap().visible = false;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = set_role(&mut s, json!({"role": "crease", "ids": [g.0]}));
|
||||
assert_eq!(r["ids"], json!([a.0]));
|
||||
assert_eq!(r["skipped"].as_u64(), Some(2), "the locked and the hidden member");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [g.0]})), [0, 1, 0, 0]);
|
||||
// Named directly, a locked or hidden path is left out too.
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, b.0, c.0]}));
|
||||
assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([a.0]), Some(2)));
|
||||
let before = steps(&s);
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [b.0]})).contains("locked"));
|
||||
assert_eq!(steps(&s), before);
|
||||
assert_eq!(counts(&mut s, json!({"ids": [b.0, c.0]})), [0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_group_s_clipping_path_is_skipped_and_counted() {
|
||||
let mut s = session("cmyk");
|
||||
let (art, mask) = (rect(&mut s, 20.0), rect(&mut s, 30.0));
|
||||
s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap();
|
||||
let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [g.0]}));
|
||||
assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([art.0]), Some(1)), "the clipping path is left out and counted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_and_its_member_count_once_and_locked_lines_count_in_every_scope() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [b.0]}));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
let r = set_role(&mut s, json!({"role": "crease", "ids": [g.0, a.0]}));
|
||||
assert_eq!(r["ids"], json!([a.0, b.0]), "each path once");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [g.0, a.0]})), [0, 2, 0, 0]);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [b.0]}));
|
||||
s.edit("lock", |d, _| {
|
||||
d.node_mut(b).unwrap().locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// A locked line keeps its role and is counted, whether its group is selected or not.
|
||||
assert_eq!(counts(&mut s, json!({"ids": [g.0]})), [1, 1, 0, 0]);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(counts(&mut s, json!({})), [1, 1, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_process_swatch_named_like_a_role_swatch_keeps_its_name() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.execute("swatch.new", &json!({"name": "Cut", "color": "#ff0000"})).unwrap();
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 2"));
|
||||
assert!(d.swatch("Cut 2").is_some_and(|w| w.spot), "the role swatch is made beside it");
|
||||
assert!(d.swatch("Cut").is_some_and(|w| !w.global), "the process swatch is left as it was");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_free_role_swatch_name_is_searched_past_ten_thousand() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
let taken = std::iter::once("Cut".to_string()).chain((2..10_000).map(|i| format!("Cut {i}"))).chain(["Cut 10004".to_string()]);
|
||||
let process = |name: String| vectorcraft_color::Swatch { name, paint: Paint::solid(Color::rgb(1.0, 0.0, 0.0)), global: false, spot: false };
|
||||
Arc::make_mut(&mut s.doc_mut().unwrap().doc).swatches.extend(taken.map(process));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 10000"));
|
||||
assert!(d.swatch("Cut 10000").is_some_and(|w| w.spot), "the role swatch is made under the first free name");
|
||||
assert!(d.swatch("Cut 10004").is_some_and(|w| !w.global), "a taken name is left as it was");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_merged_role_swatch_hands_its_role_to_the_kept_swatch() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [b.0]}));
|
||||
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("swatch.merge", &json!({"names": ["Die", "Cut"]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die"));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0], "the cut line is still a cut line");
|
||||
// A kept swatch that already carries a role keeps it; the merged role's lines take it.
|
||||
s.execute("swatch.merge", &json!({"names": ["Crease", "Die"]})).unwrap();
|
||||
let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap();
|
||||
assert_eq!((&table["cut"], &table["crease"]), (&json!("Die"), &json!("Crease")), "{table}");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [0, 2, 0, 0]);
|
||||
// The next Make Cut Line makes the Cut role's swatch again.
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert!(s.doc().unwrap().doc.swatch("Die").is_some_and(|w| w.spot));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [1, 1, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_global_process_swatch_can_carry_a_role() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "global": true})).unwrap();
|
||||
s.execute("addon.packaging.setRoleSwatch", &json!({"role": "partialCut", "swatch": "Die"})).unwrap();
|
||||
set_role(&mut s, json!({"role": "partialCut", "ids": [a.0]}));
|
||||
assert!(matches!(&node(&s, a).appearance.stroke().unwrap().paint, Paint::Solid { swatch: Some(n), .. } if n == "Die"));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 1, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roles_counts_the_selection_or_the_whole_document() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b, c) = (rect(&mut s, 20.0), rect(&mut s, 100.0), rect(&mut s, 180.0));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0, b.0]}));
|
||||
set_role(&mut s, json!({"role": "partialCut", "ids": [c.0]}));
|
||||
s.execute("select.set", &json!({"ids": [a.0, c.0]})).unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
assert_eq!((r["scope"].as_str(), r["selected"].as_u64()), (Some("selection"), Some(2)));
|
||||
assert_eq!(counts(&mut s, json!({})), [1, 0, 1, 0]);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
assert_eq!((r["scope"].as_str(), r["selected"].as_u64()), (Some("document"), Some(0)));
|
||||
assert_eq!(counts(&mut s, json!({})), [2, 0, 1, 0]);
|
||||
let rows = r["roles"].as_array().unwrap();
|
||||
assert_eq!(rows[0], json!({"role": "cut", "name": "Cut", "swatch": "Cut", "exists": true, "count": 2}));
|
||||
assert_eq!(rows[1]["exists"], json!(false), "no Crease swatch yet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_swatches_maps_a_role_to_another_swatch() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap();
|
||||
let before = steps(&s);
|
||||
let r = s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap();
|
||||
assert_eq!(r["changed"], json!(true));
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die"));
|
||||
// The old swatch's objects keep their color and lose the role.
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 0, 0]);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert!(matches!(&node(&s, a).appearance.stroke().unwrap().paint, Paint::Solid { swatch: Some(n), .. } if n == "Die"));
|
||||
// The same mapping again changes nothing.
|
||||
let steps_now = steps(&s);
|
||||
let r = s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap();
|
||||
assert_eq!((r["changed"].clone(), steps(&s)), (json!(false), steps_now));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_renamed_role_swatch_keeps_its_role() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [a.0]}));
|
||||
s.execute("swatch.edit", &json!({"name": "Crease", "newName": "Score"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["crease"], json!("Score"));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 1, 0, 0]);
|
||||
// A swatch that carries no role leaves the table alone.
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("swatch.edit", &json!({"name": "Ink", "newName": "Red Ink"})).unwrap();
|
||||
let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap();
|
||||
assert_eq!(table, json!({"cut": "Cut", "crease": "Score", "partialCut": "Partial Cut", "perforation": "Perforation"}));
|
||||
// Undo puts the old name back in the table with the swatch.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.unknown.get("packagingRoles").is_none());
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 1, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_role_swatch_renamed_to_another_role_s_name_leaves_each_role_its_own_swatch() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
// No Crease swatch exists yet, so the name is free for the Cut swatch.
|
||||
s.execute("swatch.edit", &json!({"name": "Cut", "newName": "Crease"})).unwrap();
|
||||
let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap();
|
||||
assert_eq!((&table["cut"], &table["crease"]), (&json!("Crease"), &json!("Crease 2")), "{table}");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0], "the line is still a cut line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_role_swatch_that_stops_being_global_hands_its_role_to_a_new_swatch() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "perforation", "ids": [a.0]}));
|
||||
s.execute("swatch.edit", &json!({"name": "Perforation", "spot": false, "global": false})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["perforation"], json!("Perforation 2"));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 0, 0], "the unlinked stroke has no role");
|
||||
set_role(&mut s, json!({"role": "perforation", "ids": [b.0]}));
|
||||
assert!(s.doc().unwrap().doc.swatch("Perforation 2").is_some_and(|w| w.spot));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [b.0]})), [0, 0, 0, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_group_named_like_a_role_swatch_keeps_its_name() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.execute("swatch.newGroup", &json!({"name": "Cut", "colors": ["#ff0000"]})).unwrap();
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 2"));
|
||||
assert!(d.swatch("Cut 2").is_some_and(|w| w.spot) && d.swatch("Cut").is_none());
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_role_makes_a_deleted_role_swatch_again_for_strokes_that_still_name_it() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
s.execute("swatch.delete", &json!({"name": "Cut", "unlink": false})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_none());
|
||||
let before = steps(&s);
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert_eq!(r["changed"].as_u64(), Some(0), "the stroke already names the swatch");
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_some_and(|w| w.spot), "the swatch is back");
|
||||
assert_eq!(steps(&s), before + 1, "as one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_stroke_is_shown_when_it_takes_a_role() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.edit("hide", |d, _| {
|
||||
if let Some(AppearanceItem::Stroke(st)) = d.node_mut(a).unwrap().appearance.items.iter_mut().find(|i| !i.is_fill()) {
|
||||
st.visible = false;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert!(node(&s, a).appearance.stroke().unwrap().visible);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_swatches_refuses_swatches_that_cannot_carry_a_role() {
|
||||
let mut s = session("cmyk");
|
||||
let ramp = json!({"type": "linear", "stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"}]});
|
||||
s.execute("swatch.new", &json!({"name": "Ramp", "gradient": ramp})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Plain", "color": "#336699"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink Tint", "swatch": "Ink", "tint": 0.5})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Crease", "color": {"model": "cmyk", "c": 1, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
|
||||
let before = steps(&s);
|
||||
for (swatch, says) in [
|
||||
("Nope", "no swatch"),
|
||||
("Ramp", "isn't a color swatch"),
|
||||
("Plain", "process color"),
|
||||
("Ink Tint", "tint swatch"),
|
||||
("[None]", "can't carry a role"),
|
||||
("[Registration]", "can't carry a role"),
|
||||
("Crease", "already carries the Crease role"),
|
||||
] {
|
||||
let e = err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": swatch}));
|
||||
assert!(e.contains(says), "{swatch}: {e}");
|
||||
}
|
||||
assert!(err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "none", "swatch": "Ink"})).contains("unknown role"));
|
||||
assert!(err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "cut"})).contains("swatch"));
|
||||
assert_eq!(steps(&s), before, "no refusal records an undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_role_table_reads_as_the_defaults() {
|
||||
let mut s = session("cmyk");
|
||||
s.edit("damage", |d, _| {
|
||||
d.unknown.insert("packagingRoles".into(), json!({"cut": 5, "crease": "", "partialCut": null, "extra": "x"}));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
let swatches: Vec<&str> = r["roles"].as_array().unwrap().iter().map(|r| r["swatch"].as_str().unwrap()).collect();
|
||||
assert_eq!(swatches, ["Cut", "Crease", "Partial Cut", "Perforation"]);
|
||||
s.edit("not an object", |d, _| {
|
||||
d.unknown.insert("packagingRoles".into(), json!("Cut"));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]);
|
||||
// One swatch named for two roles: the later role takes its own default.
|
||||
s.edit("duplicate", |d, _| {
|
||||
d.unknown.insert("packagingRoles".into(), json!({"cut": "Crease", "crease": "Crease", "partialCut": "Cut"}));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
let swatches: Vec<&str> = r["roles"].as_array().unwrap().iter().map(|r| r["swatch"].as_str().unwrap()).collect();
|
||||
assert_eq!(swatches, ["Crease", "Crease 2", "Cut", "Perforation"]);
|
||||
let b = rect(&mut s, 100.0);
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [b.0]}));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [b.0]})), [0, 1, 0, 0], "the crease line is a crease line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_save_and_open_keep_the_role_table_and_the_roles() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap();
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap();
|
||||
s.execute("document.open", &json!({"name": "box.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die"));
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(counts(&mut s, json!({})), [1, 0, 0, 0]);
|
||||
}
|
||||
|
||||
/// A document with one rectangle of each of Cut and Crease.
|
||||
fn two_roles() -> Session {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [b.0]}));
|
||||
s
|
||||
}
|
||||
|
||||
fn export(s: &mut Session, format: &str) -> String {
|
||||
String::from_utf8_lossy(&b64(&s.execute("document.export", &json!({"format": format})).unwrap())).into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_prints_each_role_on_its_swatch_s_separation_and_overprints_it() {
|
||||
let mut s = two_roles();
|
||||
let c = rect(&mut s, 180.0);
|
||||
set_role(&mut s, json!({"role": "partialCut", "ids": [c.0]}));
|
||||
let bytes = vectorcraft_pdf::export(
|
||||
&s.doc().unwrap().doc,
|
||||
&vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() },
|
||||
)
|
||||
.unwrap();
|
||||
let pdf = String::from_utf8_lossy(&bytes);
|
||||
assert!(pdf.contains("/Separation/Cut"), "the Cut line prints on the Cut plate");
|
||||
assert!(pdf.contains("/Separation/Crease"));
|
||||
assert!(pdf.contains("/Separation/Partial#20Cut"), "a name with a space");
|
||||
assert!(pdf.contains("/OP true"), "the role strokes overprint");
|
||||
// Without overprint, nothing in the file overprints.
|
||||
let mut plain = session("cmyk");
|
||||
let (a, b) = (rect(&mut plain, 20.0), rect(&mut plain, 100.0));
|
||||
set_role(&mut plain, json!({"role": "cut", "ids": [a.0], "overprint": false}));
|
||||
set_role(&mut plain, json!({"role": "crease", "ids": [b.0], "overprint": false}));
|
||||
let bytes = vectorcraft_pdf::export(
|
||||
&plain.doc().unwrap().doc,
|
||||
&vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() },
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!String::from_utf8_lossy(&bytes).contains("/OP true"));
|
||||
assert!(!export(&mut s, "pdf").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_dxf_and_hpgl_keep_the_default_role_swatches_apart() {
|
||||
let mut s = two_roles();
|
||||
let svg = export(&mut s, "svg");
|
||||
let strokes: BTreeSet<&str> = svg.split("stroke=\"").skip(1).filter_map(|t| t.split('"').next()).filter(|c| c.starts_with('#')).collect();
|
||||
let strokes = if strokes.is_empty() {
|
||||
svg.split("stroke:").skip(1).filter_map(|t| t.split([';', '"', '}']).next()).filter(|c| c.starts_with('#')).collect()
|
||||
} else {
|
||||
strokes
|
||||
};
|
||||
assert_eq!(strokes.len(), 2, "two stroke colors: {svg}");
|
||||
let dxf = export(&mut s, "dxf");
|
||||
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
|
||||
// The rectangles' white fills come out as true colors too.
|
||||
let colors: BTreeSet<&str> = lines.windows(2).filter(|w| w[0] == "420" && w[1] != "16777215").map(|w| w[1]).collect();
|
||||
assert_eq!(colors.len(), 2, "two stroke true colors: {colors:?}");
|
||||
let plot = s.execute("document.export", &json!({"format": "hpgl", "hpglVersion": "hpgl2"})).unwrap();
|
||||
let plot = String::from_utf8_lossy(&b64(&plot)).into_owned();
|
||||
assert!(plot.contains("SP1") && plot.contains("SP2"), "a pen per role swatch color: {plot}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compound_paths_carry_a_role() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 30.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
|
||||
assert!(matches!(node(&s, c).kind, NodeKind::Compound { .. }));
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [c.0]}));
|
||||
assert_eq!(r["ids"], json!([c.0]));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [1, 0, 0, 0]);
|
||||
// A member named by id gives its compound the role.
|
||||
let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]}));
|
||||
assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1)));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]);
|
||||
}
|
||||
@@ -1225,7 +1225,7 @@ fn expand_dashes_keeps_the_fill_below_and_follows_aligned_corners() {
|
||||
let mut centred = 0;
|
||||
for id in ids(&r) {
|
||||
let sp = path(&s, id).subpaths[0].clone();
|
||||
if let [a, b, c] = sp.anchors.as_slice()
|
||||
if let [a, b, c] = &*sp.anchors.to_vec()
|
||||
&& corners.iter().any(|k| b.p.distance(*k) < 1e-6)
|
||||
{
|
||||
assert!((a.p.distance(b.p) - 5.0).abs() < 1e-6 && (c.p.distance(b.p) - 5.0).abs() < 1e-6, "{sp:?}");
|
||||
|
||||
@@ -14,8 +14,9 @@ use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use super::super::links::{Status, statuses};
|
||||
use super::super::panelcmds::listed_artboards;
|
||||
use super::super::select::{is_selectable, on_artboard, selectable};
|
||||
use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, point_indices, switch_or, text_param};
|
||||
use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, switch_or, text_param};
|
||||
use crate::{DocState, Result, Session};
|
||||
|
||||
/// How Select by Artboards relates an object to the chosen artboards (`relation`).
|
||||
@@ -33,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select by Artboards",
|
||||
["Object", "Plug-ins", "Selection Tools"],
|
||||
None,
|
||||
"{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}",
|
||||
"{artboards: [index…] (0-based whole numbers, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}",
|
||||
has_doc,
|
||||
by_artboards
|
||||
),
|
||||
@@ -58,13 +59,12 @@ fn by_artboards(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "`relation` must be overlap, inside or outside"));
|
||||
}
|
||||
let listed = p.get("artboards").ok_or_else(|| bad(C, "missing `artboards`"))?;
|
||||
let indices = point_indices(listed).ok_or_else(|| bad(C, "`artboards` must be a list of artboard indices"))?;
|
||||
if indices.is_empty() {
|
||||
if listed.as_array().is_some_and(Vec::is_empty) {
|
||||
return Err(bad(C, "choose at least one artboard"));
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let rects =
|
||||
indices.iter().map(|i| st.doc.artboards.get(*i).map(|a| a.rect)).collect::<Option<Vec<_>>>().ok_or_else(|| bad(C, "no such artboard"))?;
|
||||
let rects: Vec<_> =
|
||||
listed_artboards(&st.doc, listed, "artboards", C)?.into_iter().filter_map(|i| st.doc.artboards.get(i)).map(|a| a.rect).collect();
|
||||
let symbols = st.doc.symbol_boxes();
|
||||
let ids: Vec<NodeId> = selectable(&st.doc, st.isolation)
|
||||
.into_iter()
|
||||
|
||||
@@ -108,6 +108,35 @@ fn bad_params_are_errors_and_leave_the_selection() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A malformed `artboards` entry is refused as one, naming the parameter, before any entry is
|
||||
/// looked up; a value that is not a list, an empty list, a left-out list and a whole number past
|
||||
/// the last artboard each have their own error.
|
||||
#[test]
|
||||
fn artboard_errors_say_what_is_wrong() {
|
||||
let mut s = three_boards();
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
let entries = "invalid parameters for `addon.select.byArtboards`: `artboards` must contain whole numbers";
|
||||
let not_a_list = "invalid parameters for `addon.select.byArtboards`: `artboards` must be a list of artboard indices";
|
||||
for (p, want) in [
|
||||
(json!({"artboards": ["1"]}), entries),
|
||||
(json!({"artboards": [-1]}), entries),
|
||||
(json!({"artboards": [1.5]}), entries),
|
||||
(json!({"artboards": [true]}), entries),
|
||||
(json!({"artboards": [9, "1"]}), entries),
|
||||
(json!({"artboards": "0"}), not_a_list),
|
||||
(json!({"artboards": null}), not_a_list),
|
||||
(json!({"artboards": []}), "invalid parameters for `addon.select.byArtboards`: choose at least one artboard"),
|
||||
(json!({}), "invalid parameters for `addon.select.byArtboards`: missing `artboards`"),
|
||||
(json!({"artboards": [9]}), "no such artboard"),
|
||||
(json!({"artboards": [0, 9]}), "no such artboard"),
|
||||
] {
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
assert_eq!(s.execute(C, &p).unwrap_err().to_string(), want, "{p}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![a], "{p}");
|
||||
}
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0, 0]})), vec![a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_instance_is_measured_by_its_art() {
|
||||
// The symbol's art, (100, 60) to (140, 80), drawn 50 pt up and left: (50, 10) to (90, 30), on
|
||||
|
||||
@@ -446,7 +446,7 @@ pub(crate) fn rows_per_target(d: &Document, of: Option<NodeId>, ids: &[NodeId],
|
||||
}
|
||||
|
||||
/// Whether the `target` param asks for the contents of groups and layers (see the module docs).
|
||||
fn targets_contents(p: &Value) -> Result<bool> {
|
||||
pub(crate) fn targets_contents(p: &Value) -> Result<bool> {
|
||||
match p.get("target") {
|
||||
None | Some(Value::Null) => Ok(false),
|
||||
Some(v) => match v.as_str() {
|
||||
@@ -508,6 +508,20 @@ pub(crate) fn drop_design_art(d: &Document, mut ids: Vec<NodeId>) -> Vec<NodeId>
|
||||
ids
|
||||
}
|
||||
|
||||
/// [`drop_design_art`] for an edit of the `item` rows of `ids` (`fill`: fill rows): an explicit `item` that a design's
|
||||
/// art has no row of that kind for is still an error of `cmd`, as on any other object.
|
||||
pub(crate) fn drop_design_art_rows(s: &Session, ids: Vec<NodeId>, item: ItemTarget, fill: bool, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
for (id, it) in ids.iter().zip(item.per_target(s, &ids)) {
|
||||
if let (Some(it), Some(n)) = (it, d.node(*id))
|
||||
&& super::graph::is_design_art(d, *id)
|
||||
{
|
||||
it.resolve(&n.appearance, fill, cmd)?;
|
||||
}
|
||||
}
|
||||
Ok(drop_design_art(d, ids))
|
||||
}
|
||||
|
||||
/// The outermost art of graph designs drawn in graph series inside `roots`: the objects directly in a series group that
|
||||
/// [`super::graph::is_design_art`] accepts.
|
||||
pub(crate) fn design_art_in(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
@@ -720,7 +734,10 @@ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bo
|
||||
let holder = match reference_of(s, p, item, cmd)? {
|
||||
Some(of) => Some(of),
|
||||
None => {
|
||||
let ids = drop_design_art(d, appearance_targets(s, p)?);
|
||||
let all = appearance_targets(s, p)?;
|
||||
// The art of a graph design is left out, unless it is all there is: the item is then a row of that art.
|
||||
let kept = drop_design_art(d, all.clone());
|
||||
let ids = if kept.is_empty() { all } else { kept };
|
||||
ids.get(item.anchor(s, &ids)).copied()
|
||||
}
|
||||
};
|
||||
|
||||
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Paint Bucket (Stroke)",
|
||||
[],
|
||||
None,
|
||||
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
|
||||
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 edges counted as drawing with stroke paint match whatever they draw with, such as the edge a double-click's first click painted), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
|
||||
has_doc,
|
||||
lp_stroke_edge
|
||||
),
|
||||
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, false)
|
||||
),
|
||||
|
||||
@@ -567,6 +567,16 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0);
|
||||
let scope = scope_param(p, C)?;
|
||||
let like = match_param(p, C, scope != LpScope::One, "\"connected\" or \"samePaint\"")?;
|
||||
let through: Vec<NodeId> = match p.get("through") {
|
||||
None => vec![],
|
||||
Some(_) if scope != LpScope::Connected => return Err(bad(C, "through applies to scope \"connected\"")),
|
||||
Some(v) => {
|
||||
let ids = v.as_array().filter(|ids| ids.len() <= 4096).ok_or_else(|| bad(C, "through must be an array of at most 4096 edge ids"))?;
|
||||
ids.iter()
|
||||
.map(|id| id.as_u64().map(NodeId).ok_or_else(|| bad(C, "through must be an array of at most 4096 edge ids")))
|
||||
.collect::<Result<_>>()?
|
||||
}
|
||||
};
|
||||
let (eid, count, changed) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?;
|
||||
@@ -575,7 +585,7 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let like = like.unwrap_or_else(|| b::lp_stroke_paint(start));
|
||||
let targets = match scope {
|
||||
LpScope::One => vec![eid],
|
||||
LpScope::Connected => b::connected_edges(n, eid, &like),
|
||||
LpScope::Connected => b::connected_edges_through(n, eid, &like, &through),
|
||||
LpScope::SamePaint => std::iter::once(eid)
|
||||
.chain(b::edges(n).into_iter().filter(|e| e.visible && e.id != eid && b::lp_stroke_paint(e) == like).map(|e| e.id))
|
||||
.collect(),
|
||||
|
||||
@@ -12,6 +12,7 @@ use super::{
|
||||
thread_local! {
|
||||
static BOX_TESTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
static CANDIDATE_VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
static TRACES_ON_THIS_THREAD: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
// ---------- Image Trace ----------
|
||||
@@ -562,15 +563,20 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve
|
||||
Ok(seams.into_iter().chain(groups).collect())
|
||||
}
|
||||
|
||||
/// What a trace depends on: the document it is made in, the object traced (an image, or an Image
|
||||
/// Trace object traced again), its image, the image's encoded bytes, and the settings it is traced
|
||||
/// with. The tracer makes the same paths of the same inputs, so a trace made away from the command
|
||||
/// ([`TraceRun`]) stands in for the command's own in the same document.
|
||||
/// What a trace depends on: the document it is made in and the content it was reverted to, the
|
||||
/// object traced (an image, or an Image Trace object traced again), its image, the image's encoded
|
||||
/// bytes, and the settings it is traced with. The tracer makes the same paths of the same inputs,
|
||||
/// so a trace made away from the command ([`TraceRun`]) stands in for the command's own in the same
|
||||
/// document until File › Revert replaces its content.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct TraceInputs {
|
||||
/// The [`DocState::uid`](crate::DocState::uid) of the document traced in. A trace made in one
|
||||
/// document never stands in for one in another, however alike their images and settings.
|
||||
doc: u64,
|
||||
/// The document's [`DocState::reverts`](crate::DocState::reverts) when the trace was prepared.
|
||||
/// A trace prepared before File › Revert never stands in for one after it, even when the
|
||||
/// restored image, pixels, object and settings are the same.
|
||||
reverts: u64,
|
||||
target: NodeId,
|
||||
image: Box<ImageObject>,
|
||||
/// The settings traced with, as JSON.
|
||||
@@ -639,7 +645,8 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
|
||||
let bytes = Arc::clone(&blob.bytes);
|
||||
let library = trace_library(c, s, &mut params)?;
|
||||
let traced_with = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let inputs = TraceInputs { doc: s.doc()?.uid, target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
|
||||
let st = s.doc()?;
|
||||
let inputs = TraceInputs { doc: st.uid, reverts: st.reverts, target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
|
||||
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library })
|
||||
}
|
||||
|
||||
@@ -655,7 +662,8 @@ pub struct Traced {
|
||||
impl Traced {
|
||||
/// Hand it to the next run of its command with the same inputs ([`TraceRun::params`]) in the
|
||||
/// document it was made in, which applies it as one undo step instead of tracing again. Any
|
||||
/// other trace drops it, a trace in another document included.
|
||||
/// other trace drops it and traces again, a trace in another document included, and so does
|
||||
/// the command after File › Revert replaced the document's content.
|
||||
pub fn hand_in(self, s: &mut Session) {
|
||||
s.trace_hand_off = Some(self);
|
||||
}
|
||||
@@ -664,6 +672,8 @@ impl Traced {
|
||||
/// Decode the image bytes of `inputs` and trace them with `params`, telling `steps` how far it has
|
||||
/// got ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`.
|
||||
fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
|
||||
#[cfg(test)]
|
||||
TRACES_ON_THIS_THREAD.with(|n| n.set(n.get() + 1));
|
||||
// An image over the tracer's size is traced scaled down (the paths are scaled back).
|
||||
let raster = tr::Raster::decode_to_fit(&inputs.bytes).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
if !steps(0, 0) {
|
||||
@@ -848,17 +858,30 @@ impl TraceRun {
|
||||
}
|
||||
|
||||
/// Does it still apply: would the command trace the same object, image, pixels and settings
|
||||
/// now, in the document it was prepared in?
|
||||
/// now, in the document it was prepared in, with no File › Revert since?
|
||||
pub fn current(&self, s: &Session) -> bool {
|
||||
prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs)
|
||||
}
|
||||
|
||||
/// Has File › Revert replaced the content of the document it was prepared in since then? False
|
||||
/// when that document is no longer open.
|
||||
pub fn reverted(&self, s: &Session) -> bool {
|
||||
let TraceInputs { doc, reverts, .. } = self.prepared.inputs;
|
||||
s.documents().iter().any(|st| st.uid == doc && st.reverts != reverts)
|
||||
}
|
||||
|
||||
/// Decode and trace the image, telling `steps` how far it has got → what it traced, or why it
|
||||
/// failed or stopped ([`EngineError::Cancelled`] once `steps` answers `false`). It touches no
|
||||
/// document, so it can run on any thread.
|
||||
pub fn run(&self, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
|
||||
trace_now(&self.prepared.inputs, &self.prepared.trace, steps)
|
||||
}
|
||||
|
||||
/// How many images this thread has decoded and traced so far.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn traces_on_this_thread() -> usize {
|
||||
TRACES_ON_THIS_THREAD.with(std::cell::Cell::get)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
|
||||
|
||||
@@ -595,6 +595,8 @@ struct Relink {
|
||||
styles: BTreeMap<u32, u32>,
|
||||
/// Swatch (its name in the document) → the colour linked colours show at 100 %.
|
||||
colors: BTreeMap<String, Color>,
|
||||
/// Leave graphic style links as they are ([`Clipboard::show_merged_colors`]).
|
||||
keep_styles: bool,
|
||||
}
|
||||
|
||||
impl Relink {
|
||||
@@ -674,7 +676,9 @@ impl Relink {
|
||||
/// Relink a node tree (the mirror of [`node_refs`]).
|
||||
fn node(&self, n: &mut Node) {
|
||||
self.appearance(&mut n.appearance);
|
||||
n.extras_mut().graphic_style = n.extras().graphic_style.and_then(|id| self.styles.get(&id).copied());
|
||||
if !self.keep_styles {
|
||||
n.extras_mut().graphic_style = n.extras().graphic_style.and_then(|id| self.styles.get(&id).copied());
|
||||
}
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
self.node(Arc::make_mut(&mut m.art));
|
||||
}
|
||||
@@ -1031,10 +1035,13 @@ impl Imported {
|
||||
self.relink.renames.entry(r).or_default().insert(from.to_string(), to.clone());
|
||||
}
|
||||
}
|
||||
/// Point a pasted copy at the document's resources.
|
||||
/// Point a pasted copy at the document's resources. A pie's legend labels in wedges that now show a color of the
|
||||
/// other darkness take the contrast a redraw sets there.
|
||||
pub(crate) fn apply(&self, n: &mut Node) {
|
||||
if self.relinks {
|
||||
let shades = super::super::graph::wedge_shades(n);
|
||||
self.relink.node(n);
|
||||
super::super::graph::follow_wedge_shades(n, &shades);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1109,6 +1116,30 @@ impl Clipboard {
|
||||
self.import_used(d, &self.used(), choices, same_doc)
|
||||
}
|
||||
|
||||
/// Give the objects' colors linked to a global or spot swatch whose conflict with `d`
|
||||
/// `choices` merge the color that swatch has in `d`, as pasting into `d` gives them (Paste
|
||||
/// without Formatting sets its pie legend labels' contrast from the wedge colors before it
|
||||
/// pastes). Nothing changes for the document the objects came from (`same_doc`).
|
||||
pub(crate) fn show_merged_colors(&mut self, d: &Document, choices: &SwatchChoices, same_doc: bool) {
|
||||
if same_doc {
|
||||
return;
|
||||
}
|
||||
let used = self.used();
|
||||
let colors: BTreeMap<String, Color> = self
|
||||
.conflicts(d, &used)
|
||||
.into_iter()
|
||||
.filter(|(w, _)| choices.of(&w.name) == SwatchChoice::Merge)
|
||||
.filter_map(|(w, _)| d.global_color(&w.name).map(|c| (w.name.clone(), c)))
|
||||
.collect();
|
||||
if colors.is_empty() {
|
||||
return;
|
||||
}
|
||||
let relink = Relink { colors, keep_styles: true, ..Default::default() };
|
||||
for n in &mut self.nodes {
|
||||
relink.node(n);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::import_into`] for the resources `used` names. Each style, symbol, pattern and brush
|
||||
/// comes after the styles, symbols, patterns and brushes it uses ([`use_order`]), so that it is
|
||||
/// compared and relinked with their names here, and each loop of definitions that use each
|
||||
|
||||
@@ -221,6 +221,8 @@ pub(crate) struct Recolor<'a> {
|
||||
patterns: HashMap<String, Option<String>>,
|
||||
new_images: Vec<(String, ImageBlob)>,
|
||||
new_patterns: Vec<PatternDef>,
|
||||
/// Objects inside the recolored ones that keep their colors, with everything inside them.
|
||||
skip: HashSet<NodeId>,
|
||||
changed: usize,
|
||||
}
|
||||
|
||||
@@ -236,6 +238,7 @@ impl<'a> Recolor<'a> {
|
||||
patterns: HashMap::new(),
|
||||
new_images: vec![],
|
||||
new_patterns: vec![],
|
||||
skip: HashSet::new(),
|
||||
changed: 0,
|
||||
}
|
||||
}
|
||||
@@ -254,7 +257,7 @@ impl<'a> Recolor<'a> {
|
||||
|
||||
/// A pass that maps colors as this one does, with nothing recolored yet.
|
||||
fn again(&self) -> Self {
|
||||
Self { links: self.links, gray_images: self.gray_images, remake: self.remake, ..Self::new(self.scope, self.f) }
|
||||
Self { links: self.links, gray_images: self.gray_images, remake: self.remake, skip: self.skip.clone(), ..Self::new(self.scope, self.f) }
|
||||
}
|
||||
|
||||
/// The entries of `objects` (ids, each with a flag) whose object this pass would change, other
|
||||
@@ -440,12 +443,20 @@ impl ColorVisitor for Visit<'_, '_> {
|
||||
fn image(&mut self, key: &str) -> Option<String> {
|
||||
self.pass.image(self.d, key)
|
||||
}
|
||||
fn enters(&mut self, n: &Node) -> bool {
|
||||
!self.pass.skip.contains(&n.id)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
|
||||
run_pass(s, p, cmd, label, Recolor::new(Scope::of(p, cmd)?, f))
|
||||
}
|
||||
|
||||
/// [`recolor`] that leaves the objects `skip` inside the recolored ones, and everything inside them, as they are.
|
||||
pub(crate) fn recolor_except(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color, skip: HashSet<NodeId>) -> Result<Value> {
|
||||
run_pass(s, p, cmd, label, Recolor { skip, ..Recolor::new(Scope::of(p, cmd)?, f) })
|
||||
}
|
||||
|
||||
/// [`recolor`] where `f` gives gray colors, so embedded images are stored with one gray channel.
|
||||
fn recolor_gray(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
|
||||
run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p, cmd)?, f) })
|
||||
|
||||
@@ -356,7 +356,8 @@ fn mirror_open(sp: &SubPath, axis: &Axis, m: Affine) -> Vec<SubPath> {
|
||||
if !end_on {
|
||||
run.reverse();
|
||||
}
|
||||
let Some((last, body)) = run.anchors.split_last() else { return vec![] };
|
||||
let run = run.anchors.into_vec();
|
||||
let Some((last, body)) = run.split_last() else { return vec![] };
|
||||
let q = axis.project(last.p);
|
||||
let mut anchors = body.to_vec();
|
||||
anchors.push(Anchor::with_handles(q, last.h_in, m * last.h_in));
|
||||
|
||||
@@ -10,6 +10,7 @@ use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection,
|
||||
use vectorcraft_geom::Vec2;
|
||||
|
||||
use super::edit::selected_roots;
|
||||
use super::panelcmds::artboard_at;
|
||||
use super::pathops::Beside;
|
||||
use super::select::{first_selectable, is_selectable, selectable_ids, walk_selectable};
|
||||
use super::{
|
||||
@@ -201,7 +202,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Guide",
|
||||
[],
|
||||
None,
|
||||
"{vertical: bool, pos: pt (x for vertical, y for horizontal), artboard?: index (an artboard guide: it runs across that artboard only and moves, is copied and is deleted with it; default a canvas guide, across the whole canvas), layer?: id (the layer it is on, shown, hidden, locked and deleted with it; default the current layer)} → {index}",
|
||||
"{vertical: bool, pos: pt (x for vertical, y for horizontal), artboard?: index (0-based whole number; an artboard guide: it runs across that artboard only and moves, is copied and is deleted with it; default, or null, a canvas guide, across the whole canvas), layer?: id (the layer it is on, shown, hidden, locked and deleted with it; default the current layer)} → {index}",
|
||||
has_doc,
|
||||
guide_add
|
||||
),
|
||||
@@ -767,15 +768,8 @@ fn clear_guides(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
fn guide_add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pos = f64_req(p, "pos", "guide.add")?;
|
||||
let vertical = switch_or(p, "vertical", false, "guide.add")?;
|
||||
let artboard = match p.get("artboard").filter(|v| !v.is_null()) {
|
||||
Some(v) => {
|
||||
let boards = &s.doc()?.doc.artboards;
|
||||
let ab = v.as_u64().and_then(|i| boards.get(usize::try_from(i).ok()?)).ok_or_else(|| EngineError::Other("no such artboard".into()))?;
|
||||
Some(ab.id)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let artboard = artboard_at(&st.doc, p, "artboard", "guide.add")?.and_then(|i| st.doc.artboards.get(i)).map(|a| a.id);
|
||||
let layer = match id_param(p, "layer") {
|
||||
Some(l) if st.doc.node(l).is_some_and(Node::is_layer) => Some(l),
|
||||
Some(_) => return Err(bad("guide.add", "layer must name a layer or sublayer")),
|
||||
|
||||
@@ -46,7 +46,7 @@ fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath {
|
||||
let sp = vectorcraft_tools::draw2::catmull_rom(&marked, false);
|
||||
if sp.anchors.len() < 3 {
|
||||
// Two anchors closed would run back over the line itself.
|
||||
return SubPath::new(sp.anchors, closed && n > 2);
|
||||
return SubPath::of(sp.anchors, closed && n > 2);
|
||||
}
|
||||
let fitted = po::simplify_with(
|
||||
&PathData::single(sp.clone()),
|
||||
@@ -62,7 +62,7 @@ fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath {
|
||||
f.h_in = f.p;
|
||||
}
|
||||
}
|
||||
SubPath::new(anchors, closed)
|
||||
SubPath::of(anchors, closed)
|
||||
}
|
||||
|
||||
/// The path of a freehand stroke: fitted at `tol` ([`fit_freehand`]), or with no `tol` the points
|
||||
@@ -133,13 +133,13 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -
|
||||
*s0 = s1.p;
|
||||
let (Some(e0), Some(e1)) = (stroke.last_mut(), sp.anchors.get(end)) else { return None };
|
||||
*e0 = e1.p;
|
||||
let fit = stroke_subpath(&stroke, tol, false).anchors;
|
||||
let fit = stroke_subpath(&stroke, tol, false).anchors.into_vec();
|
||||
let (Some(f0), Some(f1)) = (fit.first().copied(), fit.last().copied()) else { return None };
|
||||
let inner = fit.get(1..fit.len().saturating_sub(1)).unwrap_or_default();
|
||||
let (before, after): (Vec<Anchor>, Vec<Anchor>) = if sp.closed {
|
||||
((0..=(start + n - end) % n).filter_map(|k| sp.anchors.get((end + k) % n).copied()).collect(), vec![])
|
||||
} else {
|
||||
(sp.anchors.get(..=start)?.to_vec(), sp.anchors.get(end..)?.to_vec())
|
||||
(sp.anchors.get_range(..=start)?, sp.anchors.get_range(end..)?)
|
||||
};
|
||||
let mut anchors = before;
|
||||
if let Some(a) = anchors.last_mut() {
|
||||
@@ -227,12 +227,18 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
|
||||
let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) };
|
||||
*p0 = end;
|
||||
if pts.len() < 2 {
|
||||
// No stroke to add: the brush alone changes, when it is not the path's already.
|
||||
// No stroke to add: the brush alone changes, when it is not the path's already, and the
|
||||
// path is selected or deselected as a longer continuation leaves it.
|
||||
if let Some(name) = brush_name
|
||||
&& s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name))
|
||||
{
|
||||
s.edit("Paintbrush", |d, _| {
|
||||
s.edit("Paintbrush", |d, sel| {
|
||||
set_brush(d, target, name);
|
||||
if keep_selected {
|
||||
sel.set([id]);
|
||||
} else {
|
||||
sel.remove(id);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
@@ -316,12 +322,12 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
|
||||
// outgoing handle.
|
||||
let mut other_len = 0.0;
|
||||
if let Some((_, _, y, _)) = &connect
|
||||
&& let Some((y0, rest)) = y.anchors.split_first()
|
||||
&& let Some(y0) = y.anchors.first()
|
||||
{
|
||||
if let Some(last) = sp.anchors.last_mut() {
|
||||
*last = Anchor::with_handles(y0.p, last.h_in + (y0.p - last.p), y0.h_out);
|
||||
}
|
||||
sp.anchors.extend_from_slice(rest);
|
||||
sp.anchors.extend(y.anchors.iter().skip(1));
|
||||
other_len = subpath_len(y);
|
||||
}
|
||||
// What the pen recorded along the path (in the direction it is continued in), followed by
|
||||
|
||||
@@ -117,11 +117,10 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec<bool> {
|
||||
// eighth of the way round a closed path. Over that much of a circle the path turns by 45°, so a
|
||||
// loop shorter than the reach is not all corners, while a square's or a triangle's corners still are.
|
||||
let mut spans = [reach, 2.0 * reach];
|
||||
// The lengths along the path ahead and back, measured once when an anchor needs them.
|
||||
let (mut ahead, mut back) = (None, None);
|
||||
if closed {
|
||||
let mut total = 0.0;
|
||||
for i in 0..n {
|
||||
total += walk(anchors, closed, (i, true), [f64::INFINITY; 2], reach, 1).1;
|
||||
}
|
||||
let total = ahead.get_or_insert_with(|| walk_blocks(anchors, closed, true, reach)).first().map_or(0.0, |lens| lens.iter().take(n).sum());
|
||||
if !(total.is_finite() && total > 0.0) {
|
||||
return corners;
|
||||
}
|
||||
@@ -137,8 +136,10 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec<bool> {
|
||||
if !turn_between(arrive, leave).is_some_and(|t| t > SMOOTH_CORNER_DEG) {
|
||||
continue;
|
||||
}
|
||||
let [Some(back_near), Some(back_far)] = walk(anchors, closed, (i, false), spans, reach, MAX_CORNER_WALK).0 else { continue };
|
||||
let [Some(ahead_near), Some(ahead_far)] = walk(anchors, closed, (i, true), spans, reach, MAX_CORNER_WALK).0 else { continue };
|
||||
let back = back.get_or_insert_with(|| walk_blocks(anchors, closed, false, reach));
|
||||
let [Some(back_near), Some(back_far)] = spans.map(|r| point_along(anchors, closed, (i, false), r, back, reach)) else { continue };
|
||||
let ahead = ahead.get_or_insert_with(|| walk_blocks(anchors, closed, true, reach));
|
||||
let [Some(ahead_near), Some(ahead_far)] = spans.map(|r| point_along(anchors, closed, (i, true), r, ahead, reach)) else { continue };
|
||||
*flag = [(back_near, ahead_near, spans[0]), (back_far, ahead_far, spans[1])]
|
||||
.into_iter()
|
||||
.all(|(back, ahead, r)| r <= 0.0 || turn_between(a.p - back, ahead - a.p).is_some_and(|t| t > SMOOTH_CORNER_DEG));
|
||||
@@ -146,9 +147,54 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec<bool> {
|
||||
corners
|
||||
}
|
||||
|
||||
/// Most segments [`walk`] passes from an anchor before it stops, which bounds the work for each
|
||||
/// anchor on a path of very many very short segments.
|
||||
const MAX_CORNER_WALK: usize = 256;
|
||||
/// The lengths [`walk`] measures along the segments of `anchors`, in the order a walk ahead
|
||||
/// (`forward`) or back passes them, twice round, starting at the first anchor ahead or the last
|
||||
/// anchor back, and added up in blocks: element `l` holds the lengths of each run of 2^`l`
|
||||
/// segments that starts at a multiple of 2^`l`. Each block adds up only its own segments, so a short
|
||||
/// stretch keeps its length next to very long ones. The segment past an open path's end has no
|
||||
/// length.
|
||||
fn walk_blocks(anchors: &[Anchor], closed: bool, forward: bool, reach: f64) -> Vec<Vec<f64>> {
|
||||
let n = anchors.len();
|
||||
let lens: Vec<f64> =
|
||||
(0..n).map(|k| walk(anchors, closed, (if forward { k } else { n - 1 - k }, forward), [f64::INFINITY; 2], reach, 1).1).collect();
|
||||
let mut blocks = vec![(0..2 * n).map(|k| lens[k % n]).collect::<Vec<f64>>()];
|
||||
while let Some(last) = blocks.last().filter(|b| b.len() > 1) {
|
||||
let next = last.as_chunks::<2>().0.iter().map(|[a, b]| a + b).collect();
|
||||
blocks.push(next);
|
||||
}
|
||||
blocks
|
||||
}
|
||||
|
||||
/// The point `dist` along the path `anchors` from anchor `from.0`, ahead when `from.1` and back
|
||||
/// otherwise, as [`walk`] finds it: an open path's end for a distance beyond the end, and `None`
|
||||
/// when a length is not a number or is too large to add. The walk skips whole blocks of `blocks`
|
||||
/// ([`walk_blocks`] in the same direction) that end no more than `dist` along the path, so a path of
|
||||
/// very many short segments is not walked one segment at a time from each anchor.
|
||||
fn point_along(anchors: &[Anchor], closed: bool, from: (usize, bool), dist: f64, blocks: &[Vec<f64>], reach: f64) -> Option<Point> {
|
||||
let (n, (i, forward)) = (anchors.len(), from);
|
||||
let start = if forward { i } else { n - 1 - i };
|
||||
let end = start
|
||||
+ if closed {
|
||||
n
|
||||
} else if forward {
|
||||
n - 1 - i
|
||||
} else {
|
||||
i
|
||||
};
|
||||
let (mut pos, mut gone) = (start, 0.0);
|
||||
// The largest block that starts at `pos`, stays within the walk and ends within `dist`, until
|
||||
// none does; a block whose length is not a number is never skipped.
|
||||
while let Some((size, len)) = blocks.iter().enumerate().rev().find_map(|(l, lens)| {
|
||||
let size = 1usize << l;
|
||||
let len = lens.get(pos >> l).copied()?;
|
||||
(pos % size == 0 && pos + size <= end && gone + len <= dist).then_some((size, len))
|
||||
}) {
|
||||
pos += size;
|
||||
gone += len;
|
||||
}
|
||||
let at = if forward { pos % n } else { n - 1 - pos % n };
|
||||
walk(anchors, closed, (at, forward), [(dist - gone).max(0.0); 2], reach, n).0[0]
|
||||
}
|
||||
|
||||
/// A walk along the path `anchors` from anchor `from.0`, ahead when `from.1` and back otherwise,
|
||||
/// past no more than `segments` segments, measured along the lines between each curved segment's
|
||||
@@ -274,7 +320,7 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<A
|
||||
for a in &mut out {
|
||||
*a = Anchor::with_handles(a.p, a.h_in, a.h_out);
|
||||
}
|
||||
out
|
||||
out.into_vec()
|
||||
}
|
||||
|
||||
/// Distance (points) from an anchor within which a smoothed closed path starts at that anchor
|
||||
@@ -549,7 +595,7 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
|
||||
if sp.closed {
|
||||
let start = sp.anchors[0].p;
|
||||
let Some(k) = marked.iter().position(|m| !m) else {
|
||||
let corners = smooth_corners(&sp.anchors, true, radius);
|
||||
let corners = smooth_corners(&sp.anchors.contiguous(), true, radius);
|
||||
let Some(c) = corners.iter().position(|c| *c) else {
|
||||
// Everything is in range and nothing is a corner: smooth the whole closed path,
|
||||
// across its start too.
|
||||
@@ -557,7 +603,7 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
|
||||
return f.subpaths.into_iter().next().map(|r| start_nearest(r, start, sp));
|
||||
};
|
||||
// Cut the path open at a corner, which then ends the last part as well as starting the first.
|
||||
let mut open = sp.anchors.clone();
|
||||
let mut open = sp.anchors.to_vec();
|
||||
open.rotate_left(c);
|
||||
let mut cut = corners;
|
||||
cut.rotate_left(c);
|
||||
@@ -576,15 +622,14 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
|
||||
return Some(start_nearest(SubPath::new(res, true), start, sp));
|
||||
};
|
||||
// Rotate so an untouched anchor comes first, duplicate it at the end and treat as open.
|
||||
let mut open = sp.clone();
|
||||
open.anchors.rotate_left(k);
|
||||
let mut open = sp.anchors.to_vec();
|
||||
open.rotate_left(k);
|
||||
let mut m = marked.clone();
|
||||
m.rotate_left(k);
|
||||
open.anchors.push(open.anchors[0]);
|
||||
open.push(open[0]);
|
||||
m.push(false);
|
||||
open.closed = false;
|
||||
let mut res = smooth_open(&open.anchors, &m, near, tol, sigma, radius, false);
|
||||
if same_anchors(&res, &open.anchors) {
|
||||
let mut res = smooth_open(&open, &m, near, tol, sigma, radius, false);
|
||||
if same_anchors(&res, &open) {
|
||||
return None;
|
||||
}
|
||||
let l = res.pop()?;
|
||||
@@ -595,8 +640,9 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
|
||||
let res = SubPath::new(res, true);
|
||||
return Some(if k == 0 { res } else { start_nearest(res, start, sp) });
|
||||
}
|
||||
let res = smooth_open(&sp.anchors, &marked, near, tol, sigma, radius, true);
|
||||
(!same_anchors(&res, &sp.anchors)).then(|| SubPath::new(res, false))
|
||||
let anchors = sp.anchors.contiguous();
|
||||
let res = smooth_open(&anchors, &marked, near, tol, sigma, radius, true);
|
||||
(!same_anchors(&res, &anchors)).then(|| SubPath::new(res, false))
|
||||
}
|
||||
|
||||
/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it
|
||||
@@ -1099,11 +1145,12 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A 90° bump 400 pt high cut into 1 pt segments, between two long straight segments: with a reach
|
||||
/// of 10 pt its top is a corner, and with a reach of 1,000 pt, where the walk passes more segments
|
||||
/// than it measures before it gets that far, its top is not one, as the path turns by about 51°
|
||||
/// over that reach.
|
||||
/// of 10 pt, and of 300 pt, where twice the reach passes the bump's 566 segments on each side, its
|
||||
/// top is a corner, and with a reach of 1,000 pt its top is not one, as the path turns by about 51°
|
||||
/// over that reach. The turns into and between 1 pt segments that follow two segments 1e16 pt long
|
||||
/// are corners too.
|
||||
#[test]
|
||||
fn a_corner_is_not_kept_where_the_reach_is_not_measured() {
|
||||
fn a_bump_of_many_short_segments_is_a_corner_where_it_turns_over_the_reach() {
|
||||
let side = 400.0 * std::f64::consts::SQRT_2;
|
||||
let steps = side.ceil() as usize;
|
||||
let mut pts = vec![(-3000.0, 0.0)];
|
||||
@@ -1120,6 +1167,10 @@ mod tests {
|
||||
let top = steps + 1;
|
||||
assert_eq!(anchors[top].p, Point::new(0.0, 400.0));
|
||||
assert!(smooth_corners(&anchors, false, 10.0)[top]);
|
||||
assert!(smooth_corners(&anchors, false, 300.0)[top]);
|
||||
let long = polyline(&[(0.0, 0.0), (1e16, 0.0), (0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 2.0)]);
|
||||
let corners = smooth_corners(&long, false, 0.5);
|
||||
assert!(corners[2] && corners[3] && corners[4], "{corners:?}");
|
||||
assert!(!smooth_corners(&anchors, false, 1000.0)[top]);
|
||||
}
|
||||
|
||||
|
||||
@@ -179,7 +179,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste",
|
||||
["Edit"],
|
||||
Some("Cmd+V"),
|
||||
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
|
||||
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::Offset)
|
||||
),
|
||||
|
||||
@@ -367,7 +367,8 @@ fn edit_effects(
|
||||
|
||||
/// [`edit_effects`] for several effects of one list (`indices`): `f` gets each target's list and
|
||||
/// the positions of `indices` there, ascending; with `aligned`, a position a target doesn't share
|
||||
/// is left out of it, and a target sharing none of them is left out.
|
||||
/// is left out of it, and a target sharing none of them is left out. A position no target has is
|
||||
/// an error with `none`, and nothing changes.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn edit_effects_at(
|
||||
s: &mut Session,
|
||||
@@ -396,7 +397,12 @@ fn edit_effects_at(
|
||||
// Each target's list and the positions in it, in the order the targets first come up.
|
||||
let mut targets: Vec<(NodeId, Option<usize>, Vec<usize>)> = vec![];
|
||||
for &index in indices {
|
||||
for (id, at, i) in effect_targets(s, p, item, index, cmd)? {
|
||||
let found = effect_targets(s, p, item, index, cmd)?;
|
||||
// An aligned effect of a design's art that no other object has is refused, as it is given alone.
|
||||
if found.is_empty() {
|
||||
return Err(EngineError::Other(none.into()));
|
||||
}
|
||||
for (id, at, i) in found {
|
||||
match targets.iter_mut().find(|t| t.0 == id && t.1 == at) {
|
||||
Some(t) => t.2.push(i),
|
||||
None => targets.push((id, at, vec![i])),
|
||||
@@ -972,15 +978,18 @@ fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> {
|
||||
/// Expand the pieces of `m`, art evaluated from the object of the same id (its pieces share that
|
||||
/// id): those made from its own fills and strokes, or with `all` every member. The other members
|
||||
/// that repeat an id ([`repeats_an_id`]) and hold a random Transform effect ([`has_seeded`]) are
|
||||
/// expanded as well ([`expand_in_place`]). Then the members get ids of their own. Random in a
|
||||
/// Transform effect takes its seed from the id, and the canvas draws the pieces with the ids they
|
||||
/// have before that. Returns what each of those other members' expansions lists, by the member's
|
||||
/// new id.
|
||||
/// expanded as well ([`expand_in_place`]), except the objects `skip` lists. Then the members get ids
|
||||
/// of their own. Random in a Transform effect takes its seed from the id, and the canvas draws the
|
||||
/// pieces with the ids they have before that. `kept` gets the new id of each object in them that
|
||||
/// had an id `skip` lists before. Returns what each of those other members' expansions lists, by
|
||||
/// the member's new id.
|
||||
fn expand_pieces(
|
||||
d: &mut Document,
|
||||
m: &mut Node,
|
||||
all: bool,
|
||||
brushes: &[vectorcraft_brush::Brush],
|
||||
skip: &[NodeId],
|
||||
kept: &mut Vec<NodeId>,
|
||||
stroke_art: effects::StrokeArt,
|
||||
) -> std::collections::HashMap<NodeId, Vec<Listed>> {
|
||||
let id = m.id;
|
||||
@@ -996,9 +1005,23 @@ fn expand_pieces(
|
||||
if all || c.id == id {
|
||||
effects::expand_art(d, c, stroke_art);
|
||||
} else if has_seeded(c) && repeats_an_id(c, &seen) {
|
||||
listed = Some(expand_in_place(d, c, brushes));
|
||||
listed = Some(expand_in_place(d, c, brushes, skip));
|
||||
}
|
||||
let mut was = vec![];
|
||||
if !skip.is_empty() {
|
||||
c.walk(&mut |n| was.push(n.id));
|
||||
}
|
||||
fresh_ids_listed(d, c, &mut seen, listed.as_deref_mut().unwrap_or_default());
|
||||
if !was.is_empty() {
|
||||
// A copy of an object `skip` lists is left as it is too.
|
||||
let mut at = 0;
|
||||
c.walk(&mut |n| {
|
||||
if was.get(at).is_some_and(|old| *old != n.id && skip.contains(old)) {
|
||||
kept.push(n.id);
|
||||
}
|
||||
at += 1;
|
||||
});
|
||||
}
|
||||
if let Some(listed) = listed {
|
||||
expanded.insert(c.id, listed);
|
||||
}
|
||||
@@ -1052,9 +1075,9 @@ fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
|
||||
type Listed = (NodeId, usize);
|
||||
|
||||
/// [`expanded_node`] of `c` in place. Returns what the expansion lists, by places in the walk of `c`.
|
||||
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush]) -> Vec<Listed> {
|
||||
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId]) -> Vec<Listed> {
|
||||
let mut listed = vec![];
|
||||
if let Some(e) = expanded_node(d, c.clone(), brushes, &mut listed) {
|
||||
if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed) {
|
||||
*c = e;
|
||||
}
|
||||
listed
|
||||
@@ -1078,9 +1101,16 @@ fn fresh_ids_listed(d: &mut Document, c: &mut Node, seen: &mut std::collections:
|
||||
/// geometry effects are baked, raster effects become an embedded image, and the object keeps its
|
||||
/// transparency.
|
||||
pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<NodeId>) {
|
||||
expand_node_except(d, id, brushes, &[], out);
|
||||
}
|
||||
|
||||
/// [`expand_node`], leaving the objects `skip` lists, and what they hold, as they are. A geometry
|
||||
/// effect of a group or layer around one still reshapes it with the rest of its members, and the
|
||||
/// copies of it that such an effect makes are left as they are too.
|
||||
fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<NodeId>) {
|
||||
let Some(n) = d.node(id).cloned() else { return };
|
||||
let mut listed = vec![];
|
||||
let m = expanded_node(d, n, brushes, &mut listed);
|
||||
let m = expanded_node(d, n, brushes, skip, &mut listed);
|
||||
out.extend(listed.into_iter().map(|(id, _)| id));
|
||||
if let Some(mut m) = m {
|
||||
// Art made from type takes its emoji's pixels into the document.
|
||||
@@ -1093,10 +1123,10 @@ pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_b
|
||||
|
||||
/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when
|
||||
/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk
|
||||
/// of the expanded `n`, `n`'s first when its own does.
|
||||
fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<Listed>) -> Option<Node> {
|
||||
/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded.
|
||||
fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<Listed>) -> Option<Node> {
|
||||
let id = n.id;
|
||||
if !expandable(&n) {
|
||||
if skip.contains(&id) || !expandable(&n) {
|
||||
return None;
|
||||
}
|
||||
// Colour adjustments: the colours inside become the adjusted ones (an embedded image a
|
||||
@@ -1133,7 +1163,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
for (i, c) in m.children_mut().into_iter().flatten().enumerate() {
|
||||
let c = Arc::make_mut(c);
|
||||
if i == 0 {
|
||||
expanded = expand_in_place(d, c, brushes);
|
||||
expanded = expand_in_place(d, c, brushes, skip);
|
||||
fresh_ids_listed(d, c, &mut seen, &mut expanded);
|
||||
} else {
|
||||
effects::fresh_ids(d, c, &mut seen);
|
||||
@@ -1163,6 +1193,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
|d: &mut Document, path: &PathData, rule: FillRule, st: &StrokeLayer| super::pathops::outlined_stroke(d, brushes, path, rule, st);
|
||||
// Members of a group or layer that `expand_pieces` expanded, by id, with what their expansion lists.
|
||||
let mut members = std::collections::HashMap::new();
|
||||
// New ids of the copies of objects `skip` lists among those members.
|
||||
let mut kept = vec![];
|
||||
let expanded = match image {
|
||||
// Blur, feather and inner glow change the object itself: it becomes the image (a layer
|
||||
// keeps it as its only member).
|
||||
@@ -1174,7 +1206,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
} else if container {
|
||||
// A group's or layer's own fills and strokes become art among its members.
|
||||
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
|
||||
members = expand_pieces(d, &mut m, false, brushes, &mut stroke_art);
|
||||
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art);
|
||||
m
|
||||
})
|
||||
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
@@ -1195,7 +1227,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| {
|
||||
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
expand_nested_instances(d, &mut m, 1, &mut budget);
|
||||
expand_pieces(d, &mut m, true, brushes, &mut stroke_art);
|
||||
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art);
|
||||
m
|
||||
})
|
||||
};
|
||||
@@ -1217,6 +1249,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
}
|
||||
}
|
||||
if container {
|
||||
let skip = if kept.is_empty() { std::borrow::Cow::Borrowed(skip) } else { std::borrow::Cow::Owned([skip, &kept].concat()) };
|
||||
// The place of each member in the walk of `n`: after `n` and the members before it.
|
||||
let mut at = 1;
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
@@ -1229,7 +1262,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
match members.remove(&c.id) {
|
||||
Some(listed) => out.extend(listed),
|
||||
None => {
|
||||
if let Some(e) = expanded_node(d, (**c).clone(), brushes, out) {
|
||||
if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out) {
|
||||
*c = Arc::new(e);
|
||||
changed = true;
|
||||
}
|
||||
@@ -1274,9 +1307,20 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// geometry it hasn't changed.
|
||||
if vectorcraft_plugins::safe_mode::active() {
|
||||
// A dimension selected with the art it measures is left as it is, and so is the art of a graph design in a
|
||||
// series.
|
||||
// series, unless an effect of a group around it, the selected graph or series group or one inside it, draws it
|
||||
// with that group: an effect of the group's own, or a raster effect of one of its fills or strokes (the group
|
||||
// then becomes an image of all of it).
|
||||
let mut d = super::dimension::without_kept(&s.doc()?.doc, &roots);
|
||||
let designs = super::appearance::design_art_in(&d, &roots);
|
||||
let draws_members = |g: &Node| g.appearance.effects.iter().any(|e| e.visible) || !rasterfx::raster_fx(g).is_empty();
|
||||
let designs: Vec<NodeId> = super::appearance::design_art_in(&d, &roots)
|
||||
.into_iter()
|
||||
.filter(|art| {
|
||||
!d.ancestry(*art).is_some_and(|up| {
|
||||
let from = up.iter().position(|a| roots.contains(a)).unwrap_or(up.len());
|
||||
up.get(from..up.len().saturating_sub(1)).is_some_and(|around| around.iter().filter_map(|a| d.node(*a)).any(draws_members))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if !designs.is_empty() {
|
||||
let view = d.to_mut();
|
||||
for id in designs {
|
||||
@@ -1307,16 +1351,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut out = vec![];
|
||||
let threaded = super::threads::frames(d);
|
||||
for id in &roots {
|
||||
expand_node(d, *id, &brushes, &mut out);
|
||||
}
|
||||
for id in &designs {
|
||||
if let (Some(was), Some(slot)) = (before.node(*id), d.node_mut(*id)) {
|
||||
*slot = was.clone();
|
||||
}
|
||||
}
|
||||
if !designs.is_empty() {
|
||||
// A mark that expands into a group stays listed: only what lies in the restored art is left out.
|
||||
out.retain(|id| d.node(*id).is_some() && !d.ancestry(*id).is_some_and(|up| up.iter().any(|a| designs.contains(a))));
|
||||
expand_node_except(d, *id, &brushes, &designs, &mut out);
|
||||
}
|
||||
super::dimension::put_back(d, lifted);
|
||||
// A dimension whose source was replaced stays where it was, no longer linked.
|
||||
|
||||
@@ -265,18 +265,21 @@ fn gradient_expands(d: &Document, l: &Node) -> bool {
|
||||
|
||||
/// Whether type `t` has a gradient fill that Fill expands once Object has outlined it: one of the
|
||||
/// paths `type.createOutlines` makes of its glyphs, ruby glyphs and underline and strikethrough
|
||||
/// bars, each painted as its run with its unplaced gradients fitted to the layout's bounds, has one
|
||||
/// bars, each painted as its run with its unplaced gradients fitted to the layout's bounds, or the
|
||||
/// path filled with its run's stroke under a transform that is not a similarity, has one
|
||||
/// ([`gradient_expands`] on that path). Inline graphics and color glyphs become other art. Leaves
|
||||
/// the document as it is and stops at the first such path.
|
||||
fn text_gradient_expands(d: &Document, t: &TextObject) -> bool {
|
||||
if !t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))) {
|
||||
let gradient =
|
||||
|st: &vectorcraft_doc::CharStyle| matches!(st.fill, Paint::Gradient(_)) || (st.has_stroke() && matches!(st.stroke, Paint::Gradient(_)));
|
||||
if !t.runs.iter().any(|r| gradient(&r.style)) {
|
||||
return false;
|
||||
}
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
let first = t.first_style();
|
||||
let expands = |run: usize, outline: &BezPath| {
|
||||
let style = t.runs.get(run).map_or(&first, |r| &r.style);
|
||||
if !matches!(style.fill, Paint::Gradient(_)) {
|
||||
if !gradient(style) {
|
||||
return false;
|
||||
}
|
||||
let path = PathData::from_bezpath(outline);
|
||||
@@ -284,8 +287,8 @@ fn text_gradient_expands(d: &Document, t: &TextObject) -> bool {
|
||||
return false;
|
||||
}
|
||||
let mut piece = Node::path(NodeId(u64::MAX), path, Appearance::default());
|
||||
vectorcraft_render::effects::paint_type_piece(&mut piece, style, lay.bounds, t.xf);
|
||||
gradient_expands(d, &piece)
|
||||
let stroke = vectorcraft_render::effects::paint_type_piece(&mut piece, style, lay.bounds, t.xf);
|
||||
gradient_expands(d, &piece) || stroke.is_some_and(|s| gradient_expands(d, &s))
|
||||
};
|
||||
let inline = |gi: usize| lay.inlines.iter().find(|i| i.glyph == gi).is_some_and(|i| t.runs.get(i.run).is_some_and(|r| r.inline.is_some()));
|
||||
lay.glyphs.iter().enumerate().any(|(gi, g)| !inline(gi) && g.image.is_none() && g.colour.is_none() && expands(g.run, &g.outline))
|
||||
|
||||
@@ -54,6 +54,7 @@ pub mod ppi;
|
||||
pub mod progress;
|
||||
mod psdlayers;
|
||||
pub mod psdread;
|
||||
mod psdslices;
|
||||
mod pxrread;
|
||||
mod save;
|
||||
mod screens;
|
||||
@@ -93,6 +94,9 @@ pub(crate) use native::preview_png;
|
||||
pub use native::with_compression_pref;
|
||||
pub(crate) use pdfimport::opened_page_document;
|
||||
pub use pdfimport::{LoadOptions, page_document};
|
||||
pub(crate) use psdlayers::import_active as psd_layers;
|
||||
pub use psdlayers::{PsdInfo, info as psd_info};
|
||||
pub(crate) use psdslices::over as psd_slices;
|
||||
pub(crate) use save::job_for;
|
||||
pub(crate) use save::save as save_document;
|
||||
pub use save::{
|
||||
@@ -240,6 +244,8 @@ mod tests_psd;
|
||||
mod tests_psdlayers;
|
||||
#[cfg(test)]
|
||||
mod tests_psdread;
|
||||
#[cfg(test)]
|
||||
mod tests_psdslices;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_heifread;
|
||||
|
||||
@@ -149,7 +149,9 @@ pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read
|
||||
/// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for
|
||||
/// the image, for the images of the art each file draws (with chosen artboards, the art over each
|
||||
/// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask
|
||||
/// and symbol editing layers never) and of the symbols, patterns and brushes that art uses; with
|
||||
/// and symbol editing layers never, opacity masks not with SVG Tiny 1.2, and objects with effects
|
||||
/// SVG has no filters for as the images the file draws of them), of the art the file draws for each
|
||||
/// placed document, and of the symbols, patterns and brushes that art uses; with
|
||||
/// Preserve Editing Capabilities, the native document the file carries names every linked file, the relative paths kept of them
|
||||
/// and each data set's image. The error names no file or folder.
|
||||
pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &vectorcraft_doc::Document, p: &Value) -> Result<()> {
|
||||
@@ -162,21 +164,27 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu
|
||||
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
// Options that don't read as the encoder's choices count as Link, Preserve Editing and hidden
|
||||
// layers kept: the encoder refuses them anyway.
|
||||
let (link, preserve, hidden) = match super::svg::options_map(p) {
|
||||
// Options that don't read as the encoder's choices count as Link, Preserve Editing, hidden
|
||||
// layers kept and SVG 1.1: the encoder refuses them anyway.
|
||||
let (link, preserve, hidden, tiny) = match super::svg::options_map(p) {
|
||||
Ok(m) => {
|
||||
let on = |k: &str| m.get(k).is_some_and(|v| v.as_bool() != Some(false));
|
||||
(m.get("images").is_some_and(|v| v.as_str() != Some("embed")), on("preserveEditing"), on("hiddenLayers"))
|
||||
let tiny = m.get("profile").and_then(Value::as_str) == Some("tiny12");
|
||||
(m.get("images").is_some_and(|v| v.as_str() != Some("embed")), on("preserveEditing"), on("hiddenLayers"), tiny)
|
||||
}
|
||||
Err(_) => (true, true, true),
|
||||
Err(_) => (true, true, true, false),
|
||||
};
|
||||
// The opacity-mask and symbol editing layers are never written.
|
||||
let d = &*d.without_edit_modes();
|
||||
let names = |d: &vectorcraft_doc::Document| crate::cmd::links::svg_names_hidden_image(d, base, link, hidden);
|
||||
if preserve && crate::cmd::links::names_hidden_file(d, base)
|
||||
|| names(d) && super::svg::drawn(d, p).is_none_or(|files| files.iter().any(|f| names(f)))
|
||||
{
|
||||
let names = |d: &vectorcraft_doc::Document| crate::cmd::links::svg_names_hidden_image(d, base, link, hidden, tiny);
|
||||
// The SVG draws the objects with effects it has no filters for as images of them, as the
|
||||
// encoder and the clipboard prepare them.
|
||||
let drawing_names = || {
|
||||
let flat = crate::cmd::rasterfx::flatten_pixel_effects_for(d, !tiny);
|
||||
let d = flat.as_ref().unwrap_or(d);
|
||||
names(d) && super::svg::drawn(d, p).is_none_or(|files| files.iter().any(|f| names(f)))
|
||||
};
|
||||
if preserve && crate::cmd::links::names_hidden_file(d, base) || names(d) && drawing_names() {
|
||||
return Err(bad(cmd, IMAGE_OUTSIDE));
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::access::file_list;
|
||||
use super::formats::formats;
|
||||
use super::{CommandSpec, action_batch, always, batch, cmd, export, has_doc, has_selection, load, pdfimport, save, screens};
|
||||
use super::{CommandSpec, action_batch, always, batch, cmd, export, has_doc, has_selection, load, pdfimport, psdlayers, save, screens};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Open Document",
|
||||
[],
|
||||
None,
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.p
Line truncated
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG
Line truncated
|
||||
always,
|
||||
load::open
|
||||
),
|
||||
@@ -139,6 +139,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
pdfimport::pdf_info
|
||||
),
|
||||
cmd!(
|
||||
query "document.psdInfo",
|
||||
"PSD Info",
|
||||
[],
|
||||
None,
|
||||
"{path} or {name?, dataBase64} what a PSD or PSB file holds, read from its header, slices and layer records without decoding pixels → {format: psd|psb, width, height (the canvas, px), layers (group markers not counted), hiddenLayers (the hidden ones among them), groups, slices (those importSlices brings in; 0 when the file has none or they can't be read)}; a file without layer records, or whose layer records can't be read, has layers: 0 and opens and places as its merged image; a file that is not a PSD or PSB file is an error",
|
||||
always,
|
||||
psdlayers::psd_info
|
||||
),
|
||||
cmd!(
|
||||
"document.exportForOffice",
|
||||
"Save for Office Documents…",
|
||||
|
||||
@@ -528,17 +528,26 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
}
|
||||
// A PSD or PSB file's layers become layers (`layers`, default on); without layers, or with
|
||||
// `layers: false`, its merged image opens. Layers that can't be read leave the merged image.
|
||||
"psd" | "psb" if opts.layers => {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
match super::psdlayers::import(bytes, opts.hidden_layers, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)) {
|
||||
Ok(Some((doc, warnings))) => (doc, warnings, false),
|
||||
Ok(None) => (raster_doc(&title, bytes)?, vec![], false),
|
||||
Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false),
|
||||
}
|
||||
}
|
||||
"psd" | "psb" if opts.layers => match super::psdlayers::import_active(bytes, opts.hidden_layers) {
|
||||
Ok(Some((doc, warnings))) => (doc, warnings, false),
|
||||
Ok(None) => (raster_doc(&title, bytes)?, vec![], false),
|
||||
Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false),
|
||||
},
|
||||
_ if format.raster => (raster_doc(&title, bytes)?, vec![], false),
|
||||
_ => return Err(err(format!("{} files can't be opened yet", format.label))),
|
||||
};
|
||||
// A PSD or PSB file's slices become user slices over its canvas (`importSlices`, default on),
|
||||
// whether its layers or its merged image came in.
|
||||
if matches!(format.id, "psd" | "psb")
|
||||
&& opts.import_slices
|
||||
&& let Some(canvas) = doc.artboards.first().map(|a| a.rect)
|
||||
{
|
||||
let (slices, notes) = super::psd_slices(bytes, canvas);
|
||||
for (rect, options) in slices {
|
||||
crate::cmd::slices::add_slice(&mut doc, rect, options);
|
||||
}
|
||||
warnings.extend(notes);
|
||||
}
|
||||
// A PDF, `.ai` or `.ait` read from its pages or its editing copy, not restored from the document
|
||||
// it carries, opens with the File Info it gives (a PostScript `.ai` gives none).
|
||||
if matches!(format.id, "pdf" | "ai" | "ait")
|
||||
@@ -885,12 +894,19 @@ pub(crate) fn too_large_note(bytes: &[u8]) -> Option<String> {
|
||||
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
|
||||
return Some(format!("an image of {w} × {h} pixels is too large to draw"));
|
||||
}
|
||||
let d = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?;
|
||||
let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
|
||||
let format = reader.format()?;
|
||||
let d = reader.into_decoder().ok()?;
|
||||
let (w, h) = d.dimensions();
|
||||
// The allowance also counts the pixels as RGBA: an image of fewer than 4 bytes a pixel (gray,
|
||||
// gray with alpha, RGB) takes more than the decoder counts (#1717).
|
||||
let rgba_over = u64::from(w) * u64::from(h) > MAX_RASTER_ALLOC / 4;
|
||||
(rgba_over || d.total_bytes() > MAX_RASTER_ALLOC).then(|| format!("an image of {w} × {h} pixels is too large to draw"))
|
||||
let samples_over = d.total_bytes() > MAX_RASTER_ALLOC;
|
||||
// The renderer can stream a non-interlaced PNG a row at a time when those buffers fit. Its
|
||||
// full decoded byte count can exceed the allowance even though drawing it at native size is
|
||||
// safe; use the renderer's decision for that case instead of warning from total_bytes alone.
|
||||
let png_streams_at_size = samples_over && format == image::ImageFormat::Png && vectorcraft_render::reduced_size(bytes) == Some((w, h));
|
||||
(rgba_over || (samples_over && !png_streams_at_size)).then(|| format!("an image of {w} × {h} pixels is too large to draw"))
|
||||
}
|
||||
|
||||
/// What Open, Place and the Links panel say of encoded image `bytes` that [`too_large_note`] is
|
||||
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export PDF",
|
||||
[],
|
||||
None,
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destinatio
Line truncated
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destinatio
Line truncated
|
||||
has_doc,
|
||||
export_pdf
|
||||
),
|
||||
|
||||
@@ -36,6 +36,8 @@ pub struct LoadOptions {
|
||||
pub layers: bool,
|
||||
/// A PSD or PSB file's hidden layers come in, hidden (`hiddenLayers`; else they are left out).
|
||||
pub hidden_layers: bool,
|
||||
/// A PSD or PSB file's slices become user slices (`importSlices`; else they are left out).
|
||||
pub import_slices: bool,
|
||||
/// How a DXF drawing comes in (the `dxf` param, see [`super::dxfimport`]).
|
||||
pub dxf: vectorcraft_cad::ImportOptions,
|
||||
/// An Illustrator EPS or `.ai` that carries the editing copy of its art opens from it (its
|
||||
@@ -67,6 +69,7 @@ impl Default for LoadOptions {
|
||||
text_as: TextAs::default(),
|
||||
layers: true,
|
||||
hidden_layers: false,
|
||||
import_slices: true,
|
||||
dxf: Default::default(),
|
||||
editing_data: true,
|
||||
trust_editing_data: false,
|
||||
@@ -81,7 +84,7 @@ impl LoadOptions {
|
||||
/// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when
|
||||
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
|
||||
/// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false),
|
||||
/// `editingData` (true | false | `always`),
|
||||
/// `importSlices` (true | false), `editingData` (true | false | `always`),
|
||||
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]), `linkPages` (true |
|
||||
/// false) and `dxf` (the DXF import options).
|
||||
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
|
||||
@@ -111,6 +114,10 @@ impl LoadOptions {
|
||||
None => false,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "hiddenLayers must be true or false"))?,
|
||||
};
|
||||
let import_slices = match p.get("importSlices").filter(|v| !v.is_null()) {
|
||||
None => true,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "importSlices must be true or false"))?,
|
||||
};
|
||||
let (editing_data, trust_editing_data) = match p.get("editingData").filter(|v| !v.is_null()) {
|
||||
None => (true, false),
|
||||
Some(Value::String(s)) if s.eq_ignore_ascii_case("always") => (true, true),
|
||||
@@ -137,6 +144,7 @@ impl LoadOptions {
|
||||
text_as,
|
||||
layers,
|
||||
hidden_layers,
|
||||
import_slices,
|
||||
dxf,
|
||||
editing_data,
|
||||
trust_editing_data,
|
||||
|
||||
@@ -43,6 +43,7 @@ use std::cell::Cell;
|
||||
use std::sync::Arc;
|
||||
|
||||
use image::RgbaImage;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::BlendMode;
|
||||
use vectorcraft_color::blend::{blend_rgb, composite};
|
||||
use vectorcraft_color::cms::{Lab, lab::lab_to_srgb};
|
||||
@@ -51,6 +52,7 @@ use vectorcraft_geom::Affine;
|
||||
|
||||
use super::load::{RasterImage, as_png};
|
||||
use super::psdread::{Header, Reader, byte, header, layer_channel, layer_info, long_key, row_bytes, sample, to_rgb};
|
||||
use crate::cmd::Session;
|
||||
use crate::cmd::place::text::mac_roman;
|
||||
|
||||
/// Most layer groups inside one another.
|
||||
@@ -1527,3 +1529,65 @@ pub(super) fn import(
|
||||
doc.limit_depth_noting(&mut warnings);
|
||||
Ok(Some((doc, warnings)))
|
||||
}
|
||||
|
||||
/// [`import`] within the memory allowed for one image, CMYK converted with the active color
|
||||
/// settings: what `document.open` and `file.place` read a PSD or PSB file's layers with.
|
||||
pub(crate) fn import_active(bytes: &[u8], hidden: bool) -> Result<Option<(Document, Vec<String>)>, String> {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
import(bytes, hidden, super::MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false))
|
||||
}
|
||||
|
||||
/// What a PSD or PSB file holds (`document.psdInfo`, the PSD Import Options dialog).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct PsdInfo {
|
||||
/// The large document format.
|
||||
pub psb: bool,
|
||||
/// The canvas, in pixels.
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// The layers, group markers left out.
|
||||
pub layers: usize,
|
||||
/// The layers among them that are hidden.
|
||||
pub hidden: usize,
|
||||
/// The layer groups.
|
||||
pub groups: usize,
|
||||
/// The slices that come in with `importSlices` (those generated automatically, and those
|
||||
/// outside the canvas, left out).
|
||||
pub slices: usize,
|
||||
}
|
||||
|
||||
/// What PSD or PSB file `bytes` holds, read from its header, its slices and its layer records
|
||||
/// without decoding any pixels. A file without layer records, or whose layer records can't be read, has no layers: it
|
||||
/// opens and places as its merged image.
|
||||
pub fn info(bytes: &[u8]) -> Result<PsdInfo, String> {
|
||||
let mut r = Reader::new(bytes);
|
||||
let h = header(&mut r)?;
|
||||
let records = layer_info(h.layers, h.psb).filter(|info| info.len() > 2).and_then(|info| records(info, h.psb).ok()).unwrap_or_default();
|
||||
let layers = records.iter().filter(|r| r.divider == 0);
|
||||
Ok(PsdInfo {
|
||||
psb: h.psb,
|
||||
width: h.width,
|
||||
height: h.height,
|
||||
layers: layers.clone().count(),
|
||||
hidden: layers.filter(|r| r.hidden).count(),
|
||||
groups: records.iter().filter(|r| matches!(r.divider, 1 | 2)).count(),
|
||||
slices: super::psdslices::count(bytes),
|
||||
})
|
||||
}
|
||||
|
||||
const INFO: &str = "document.psdInfo";
|
||||
|
||||
/// `document.psdInfo`.
|
||||
pub(super) fn psd_info(_: &mut Session, p: &Value) -> crate::cmd::Result<Value> {
|
||||
let bytes = super::source(p, INFO)?.bytes;
|
||||
let i = info(&bytes).map_err(super::load::err)?;
|
||||
Ok(json!({
|
||||
"format": if i.psb { "psb" } else { "psd" },
|
||||
"width": i.width,
|
||||
"height": i.height,
|
||||
"layers": i.layers,
|
||||
"hiddenLayers": i.hidden,
|
||||
"groups": i.groups,
|
||||
"slices": i.slices,
|
||||
}))
|
||||
}
|
||||
@@ -105,7 +105,7 @@ pub(super) struct Header<'a> {
|
||||
/// Colour mode data: an indexed image's palette (256 reds, then greens, then blues).
|
||||
palette: &'a [u8],
|
||||
/// The image resources.
|
||||
resources: &'a [u8],
|
||||
pub(super) resources: &'a [u8],
|
||||
/// The layer and mask information.
|
||||
pub(super) layers: &'a [u8],
|
||||
}
|
||||
@@ -172,25 +172,50 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
|
||||
/// The image resource blocks of `resources`, in file order: each one's id, name (the bytes of its
|
||||
/// Pascal string) and data. Stops at the first block that is cut short. With `signed`, only the
|
||||
/// blocks whose signature is `8BIM` are given.
|
||||
fn resources(resources: &[u8], signed: bool) -> impl Iterator<Item = (u16, &[u8], &[u8])> {
|
||||
pub(super) fn resources(resources: &[u8], signed: bool) -> impl Iterator<Item = (u16, &[u8], &[u8])> {
|
||||
let mut r = Reader::new(resources);
|
||||
std::iter::from_fn(move || {
|
||||
if r.rest().is_empty() {
|
||||
return None;
|
||||
std::iter::from_fn(move || if r.rest().is_empty() { None } else { block(&mut r).ok() })
|
||||
.filter(move |(ours, ..)| *ours || !signed)
|
||||
.map(|(_, id, name, data)| (id, name, data))
|
||||
}
|
||||
|
||||
/// The data of the first `8BIM` image resource block `id` of `resources`. `None` when there is
|
||||
/// none before the blocks end or before a block that is cut short ahead of it. An error when
|
||||
/// that block itself is cut short.
|
||||
pub(super) fn resource(resources: &[u8], id: u16) -> Result<Option<&[u8]>, String> {
|
||||
let mut r = Reader::new(resources);
|
||||
while !r.rest().is_empty() {
|
||||
match block(&mut r) {
|
||||
Ok((true, i, _, data)) if i == id => return Ok(Some(data)),
|
||||
Ok(_) => {}
|
||||
Err(Some((true, i))) if i == id => return Err(TRUNCATED.into()),
|
||||
Err(_) => return Ok(None),
|
||||
}
|
||||
let ours = r.take(4).ok()? == b"8BIM";
|
||||
let id = r.u16().ok()?;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// An image resource block: whether its signature is `8BIM`, its id, its name (the bytes of its
|
||||
/// Pascal string) and its data.
|
||||
type Block<'a> = (bool, u16, &'a [u8], &'a [u8]);
|
||||
|
||||
/// The image resource block that `r` starts with. When it is cut short, the error gives whether
|
||||
/// its signature is `8BIM` and its id, when those were read.
|
||||
fn block<'a>(r: &mut Reader<'a>) -> Result<Block<'a>, Option<(bool, u16)>> {
|
||||
let ours = r.take(4).map_err(|_| None)? == b"8BIM";
|
||||
let id = r.u16().map_err(|_| None)?;
|
||||
let mut rest = || -> Result<(&'a [u8], &'a [u8]), String> {
|
||||
// A Pascal string padded to an even size, length byte included.
|
||||
let len = usize::from(r.u8().ok()?);
|
||||
let name = r.take(len).ok()?;
|
||||
r.take((len + 1) % 2).ok()?;
|
||||
let size = usize::try_from(r.u32().ok()?).ok()?;
|
||||
let data = r.take(size).ok()?;
|
||||
r.take(size % 2).ok()?;
|
||||
Some((ours, id, name, data))
|
||||
})
|
||||
.filter(move |(ours, ..)| *ours || !signed)
|
||||
.map(|(_, id, name, data)| (id, name, data))
|
||||
let len = usize::from(r.u8()?);
|
||||
let name = r.take(len)?;
|
||||
r.take((len + 1) % 2)?;
|
||||
let size = usize::try_from(r.u32()?).map_err(|_| TRUNCATED.to_string())?;
|
||||
let data = r.take(size)?;
|
||||
r.take(size % 2)?;
|
||||
Ok((name, data))
|
||||
};
|
||||
let (name, data) = rest().map_err(|_| Some((ours, id)))?;
|
||||
Ok((ours, id, name, data))
|
||||
}
|
||||
|
||||
/// The resource naming the document's clipping path.
|
||||
|
||||
@@ -0,0 +1,446 @@
|
||||
//! The slices a Photoshop document (PSD or PSB) stores, for `document.open` and `file.place`
|
||||
//! with `importSlices`: image resource 1050, read from the "Slices resource format" of Adobe's
|
||||
//! public Photoshop File Formats Specification
|
||||
//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). Version 6 stores the slices
|
||||
//! as records; versions 7 and 8 store them in a descriptor. The descriptor's keys, and the meaning
|
||||
//! of the origin, type and background values, are read as the MIT-licensed ag-psd reads them
|
||||
//! (<https://github.com/Agamnentzar/ag-psd>, `src/imageResources.ts` and `src/descriptor.ts`),
|
||||
//! which agrees with psd.rb (<https://github.com/layervault/psd.rb>,
|
||||
//! `lib/psd/resources/slices.rb`) on the keys both read.
|
||||
//!
|
||||
//! A slice the file marks as generated automatically is left out: the document lays out its own
|
||||
//! auto slices around the others. A slice that follows a layer comes in as a user slice over the
|
||||
//! rectangle the file stores for it. Each slice keeps its name, its type (Image or No Image), its
|
||||
//! link, target, message, alternative text, cell text and background color; text alignment isn't
|
||||
//! read. The file is untrusted: every read is checked, and the slice count, the strings and the
|
||||
//! descriptor's nesting and item count are capped.
|
||||
|
||||
use vectorcraft_doc::{SliceKind, SliceOptions};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::psdread::{Reader, TRUNCATED, header, resource};
|
||||
|
||||
/// The image resource that holds the slices.
|
||||
const SLICES: u16 = 1050;
|
||||
|
||||
/// The most slices one file brings in.
|
||||
const MAX_SLICES: usize = 10_000;
|
||||
|
||||
/// The deepest descriptor objects and lists nest.
|
||||
const MAX_DEPTH: usize = 16;
|
||||
|
||||
/// The most values the descriptors of one slices resource hold together, nested ones included.
|
||||
const MAX_VALUES: usize = 200_000;
|
||||
|
||||
/// The error of descriptors that hold more than [`MAX_VALUES`].
|
||||
const TOO_MANY_VALUES: &str = "the slices' descriptor holds too many values";
|
||||
|
||||
/// One slice as the file stores it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct PsdSlice {
|
||||
/// Left, top, right and bottom, in the canvas's pixels.
|
||||
rect: [i64; 4],
|
||||
options: SliceOptions,
|
||||
}
|
||||
|
||||
/// The slices a file stores, those generated automatically left out, and its canvas.
|
||||
struct Stored {
|
||||
slices: Vec<PsdSlice>,
|
||||
/// The canvas's width and height, in pixels.
|
||||
size: (u32, u32),
|
||||
}
|
||||
|
||||
/// The slices PSD or PSB file `bytes` stores. `None` when it stores none (no `8BIM` resource 1050
|
||||
/// before the image resources end, or before a block that is cut short ahead of it). An error when
|
||||
/// the file isn't a PSD or PSB file, resource 1050 is cut short, or its slices can't be read.
|
||||
fn read(bytes: &[u8]) -> Result<Option<Stored>, String> {
|
||||
let mut r = Reader::new(bytes);
|
||||
let h = header(&mut r)?;
|
||||
let Some(data) = resource(h.resources, SLICES)? else { return Ok(None) };
|
||||
Ok(Some(Stored { slices: decode(data)?, size: (h.width, h.height) }))
|
||||
}
|
||||
|
||||
/// The slices of resource 1050's `data`.
|
||||
fn decode(data: &[u8]) -> Result<Vec<PsdSlice>, String> {
|
||||
let mut r = Reader::new(data);
|
||||
// The values every descriptor of the resource may hold together.
|
||||
let mut budget = MAX_VALUES;
|
||||
match r.u32()? {
|
||||
6 => version_6(&mut r, &mut budget),
|
||||
7 | 8 => {
|
||||
if r.u32()? != 16 {
|
||||
return Err("the slices' descriptor has a version other than 16".into());
|
||||
}
|
||||
let d = descriptor(&mut r, 0, &mut budget)?;
|
||||
from_descriptor(&d)
|
||||
}
|
||||
v => Err(format!("the slices are stored in version {v}, which isn't read")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Version 6: the bounds of all the slices, the group's name, the count, then each slice's record.
|
||||
/// The descriptors that follow the records spend one `budget` of values between them.
|
||||
fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result<Vec<PsdSlice>, String> {
|
||||
r.take(16)?;
|
||||
unicode(r)?;
|
||||
let count = r.u32()? as usize;
|
||||
if count > MAX_SLICES {
|
||||
return Err(format!("the file has {count} slices, more than the {MAX_SLICES} read"));
|
||||
}
|
||||
let one_after_another = records_one_after_another(Reader::new(r.rest()), count, *budget);
|
||||
let mut out = vec![];
|
||||
for i in 0..count {
|
||||
// The ID and group ID.
|
||||
r.take(8)?;
|
||||
let origin = r.u32()?;
|
||||
// A slice that follows a layer gives the layer's ID.
|
||||
if origin == 1 {
|
||||
r.take(4)?;
|
||||
}
|
||||
let name = unicode(r)?;
|
||||
let kind = if r.u32()? == 0 { SliceKind::NoImage } else { SliceKind::Image };
|
||||
let mut rect = [0i64; 4];
|
||||
for v in &mut rect {
|
||||
*v = i64::from(r.u32()? as i32);
|
||||
}
|
||||
let (url, target, message, alt) = (unicode(r)?, unicode(r)?, unicode(r)?, unicode(r)?);
|
||||
let html = r.u8()? != 0;
|
||||
let cell = unicode(r)?;
|
||||
// The horizontal and vertical alignment.
|
||||
r.take(8)?;
|
||||
let [a, red, green, blue] = r.array::<4>()?;
|
||||
let background = if a == 0 && red == 0 && green == 0 && blue == 0 {
|
||||
String::new()
|
||||
} else if a == 0 {
|
||||
"matte".into()
|
||||
} else {
|
||||
format!("#{red:02x}{green:02x}{blue:02x}")
|
||||
};
|
||||
// Photoshop 7 and later may follow a record with a descriptor (version 16); a record that
|
||||
// doesn't start one is the next slice. When the records follow one another, only the
|
||||
// last one may be followed by a descriptor. A descriptor read that uses up the budget is
|
||||
// an error.
|
||||
if (!one_after_another || i + 1 == count) && r.rest().starts_with(&16u32.to_be_bytes()) {
|
||||
let mut ahead = Reader::new(r.rest());
|
||||
ahead.u32()?;
|
||||
match descriptor(&mut ahead, 0, budget) {
|
||||
Ok(_) => {
|
||||
let used = r.rest().len() - ahead.rest().len();
|
||||
r.take(used)?;
|
||||
}
|
||||
Err(e) if e == TOO_MANY_VALUES => return Err(e),
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
// Origin 0 is a slice generated automatically.
|
||||
if origin != 0 {
|
||||
let options = SliceOptions { kind, name, url, target, message, alt, text: cell_text(cell, html), background, ..Default::default() };
|
||||
out.push(PsdSlice { rect, options: for_kind(options) });
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Whether `r` holds `count` version 6 records one after another, followed by nothing or by one
|
||||
/// descriptor (version 16) that reads within `budget`, as ag-psd writes them. A record whose ID is
|
||||
/// 16 then isn't taken for a descriptor. Otherwise each record may be followed by a descriptor.
|
||||
fn records_one_after_another(mut r: Reader<'_>, count: usize, mut budget: usize) -> bool {
|
||||
if !(0..count).all(|_| skip_record(&mut r).is_ok()) {
|
||||
return false;
|
||||
}
|
||||
r.rest().is_empty() || (r.rest().starts_with(&16u32.to_be_bytes()) && r.u32().is_ok() && descriptor(&mut r, 0, &mut budget).is_ok())
|
||||
}
|
||||
|
||||
/// Reads past the version 6 record `r` starts with, in the layout [`version_6`] reads. Its strings
|
||||
/// are checked and read past without being decoded.
|
||||
fn skip_record(r: &mut Reader<'_>) -> Result<(), String> {
|
||||
// The ID and group ID.
|
||||
r.take(8)?;
|
||||
if r.u32()? == 1 {
|
||||
r.take(4)?;
|
||||
}
|
||||
units(r)?;
|
||||
// The type and the rectangle.
|
||||
r.take(20)?;
|
||||
for _ in 0..4 {
|
||||
units(r)?;
|
||||
}
|
||||
r.take(1)?;
|
||||
units(r)?;
|
||||
// The alignments and the background color.
|
||||
r.take(12)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Versions 7 and 8: the descriptor's `slices` list, each slice an object.
|
||||
fn from_descriptor(d: &[(String, Value)]) -> Result<Vec<PsdSlice>, String> {
|
||||
let Some(Value::List(list)) = field(d, "slices") else { return Err("the slices' descriptor has no list of slices".into()) };
|
||||
if list.len() > MAX_SLICES {
|
||||
return Err(format!("the file has {} slices, more than the {MAX_SLICES} read", list.len()));
|
||||
}
|
||||
let mut out = vec![];
|
||||
for s in list {
|
||||
let Value::Object(s) = s else { return Err("the slices' descriptor lists something other than a slice".into()) };
|
||||
if matches!(field(s, "origin"), Some(Value::Enum(_, v)) if v == "autoGenerated") {
|
||||
continue;
|
||||
}
|
||||
let Some(Value::Object(b)) = field(s, "bounds") else { return Err("a slice in the slices' descriptor has no bounds".into()) };
|
||||
let edge = |k: &str| number(field(b, k)).ok_or_else(|| "a slice's bounds in the slices' descriptor aren't numbers".to_string());
|
||||
let rect = [edge("Left")?, edge("Top ")?, edge("Rght")?, edge("Btom")?];
|
||||
let text = |k: &str| match field(s, k) {
|
||||
Some(Value::Text(t)) => t.clone(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let kind = if matches!(field(s, "Type"), Some(Value::Enum(_, v)) if v == "noImage") { SliceKind::NoImage } else { SliceKind::Image };
|
||||
let html = matches!(field(s, "cellTextIsHTML"), Some(Value::Bool(true)));
|
||||
let background = match field(s, "bgColorType") {
|
||||
Some(Value::Enum(_, v)) if v == "matte" => "matte".into(),
|
||||
Some(Value::Enum(_, v)) if v == "Clr " => match field(s, "bgColor") {
|
||||
Some(Value::Object(c)) => {
|
||||
let channel = |k: &str| number(field(c, k)).map(|v| v.clamp(0, 255));
|
||||
match (channel("Rd "), channel("Grn "), channel("Bl ")) {
|
||||
(Some(r), Some(g), Some(b)) => format!("#{r:02x}{g:02x}{b:02x}"),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
_ => String::new(),
|
||||
},
|
||||
_ => String::new(),
|
||||
};
|
||||
let options = SliceOptions {
|
||||
kind,
|
||||
name: text("Nm "),
|
||||
url: text("url"),
|
||||
target: text("null"),
|
||||
message: text("Msge"),
|
||||
alt: text("altTag"),
|
||||
text: cell_text(text("cellText"), html),
|
||||
background,
|
||||
..Default::default()
|
||||
};
|
||||
out.push(PsdSlice { rect, options: for_kind(options) });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `o` with only the options of its slice type: an Image slice's cell text isn't shown, and a No
|
||||
/// Image slice has no link, target, message or alternative text.
|
||||
fn for_kind(mut o: SliceOptions) -> SliceOptions {
|
||||
if o.kind == SliceKind::Image {
|
||||
o.text.clear();
|
||||
} else {
|
||||
for s in [&mut o.url, &mut o.target, &mut o.message, &mut o.alt] {
|
||||
s.clear();
|
||||
}
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
/// A cell's text as the HTML a No Image slice shows: plain text has `&`, `<` and `>` escaped.
|
||||
fn cell_text(text: String, html: bool) -> String {
|
||||
if html { text } else { text.replace('&', "&").replace('<', "<").replace('>', ">") }
|
||||
}
|
||||
|
||||
/// The longest text one string, key or class ID holds (UTF-16 units or bytes).
|
||||
const MAX_TEXT: usize = 65_536;
|
||||
|
||||
/// An error unless `n`, the length a string or ID declares, is at most [`MAX_TEXT`].
|
||||
fn text_len(n: usize) -> Result<usize, String> {
|
||||
if n > MAX_TEXT {
|
||||
return Err(format!("a text in the slices has more than the {MAX_TEXT} characters read"));
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// A Unicode string: a count of UTF-16 units, then the units; trailing NULs dropped.
|
||||
fn unicode(r: &mut Reader<'_>) -> Result<String, String> {
|
||||
let bytes = units(r)?;
|
||||
let units: Vec<u16> = bytes.as_chunks::<2>().0.iter().map(|u| u16::from_be_bytes(*u)).collect();
|
||||
Ok(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string())
|
||||
}
|
||||
|
||||
/// A Unicode string's units, as bytes: a count of UTF-16 units, then the units.
|
||||
fn units<'a>(r: &mut Reader<'a>) -> Result<&'a [u8], String> {
|
||||
let n = text_len(r.u32()? as usize)?;
|
||||
r.take(n.checked_mul(2).ok_or(TRUNCATED)?)
|
||||
}
|
||||
|
||||
/// A descriptor's value, as far as the slices need it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Value {
|
||||
Long(i32),
|
||||
Double(f64),
|
||||
Bool(bool),
|
||||
Text(String),
|
||||
/// An enumeration's type and value.
|
||||
Enum(String, String),
|
||||
Object(Vec<(String, Value)>),
|
||||
List(Vec<Value>),
|
||||
/// A value of another type, read past.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// The value with key `key`.
|
||||
fn field<'a>(d: &'a [(String, Value)], key: &str) -> Option<&'a Value> {
|
||||
d.iter().find(|(k, _)| k == key).map(|(_, v)| v)
|
||||
}
|
||||
|
||||
/// A whole number: a long, or a finite double rounded.
|
||||
fn number(v: Option<&Value>) -> Option<i64> {
|
||||
match v? {
|
||||
Value::Long(n) => Some(i64::from(*n)),
|
||||
Value::Double(d) if d.is_finite() && d.abs() < 1e12 => Some(d.round() as i64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A key or class ID: a length, then that many characters, or four when the length is 0.
|
||||
fn id(r: &mut Reader<'_>) -> Result<String, String> {
|
||||
let n = text_len(r.u32()? as usize)?;
|
||||
let b = r.take(if n == 0 { 4 } else { n })?;
|
||||
Ok(String::from_utf8_lossy(b).into_owned())
|
||||
}
|
||||
|
||||
/// A class: its Unicode name, then its ID.
|
||||
fn class(r: &mut Reader<'_>) -> Result<(), String> {
|
||||
unicode(r)?;
|
||||
id(r)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A descriptor: its class, the count of its items, then each item's key, type and value.
|
||||
fn descriptor(r: &mut Reader<'_>, depth: usize, budget: &mut usize) -> Result<Vec<(String, Value)>, String> {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err("the slices' descriptor nests too deep".into());
|
||||
}
|
||||
class(r)?;
|
||||
let count = r.u32()? as usize;
|
||||
let mut out = vec![];
|
||||
for _ in 0..count {
|
||||
let key = id(r)?;
|
||||
let kind = r.array::<4>()?;
|
||||
out.push((key, value(r, &kind, depth, budget)?));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A value of type `kind`.
|
||||
fn value(r: &mut Reader<'_>, kind: &[u8; 4], depth: usize, budget: &mut usize) -> Result<Value, String> {
|
||||
*budget = budget.checked_sub(1).ok_or(TOO_MANY_VALUES)?;
|
||||
Ok(match kind {
|
||||
b"long" => Value::Long(r.u32()? as i32),
|
||||
b"doub" => Value::Double(f64::from_be_bytes(r.array()?)),
|
||||
b"UntF" => {
|
||||
r.take(4)?;
|
||||
Value::Double(f64::from_be_bytes(r.array()?))
|
||||
}
|
||||
b"UnFl" => {
|
||||
r.take(4)?;
|
||||
Value::Double(f64::from(f32::from_be_bytes(r.array()?)))
|
||||
}
|
||||
b"bool" => Value::Bool(r.u8()? != 0),
|
||||
b"TEXT" => Value::Text(unicode(r)?),
|
||||
b"enum" => Value::Enum(id(r)?, id(r)?),
|
||||
b"Objc" | b"GlbO" => Value::Object(descriptor(r, depth + 1, budget)?),
|
||||
b"VlLs" => {
|
||||
if depth >= MAX_DEPTH {
|
||||
return Err("the slices' descriptor nests too deep".into());
|
||||
}
|
||||
let count = r.u32()? as usize;
|
||||
let mut items = vec![];
|
||||
for _ in 0..count {
|
||||
let kind = r.array::<4>()?;
|
||||
items.push(value(r, &kind, depth + 1, budget)?);
|
||||
}
|
||||
Value::List(items)
|
||||
}
|
||||
b"comp" => {
|
||||
r.take(8)?;
|
||||
Value::Other
|
||||
}
|
||||
b"type" | b"GlbC" => {
|
||||
class(r)?;
|
||||
Value::Other
|
||||
}
|
||||
b"tdta" | b"alis" => {
|
||||
let n = r.u32()? as usize;
|
||||
r.take(n)?;
|
||||
Value::Other
|
||||
}
|
||||
b"obj " => {
|
||||
let count = r.u32()? as usize;
|
||||
for _ in 0..count {
|
||||
*budget = budget.checked_sub(1).ok_or(TOO_MANY_VALUES)?;
|
||||
match &r.array::<4>()? {
|
||||
b"prop" => {
|
||||
class(r)?;
|
||||
id(r)?;
|
||||
}
|
||||
b"Clss" => class(r)?,
|
||||
b"Enmr" => {
|
||||
class(r)?;
|
||||
id(r)?;
|
||||
id(r)?;
|
||||
}
|
||||
b"rele" => {
|
||||
class(r)?;
|
||||
r.take(4)?;
|
||||
}
|
||||
b"Idnt" | b"indx" => {
|
||||
r.take(4)?;
|
||||
}
|
||||
b"name" => {
|
||||
class(r)?;
|
||||
unicode(r)?;
|
||||
}
|
||||
k => return Err(format!("the slices' descriptor has a reference of an unknown kind ({})", String::from_utf8_lossy(k))),
|
||||
}
|
||||
}
|
||||
Value::Other
|
||||
}
|
||||
k => return Err(format!("the slices' descriptor has a value of an unknown type ({})", String::from_utf8_lossy(k))),
|
||||
})
|
||||
}
|
||||
|
||||
/// The slices of PSD or PSB file `bytes` laid over `canvas`, the box its canvas takes (points),
|
||||
/// each clipped to the canvas, with warnings: for slices that lie wholly outside it or have no
|
||||
/// size, and for slices that can't be read (the file comes in without them). Empty, without a
|
||||
/// warning, when the file stores no slices.
|
||||
pub(crate) fn over(bytes: &[u8], canvas: Rect) -> (Vec<(Rect, SliceOptions)>, Vec<String>) {
|
||||
match read(bytes) {
|
||||
Ok(None) => (vec![], vec![]),
|
||||
Ok(Some(s)) => laid_over(&s.slices, s.size, canvas),
|
||||
Err(e) => (vec![], vec![format!("the slices can't be read ({e}) and were left out")]),
|
||||
}
|
||||
}
|
||||
|
||||
/// `slices` of a canvas of `size` pixels laid over `canvas` (points).
|
||||
fn laid_over(slices: &[PsdSlice], (w, h): (u32, u32), canvas: Rect) -> (Vec<(Rect, SliceOptions)>, Vec<String>) {
|
||||
let (sx, sy) = (canvas.width() / f64::from(w.max(1)), canvas.height() / f64::from(h.max(1)));
|
||||
let mut out = vec![];
|
||||
for s in slices {
|
||||
let [l, t, r, b] = s.rect;
|
||||
let (l, r) = (l.clamp(0, i64::from(w)), r.clamp(0, i64::from(w)));
|
||||
let (t, b) = (t.clamp(0, i64::from(h)), b.clamp(0, i64::from(h)));
|
||||
if l < r && t < b {
|
||||
let x = |v: i64| canvas.x0 + v as f64 * sx;
|
||||
let y = |v: i64| canvas.y0 + v as f64 * sy;
|
||||
out.push((Rect::new(x(l), y(t), x(r), y(b)), s.options.clone()));
|
||||
}
|
||||
}
|
||||
let warnings = match slices.len() - out.len() {
|
||||
0 => vec![],
|
||||
1 => vec!["1 slice lies outside the canvas or has no size and was left out".to_string()],
|
||||
n => vec![format!("{n} slices lie outside the canvas or have no size and were left out")],
|
||||
};
|
||||
(out, warnings)
|
||||
}
|
||||
|
||||
/// How many slices of PSD or PSB file `bytes` come in (`document.psdInfo`): 0 when it stores none
|
||||
/// or they can't be read.
|
||||
pub(crate) fn count(bytes: &[u8]) -> usize {
|
||||
match read(bytes) {
|
||||
Ok(Some(Stored { slices, size: (w, h) })) => laid_over(&slices, (w, h), Rect::new(0.0, 0.0, f64::from(w), f64::from(h))).0.len(),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
@@ -38,3 +38,19 @@ fn export_pdf_converts_colours_writes_the_output_intent_and_real_text() {
|
||||
let bad = s.execute("document.exportPdf", &json!({"output": {"conversion": "destination", "destination": "Missing"}}));
|
||||
assert!(matches!(bad, Err(crate::EngineError::BadParams { .. })), "{bad:?}");
|
||||
}
|
||||
|
||||
/// Over a saved preset whose Profiles setting is `none`, `"default"` leaves the setting unset,
|
||||
/// while `null` keeps the preset's value; an unknown value is a bad parameter.
|
||||
#[test]
|
||||
fn profiles_default_unsets_a_presets_profiles_setting() {
|
||||
use vectorcraft_pdf::{PdfPreset, PdfSettings, ProfileInclusion};
|
||||
let mut settings = PdfSettings::default();
|
||||
settings.output.profiles = Some(ProfileInclusion::None);
|
||||
let saved = [PdfPreset { name: "No profiles".into(), description: String::new(), settings }];
|
||||
let resolve = |output: Value| pdf::resolve("document.exportPdf", &json!({"preset": "No profiles", "output": output}), &saved);
|
||||
assert_eq!(resolve(json!({"profiles": "default"})).unwrap().output.profiles, None);
|
||||
assert_eq!(resolve(json!({"profiles": null})).unwrap().output.profiles, Some(ProfileInclusion::None));
|
||||
assert_eq!(resolve(json!({"profiles": "all"})).unwrap().output.profiles, Some(ProfileInclusion::All));
|
||||
let bad = resolve(json!({"profiles": "sometimes"}));
|
||||
assert!(matches!(bad, Err(crate::EngineError::BadParams { .. })), "{bad:?}");
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Opening PSD and PSB files with their layers as layers (`document.open`'s `layers` and
|
||||
//! `hiddenLayers`): names, visibility, opacity, blend modes, groups, layer masks, clipped layers
|
||||
//! and blend modes VectorCraft lacks merged, 16-bit and PSB files, VectorCraft's own PSD export
|
||||
//! read back, and damaged files read without a panic.
|
||||
//! read back, and damaged files read without a panic. Placing them with their layers as objects
|
||||
//! (`file.place`'s `layers` and `hiddenLayers`), and `document.psdInfo`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::BlendMode;
|
||||
@@ -967,10 +968,12 @@ fn damaged_layers_never_panic() {
|
||||
let mut f = good.clone();
|
||||
f[i] = v;
|
||||
let _ = psdlayers::import(&f, true, 1 << 30, cms);
|
||||
let _ = psdlayers::info(&f);
|
||||
}
|
||||
}
|
||||
for n in 0..good.len() {
|
||||
let _ = psdlayers::import(&good[..n], true, 1 << 30, cms);
|
||||
let _ = psdlayers::info(&good[..n]);
|
||||
}
|
||||
// A layer past the memory allowed is refused, not read.
|
||||
assert!(psdlayers::import(&good, true, 64, cms).unwrap_err().contains("too large"));
|
||||
@@ -1015,3 +1018,186 @@ fn merges_keep_pass_through_groups_blending_with_what_is_below() {
|
||||
assert!(px.iter().zip([75, 150, 38, 255]).all(|(&a, b)| a.abs_diff(b) <= 1), "{px:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `file.place` of `f` with `p` into a new 100 × 100 pt document, centred on (50, 50).
|
||||
fn place(f: &[u8], p: Value) -> (Session, crate::cmd::Result<Value>) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let r = s.execute("file.place", &merge(json!({"name": "layers.psd", "dataBase64": vectorcraft_format::base64_encode(f), "at": [50, 50]}), p));
|
||||
(s, r)
|
||||
}
|
||||
|
||||
/// The one object `file.place` placed.
|
||||
fn placed(s: &Session, r: &Value) -> Node {
|
||||
let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap());
|
||||
s.doc().unwrap().doc.node(id).unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placing_with_layers_embeds_the_layers_as_one_group() {
|
||||
let f = file(8, 8, &stack(), 8, false, false);
|
||||
let (mut s, r) = place(&f, json!({"layers": true}));
|
||||
let r = r.unwrap();
|
||||
assert_eq!((&r["format"], &r["linked"], &r["warnings"]), (&json!("psd"), &json!(false), &json!([HIDDEN_1])), "{r}");
|
||||
let g = placed(&s, &r);
|
||||
assert!(matches!(g.kind, NodeKind::Group { clip: false, .. }), "one group, unclipped: its layers lie on the canvas");
|
||||
assert_eq!(name(&g), "layers.psd");
|
||||
let kids = g.children().unwrap();
|
||||
assert_eq!(kids.iter().map(|c| name(c)).collect::<Vec<_>>(), ["Bottom", "Folder", "Screens", "Faded"], "bottom first");
|
||||
// A layer is its image, where the merged image would put it: the 8 pt canvas centred on (50, 50).
|
||||
let ((x, y), px) = pixels_of(&s, &kids[0]);
|
||||
assert_eq!(((x, y), px.dimensions(), px.get_pixel(3, 3).0), ((46.0, 46.0), (8, 8), [255, 0, 0, 255]));
|
||||
// A group is a group of its layers; a pass-through group isn't isolated, another mode's is.
|
||||
let folder = &kids[1];
|
||||
assert!(matches!(folder.kind, NodeKind::Group { .. }) && !folder.isolate && folder.blend == BlendMode::Normal);
|
||||
let inner = folder.children().unwrap();
|
||||
assert_eq!(inner.iter().map(|c| name(c)).collect::<Vec<_>>(), ["Inner A"], "the hidden layer is left out");
|
||||
assert!(matches!(inner[0].kind, NodeKind::Image(_)) && inner[0].blend == BlendMode::Multiply && (inner[0].opacity - 128.0 / 255.0).abs() < 1e-6);
|
||||
let screens = &kids[2];
|
||||
assert!(screens.isolate && screens.blend == BlendMode::Screen);
|
||||
let ((x, y), px) = pixels_of(&s, &screens.children().unwrap()[0]);
|
||||
assert_eq!(((x, y), px.get_pixel(0, 0).0), ((48.0, 48.0), [10, 20, 30, 128]));
|
||||
assert!((kids[3].opacity - 102.0 / 255.0).abs() < 1e-6, "fill opacity: {}", kids[3].opacity);
|
||||
// One undo step.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)));
|
||||
// Hidden layers come in hidden when asked for.
|
||||
let (s, r) = place(&f, json!({"layers": true, "hiddenLayers": true}));
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r["warnings"], json!([]), "{r}");
|
||||
let g = placed(&s, &r);
|
||||
let inner: Vec<(&str, bool)> = g.children().unwrap()[1].children().unwrap().iter().map(|c| (name(c), c.visible)).collect();
|
||||
assert_eq!(inner, [("Inner A", true), ("Inner B", false)]);
|
||||
// Without `layers`, the merged image, in the same box.
|
||||
let (s, r) = place(&f, json!({}));
|
||||
let r = r.unwrap();
|
||||
let flat = placed(&s, &r);
|
||||
let ((x, y), px) = pixels_of(&s, &flat);
|
||||
assert_eq!(((x, y), px.dimensions(), px.get_pixel(0, 0).0), ((46.0, 46.0), (8, 8), [128, 128, 128, 255]), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placed_layers_keep_their_masks_and_are_clipped_to_the_canvas() {
|
||||
let mut masked = layer("Masked", [0, 0, 8, 8], [255, 255, 255, 255]);
|
||||
masked.mask = Some(([2, 2, 4, 4], 0, 0, vec![255, 128, 0, 255]));
|
||||
let (s, r) = place(&file(8, 8, &[masked], 8, false, false), json!({"layers": true}));
|
||||
let g = placed(&s, &r.unwrap());
|
||||
let kids = g.children().unwrap();
|
||||
assert!(matches!(kids[0].kind, NodeKind::Image(_)), "the layer is its image");
|
||||
let m = kids[0].extras().mask.as_deref().expect("the layer mask as the image's opacity mask");
|
||||
let ((x, y), px) = pixels_of(&s, &m.art);
|
||||
assert_eq!(((x, y), px.dimensions(), m.clip), ((48.0, 48.0), (2, 2), true), "the mask moves with its layer");
|
||||
// A layer that reaches past the canvas: the group is clipped to the canvas, as the merged
|
||||
// image shows only the canvas.
|
||||
let over = layer("Over", [-2, -2, 6, 6], [0, 255, 0, 255]);
|
||||
let (s, r) = place(&file(8, 8, &[layer("Bottom", [0, 0, 8, 8], [255, 0, 0, 255]), over], 8, false, false), json!({"layers": true}));
|
||||
let r = r.unwrap();
|
||||
let g = placed(&s, &r);
|
||||
assert!(matches!(g.kind, NodeKind::Group { clip: true, .. }), "{r}");
|
||||
let kids = g.children().unwrap();
|
||||
let b = kids[0].geometric_bounds_with(&s.doc().unwrap().doc.symbol_boxes()).unwrap();
|
||||
assert!(matches!(kids[0].kind, NodeKind::Path { clipping: true, .. }));
|
||||
assert_eq!((b.x0, b.y0, b.x1, b.y1), (46.0, 46.0, 54.0, 54.0), "the clipping path is the canvas");
|
||||
assert_eq!(kids[1..].iter().map(|c| name(c)).collect::<Vec<_>>(), ["Bottom", "Over"]);
|
||||
assert_eq!(pixels_of(&s, &kids[2]).0, (44.0, 44.0));
|
||||
// A hidden layer that reaches past the canvas clips the group too, so showing it later draws
|
||||
// only the canvas. Left out, it doesn't.
|
||||
let mut hidden = layer("Hidden", [-2, -2, 6, 6], [0, 255, 0, 255]);
|
||||
hidden.hidden = true;
|
||||
let f = file(8, 8, &[layer("Bottom", [0, 0, 8, 8], [255, 0, 0, 255]), hidden], 8, false, false);
|
||||
let (s, r) = place(&f, json!({"layers": true, "hiddenLayers": true}));
|
||||
let r = r.unwrap();
|
||||
let g = placed(&s, &r);
|
||||
assert!(matches!(g.kind, NodeKind::Group { clip: true, .. }), "{r}");
|
||||
assert_eq!(g.children().unwrap()[1..].iter().map(|c| (name(c), c.visible)).collect::<Vec<_>>(), [("Bottom", true), ("Hidden", false)]);
|
||||
let (s, r) = place(&f, json!({"layers": true}));
|
||||
assert!(matches!(placed(&s, &r.unwrap()).kind, NodeKind::Group { clip: false, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placing_with_layers_never_links_and_refuses_values_it_cant_use() {
|
||||
let f = file(8, 8, &stack(), 8, false, false);
|
||||
let dir = std::env::temp_dir().join(format!("vc-psd-place-layers-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("layers.psd");
|
||||
std::fs::write(&path, &f).unwrap();
|
||||
let from_path = |p: Value| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let r = s.execute("file.place", &merge(json!({"path": path.to_str().unwrap()}), p));
|
||||
(s, r)
|
||||
};
|
||||
// From a path, `layers` embeds: `link` is then false unless given, and `link: true` is refused.
|
||||
let (s, r) = from_path(json!({"layers": true}));
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r["linked"], json!(false), "{r}");
|
||||
assert!(matches!(placed(&s, &r).kind, NodeKind::Group { .. }));
|
||||
let (s, r) = from_path(json!({"layers": true, "link": true}));
|
||||
assert!(r.unwrap_err().to_string().contains("a linked PSD file is placed as its flat image"));
|
||||
assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "nothing is placed");
|
||||
// Without `layers` the file is linked as before.
|
||||
let (s, r) = from_path(json!({}));
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r["linked"], json!(true), "{r}");
|
||||
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
|
||||
// A file without layers is embedded as its merged image, without a warning.
|
||||
let flat = {
|
||||
let mut f = file(2, 2, &[layer("x", [0, 0, 2, 2], [9, 9, 9, 255])], 8, false, false);
|
||||
let at = 26 + 8;
|
||||
let len = u32::from_be_bytes(f[at..at + 4].try_into().unwrap()) as usize;
|
||||
f.splice(at..at + 4 + len, 0u32.to_be_bytes());
|
||||
f
|
||||
};
|
||||
std::fs::write(&path, &flat).unwrap();
|
||||
let (s, r) = from_path(json!({"layers": true}));
|
||||
let r = r.unwrap();
|
||||
assert_eq!((&r["linked"], &r["warnings"]), (&json!(false), &json!([])), "{r}");
|
||||
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
|
||||
// Layers that are all left out: the merged image, with the importer's warnings.
|
||||
let mut gone = layer("Gone", [0, 0, 2, 2], [9, 9, 9, 255]);
|
||||
gone.hidden = true;
|
||||
let (s, r) = place(&file(2, 2, &[gone], 8, false, false), json!({"layers": true}));
|
||||
let r = r.unwrap();
|
||||
assert_eq!((&r["linked"], r["warnings"].as_array().map(Vec::len)), (&json!(false), Some(1)), "{r}");
|
||||
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
|
||||
// Layers that can't be read: the merged image, with a warning.
|
||||
let mut cut = file(4, 4, &[layer("x", [0, 0, 4, 4], [9, 9, 9, 255])], 8, false, false);
|
||||
let at = cut.windows(4).position(|w| w == [0, 0, 0, 18]).unwrap();
|
||||
cut[at..at + 4].copy_from_slice(&1000u32.to_be_bytes());
|
||||
let (s, r) = place(&cut, json!({"layers": true}));
|
||||
let r = r.unwrap();
|
||||
assert!(r["warnings"][0].as_str().unwrap().starts_with("the layers can't be read"), "{r}");
|
||||
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
|
||||
// Values the command can't use are errors, and nothing is placed.
|
||||
for (p, why) in [
|
||||
(json!({"hiddenLayers": true}), "hiddenLayers applies to a PSD file placed with layers: true"),
|
||||
(json!({"layers": true, "link": true}), "a linked PSD file is placed as its flat image"),
|
||||
(json!({"layers": "yes"}), "layers must be true or false"),
|
||||
(json!({"layers": true, "hiddenLayers": 1}), "hiddenLayers must be true or false"),
|
||||
] {
|
||||
let (s, r) = place(&f, p.clone());
|
||||
assert!(r.unwrap_err().to_string().contains(why), "{p}");
|
||||
assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "{p}");
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let q = s.execute("file.place.queue", &json!({"paths": [path.to_str().unwrap()], "layers": "yes"}));
|
||||
assert!(q.unwrap_err().to_string().contains("`layers` must be true or false"));
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_info_counts_the_layers_without_opening_the_file() {
|
||||
let mut s = Session::new();
|
||||
let info = |s: &mut Session, f: &[u8]| s.execute("document.psdInfo", &json!({"dataBase64": vectorcraft_format::base64_encode(f)}));
|
||||
let r = info(&mut s, &file(8, 8, &stack(), 8, false, false)).unwrap();
|
||||
assert_eq!(r, json!({"format": "psd", "width": 8, "height": 8, "layers": 5, "hiddenLayers": 1, "groups": 2, "slices": 0}));
|
||||
let r = info(&mut s, &file(4, 2, &[layer("x", [0, 0, 2, 2], [9, 9, 9, 255])], 16, true, true)).unwrap();
|
||||
assert_eq!((&r["format"], &r["width"], &r["height"], &r["layers"]), (&json!("psb"), &json!(4), &json!(2), &json!(1)), "{r}");
|
||||
// Layer records that can't be read count as no layers: the file opens as its merged image.
|
||||
let mut cut = file(4, 4, &[layer("x", [0, 0, 4, 4], [9, 9, 9, 255])], 8, false, false);
|
||||
let at = cut.windows(4).position(|w| w == [0, 0, 0, 18]).unwrap();
|
||||
cut[at..at + 4].copy_from_slice(&1000u32.to_be_bytes());
|
||||
assert_eq!(info(&mut s, &cut).unwrap()["layers"], json!(0));
|
||||
assert!(info(&mut s, b"not a psd").unwrap_err().to_string().contains("not a PSD file"));
|
||||
}
|
||||
@@ -0,0 +1,508 @@
|
||||
//! A PSD or PSB file's slices (image resource 1050) opened and placed as user slices
|
||||
//! (`document.open`'s and `file.place`'s `importSlices`): version 6 records and version 7 and 8
|
||||
//! descriptors, built from the Photoshop File Formats Specification's "Slices resource format";
|
||||
//! their options, slices outside the canvas, damaged or unknown slice data, placing scaled and
|
||||
//! moved in one undo step, linked files, and `document.psdInfo`'s count.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{SliceKind, SliceOptions};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// A Unicode string: a count of UTF-16 units, then the units.
|
||||
fn ustr(s: &str) -> Vec<u8> {
|
||||
let units: Vec<u16> = s.encode_utf16().collect();
|
||||
let mut b = (units.len() as u32).to_be_bytes().to_vec();
|
||||
b.extend(units.iter().flat_map(|u| u.to_be_bytes()));
|
||||
b
|
||||
}
|
||||
|
||||
/// One version 6 slice record.
|
||||
#[derive(Clone)]
|
||||
struct S {
|
||||
/// 0: generated automatically, 1: follows a layer, 2: made by the user.
|
||||
origin: u32,
|
||||
name: &'static str,
|
||||
/// 0: No Image, 1: Image.
|
||||
kind: u32,
|
||||
/// Left, top, right, bottom (px).
|
||||
rect: [i32; 4],
|
||||
url: &'static str,
|
||||
target: &'static str,
|
||||
message: &'static str,
|
||||
alt: &'static str,
|
||||
html: bool,
|
||||
cell: &'static str,
|
||||
/// Alpha, red, green, blue.
|
||||
argb: [u8; 4],
|
||||
}
|
||||
|
||||
fn user(name: &'static str, rect: [i32; 4]) -> S {
|
||||
S { origin: 2, name, kind: 1, rect, url: "", target: "", message: "", alt: "", html: false, cell: "", argb: [0; 4] }
|
||||
}
|
||||
|
||||
/// Resource 1050 in version 6, each record followed by `trailing` (a Photoshop 7 descriptor, or
|
||||
/// nothing).
|
||||
fn v6(slices: &[S], trailing: &[u8]) -> Vec<u8> {
|
||||
let mut b = 6u32.to_be_bytes().to_vec();
|
||||
b.extend([0u8; 16]);
|
||||
b.extend(ustr("group"));
|
||||
b.extend((slices.len() as u32).to_be_bytes());
|
||||
for (i, s) in slices.iter().enumerate() {
|
||||
b.extend((i as u32 + 1).to_be_bytes());
|
||||
b.extend(0u32.to_be_bytes());
|
||||
b.extend(s.origin.to_be_bytes());
|
||||
if s.origin == 1 {
|
||||
b.extend(7u32.to_be_bytes());
|
||||
}
|
||||
b.extend(ustr(s.name));
|
||||
b.extend(s.kind.to_be_bytes());
|
||||
for v in s.rect {
|
||||
b.extend(v.to_be_bytes());
|
||||
}
|
||||
for t in [s.url, s.target, s.message, s.alt] {
|
||||
b.extend(ustr(t));
|
||||
}
|
||||
b.push(u8::from(s.html));
|
||||
b.extend(ustr(s.cell));
|
||||
b.extend([0u8; 8]);
|
||||
b.extend(s.argb);
|
||||
b.extend(trailing);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// A descriptor value.
|
||||
enum D {
|
||||
Long(i32),
|
||||
Doub(f64),
|
||||
Bool(bool),
|
||||
Text(&'static str),
|
||||
Enum(&'static str, &'static str),
|
||||
Obj(Vec<(&'static str, D)>),
|
||||
List(Vec<D>),
|
||||
}
|
||||
|
||||
/// A key or class ID: a four-character one with length 0, else its length and characters.
|
||||
fn key(k: &str) -> Vec<u8> {
|
||||
let mut b = if k.len() == 4 { 0u32 } else { k.len() as u32 }.to_be_bytes().to_vec();
|
||||
b.extend(k.as_bytes());
|
||||
b
|
||||
}
|
||||
|
||||
/// A descriptor: an empty class name, the class ID, the count, then each item.
|
||||
fn descriptor(items: &[(&str, D)]) -> Vec<u8> {
|
||||
let mut b = ustr("");
|
||||
b.extend(key("null"));
|
||||
b.extend((items.len() as u32).to_be_bytes());
|
||||
for (k, v) in items {
|
||||
b.extend(key(k));
|
||||
b.extend(value(v));
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// A value's type, then the value.
|
||||
fn value(v: &D) -> Vec<u8> {
|
||||
let mut b = vec![];
|
||||
match v {
|
||||
D::Long(n) => {
|
||||
b.extend(b"long");
|
||||
b.extend(n.to_be_bytes());
|
||||
}
|
||||
D::Doub(d) => {
|
||||
b.extend(b"doub");
|
||||
b.extend(d.to_be_bytes());
|
||||
}
|
||||
D::Bool(on) => {
|
||||
b.extend(b"bool");
|
||||
b.push(u8::from(*on));
|
||||
}
|
||||
D::Text(t) => {
|
||||
b.extend(b"TEXT");
|
||||
b.extend(ustr(t));
|
||||
}
|
||||
D::Enum(t, e) => {
|
||||
b.extend(b"enum");
|
||||
b.extend(key(t));
|
||||
b.extend(key(e));
|
||||
}
|
||||
D::Obj(items) => {
|
||||
b.extend(b"Objc");
|
||||
b.extend(descriptor(items));
|
||||
}
|
||||
D::List(items) => {
|
||||
b.extend(b"VlLs");
|
||||
b.extend((items.len() as u32).to_be_bytes());
|
||||
for i in items {
|
||||
b.extend(value(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// A bounds object: top, left, bottom and right.
|
||||
fn bounds(l: i32, t: i32, r: i32, b: i32) -> D {
|
||||
D::Obj(vec![("Top ", D::Long(t)), ("Left", D::Long(l)), ("Btom", D::Long(b)), ("Rght", D::Long(r))])
|
||||
}
|
||||
|
||||
/// Resource 1050 in `version` 7 or 8 holding `slices`.
|
||||
fn v7(version: u32, slices: Vec<D>) -> Vec<u8> {
|
||||
let mut b = version.to_be_bytes().to_vec();
|
||||
b.extend(16u32.to_be_bytes());
|
||||
b.extend(descriptor(&[("bounds", bounds(0, 0, 20, 20)), ("baseName", D::Text("poster")), ("slices", D::List(slices))]));
|
||||
b
|
||||
}
|
||||
|
||||
/// A 20 × 20 px PSD file written by `document.export`, with its layers (two) or flat.
|
||||
fn psd(layers: bool) -> Vec<u8> {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
|
||||
s.execute("paint.setFill", &json!({ "color": "#ff0000" })).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
|
||||
s.execute("layer.new", &json!({ "name": "Top" })).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 8, "y": 8, "width": 10, "height": 10})).unwrap();
|
||||
let r = s.execute("document.export", &json!({"format": "psd", "layers": layers})).unwrap();
|
||||
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// `psd` with image resource `id` holding `data` added to its image resources.
|
||||
fn with_resource(psd: &[u8], id: u16, data: &[u8]) -> Vec<u8> {
|
||||
let u32_at = |at: usize| u32::from_be_bytes(psd[at..at + 4].try_into().unwrap()) as usize;
|
||||
let colors = 26 + 4 + u32_at(26);
|
||||
let len = u32_at(colors);
|
||||
let mut block = b"8BIM".to_vec();
|
||||
block.extend(id.to_be_bytes());
|
||||
block.extend([0, 0]);
|
||||
block.extend((data.len() as u32).to_be_bytes());
|
||||
block.extend(data);
|
||||
block.resize(block.len().next_multiple_of(2), 0);
|
||||
let mut out = psd[..colors].to_vec();
|
||||
out.extend(((len + block.len()) as u32).to_be_bytes());
|
||||
out.extend(&psd[colors + 4..colors + 4 + len]);
|
||||
out.extend(block);
|
||||
out.extend(&psd[colors + 4 + len..]);
|
||||
out
|
||||
}
|
||||
|
||||
fn b64(f: &[u8]) -> String {
|
||||
vectorcraft_format::base64_encode(f)
|
||||
}
|
||||
|
||||
fn open(f: &[u8], extra: Value) -> (Session, Value) {
|
||||
let mut s = Session::new();
|
||||
let mut p = json!({"name": "poster.psd", "dataBase64": b64(f)});
|
||||
for (k, v) in extra.as_object().unwrap() {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
let r = s.execute("document.open", &p).unwrap();
|
||||
(s, r)
|
||||
}
|
||||
|
||||
/// The document's user slices: rectangle and options.
|
||||
fn slices(s: &Session) -> Vec<(Rect, SliceOptions)> {
|
||||
s.doc().unwrap().doc.slices.iter().map(|x| (x.rect, x.options.clone())).collect()
|
||||
}
|
||||
|
||||
fn warnings(r: &Value) -> Vec<String> {
|
||||
r["warnings"].as_array().map(|a| a.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_6_slices_open_as_user_slices_with_their_options() {
|
||||
let linked = S { origin: 1, url: "https://example.com/", target: "_blank", message: "Go", alt: "Logo", ..user("logo", [2, 4, 10, 8]) };
|
||||
let plain = S { kind: 0, cell: "a < b & c", argb: [0, 0, 0, 0], ..user("note", [10, 10, 20, 20]) };
|
||||
let html = S { kind: 0, html: true, cell: "<b>Hi</b>", argb: [255, 0x12, 0x34, 0x56], ..user("", [0, 12, 6, 18]) };
|
||||
let matte = S { argb: [0, 1, 2, 3], cell: "ignored", ..user("matte", [12, 0, 18, 6]) };
|
||||
let auto = S { origin: 0, ..user("auto", [0, 0, 20, 2]) };
|
||||
let data = v6(&[linked, plain, html, matte, auto], &[]);
|
||||
for layers in [true, false] {
|
||||
let f = with_resource(&psd(layers), 1050, &data);
|
||||
// Either conversion brings the slices in; the automatic one stays out.
|
||||
for p in [json!({}), json!({"layers": false})] {
|
||||
let (s, r) = open(&f, p);
|
||||
assert!(warnings(&r).is_empty(), "{r}");
|
||||
let got = slices(&s);
|
||||
assert_eq!(got.len(), 4, "{got:?}");
|
||||
assert_eq!(got[0].0, Rect::new(2.0, 4.0, 10.0, 8.0));
|
||||
assert_eq!(
|
||||
got[0].1,
|
||||
SliceOptions {
|
||||
kind: SliceKind::Image,
|
||||
name: "logo".into(),
|
||||
url: "https://example.com/".into(),
|
||||
target: "_blank".into(),
|
||||
message: "Go".into(),
|
||||
alt: "Logo".into(),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
// Plain cell text is escaped as the HTML a No Image cell shows; HTML stays as it is.
|
||||
assert_eq!((got[1].1.kind, got[1].1.text.as_str(), got[1].1.background.as_str()), (SliceKind::NoImage, "a < b & c", ""));
|
||||
assert_eq!((got[2].1.text.as_str(), got[2].1.background.as_str(), got[2].1.name.as_str()), ("<b>Hi</b>", "#123456", ""));
|
||||
// An Image slice's cell text isn't kept; a background with no alpha is the matte.
|
||||
assert_eq!((got[3].1.text.as_str(), got[3].1.background.as_str()), ("", "matte"));
|
||||
// Web output lays them out with auto slices around them.
|
||||
let layout = s.doc().unwrap().doc.slice_layout();
|
||||
assert_eq!(layout.iter().filter(|a| a.source == vectorcraft_doc::SliceSource::User).count(), 4);
|
||||
assert!(layout.iter().any(|a| a.source == vectorcraft_doc::SliceSource::Auto));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn photoshop_7_descriptors_after_version_6_records_are_read_past() {
|
||||
let trailing = [16u32.to_be_bytes().to_vec(), descriptor(&[("topOutset", D::Long(0))])].concat();
|
||||
let f = with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 5, 5]), user("b", [5, 5, 10, 10])], &trailing));
|
||||
let (s, r) = open(&f, json!({}));
|
||||
assert!(warnings(&r).is_empty(), "{r}");
|
||||
let names: Vec<String> = slices(&s).into_iter().map(|(_, o)| o.name).collect();
|
||||
assert_eq!(names, ["a", "b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_version_6_record_whose_id_is_16_is_a_slice_not_a_descriptor() {
|
||||
// The 16th record has ID 16, group ID 0, origin 2, no name and the Image type: its first 18
|
||||
// bytes also read as a descriptor of version 16 with no items.
|
||||
let records: Vec<S> = (1..=17).map(|id| if id == 16 { user("", [1, 1, 4, 4]) } else { user("a", [0, 0, 5, 5]) }).collect();
|
||||
let descriptor_after = [16u32.to_be_bytes().to_vec(), descriptor(&[("topOutset", D::Long(0))])].concat();
|
||||
for trailing in [vec![], descriptor_after] {
|
||||
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records, &trailing)), json!({}));
|
||||
assert!(warnings(&r).is_empty(), "{r}");
|
||||
let got = slices(&s);
|
||||
assert_eq!(got.len(), 17, "{got:?}");
|
||||
assert_eq!((got[15].0, got[15].1.name.as_str()), (Rect::new(1.0, 1.0, 4.0, 4.0), ""));
|
||||
assert_eq!(got[16].1.name, "a");
|
||||
}
|
||||
// A descriptor after each record whose class ID is four zero bytes, with no items, followed by
|
||||
// records with no strings: the records don't also read one after another.
|
||||
let empty = [ustr(""), 0u32.to_be_bytes().to_vec(), vec![0; 4], 0u32.to_be_bytes().to_vec()].concat();
|
||||
let trailing = [16u32.to_be_bytes().to_vec(), empty].concat();
|
||||
for rect in [[0, 0, 0, 0], [0, 0, 5, 5]] {
|
||||
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&[user("", rect), user("", rect), user("", rect)], &trailing)), json!({}));
|
||||
let w = warnings(&r);
|
||||
assert!(!w.iter().any(|w| w.starts_with("the slices can't be read")), "{w:?}");
|
||||
assert_eq!(slices(&s).len(), if rect[2] > 0 { 3 } else { 0 }, "{w:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_6_descriptors_share_one_budget_of_values() {
|
||||
// Each record's descriptor holds 2,501 values, well under the 200,000 one descriptor may hold;
|
||||
// 100 of them hold 250,100 together.
|
||||
let list = D::List((0..2_500).map(D::Long).collect());
|
||||
let trailing = [16u32.to_be_bytes().to_vec(), descriptor(&[("many", list)])].concat();
|
||||
let records: Vec<S> = (0..100).map(|_| user("a", [0, 0, 5, 5])).collect();
|
||||
// Alone, one such descriptor is read past.
|
||||
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records[..1], &trailing)), json!({}));
|
||||
assert!(warnings(&r).is_empty(), "{r}");
|
||||
assert_eq!(slices(&s).len(), 1);
|
||||
// Together they are refused, and the file opens without slices.
|
||||
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records, &trailing)), json!({}));
|
||||
let w = warnings(&r);
|
||||
assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains("too many values")), "{w:?}");
|
||||
assert!(slices(&s).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_7_and_8_descriptors_open_as_user_slices() {
|
||||
let slice = |origin: &'static str, kind: &'static str, l: i32, t: i32, r: i32, b: i32| {
|
||||
D::Obj(vec![
|
||||
("sliceID", D::Long(1)),
|
||||
("groupID", D::Long(0)),
|
||||
("origin", D::Enum("ESliceOrigin", origin)),
|
||||
("Type", D::Enum("ESliceType", kind)),
|
||||
("bounds", bounds(l, t, r, b)),
|
||||
("Nm ", D::Text("cell")),
|
||||
("url", D::Text("https://example.com/")),
|
||||
("null", D::Text("_top")),
|
||||
("Msge", D::Text("msg")),
|
||||
("altTag", D::Text("alt")),
|
||||
("cellTextIsHTML", D::Bool(false)),
|
||||
("cellText", D::Text("x>y")),
|
||||
("bgColorType", D::Enum("ESliceBGColorType", "Clr ")),
|
||||
("bgColor", D::Obj(vec![("Rd ", D::Doub(255.0)), ("Grn ", D::Doub(128.0)), ("Bl ", D::Long(0))])),
|
||||
])
|
||||
};
|
||||
for version in [7, 8] {
|
||||
let data = v7(
|
||||
version,
|
||||
vec![slice("userGenerated", "Img ", 1, 2, 9, 10), slice("autoGenerated", "Img ", 0, 0, 20, 1), slice("layer", "noImage", 10, 10, 15, 15)],
|
||||
);
|
||||
let (s, r) = open(&with_resource(&psd(true), 1050, &data), json!({}));
|
||||
assert!(warnings(&r).is_empty(), "{r}");
|
||||
let got = slices(&s);
|
||||
assert_eq!(got.len(), 2, "{got:?}");
|
||||
assert_eq!(got[0].0, Rect::new(1.0, 2.0, 9.0, 10.0));
|
||||
assert_eq!(
|
||||
got[0].1,
|
||||
SliceOptions {
|
||||
name: "cell".into(),
|
||||
url: "https://example.com/".into(),
|
||||
target: "_top".into(),
|
||||
message: "msg".into(),
|
||||
alt: "alt".into(),
|
||||
background: "#ff8000".into(),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
assert_eq!((got[1].1.kind, got[1].1.text.as_str(), got[1].1.url.as_str()), (SliceKind::NoImage, "x>y", ""));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_slices_false_leaves_them_out_and_must_be_a_switch() {
|
||||
let f = with_resource(&psd(true), 1050, &v6(&[user("a", [0, 0, 5, 5])], &[]));
|
||||
let (s, _) = open(&f, json!({"importSlices": false}));
|
||||
assert!(slices(&s).is_empty());
|
||||
let mut s = Session::new();
|
||||
let e = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f), "importSlices": "yes"})).unwrap_err();
|
||||
assert!(e.to_string().contains("importSlices must be true or false"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slices_that_cant_be_read_warn_and_the_file_still_opens() {
|
||||
let good = v6(&[user("a", [0, 0, 5, 5])], &[]);
|
||||
let mut bad_descriptor = v7(7, vec![]);
|
||||
bad_descriptor[4..8].copy_from_slice(&15u32.to_be_bytes());
|
||||
let cases: Vec<(Vec<u8>, &str)> = vec![
|
||||
(good[..good.len() - 3].to_vec(), "cut short"),
|
||||
([9u32.to_be_bytes().to_vec(), good[4..].to_vec()].concat(), "version 9"),
|
||||
(bad_descriptor, "version other than 16"),
|
||||
// The count follows the version, the bounds and the group's name.
|
||||
([&good[..34], &u32::MAX.to_be_bytes()[..], &good[38..]].concat(), "more than the 10000 read"),
|
||||
(v7(8, vec![D::Long(3)]), "other than a slice"),
|
||||
// A whole record whose name is longer than a slice's text may be.
|
||||
(v6(&[user("a".repeat(65_537).leak(), [0, 0, 5, 5])], &[]), "more than the 65536 characters read"),
|
||||
];
|
||||
for (data, why) in cases {
|
||||
for layers in [true, false] {
|
||||
let (s, r) = open(&with_resource(&psd(layers), 1050, &data), json!({}));
|
||||
let w = warnings(&r);
|
||||
assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains(why)), "{why}: {w:?}");
|
||||
assert!(slices(&s).is_empty());
|
||||
// The art still came in.
|
||||
assert!(s.doc().unwrap().doc.art_bounds().is_some(), "{why}");
|
||||
}
|
||||
}
|
||||
// A name of the longest length read comes in.
|
||||
let longest = v6(&[user("a".repeat(65_536).leak(), [0, 0, 5, 5])], &[]);
|
||||
let (s, r) = open(&with_resource(&psd(false), 1050, &longest), json!({}));
|
||||
assert!(warnings(&r).is_empty(), "{r}");
|
||||
assert_eq!(slices(&s).first().map(|(_, o)| o.name.len()), Some(65_536));
|
||||
// A file without slices opens without a word about them.
|
||||
let (s, r) = open(&psd(true), json!({}));
|
||||
assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slices_resource_cut_short_warns_and_the_file_still_opens() {
|
||||
let good = v6(&[user("a", [0, 0, 5, 5])], &[]);
|
||||
// Image resource `id`, the last of the image resources, declares 10 bytes more than they hold.
|
||||
let cut = |layers: bool, id: u16, data: &[u8]| {
|
||||
let mut f = with_resource(&psd(layers), id, data);
|
||||
let sig = [&b"8BIM"[..], &id.to_be_bytes()].concat();
|
||||
let at = f.windows(6).rposition(|w| w == sig.as_slice()).unwrap() + 8;
|
||||
f[at..at + 4].copy_from_slice(&(data.len() as u32 + 10).to_be_bytes());
|
||||
f
|
||||
};
|
||||
for layers in [true, false] {
|
||||
let (s, r) = open(&cut(layers, 1050, &good), json!({}));
|
||||
let w = warnings(&r);
|
||||
assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains("cut short")), "{w:?}");
|
||||
assert!(slices(&s).is_empty());
|
||||
assert!(s.doc().unwrap().doc.art_bounds().is_some());
|
||||
// Another resource cut short says nothing about slices.
|
||||
let (s, r) = open(&cut(layers, 1051, &[0, 1]), json!({}));
|
||||
assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slices_are_clipped_to_the_canvas_and_those_outside_it_are_left_out() {
|
||||
let data = v6(&[user("over", [-5, -5, 5, 30]), user("out", [25, 0, 30, 5]), user("empty", [4, 4, 4, 9]), user("in", [1, 1, 2, 2])], &[]);
|
||||
let (s, r) = open(&with_resource(&psd(false), 1050, &data), json!({}));
|
||||
assert_eq!(warnings(&r), ["2 slices lie outside the canvas or have no size and were left out"]);
|
||||
let got: Vec<(Rect, String)> = slices(&s).into_iter().map(|(r, o)| (r, o.name)).collect();
|
||||
assert_eq!(got, [(Rect::new(0.0, 0.0, 5.0, 20.0), "over".to_string()), (Rect::new(1.0, 1.0, 2.0, 2.0), "in".to_string())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placed_embedded_files_bring_their_slices_with_the_art_in_one_undo_step() {
|
||||
let data = v6(&[user("a", [0, 0, 10, 10]), user("b", [10, 10, 20, 20])], &[]);
|
||||
for layers in [false, true] {
|
||||
let f = with_resource(&psd(layers), 1050, &data);
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
// Fitted into a 40 pt square at (100, 60): twice the size.
|
||||
let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "rect": [100, 60, 40, 40], "layers": layers})).unwrap();
|
||||
assert_eq!(r["slices"].as_array().map(Vec::len), Some(2), "{r}");
|
||||
let got: Vec<Rect> = slices(&s).into_iter().map(|(r, _)| r).collect();
|
||||
assert_eq!(got, [Rect::new(100.0, 60.0, 120.0, 80.0), Rect::new(120.0, 80.0, 140.0, 100.0)]);
|
||||
// The placed art stays selected, and one undo takes the art and the slices away.
|
||||
assert_eq!(s.doc().unwrap().selection.objects.len(), 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(slices(&s).is_empty());
|
||||
assert!(s.doc().unwrap().doc.art_bounds().is_none());
|
||||
// Centered on `at` at 100%.
|
||||
s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "at": [100, 100], "layers": layers})).unwrap();
|
||||
assert_eq!(slices(&s)[0].0, Rect::new(90.0, 90.0, 100.0, 100.0));
|
||||
// `importSlices: false` places the art alone.
|
||||
let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "importSlices": false, "layers": layers})).unwrap();
|
||||
assert!(r.get("slices").is_none());
|
||||
assert_eq!(slices(&s).len(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_files_are_placed_without_their_slices() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-psd-slices-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("poster.psd");
|
||||
std::fs::write(&path, with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 5, 5])], &[]))).unwrap();
|
||||
let path = path.to_string_lossy().into_owned();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let r = s.execute("file.place", &json!({ "path": path })).unwrap();
|
||||
assert_eq!((&r["linked"], r.get("slices")), (&json!(true), None));
|
||||
assert!(slices(&s).is_empty());
|
||||
let e = s.execute("file.place", &json!({ "path": path, "importSlices": true })).unwrap_err();
|
||||
assert!(e.to_string().contains("importSlices: a linked PSD file is placed as its flat image"), "{e}");
|
||||
// Embedded from its path, they come in.
|
||||
let r = s.execute("file.place", &json!({ "path": path, "link": false })).unwrap();
|
||||
assert_eq!((&r["linked"], r["slices"].as_array().map(Vec::len)), (&json!(false), Some(1)));
|
||||
// file.place.info counts what a place would bring in.
|
||||
let info = s.execute("file.place.info", &json!({ "path": path, "link": false })).unwrap();
|
||||
assert_eq!(info["slices"], json!(1));
|
||||
let info = s.execute("file.place.info", &json!({ "path": path })).unwrap();
|
||||
assert_eq!(info["slices"], json!(0));
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_info_counts_the_slices_that_come_in() {
|
||||
let mut s = Session::new();
|
||||
let info = |s: &mut Session, f: &[u8]| s.execute("document.psdInfo", &json!({"dataBase64": b64(f)})).unwrap();
|
||||
let data = v6(&[user("a", [0, 0, 5, 5]), S { origin: 0, ..user("auto", [5, 5, 20, 20]) }, user("out", [30, 30, 40, 40])], &[]);
|
||||
assert_eq!(info(&mut s, &with_resource(&psd(false), 1050, &data))["slices"], json!(1));
|
||||
assert_eq!(info(&mut s, &with_resource(&psd(true), 1050, &data[..data.len() - 4]))["slices"], json!(0));
|
||||
assert_eq!(info(&mut s, &psd(true))["slices"], json!(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_slices_never_panic() {
|
||||
let data = v7(8, vec![D::Obj(vec![("origin", D::Enum("ESliceOrigin", "userGenerated")), ("bounds", bounds(0, 0, 5, 5))])]);
|
||||
let base = with_resource(&psd(false), 1050, &data);
|
||||
let start = base.windows(data.len()).position(|w| w == data).unwrap();
|
||||
for at in (start - 12..start + data.len()).step_by(3) {
|
||||
for v in [0u8, 0x7f, 0xff] {
|
||||
let mut f = base.clone();
|
||||
f[at] = v;
|
||||
let mut s = Session::new();
|
||||
let _ = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f)}));
|
||||
let _ = s.execute("document.psdInfo", &json!({"dataBase64": b64(&f)}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -185,9 +185,12 @@ impl Sets {
|
||||
/// horizontal extent, would otherwise compare every pair). An open box inside a later box of
|
||||
/// its group, ending no further right, is closed early, and a box inside an open box of its group,
|
||||
/// ending no further right, isn't opened: whatever overlaps it overlaps that box. An open box that
|
||||
/// a later box of its group overlaps, starting lower and ending no further right or lower, keeps
|
||||
/// only its part above the later box's top, so boxes staggered right and down each meet only the
|
||||
/// one before. Fails only when cancelled ([`vectorcraft_doc::cancel`]).
|
||||
/// a later box of its group overlaps and ends no further right than keeps only the part the later
|
||||
/// box doesn't cover: its part above the later box's top when the later box starts lower and ends
|
||||
/// no higher than it, and its part below the later box's bottom when the later box starts no lower
|
||||
/// and ends higher than it. The open box's top then moves down in the tree, so boxes staggered right
|
||||
/// and down, or right and up, each meet only the one before. Fails only when cancelled
|
||||
/// ([`vectorcraft_doc::cancel`]).
|
||||
pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, Cancelled> {
|
||||
Ok(sweep(bounds, None)?.groups())
|
||||
}
|
||||
@@ -206,27 +209,25 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
|
||||
};
|
||||
let boxes: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.filter(finite).map(|b| (i, b))).collect();
|
||||
let n = boxes.len();
|
||||
// Each box's place in the tree: by top (then index).
|
||||
let mut by_top: Vec<usize> = (0..n).collect();
|
||||
by_top.sort_by(|&a, &b| boxes[a].1.y0.total_cmp(&boxes[b].1.y0).then(a.cmp(&b)));
|
||||
let tops: Vec<f64> = by_top.iter().map(|&k| boxes[k].1.y0).collect();
|
||||
let mut leaf = vec![0usize; n];
|
||||
for (pos, &k) in by_top.iter().enumerate() {
|
||||
leaf[k] = pos;
|
||||
}
|
||||
// The lowest bottom of the open boxes below each node (−∞: none open), in the tree of the
|
||||
// boxes without transparency (every box without `see_through`) and the see-through boxes'.
|
||||
let size = n.next_power_of_two().max(1);
|
||||
let mut low = [vec![f64::NEG_INFINITY; 2 * size], if see_through.is_some() { vec![f64::NEG_INFINITY; 2 * size] } else { vec![] }];
|
||||
let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0]));
|
||||
let set = |low: &mut [f64], pos: usize, v: f64| {
|
||||
let mut i = pos + size;
|
||||
low[i] = v;
|
||||
while i > 1 {
|
||||
i /= 2;
|
||||
low[i] = low[2 * i].max(low[2 * i + 1]);
|
||||
}
|
||||
// The places an open box's top can be at in the tree: a box's top, or just below a box's
|
||||
// bottom, where a later box cuts it short (`-0.0` as `0.0`).
|
||||
let mut places: Vec<f64> = boxes.iter().flat_map(|(_, b)| [b.y0 + 0.0, b.y1.next_up() + 0.0]).collect();
|
||||
places.sort_by(f64::total_cmp);
|
||||
places.dedup_by(|a, b| a.total_cmp(b).is_eq());
|
||||
let place = |y: f64| {
|
||||
let y = y + 0.0;
|
||||
let p = places.partition_point(|t| t.total_cmp(&y).is_lt());
|
||||
places.get(p).is_some_and(|t| t.total_cmp(&y).is_eq()).then_some(p)
|
||||
};
|
||||
// Each box's part still open, from its top to its bottom, and the place of its top while it
|
||||
// is open.
|
||||
let mut top: Vec<f64> = boxes.iter().map(|(_, b)| b.y0).collect();
|
||||
let mut bottom: Vec<f64> = boxes.iter().map(|(_, b)| b.y1).collect();
|
||||
let mut open: Vec<Option<usize>> = vec![None; n];
|
||||
// The tree of the open boxes without transparency (every box without `see_through`) and the
|
||||
// see-through boxes'.
|
||||
let mut trees = [Open::new(places.len()), Open::new(if see_through.is_some() { places.len() } else { 0 })];
|
||||
let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0]));
|
||||
let mut by_left: Vec<usize> = (0..n).collect();
|
||||
by_left.sort_by(|&a, &b| boxes[a].1.x0.total_cmp(&boxes[b].1.x0));
|
||||
let mut by_right: Vec<usize> = (0..n).collect();
|
||||
@@ -241,7 +242,9 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
|
||||
while let Some(&c) = by_right.get(closing)
|
||||
&& boxes[c].1.x1 < b.x0
|
||||
{
|
||||
set(&mut low[tree(c)], leaf[c], f64::NEG_INFINITY);
|
||||
if let Some(p) = open[c].take() {
|
||||
trees[tree(c)].take(p, c, &bottom);
|
||||
}
|
||||
closing += 1;
|
||||
}
|
||||
// The open boxes it joins with their top at most this bottom and their bottom at least
|
||||
@@ -253,21 +256,32 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
|
||||
Some(_) if shadows => &[0, 1],
|
||||
Some(_) => &[1],
|
||||
};
|
||||
let below = tops.partition_point(|t| *t <= b.y1);
|
||||
let below = places.partition_point(|t| *t <= b.y1);
|
||||
met.clear();
|
||||
for &t in looks {
|
||||
let tr = &trees[t];
|
||||
stack.clear();
|
||||
stack.push((1, 0, size));
|
||||
stack.push((1, 0, tr.size));
|
||||
while let Some((node, lo, hi)) = stack.pop() {
|
||||
work += 1;
|
||||
if work.is_multiple_of(4096) {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
}
|
||||
if lo >= below || low[t][node] < b.y0 {
|
||||
if lo >= below || tr.low[node] < b.y0 {
|
||||
continue;
|
||||
}
|
||||
if hi - lo == 1 {
|
||||
met.push(by_top[lo]);
|
||||
// The boxes with their top here, lowest bottom first.
|
||||
for &(_, o) in tr.at[lo].iter().rev() {
|
||||
if bottom[o] < b.y0 {
|
||||
break;
|
||||
}
|
||||
work += 1;
|
||||
if work.is_multiple_of(4096) {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
}
|
||||
met.push(o);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let mid = (lo + hi) / 2;
|
||||
@@ -286,30 +300,91 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
|
||||
let ob = boxes[o].1;
|
||||
see_through.is_none_or(|s| s[boxes[o].0]) && b.x1 <= ob.x1 && ob.y0 <= b.y0 && b.y1 <= ob.y1
|
||||
});
|
||||
// Whatever overlaps a box inside this one overlaps this one, and joins it when this one is
|
||||
// see-through. Likewise, whatever later overlaps the part of an open box at or below this
|
||||
// one's top, when that box ends no further right or lower than this one, overlaps this
|
||||
// one: the open box then keeps only the part above this one's top.
|
||||
let cut = b.y0.next_down();
|
||||
// Whatever overlaps the open part of a box inside this one overlaps this one, and joins it
|
||||
// when this one is see-through. Likewise, whatever later overlaps the part of an open box
|
||||
// this one covers, when that box ends no further right than this one, overlaps this one:
|
||||
// the open box then keeps only the part above this one's top, when this one reaches its
|
||||
// bottom, or only the part below this one's bottom, when this one reaches its top.
|
||||
for &o in &met {
|
||||
sets.join(boxes[k].0, boxes[o].0);
|
||||
let ob = boxes[o].1;
|
||||
if !shadows || Some(o) == holder || b.x1 < ob.x1 || b.y1 < ob.y1 {
|
||||
let Some(p) = open[o] else { continue };
|
||||
if !shadows || Some(o) == holder || b.x1 < boxes[o].1.x1 {
|
||||
continue;
|
||||
}
|
||||
if b.y0 <= ob.y0 {
|
||||
set(&mut low[tree(o)], leaf[o], f64::NEG_INFINITY);
|
||||
} else if holder.is_none() && cut < low[tree(o)][leaf[o] + size] {
|
||||
set(&mut low[tree(o)], leaf[o], cut);
|
||||
let (t, u) = (top[o], bottom[o]);
|
||||
let tr = &mut trees[tree(o)];
|
||||
if b.y0 <= t && u <= b.y1 {
|
||||
tr.take(p, o, &bottom);
|
||||
open[o] = None;
|
||||
continue;
|
||||
}
|
||||
if holder.is_some() || (b.y1 < u && t < b.y0) {
|
||||
continue;
|
||||
}
|
||||
let (t, u) = if u <= b.y1 { (t, b.y0.next_down()) } else { (b.y1.next_up(), u) };
|
||||
// Every top it can get has a place; one without stays as it is.
|
||||
let Some(q) = place(t) else { continue };
|
||||
tr.take(p, o, &bottom);
|
||||
(top[o], bottom[o]) = (t, u);
|
||||
open[o] = (t <= u).then_some(q);
|
||||
if t <= u {
|
||||
tr.put(q, o, &bottom);
|
||||
}
|
||||
}
|
||||
if holder.is_none() {
|
||||
set(&mut low[tree(k)], leaf[k], b.y1);
|
||||
if holder.is_none()
|
||||
&& let Some(p) = place(b.y0)
|
||||
{
|
||||
open[k] = Some(p);
|
||||
trees[tree(k)].put(p, k, &bottom);
|
||||
}
|
||||
}
|
||||
Ok(sets)
|
||||
}
|
||||
|
||||
/// The open boxes of [`sweep`] by the place of their tops, in a tree that knows the lowest bottom
|
||||
/// below each of its branches.
|
||||
struct Open {
|
||||
size: usize,
|
||||
/// The lowest bottom of the open boxes below each node (−∞: none open).
|
||||
low: Vec<f64>,
|
||||
/// The open boxes at each place, by bottom ([`order`]) and then index.
|
||||
at: Vec<BTreeSet<(i64, usize)>>,
|
||||
}
|
||||
|
||||
impl Open {
|
||||
fn new(places: usize) -> Self {
|
||||
let size = places.next_power_of_two().max(1);
|
||||
Self { size, low: vec![f64::NEG_INFINITY; 2 * size], at: vec![BTreeSet::new(); places] }
|
||||
}
|
||||
|
||||
/// Opens box `k` at place `p`, with its bottom `bottom[k]`.
|
||||
fn put(&mut self, p: usize, k: usize, bottom: &[f64]) {
|
||||
self.at[p].insert((order(bottom[k]), k));
|
||||
self.fix(p, bottom);
|
||||
}
|
||||
|
||||
/// Closes box `k` at place `p`, while its bottom is still `bottom[k]`.
|
||||
fn take(&mut self, p: usize, k: usize, bottom: &[f64]) {
|
||||
self.at[p].remove(&(order(bottom[k]), k));
|
||||
self.fix(p, bottom);
|
||||
}
|
||||
|
||||
fn fix(&mut self, p: usize, bottom: &[f64]) {
|
||||
let mut i = p + self.size;
|
||||
self.low[i] = self.at[p].last().map_or(f64::NEG_INFINITY, |&(_, k)| bottom[k]);
|
||||
while i > 1 {
|
||||
i /= 2;
|
||||
self.low[i] = self.low[2 * i].max(self.low[2 * i + 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` as an integer in the same order as [`f64::total_cmp`].
|
||||
fn order(v: f64) -> i64 {
|
||||
let b = v.to_bits() as i64;
|
||||
b ^ (((b >> 63) as u64) >> 1) as i64
|
||||
}
|
||||
|
||||
/// Boxes in blocks of nearby ones, each block with the box around it, to find the boxes a box
|
||||
/// touches.
|
||||
struct Blocks {
|
||||
@@ -775,6 +850,136 @@ mod tests {
|
||||
assert_eq!(sets.groups(), vec![(0..n).collect::<Vec<_>>()]);
|
||||
}
|
||||
|
||||
/// `n` boxes of one size, each a little right of and above the one before, all overlapping and
|
||||
/// none inside another.
|
||||
fn staggered_up(n: usize) -> Vec<Option<Rect>> {
|
||||
let w = 2.0 * n as f64;
|
||||
(0..n).map(|i| Some(Rect::new(i as f64, -(i as f64), w + i as f64, w - i as f64))).collect()
|
||||
}
|
||||
|
||||
/// Each box of a stagger right and up meets only the box before it, which keeps only its part
|
||||
/// below the new box's bottom, not every box still open; so does each box of a stagger left and
|
||||
/// down, which the sweep meets right and up.
|
||||
#[test]
|
||||
fn boxes_staggered_up_meet_only_the_box_before() {
|
||||
let n = 512;
|
||||
let bounds = staggered_up(n);
|
||||
let all = vec![(0..n).collect::<Vec<_>>()];
|
||||
let mut sets = sweep(&bounds, None).unwrap();
|
||||
assert_eq!(sets.meets, n - 1);
|
||||
assert_eq!(sets.groups(), every_pair(&bounds));
|
||||
assert_eq!(sets.groups(), all);
|
||||
let mut sets = sweep(&bounds, Some(&vec![true; n])).unwrap();
|
||||
assert_eq!(sets.meets, n - 1);
|
||||
assert_eq!(sets.groups(), all);
|
||||
let mut reversed = bounds.clone();
|
||||
reversed.reverse();
|
||||
let mut sets = sweep(&reversed, None).unwrap();
|
||||
assert_eq!(sets.meets, n - 1);
|
||||
assert_eq!(sets.groups(), all);
|
||||
let mut sets = sweep(&reversed, Some(&vec![true; n])).unwrap();
|
||||
assert_eq!(sets.meets, n - 1);
|
||||
assert_eq!(sets.groups(), all);
|
||||
}
|
||||
|
||||
/// An open box cut short from above keeps the part a later box would meet without meeting the
|
||||
/// box that cut it: a part below that box, a part further right, or any part when that box is
|
||||
/// opaque or held; a box cut from above and from below keeps its middle.
|
||||
#[test]
|
||||
fn a_box_is_cut_short_from_above_only_where_the_later_box_covers_it() {
|
||||
let k = Rect::new(5.0, -5.0, 15.0, 10.0);
|
||||
let cases = [
|
||||
// Below `k`: the last box overlaps only the bottom of the first.
|
||||
("below", vec![Some(Rect::new(0.0, 0.0, 10.0, 20.0)), Some(k), Some(Rect::new(8.0, 15.0, 9.0, 25.0))], vec![true, true, false]),
|
||||
// Further right than `k`: `k` cuts nothing and the last box overlaps the first.
|
||||
("right", vec![Some(Rect::new(0.0, 0.0, 20.0, 20.0)), Some(k), Some(Rect::new(17.0, 2.0, 25.0, 4.0))], vec![true, true, false]),
|
||||
// Just below `k`'s bottom, and touching it.
|
||||
(
|
||||
"edge",
|
||||
vec![Some(Rect::new(0.0, 0.0, 10.0, 20.0)), Some(k), Some(Rect::new(8.0, 10.0, 9.0, 12.0)), Some(Rect::new(8.0, 10.5, 9.0, 12.0))],
|
||||
vec![false, true, false, false],
|
||||
),
|
||||
// An opaque `k` doesn't join the opaque last box, which joins the see-through first one.
|
||||
("opaque", vec![Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(k), Some(Rect::new(6.0, -10.0, 7.0, 2.0))], vec![true, false, false]),
|
||||
// A see-through `k` held by a see-through box around it isn't opened and cuts nothing short.
|
||||
(
|
||||
"held",
|
||||
vec![
|
||||
Some(Rect::new(0.0, -6.0, 30.0, 28.0)),
|
||||
Some(Rect::new(1.0, 0.0, 10.0, 20.0)),
|
||||
Some(k),
|
||||
Some(Rect::new(6.0, 11.0, 7.0, 13.0)),
|
||||
Some(Rect::new(6.0, 4.0, 7.0, 6.0)),
|
||||
],
|
||||
vec![true, false, true, false, false],
|
||||
),
|
||||
// Cut from above, then from below: a later box inside what is left joins the first.
|
||||
(
|
||||
"middle",
|
||||
vec![
|
||||
Some(Rect::new(0.0, 0.0, 10.0, 30.0)),
|
||||
Some(Rect::new(2.0, -5.0, 12.0, 10.0)),
|
||||
Some(Rect::new(3.0, 20.0, 13.0, 40.0)),
|
||||
Some(Rect::new(5.0, 15.0, 6.0, 16.0)),
|
||||
Some(Rect::new(5.0, 9.0, 6.0, 10.0)),
|
||||
Some(Rect::new(5.0, 20.0, 6.0, 20.0)),
|
||||
],
|
||||
vec![false, true, true, false, false, false],
|
||||
),
|
||||
// Signed zeros, a point and a box that isn't finite.
|
||||
(
|
||||
"zeros",
|
||||
vec![
|
||||
Some(Rect::new(-0.0, -0.0, 4.0, 8.0)),
|
||||
Some(Rect::new(0.0, -2.0, 6.0, -0.0)),
|
||||
Some(Rect::new(1.0, 0.0, 1.0, 0.0)),
|
||||
Some(Rect::new(2.0, f64::NEG_INFINITY, 3.0, 1.0)),
|
||||
Some(Rect::new(3.0, f64::MAX, 3.0, f64::MAX)),
|
||||
Some(Rect::new(3.5, 0.0, 3.5, 0.0)),
|
||||
],
|
||||
vec![false, true, false, true, true, false],
|
||||
),
|
||||
];
|
||||
for (what, bounds, see) in cases {
|
||||
assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "{what}");
|
||||
let mut sets = sweep(&bounds, Some(&see)).unwrap();
|
||||
assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "{what}, with transparency");
|
||||
let mut sets = sweep(&bounds, Some(&vec![true; bounds.len()])).unwrap();
|
||||
assert_eq!(sets.groups(), every_pair(&bounds), "{what}, all see-through");
|
||||
}
|
||||
}
|
||||
|
||||
/// Boxes stepping right and alternately up and down, so that open boxes are cut short from
|
||||
/// above and from below, of mixed sizes, some see-through, group as comparing every pair groups
|
||||
/// them.
|
||||
#[test]
|
||||
fn boxes_stepping_up_and_down_group_as_comparing_every_pair() {
|
||||
let mut seed = 0x6a09_e667_f3bc_c908u64;
|
||||
let mut next = |m: f64| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed % 1000) as f64 / 1000.0 * m
|
||||
};
|
||||
for round in 0..40 {
|
||||
let n = 10 + round * 3;
|
||||
let mut y = 0.0;
|
||||
let bounds: Vec<Option<Rect>> = (0..n)
|
||||
.map(|i| {
|
||||
let up = if (i / (1 + round % 3)) % 2 == 0 { -1.0 } else { 1.0 };
|
||||
y += up * (next(4.0).floor() + 1.0);
|
||||
let x = i as f64 + next(2.0).floor();
|
||||
let (w, h) = (next(12.0).floor() + 4.0, next(16.0).floor() + 2.0);
|
||||
Some(Rect::new(x, y, x + w, y + h))
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}");
|
||||
let see: Vec<bool> = (0..n).map(|_| next(1.0) < if round % 2 == 0 { 0.5 } else { 0.9 }).collect();
|
||||
let mut sets = sweep(&bounds, Some(&see)).unwrap();
|
||||
assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "round {round}, with transparency");
|
||||
}
|
||||
}
|
||||
|
||||
/// An open box keeps the part a later box would meet without meeting the box that cut it short:
|
||||
/// a part lower than that box, a part further right, or any part when that box is opaque.
|
||||
#[test]
|
||||
|
||||
@@ -10,9 +10,10 @@ use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::panelcmds::listed_artboards;
|
||||
use super::select::on_artboard;
|
||||
use super::typecmd::refresh_bounds;
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, index, str_param};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -39,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select Text by Font",
|
||||
[],
|
||||
None,
|
||||
"{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, the instances of the symbols whose art uses it, the text whose inline graphics draw such a symbol, the objects painted with a pattern whose art uses it (by a visible fill or stroke whose opacity is above 0, a stroke wider than 0) and the objects whose opacity mask uses it (in type that is not hidden or locked in that art), that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; a pattern swatch that nothing paints, or a layer's mask, selects nothing; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}",
|
||||
"{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based whole numbers)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, the instances of the symbols whose art uses it, the text whose inline graphics draw such a symbol, the objects painted with a pattern whose art uses it (by a visible fill or stroke whose opacity is above 0, a stroke wider than 0) and the objects whose opacity mask uses it (in type that is not hidden or locked in that art), that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; a pattern swatch that nothing paints, or a layer's mask, selects nothing; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}",
|
||||
has_doc,
|
||||
select_font
|
||||
),
|
||||
@@ -1080,9 +1081,9 @@ impl FontScope {
|
||||
Some(_) => Err(bad(C, format!("`scope.{key}` must be a non-empty array"))),
|
||||
}
|
||||
};
|
||||
if let Some(a) = list("artboards")? {
|
||||
let rect = |v: &Value| v.as_u64().and_then(|i| d.artboards.get(index(i))).map(|b| b.rect);
|
||||
return a.iter().map(|v| rect(v).ok_or_else(|| bad(C, format!("no such artboard {v}")))).collect::<Result<_>>().map(Self::Artboards);
|
||||
if let (Some(v), Some(_)) = (scope.get("artboards"), list("artboards")?) {
|
||||
let indices = listed_artboards(d, v, "scope.artboards", C)?;
|
||||
return Ok(Self::Artboards(indices.into_iter().filter_map(|i| d.artboards.get(i)).map(|b| b.rect).collect()));
|
||||
}
|
||||
if let Some(a) = list("layers")? {
|
||||
let layer = |v: &Value| v.as_u64().map(NodeId).filter(|id| d.node(*id).is_some_and(Node::is_layer));
|
||||
@@ -1292,6 +1293,40 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Select Text by Font refuses a `scope.artboards` entry that is not a whole number, naming the
|
||||
/// parameter, before it looks at the artboards, and leaves the selection as it was; a whole
|
||||
/// number past the last artboard is `no such artboard`.
|
||||
#[test]
|
||||
fn select_font_refuses_artboards_that_are_not_whole_numbers() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 300, "y": 0, "width": 200, "height": 200})).unwrap();
|
||||
let text = |s: &mut Session, x: i32| {
|
||||
NodeId(s.execute("text.create", &json!({"x": x, "y": 50, "text": "Serif", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap())
|
||||
};
|
||||
let first = text(&mut s, 10);
|
||||
let second = text(&mut s, 350);
|
||||
let run =
|
||||
|s: &mut Session, artboards: Value| s.execute("select.font", &json!({"family": "Source Serif 4", "scope": {"artboards": artboards}}));
|
||||
let malformed = "invalid parameters for `select.font`: `scope.artboards` must contain whole numbers";
|
||||
for (artboards, want) in [
|
||||
(json!(["1"]), malformed),
|
||||
(json!([-1]), malformed),
|
||||
(json!([1.5]), malformed),
|
||||
(json!([true]), malformed),
|
||||
(json!([null]), malformed),
|
||||
(json!([9, "1"]), malformed),
|
||||
(json!([9]), "no such artboard"),
|
||||
(json!([1, 9]), "no such artboard"),
|
||||
] {
|
||||
s.execute("select.set", &json!({"ids": [first.0]})).unwrap();
|
||||
assert_eq!(run(&mut s, artboards.clone()).unwrap_err().to_string(), want, "{artboards}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [first], "{artboards}");
|
||||
}
|
||||
run(&mut s, json!([1, 1])).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [second]);
|
||||
}
|
||||
|
||||
/// Select Text by Font with a layer scope takes the text in the layers, their sublayers
|
||||
/// included, and still leaves out hidden and locked text.
|
||||
#[test]
|
||||
|
||||
@@ -534,7 +534,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Objects were given or selected, even when all of them are graph design art left out below: the stroke mode is then
|
||||
// not one for new art.
|
||||
let selected = !ids.is_empty();
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
|
||||
let ids = super::appearance::drop_design_art_rows(s, ids, item, !stroke, C)?;
|
||||
// How the gradient lies on a stroke (the panel's Stroke buttons).
|
||||
let mode = match str_param(p, "strokeMode") {
|
||||
None => None,
|
||||
@@ -558,7 +558,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => None,
|
||||
});
|
||||
let for_default = match p.get("aspect").and_then(Value::as_f64) {
|
||||
Some(a) if a < 0.0 && !ids.is_empty() && default_kind != Some(GradientKind::Conic) => {
|
||||
Some(a) if a < 0.0 && selected && default_kind != Some(GradientKind::Conic) => {
|
||||
let mut q = p.clone();
|
||||
q["aspect"] = json!(-a);
|
||||
std::borrow::Cow::Owned(q)
|
||||
@@ -568,7 +568,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A spread for selected gradients leaves a freeform default (which has no ends) as it is.
|
||||
let spreads = matches!(spread_param(p), Ok(Some(sp)) if !sp.is_pad());
|
||||
let for_default = match for_default {
|
||||
q if spreads && !ids.is_empty() && default_kind == Some(GradientKind::Freeform) => {
|
||||
q if spreads && selected && default_kind == Some(GradientKind::Freeform) => {
|
||||
let mut q = q.into_owned();
|
||||
if let Some(o) = q.as_object_mut() {
|
||||
o.remove("spread");
|
||||
@@ -579,8 +579,14 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model)
|
||||
.map_err(|e| bad(C, e))?;
|
||||
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
|
||||
let of = super::appearance::reference_of(s, p, item, C)?;
|
||||
// Only design art was given or selected: nothing changes, the defaults and the remembered paint included.
|
||||
if selected && ids.is_empty() {
|
||||
// An aligned `item` of the art alone is still checked: a row the art lacks, or that no other object has, is an error.
|
||||
edit_items(s, &ids, item, of, C, "Gradient", !stroke, |_, _| Ok(()))?;
|
||||
return Ok(json!({"ids": []}));
|
||||
}
|
||||
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
|
||||
let shown_at = super::appearance::first_edited(s, item, of, &ids);
|
||||
// The objects returned: with a design's art, those with a row equal to the art's.
|
||||
let edited = edit_items(s, &ids, item, of, C, "Gradient", !stroke, |n, index| {
|
||||
@@ -770,7 +776,7 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if targets.is_empty() {
|
||||
return Err(EngineError::Other("nothing selected".into()));
|
||||
}
|
||||
let targets = super::appearance::drop_design_art(&s.doc()?.doc, targets);
|
||||
let targets = super::appearance::drop_design_art_rows(s, targets, item, !stroke, C)?;
|
||||
let model = super::paint::new_color_model(s, &Value::Null);
|
||||
let of = super::appearance::reference_of(s, p, item, C)?;
|
||||
// The objects returned: with a design's art, those with a row equal to the art's.
|
||||
|
||||
@@ -49,9 +49,9 @@ use generate::generate;
|
||||
use series::default_series_color;
|
||||
pub(crate) use series::{
|
||||
LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows,
|
||||
capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art,
|
||||
label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, series_groups_among,
|
||||
series_marks_in, series_object_opacity_differs, shown_paint,
|
||||
capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades,
|
||||
is_design_art, label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where,
|
||||
series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use vectorcraft_color::BlendMode;
|
||||
use vectorcraft_doc::swatches::walk_with_masks;
|
||||
use vectorcraft_geom::Shape;
|
||||
|
||||
use super::axis::radar_axis;
|
||||
@@ -767,6 +768,68 @@ fn set_legend_fills(n: &mut Node, on_dark: &HashMap<NodeId, bool>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether each wedge shows a dark fill, for each pie in `n` (`n` itself or one inside it, opacity-mask art included)
|
||||
/// with Legends in Wedges whose legend labels' fill is not their own, so a redraw sets it by its wedge. Read before a
|
||||
/// paste links the pie's colors to the document's swatches, for [`follow_wedge_shades`].
|
||||
pub(crate) fn wedge_shades(n: &Node) -> HashMap<NodeId, Vec<bool>> {
|
||||
let mut out = HashMap::new();
|
||||
walk_with_masks(n, &mut |m| {
|
||||
if let Some(g) = m.extras().graph.as_deref()
|
||||
&& g.kind == GraphKind::Pie
|
||||
&& g.legend
|
||||
&& g.pie_legend_in_wedges
|
||||
&& !g.label_styles.legend_fill_is_own()
|
||||
{
|
||||
out.insert(m.id, pie_wedges(m).iter().map(|w| w.dark).collect());
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Give the legend labels of each pie in `n` that [`wedge_shades`] read as `was` the contrast a redraw sets, where a
|
||||
/// wedge now shows a fill of the other darkness: white on a dark wedge, black on a light one. Pies whose wedges all kept
|
||||
/// their darkness keep their labels as they are.
|
||||
pub(crate) fn follow_wedge_shades(n: &mut Node, was: &HashMap<NodeId, Vec<bool>>) {
|
||||
let mut changed = vec![];
|
||||
walk_with_masks(n, &mut |m| {
|
||||
if let Some(before) = was.get(&m.id)
|
||||
&& pie_wedges(m).iter().map(|w| w.dark).ne(before.iter().copied())
|
||||
{
|
||||
changed.push(m.id);
|
||||
}
|
||||
});
|
||||
if !changed.is_empty() {
|
||||
restore_contrast(n, &changed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the legend labels of the pies `ids` in `n` (`n` itself or ones inside it, opacity-mask art included) as a redraw
|
||||
/// sets them on their wedges.
|
||||
fn restore_contrast(n: &mut Node, ids: &[NodeId]) {
|
||||
if ids.contains(&n.id) {
|
||||
let on_dark = match n.extras().graph.as_deref() {
|
||||
Some(g) => redrawn_on_dark(n, g).unwrap_or_else(|| legend_on_dark(n, g)),
|
||||
None => HashMap::new(),
|
||||
};
|
||||
set_legend_fills(n, &on_dark);
|
||||
}
|
||||
let holds = |c: &Node| {
|
||||
let mut found = false;
|
||||
walk_with_masks(c, &mut |m| found |= ids.contains(&m.id));
|
||||
found
|
||||
};
|
||||
if n.extras().mask.as_ref().is_some_and(|m| holds(&m.art))
|
||||
&& let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
|
||||
{
|
||||
restore_contrast(Arc::make_mut(&mut m.art), ids);
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
if holds(c) {
|
||||
restore_contrast(Arc::make_mut(c), ids);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The legend labels of graph `n`: the type in its Legend group, as [`own_labels`] finds them.
|
||||
fn legend_labels(n: &Node) -> Vec<&Node> {
|
||||
legend_in(n.children().map_or(&[], |c| c.as_slice()))
|
||||
|
||||
@@ -454,7 +454,7 @@ fn an_edit_of_a_graph_designs_art_is_lost_when_the_graph_is_drawn_again() {
|
||||
/// it, and edit the other objects they are given.
|
||||
#[test]
|
||||
fn paint_commands_leave_a_graph_designs_art_out() {
|
||||
let (mut s, _, copy, art, mark) = design_art();
|
||||
let (mut s, graph, copy, art, mark) = design_art();
|
||||
let fill = top_row(&s, art, true);
|
||||
let commands = [
|
||||
("stroke.set", json!({"weight": 5})),
|
||||
@@ -466,6 +466,7 @@ fn paint_commands_leave_a_graph_designs_art_out() {
|
||||
("paint.swap", json!({})),
|
||||
("paint.default", json!({})),
|
||||
("paint.invert", json!({"item": fill, "stroke": false})),
|
||||
("paint.invert", json!({})),
|
||||
];
|
||||
let (copy_was, art_was) = (look(&s, copy), look(&s, art));
|
||||
for (cmd, p) in &commands {
|
||||
@@ -489,6 +490,11 @@ fn paint_commands_leave_a_graph_designs_art_out() {
|
||||
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 5})).unwrap();
|
||||
assert_eq!(look(&s, art), art_was);
|
||||
// Given the whole graph, Invert recolors the marks and leaves the art.
|
||||
let mark_was = look(&s, mark);
|
||||
s.execute("paint.invert", &json!({"ids": [graph.0]})).unwrap();
|
||||
assert_eq!(look(&s, art), art_was);
|
||||
assert_ne!(look(&s, mark), mark_was);
|
||||
// A freeform gradient point is refused on the art alone.
|
||||
refused_on_design_art(&mut s, "paint.freeform.addPoint", json!({"ids": [art.0], "at": [0, 0]}));
|
||||
}
|
||||
@@ -517,6 +523,182 @@ fn stroke_edits_of_selected_design_art_leave_the_new_art_stroke() {
|
||||
assert_eq!(s.new_art_stroke().gradient_mode, mode, "paint.editGradient");
|
||||
}
|
||||
|
||||
/// With only the art of a graph design given or selected, the gradient, swap, default and recolor commands leave the
|
||||
/// paint for new art and the remembered colors as they are.
|
||||
#[test]
|
||||
fn paint_edits_of_design_art_alone_leave_the_defaults() {
|
||||
let (mut s, _, _, art, _) = design_art();
|
||||
let fill = top_row(&s, art, true);
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 3})).unwrap();
|
||||
let defaults = |s: &Session| format!("{:?}", (&s.paint, s.last_solid, &s.last_gradient, &s.recent_colors));
|
||||
let commands = [
|
||||
("paint.editGradient", json!({"kind": "linear"})),
|
||||
("paint.editGradient", json!({"kind": "radial", "stroke": true})),
|
||||
("paint.swap", json!({})),
|
||||
("paint.default", json!({})),
|
||||
("paint.invert", json!({"item": fill, "stroke": false})),
|
||||
("paint.complement", json!({"item": fill, "stroke": false})),
|
||||
("paint.invert", json!({})),
|
||||
("paint.complement", json!({"stroke": true})),
|
||||
("stroke.set", json!({"weight": 7})),
|
||||
("stroke.weightUp", json!({})),
|
||||
];
|
||||
for (cmd, p) in &commands {
|
||||
let was = defaults(&s);
|
||||
let mut q = p.clone();
|
||||
q["ids"] = json!([art.0]);
|
||||
s.execute(cmd, &q).unwrap();
|
||||
assert_eq!(defaults(&s), was, "{cmd}, given");
|
||||
// Selecting the art makes the defaults take its paint.
|
||||
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
|
||||
let was = defaults(&s);
|
||||
s.execute(cmd, p).unwrap();
|
||||
assert_eq!(defaults(&s), was, "{cmd}, selected");
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
}
|
||||
// A bad `item`, `aligned` or `target` is still an error with only design art given.
|
||||
for bad in [
|
||||
json!({"ids": [art.0], "item": "top"}),
|
||||
json!({"ids": [art.0], "item": fill, "aligned": "yes"}),
|
||||
json!({"ids": [art.0], "item": fill, "target": "nowhere"}),
|
||||
json!({"ids": [art.0], "target": "nowhere"}),
|
||||
] {
|
||||
assert!(s.execute("paint.invert", &bad).is_err(), "{bad}");
|
||||
assert!(s.execute("paint.complement", &bad).is_err(), "{bad}");
|
||||
}
|
||||
// So is an `item` the art has no row for, in each command that leaves the art out.
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
for (cmd, p) in [
|
||||
("paint.invert", json!({})),
|
||||
("stroke.set", json!({"weight": 2})),
|
||||
("stroke.weightUp", json!({})),
|
||||
("stroke.setAdvanced", json!({"swapArrows": true})),
|
||||
("paint.editGradient", json!({"kind": "linear"})),
|
||||
("paint.setGradientGeom", json!({"start": [0, 0], "end": [50, 50]})),
|
||||
("object.setOverprint", json!({"fill": true})),
|
||||
] {
|
||||
let mut q = p.clone();
|
||||
q["ids"] = json!([art.0]);
|
||||
q["item"] = json!(99);
|
||||
assert!(s.execute(cmd, &q).is_err(), "{cmd}");
|
||||
}
|
||||
// The art's stroke row named without `stroke` is a stroke row: the gradient commands succeed and change nothing.
|
||||
let stroke_row = top_row(&s, art, false);
|
||||
for p in [json!({"kind": "linear"}), json!({"start": [0, 0], "end": [50, 50]})] {
|
||||
let cmd = if p.get("kind").is_some() { "paint.editGradient" } else { "paint.setGradientGeom" };
|
||||
let mut q = p.clone();
|
||||
q["ids"] = json!([art.0]);
|
||||
q["item"] = json!(stroke_row);
|
||||
s.execute(cmd, &q).unwrap();
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
// With nothing selected, the swap still swaps the defaults.
|
||||
let was = defaults(&s);
|
||||
s.execute("paint.swap", &json!({})).unwrap();
|
||||
assert_ne!(defaults(&s), was);
|
||||
}
|
||||
|
||||
/// A spread or a negative aspect for the art of a graph design alone changes nothing, whatever kind of gradient the
|
||||
/// default fill is; a bad value is still an error.
|
||||
#[test]
|
||||
fn gradient_edits_of_design_art_alone_skip_the_default_kind_checks() {
|
||||
let (mut s, _, _, art, _) = design_art();
|
||||
for (default, p) in [("freeform", json!({"spread": "repeat"})), ("linear", json!({"aspect": -50}))] {
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
s.execute("paint.editGradient", &json!({"kind": default})).unwrap();
|
||||
let (was, art_was, steps) = (format!("{:?}", s.paint), look(&s, art), s.doc().unwrap().history.undo.len());
|
||||
let mut q = p.clone();
|
||||
q["ids"] = json!([art.0]);
|
||||
s.execute("paint.editGradient", &q).unwrap_or_else(|e| panic!("{q}: {e}"));
|
||||
assert_eq!(format!("{:?}", s.paint), was, "{default}");
|
||||
assert_eq!(look(&s, art), art_was, "{default}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{default}");
|
||||
}
|
||||
assert!(s.execute("paint.editGradient", &json!({"ids": [art.0], "spread": "sideways"})).is_err());
|
||||
}
|
||||
|
||||
/// Invert given a group around a graph recolors the group's own fill and the series marks, and leaves the art of a
|
||||
/// graph design as it is. With `target: "contents"` the group's own fill stays as it is.
|
||||
#[test]
|
||||
fn invert_of_a_group_recolors_its_own_fill_and_leaves_design_art() {
|
||||
let (mut s, graph, _, art, mark) = design_art();
|
||||
s.execute("select.set", &json!({"ids": [graph.0]})).unwrap();
|
||||
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap();
|
||||
let row = top_row(&s, group, true);
|
||||
s.execute("paint.setFill", &json!({"ids": [group.0], "item": row, "color": "#ff0000"})).unwrap();
|
||||
let own = |s: &Session| format!("{:?}", s.doc().unwrap().doc.node(group).unwrap().appearance.items);
|
||||
let (own_was, art_was, mark_was) = (own(&s), look(&s, art), look(&s, mark));
|
||||
s.execute("paint.invert", &json!({"ids": [group.0]})).unwrap();
|
||||
assert_ne!(own(&s), own_was, "the group's own fill");
|
||||
assert_ne!(look(&s, mark), mark_was);
|
||||
assert_eq!(look(&s, art), art_was);
|
||||
// The color remembered is the group's own new fill, which the Fill proxy shows.
|
||||
let Some(Paint::Solid { color, .. }) = s.doc().unwrap().doc.node(group).unwrap().proxy_paint_only(false, None).cloned() else {
|
||||
panic!("the group's fill is not a solid color")
|
||||
};
|
||||
assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color)));
|
||||
let (own_was, mark_was) = (own(&s), look(&s, mark));
|
||||
s.execute("paint.invert", &json!({"ids": [group.0], "target": "contents"})).unwrap();
|
||||
assert_eq!(own(&s), own_was, "target: contents");
|
||||
assert_ne!(look(&s, mark), mark_was);
|
||||
assert_eq!(look(&s, art), art_was);
|
||||
}
|
||||
|
||||
/// Invert and Complement given a series group that holds only a graph design's art recolor the group's own fill and
|
||||
/// remember that color, as the last color and the newest recent color. With several such groups the color remembered
|
||||
/// is that of the first group whose fill changed.
|
||||
#[test]
|
||||
fn recoloring_a_group_of_design_art_alone_remembers_its_own_fill() {
|
||||
// A fill of its own for `group`, painted `hex` (the color of a rectangle painted with it).
|
||||
let paint_own = |s: &mut Session, group: NodeId, hex: &str| {
|
||||
s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap();
|
||||
let t = NodeId(s.execute("shape.rectangle", &json!({"x": 700, "y": 700, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [t.0], "color": hex})).unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let paint = d.node(t).unwrap().proxy_paint_only(false, None).unwrap().clone();
|
||||
d.node_mut(group).unwrap().appearance.fill_at_mut(None).unwrap().paint = paint;
|
||||
};
|
||||
// Series 0's group with its own fill painted `hex`.
|
||||
let painted_series = |hex: &str| {
|
||||
let (mut s, graph, _, art, _) = design_art();
|
||||
let group = series(s.doc().unwrap().doc.node(graph).unwrap(), 0).id;
|
||||
paint_own(&mut s, group, hex);
|
||||
(s, group, art)
|
||||
};
|
||||
for cmd in ["paint.invert", "paint.complement"] {
|
||||
let (mut s, group, art) = painted_series("#ff0000");
|
||||
let fill = |s: &Session| s.doc().unwrap().doc.node(group).unwrap().proxy_paint_only(false, None).unwrap().clone();
|
||||
let (art_was, fill_was) = (look(&s, art), fill(&s));
|
||||
s.execute(cmd, &json!({"ids": [group.0]})).unwrap();
|
||||
assert_eq!(look(&s, art), art_was, "{cmd}");
|
||||
assert_ne!(fill(&s), fill_was, "{cmd}: the group's fill is recolored");
|
||||
let Paint::Solid { color, .. } = fill(&s) else { panic!("{cmd}: the group's fill is not a solid color") };
|
||||
assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color)), "{cmd}");
|
||||
}
|
||||
// A gray fill is its own complement: nothing changes, and the remembered colors stay as they were.
|
||||
let (mut s, group, _) = painted_series("#808080");
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
|
||||
let remembered = |s: &Session| format!("{:?}", (s.last_solid, &s.recent_colors));
|
||||
let was = remembered(&s);
|
||||
assert_eq!(s.execute("paint.complement", &json!({"ids": [group.0]})).unwrap()["changed"], json!(0));
|
||||
assert_eq!(remembered(&s), was);
|
||||
// Both series groups hold only the design's art: a gray one first and a red one, given together.
|
||||
let (mut s, graph, _, _, _) = design_art();
|
||||
s.execute("graph.column", &json!({"id": graph.0, "seriesIndexes": [1], "design": "Square"})).unwrap();
|
||||
let groups = [0, 1].map(|i| series(s.doc().unwrap().doc.node(graph).unwrap(), i).id);
|
||||
paint_own(&mut s, groups[0], "#808080");
|
||||
paint_own(&mut s, groups[1], "#ff0000");
|
||||
s.execute("paint.complement", &json!({"ids": [groups[0].0, groups[1].0]})).unwrap();
|
||||
let Some(Paint::Solid { color, .. }) = s.doc().unwrap().doc.node(groups[1]).unwrap().proxy_paint_only(false, None).cloned() else {
|
||||
panic!("the red group's fill is not a solid color")
|
||||
};
|
||||
assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color)));
|
||||
}
|
||||
|
||||
/// `transparency.set` without `item` refuses the art of a graph design in a series, and given it with other objects
|
||||
/// sets only theirs.
|
||||
#[test]
|
||||
@@ -596,6 +778,81 @@ fn expand_appearance_leaves_a_graph_designs_art() {
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(other)).is_none_or(|m| m.appearance.effects.is_empty()));
|
||||
}
|
||||
|
||||
/// `effect` with `params`, as `effect.apply` gives it to an object.
|
||||
fn an_effect(s: &mut Session, effect: &str, params: serde_json::Value) -> vectorcraft_doc::Effect {
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 700, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": effect, "ids": [r], "params": params})).unwrap();
|
||||
s.doc().unwrap().doc.node(NodeId(r)).unwrap().appearance.effects[0].clone()
|
||||
}
|
||||
|
||||
/// Expand Appearance of a graph neither lists the art of a design in a series whose own effect it leaves, nor adds an
|
||||
/// image of that effect to the document.
|
||||
#[test]
|
||||
fn expand_appearance_lists_no_design_art_and_rasterizes_none() {
|
||||
let (mut s, id, copy, _, mark) = design_art();
|
||||
let shadow = an_effect(&mut s, "stylize.dropShadow", json!({}));
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(copy).unwrap().appearance.effects.push(shadow);
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [mark.0]})).unwrap();
|
||||
let copy_was = look(&s, copy);
|
||||
let images = |s: &Session| s.doc().unwrap().doc.images.len();
|
||||
let before = images(&s);
|
||||
s.execute("select.set", &json!({"ids": [mark.0]})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
let per_mark = images(&s) - before;
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let expanded = s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
assert_eq!(expanded["ids"], json!([mark.0]));
|
||||
assert_eq!(look(&s, copy), copy_was);
|
||||
assert_eq!(images(&s) - before, per_mark, "only the mark's shadow becomes an image");
|
||||
}
|
||||
|
||||
/// A geometry effect of a series group that Expand Appearance bakes moves the art of a design in that series with the
|
||||
/// marks.
|
||||
#[test]
|
||||
fn expand_appearance_moves_design_art_with_its_series_groups_effect() {
|
||||
let (mut s, id, copy, _, _) = design_art();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let group = series(&n, 0).id;
|
||||
let shift = an_effect(&mut s, "distort.transform", json!({"moveH": 50}));
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(group).unwrap().appearance.effects.push(shift);
|
||||
let left = |s: &Session| {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
series(&n, 0).children().unwrap()[0].geometric_bounds().unwrap().x0
|
||||
};
|
||||
let was = left(&s);
|
||||
assert_eq!(series(&n, 0).children().unwrap()[0].id, copy);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
assert!((left(&s) - was - 50.0).abs() < 1e-6, "{} then {}", was, left(&s));
|
||||
}
|
||||
|
||||
/// The copies that a Transform effect of a series group makes of a design's art keep their own effects when Expand
|
||||
/// Appearance bakes the series group's effect, as the art they copy does.
|
||||
#[test]
|
||||
fn expand_appearance_leaves_the_effects_of_design_art_copies() {
|
||||
let (mut s, id, copy, _, _) = design_art();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let group = series(&n, 0).id;
|
||||
let shadow = an_effect(&mut s, "stylize.dropShadow", json!({}));
|
||||
let copies = an_effect(&mut s, "distort.transform", json!({"moveH": 50, "copies": 2}));
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
doc.node_mut(copy).unwrap().appearance.effects.push(shadow);
|
||||
doc.node_mut(group).unwrap().appearance.effects.push(copies);
|
||||
let shadows = |s: &Session| {
|
||||
let mut count = 0;
|
||||
s.doc().unwrap().doc.node(id).unwrap().walk(&mut |m| count += m.appearance.effects.iter().filter(|e| e.id == "stylize.dropShadow").count());
|
||||
count
|
||||
};
|
||||
let images = |s: &Session| s.doc().unwrap().doc.images.len();
|
||||
let before = images(&s);
|
||||
assert_eq!(shadows(&s), 1);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
assert_eq!(shadows(&s), 3, "the art and its two copies keep their shadows");
|
||||
assert_eq!(images(&s), before, "no shadow becomes an image");
|
||||
}
|
||||
|
||||
/// The commands that give rows, effects or graphic styles refuse the art of a graph design inside a series, given by
|
||||
/// id (the design's copy or a path inside it) or selected: the graph draws that art again from the design.
|
||||
#[test]
|
||||
@@ -1109,6 +1366,42 @@ fn aligned_effect_indices_past_the_end_of_a_graph_designs_art_are_refused() {
|
||||
assert!(rows(&s, mark).effects.is_empty());
|
||||
}
|
||||
|
||||
/// With a graph design's art given first and `aligned: true`, `effect.remove` and `effect.duplicate` with `indices` are an
|
||||
/// error and change nothing when one of the art's effects is one no other object has, as with that index given alone.
|
||||
#[test]
|
||||
fn aligned_effect_indices_of_a_graph_designs_art_that_no_object_has_are_refused() {
|
||||
let rows = |s: &Session, id: NodeId| (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone();
|
||||
let (mut s, _, art, mark) = aligned_design_art();
|
||||
// The art has a shadow and a roughen, the mark the shadow only.
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [mark.0], "item": null})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "distort.roughen", "ids": [mark.0], "item": null})).unwrap();
|
||||
s.edit("Effects", |d, _| {
|
||||
let effects = d.node(mark).unwrap().appearance.effects.clone();
|
||||
d.node_mut(art).unwrap().appearance.effects = effects;
|
||||
d.node_mut(mark).unwrap().appearance.effects.pop();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let (art_was, mark_was) = (rows(&s, art), rows(&s, mark));
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
for cmd in ["effect.remove", "effect.duplicate"] {
|
||||
assert!(s.execute(cmd, &json!({"ids": [art.0, mark.0], "item": null, "index": 1, "aligned": true})).is_err(), "{cmd}");
|
||||
let e = s.execute(cmd, &json!({"ids": [art.0, mark.0], "item": null, "indices": [0, 1], "aligned": true})).unwrap_err();
|
||||
assert!(e.to_string().contains("no effects at indices 0, 1"), "{cmd}: {e}");
|
||||
assert_eq!((rows(&s, art), rows(&s, mark)), (art_was.clone(), mark_was.clone()), "{cmd}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{cmd}");
|
||||
}
|
||||
// With the roughen on the mark too, both of its effects are removed.
|
||||
s.edit("Roughen", |d, _| {
|
||||
let roughen = d.node(art).unwrap().appearance.effects[1].clone();
|
||||
d.node_mut(mark).unwrap().appearance.effects.push(roughen);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("effect.remove", &json!({"ids": [art.0, mark.0], "item": null, "indices": [0, 1], "aligned": true})).unwrap();
|
||||
assert!(rows(&s, mark).effects.is_empty());
|
||||
}
|
||||
|
||||
/// A blur on a series group makes the whole group an image, which draws the design's art with the series' other art:
|
||||
/// Expand Appearance does not put the art back beside the image.
|
||||
#[test]
|
||||
|
||||
@@ -1314,27 +1314,54 @@ pub(crate) fn file_hidden(path: &str, doc_path: Option<&str>) -> bool {
|
||||
/// gray or missing names none: the SVG writes gray pixels colorized and leaves out an image
|
||||
/// without pixels. The images of the art the SVG writes (opacity masks included) and of the
|
||||
/// symbols, patterns and brushes that art uses, as Copy follows them, are checked: the SVG writes
|
||||
/// no other resource. Hidden layers and objects are written only with
|
||||
/// SVG Options › hidden layers kept (`hidden`), and template layers never ([`svg_written`]).
|
||||
/// Always `false` without read roots in force.
|
||||
pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool) -> bool {
|
||||
if crate::file_access::current().is_none() || !names_hidden_image(d, base, link) {
|
||||
/// no other resource. A placed document's images are those of the art the SVG draws for it. Hidden
|
||||
/// layers and objects are written only with SVG Options › hidden layers kept (`hidden`), in the
|
||||
/// layers and in the symbols, patterns and graph designs alike, and template layers never. SVG Tiny
|
||||
/// 1.2 (`tiny`) writes no opacity masks ([`svg_written`]). Always `false` without read roots in
|
||||
/// force.
|
||||
pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool, tiny: bool) -> bool {
|
||||
if crate::file_access::current().is_none() {
|
||||
return false;
|
||||
}
|
||||
let art = d.layers.iter().filter_map(|l| svg_written(l, hidden)).collect();
|
||||
names_hidden_image(&super::clipboard::Clipboard::gather(d, art).to_document(), base, link)
|
||||
if !d.has_placed() && !names_hidden_image(d, base, link) {
|
||||
return false;
|
||||
}
|
||||
// The writer draws placed documents' art with the pixels their files hold.
|
||||
let placed = d.with_placed_art();
|
||||
let d = &*placed;
|
||||
let art = d.layers.iter().filter_map(|l| svg_written(d, l, hidden, tiny)).collect();
|
||||
let mut out = super::clipboard::Clipboard::gather(d, art).to_document();
|
||||
let written = |n: &std::sync::Arc<Node>| {
|
||||
let empty = || Node::new(n.id, NodeKind::Group { children: vec![], clip: false });
|
||||
std::sync::Arc::new(svg_written(d, n, hidden, tiny).unwrap_or_else(empty))
|
||||
};
|
||||
for s in &mut out.symbols {
|
||||
s.art = written(&s.art);
|
||||
}
|
||||
for g in &mut out.graph_designs {
|
||||
g.art = written(&g.art);
|
||||
}
|
||||
for p in &mut out.patterns {
|
||||
p.art = p.art.iter().filter_map(|n| svg_written(d, n, hidden, tiny)).map(std::sync::Arc::new).collect();
|
||||
}
|
||||
names_hidden_image(&out, base, link)
|
||||
}
|
||||
|
||||
/// `n` as the SVG writer writes it, or `None` when it writes none of it: a hidden layer or object
|
||||
/// is left out unless `hidden`, a template layer's art always, and a disabled opacity mask's art.
|
||||
/// Only layers and groups lose members; other objects keep theirs as they are.
|
||||
fn svg_written(n: &Node, hidden: bool) -> Option<Node> {
|
||||
/// `n` (an object of `d`) as the SVG writer writes it, or `None` when it writes none of it: a
|
||||
/// hidden layer or object is left out unless `hidden`, a template layer's art always, a disabled
|
||||
/// opacity mask's art, and with SVG Tiny 1.2 (`tiny`) every opacity mask's art. A placed document
|
||||
/// is the art the writer draws for it. Only layers and groups lose members; other objects keep
|
||||
/// theirs as they are.
|
||||
fn svg_written(d: &Document, n: &Node, hidden: bool, tiny: bool) -> Option<Node> {
|
||||
if !(n.visible || hidden) {
|
||||
return None;
|
||||
}
|
||||
if matches!(n.kind, NodeKind::PlacedDocument(_)) {
|
||||
return svg_written(d, &vectorcraft_render::effects::expand_live_deep(Some(d), n), hidden, tiny);
|
||||
}
|
||||
let mut n = n.clone();
|
||||
let mask = n.extras().mask.as_deref().filter(|m| !m.disabled).and_then(|m| {
|
||||
let art = svg_written(&m.art, hidden)?;
|
||||
let mask = n.extras().mask.as_deref().filter(|m| !m.disabled && !tiny).and_then(|m| {
|
||||
let art = svg_written(d, &m.art, hidden, tiny)?;
|
||||
Some(Box::new(vectorcraft_doc::OpacityMask { art: std::sync::Arc::new(art), ..m.clone() }))
|
||||
});
|
||||
if n.extras().mask.is_some() {
|
||||
@@ -1343,7 +1370,7 @@ fn svg_written(n: &Node, hidden: bool) -> Option<Node> {
|
||||
match &mut n.kind {
|
||||
NodeKind::Layer { template: true, children, .. } => children.clear(),
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
|
||||
*children = children.iter().filter_map(|c| svg_written(c, hidden)).map(std::sync::Arc::new).collect();
|
||||
*children = children.iter().filter_map(|c| svg_written(d, c, hidden, tiny)).map(std::sync::Arc::new).collect();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -126,14 +126,18 @@ fn kinds(p: &Value, cmd: &str, keys: [&str; 2]) -> Result<Vec<(bool, bool)>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Each kind's item target and objects: (fill?, item, ids).
|
||||
fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator<Item = bool>) -> Result<Vec<(bool, ItemTarget, Vec<NodeId>)>> {
|
||||
/// Each kind's item target and objects: (fill?, item, ids). With `edit`, the art of graph designs drawn in graph series
|
||||
/// is left out, and an explicit item that the art left out has no row of that kind for is an error, as when the edit
|
||||
/// resolves it on the other objects. Without it, the art is read with the other objects.
|
||||
fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator<Item = bool>, edit: bool) -> Result<Vec<(bool, ItemTarget, Vec<NodeId>)>> {
|
||||
let item = item_target(s, p, cmd)?;
|
||||
kinds
|
||||
.into_iter()
|
||||
.map(|fill| {
|
||||
let it = item.of_kind(s, fill);
|
||||
Ok((fill, it, it.targets(s, p)?))
|
||||
let ids = it.targets(s, p)?;
|
||||
let ids = if edit { super::appearance::drop_design_art_rows(s, ids, it, fill, cmd)? } else { ids };
|
||||
Ok((fill, it, ids))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -159,12 +163,7 @@ pub(super) type OverprintJob = ((bool, ItemTarget, Vec<NodeId>), bool);
|
||||
/// `object.setOverprint` aims, leaving out the art of graph designs drawn in graph series.
|
||||
pub(super) fn overprint_jobs(s: &Session, p: &Value, cmd: &str, keys: [&str; 2]) -> Result<Vec<OverprintJob>> {
|
||||
let kinds = kinds(p, cmd, keys)?;
|
||||
let d = &s.doc()?.doc;
|
||||
Ok(aims(s, p, cmd, kinds.iter().map(|k| k.0))?
|
||||
.into_iter()
|
||||
.map(|(fill, it, ids)| (fill, it, super::appearance::drop_design_art(d, ids)))
|
||||
.zip(kinds.iter().map(|k| k.1))
|
||||
.collect())
|
||||
Ok(aims(s, p, cmd, kinds.iter().map(|k| k.0), true)?.into_iter().zip(kinds.iter().map(|k| k.1)).collect())
|
||||
}
|
||||
|
||||
/// Apply `jobs` to `d`, adding the objects changed to `changed`.
|
||||
@@ -203,7 +202,7 @@ fn attributes(s: &Session, p: &Value) -> Result<AttributesInfo> {
|
||||
let d = &s.doc()?.doc;
|
||||
let mut info = AttributesInfo { ids: targets(s, p)?, recent_urls: s.recent_urls.clone(), ..Default::default() };
|
||||
super::attributes::fill_info(d, &mut info);
|
||||
for (fill, item, ids) in aims(s, p, C, [true, false])? {
|
||||
for (fill, item, ids) in aims(s, p, C, [true, false], false)? {
|
||||
let mut all =
|
||||
ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| Some(flags(n, fill, item.resolve(&n.appearance, fill, C).ok()?))).flatten();
|
||||
let same = all.next().and_then(|first| all.all(|b| b == first).then_some(first));
|
||||
|
||||
@@ -96,7 +96,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Invert",
|
||||
[],
|
||||
None,
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
|
||||
has_doc,
|
||||
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
|
||||
),
|
||||
@@ -555,9 +555,15 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
let ids = super::graph::paint_targets(&s.doc()?.doc, &selected);
|
||||
let of = super::appearance::reference_of(s, p, item, cmd)?;
|
||||
let paint = if span {
|
||||
// With a design's art, the gradient spans only the objects with a row equal to the art's, which take it.
|
||||
let spanned: Vec<NodeId> = ids.iter().zip(item.per_target_of(s, of, &ids)).filter_map(|(id, it)| it.map(|_| *id)).collect();
|
||||
placed_across(&s.doc()?.doc, &spanned, paint, p, fill)
|
||||
// With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. Each
|
||||
// object's box is that of the row it edits.
|
||||
let d = &s.doc()?.doc;
|
||||
let mut spanned = Vec::with_capacity(ids.len());
|
||||
for (id, it) in ids.iter().zip(item.per_target_of(s, of, &ids)) {
|
||||
let (Some(it), Some(n)) = (it, d.node(*id)) else { continue };
|
||||
spanned.push((*id, it.resolve(&n.appearance, fill, cmd)?));
|
||||
}
|
||||
placed_across(d, &spanned, paint, p, fill)
|
||||
} else {
|
||||
paint
|
||||
};
|
||||
@@ -730,14 +736,15 @@ fn spans_targets(p: &Value, paint: &Paint) -> std::result::Result<bool, String>
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// `paint` placed once on the union of the bounds of `ids` (each one's fill box, or the box its
|
||||
/// stroke paints), at the gradient's angle and aspect: every target gets the same vector in
|
||||
/// document coordinates, so the ramp runs on across them (#2127).
|
||||
fn placed_across(d: &Document, ids: &[NodeId], paint: Paint, p: &Value, fill: bool) -> Paint {
|
||||
/// `paint` placed once on the union of the bounds of `ids` (each one's fill box, or the box the
|
||||
/// stroke it edits paints: the row given with it, `None` for the topmost), at the gradient's angle
|
||||
/// and aspect: every target gets the same vector in document coordinates, so the ramp runs on
|
||||
/// across them (#2127).
|
||||
fn placed_across(d: &Document, ids: &[(NodeId, Option<usize>)], paint: Paint, p: &Value, fill: bool) -> Paint {
|
||||
let union = ids
|
||||
.iter()
|
||||
.filter_map(|id| d.node(*id))
|
||||
.filter_map(|n| item_paint_bounds(n, None, fill).or_else(|| n.geometric_bounds()))
|
||||
.filter_map(|(id, index)| Some((d.node(*id)?, *index)))
|
||||
.filter_map(|(n, index)| item_paint_bounds(n, index, fill).or_else(|| n.geometric_bounds()))
|
||||
.filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()))
|
||||
.reduce(|a, b| a.union(b));
|
||||
let (Some(union), Paint::Gradient(g)) = (union, &paint) else { return paint };
|
||||
@@ -975,7 +982,13 @@ pub(super) fn restore_unpainted_stroke(ap: &mut Appearance, index: Option<usize>
|
||||
}
|
||||
|
||||
fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, paint_targets(s, p)?);
|
||||
let targets = paint_targets(s, p)?;
|
||||
let given = !targets.is_empty();
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets);
|
||||
// Only design art was given or selected: nothing changes, the defaults included.
|
||||
if given && ids.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
// When every object comes out as it was, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
@@ -1010,7 +1023,13 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, paint_targets(s, p)?);
|
||||
let targets = paint_targets(s, p)?;
|
||||
let given = !targets.is_empty();
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets);
|
||||
// Only design art was given or selected: nothing changes, the defaults included.
|
||||
if given && ids.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
// When every object comes out as it was, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
@@ -1079,10 +1098,26 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
|
||||
return Ok(json!({ "changed": changed as usize }));
|
||||
}
|
||||
let item = item_target(s, p, cmd)?.of_kind(s, !stroke);
|
||||
// Read before the check below, so that a bad param (such as `target` or `aligned`, or an explicit `item` the art has
|
||||
// no row for) is still an error.
|
||||
let targets = super::appearance::drop_design_art_rows(s, item.targets(s, p)?, item, !stroke, cmd)?;
|
||||
let of = match item {
|
||||
ItemTarget::Item { .. } => super::appearance::reference_of(s, p, item, cmd)?,
|
||||
ItemTarget::Top => None,
|
||||
};
|
||||
// Read before the check below too: `targets` reads no `target` for the topmost fill or stroke.
|
||||
let contents = super::appearance::targets_contents(p)?;
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
|
||||
// Only design art was given or selected: nothing changes, the defaults and remembered colors included.
|
||||
if ids.is_empty() {
|
||||
return Ok(json!({ "changed": 0 }));
|
||||
}
|
||||
let (r, shown_at) = match item {
|
||||
ItemTarget::Item { .. } => {
|
||||
let targets = super::appearance::drop_design_art(&s.doc()?.doc, item.targets(s, p)?);
|
||||
let of = super::appearance::reference_of(s, p, item, cmd)?;
|
||||
// Only design art was given or selected: nothing changes, the remembered colors included.
|
||||
if targets.is_empty() {
|
||||
return Ok(json!({ "changed": 0 }));
|
||||
}
|
||||
// The row shown is the one edited in the first object that has it: an aligned row maps to each object's equal row.
|
||||
let shown_at = super::appearance::first_edited(s, item, of, &targets).and_then(|(id, it)| match it {
|
||||
ItemTarget::Item { index, .. } => Some((id, Some(index))),
|
||||
@@ -1098,9 +1133,56 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
|
||||
(json!({ "changed": changed }), shown_at)
|
||||
}
|
||||
// The proxy recolors its paints, including a colorized image's fill, without changing image pixels or pattern tiles.
|
||||
// A given group's own fills and strokes change with the objects inside it, except with `target: "contents"`; other
|
||||
// objects change as their paint targets do (a compound path's member stands for the compound path). Design art
|
||||
// inside a given graph or series group is left out.
|
||||
ItemTarget::Top => {
|
||||
let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()});
|
||||
(super::colorcmds::recolor(s, &q, cmd, label, f)?, leaf_targets(s, &ids)?.first().map(|id| (*id, None)))
|
||||
let mut roots = vec![];
|
||||
for id in &ids {
|
||||
let n = s.doc()?.doc.node(*id);
|
||||
let group =
|
||||
!contents && n.is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape());
|
||||
if group {
|
||||
roots.push(*id);
|
||||
} else {
|
||||
roots.extend(leaf_targets(s, &[*id])?);
|
||||
}
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
roots.retain(|id| seen.insert(*id));
|
||||
let roots = super::appearance::drop_design_art(d, roots);
|
||||
if roots.is_empty() {
|
||||
return Ok(json!({ "changed": 0 }));
|
||||
}
|
||||
let art = super::appearance::design_art_in(d, &roots).into_iter().collect();
|
||||
// The fill or stroke the proxy shows of each group among the roots, before the edit.
|
||||
let own = |d: &Document, id: NodeId| {
|
||||
d.node(id)
|
||||
.filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }))
|
||||
.and_then(|n| n.proxy_paint_only(stroke, None))
|
||||
.cloned()
|
||||
};
|
||||
let own_before: std::collections::HashMap<NodeId, Paint> = roots.iter().filter_map(|id| Some((*id, own(d, *id)?))).collect();
|
||||
let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": roots.iter().map(|i| i.0).collect::<Vec<_>>()});
|
||||
let r = super::colorcmds::recolor_except(s, &q, cmd, label, f, art)?;
|
||||
// As the proxy shows a group: its own fill or stroke when the edit changed it, else the first object inside it
|
||||
// that is not design art (which keeps its paint). The first object given that has either shows it.
|
||||
let d = &s.doc()?.doc;
|
||||
let mut shown_at = None;
|
||||
for id in &ids {
|
||||
if let Some(was) = own_before.get(id)
|
||||
&& own(d, *id).as_ref() != Some(was)
|
||||
{
|
||||
shown_at = Some((*id, None));
|
||||
break;
|
||||
}
|
||||
if let Some(leaf) = super::appearance::drop_design_art(d, leaf_targets(s, &[*id])?).first() {
|
||||
shown_at = Some((*leaf, None));
|
||||
break;
|
||||
}
|
||||
}
|
||||
(r, shown_at)
|
||||
}
|
||||
};
|
||||
// The paint remembered is one the edit recolored: a graph design's art that the item edit leaves out gives none.
|
||||
|
||||
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character / Paragraph",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), 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\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (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; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), 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\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tent
Line truncated
|
||||
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), 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\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (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; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), 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\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tent
Line truncated
|
||||
has_doc,
|
||||
set_format
|
||||
),
|
||||
@@ -255,7 +255,7 @@ pub(crate) fn artboard_indices(d: &vectorcraft_doc::Document, p: &Value, cmd: &s
|
||||
/// list of artboard indices", and a list with an entry that is not a whole number is "`{key}` must
|
||||
/// contain whole numbers"; a whole number past the last artboard is `no such artboard`. Every entry
|
||||
/// is checked for its form before any is checked against the artboards.
|
||||
fn listed_artboards(d: &vectorcraft_doc::Document, v: &Value, key: &str, cmd: &str) -> Result<Vec<usize>> {
|
||||
pub(crate) fn listed_artboards(d: &vectorcraft_doc::Document, v: &Value, key: &str, cmd: &str) -> Result<Vec<usize>> {
|
||||
let entries = v.as_array().ok_or_else(|| bad(cmd, format!("`{key}` must be a list of artboard indices")))?;
|
||||
if entries.is_empty() {
|
||||
return Err(bad(cmd, format!("`{key}` must be a non-empty list of artboard indices")));
|
||||
@@ -614,6 +614,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"akiLeft",
|
||||
"akiRight",
|
||||
"tsume",
|
||||
"diacriticHorizontal",
|
||||
"diacriticVertical",
|
||||
"standardVerticalRoman",
|
||||
"noBreak",
|
||||
"digits",
|
||||
@@ -645,7 +647,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(v) => Some(match v.as_str() {
|
||||
Some("singleLine") => Composer::SingleLine,
|
||||
Some("everyLine") => Composer::EveryLine,
|
||||
_ => return Err(bad(C, "composer must be \"singleLine\" or \"everyLine\"")),
|
||||
Some("standardSingleLine") => Composer::StandardSingleLine,
|
||||
Some("standardEveryLine") => Composer::StandardEveryLine,
|
||||
_ => return Err(bad(C, "composer must be \"singleLine\", \"everyLine\", \"standardSingleLine\" or \"standardEveryLine\"")),
|
||||
}),
|
||||
};
|
||||
let (position, small_caps) = super::docsetup::script_params(p, &s.doc()?.doc.setup, C)?;
|
||||
@@ -661,6 +665,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let aki_left = super::textedit::aki_param(p, "akiLeft", C)?;
|
||||
let aki_right = super::textedit::aki_param(p, "akiRight", C)?;
|
||||
let tsume = super::textedit::tsume_param(p, C)?;
|
||||
let diacritic_horizontal = super::textedit::diacritic_param(p, "diacriticHorizontal", C)?;
|
||||
let diacritic_vertical = super::textedit::diacritic_param(p, "diacriticVertical", C)?;
|
||||
let warichu_lines = super::textedit::warichu_lines_param(p, C)?;
|
||||
let warichu_gap = super::textedit::warichu_number_param(p, "warichuGap", C)?;
|
||||
let warichu_scale = super::textedit::warichu_number_param(p, "warichuScale", C)?;
|
||||
@@ -851,6 +857,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(v) = tsume {
|
||||
st.tsume = v;
|
||||
}
|
||||
st.diacritic_horizontal = diacritic_horizontal.unwrap_or(st.diacritic_horizontal);
|
||||
st.diacritic_vertical = diacritic_vertical.unwrap_or(st.diacritic_vertical);
|
||||
if let Some(v) = flag("standardVerticalRoman") {
|
||||
st.standard_vertical_roman = v;
|
||||
}
|
||||
|
||||
@@ -369,6 +369,12 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
|
||||
{
|
||||
return Err(bad(id, "`origin` must be [x, y] in points"));
|
||||
}
|
||||
if effect == vectorcraft_render::effects::SVG_FILTER
|
||||
&& let Some(axes) = given.get("axes")
|
||||
&& vectorcraft_render::effects::svg_filter::valid_axes(axes).is_none()
|
||||
{
|
||||
return Err(bad(id, "`axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0"));
|
||||
}
|
||||
// Its name is the filter's id.
|
||||
if effect == vectorcraft_render::effects::SVG_FILTER && given.contains_key("name") && !given.contains_key("xml") {
|
||||
return Err(bad(id, "an SVG filter is named by its id: give `xml` with `name`"));
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling, Selection};
|
||||
use vectorcraft_geom::{Anchor, AnchorKind, PathData, Point, SubPath, Vec2};
|
||||
use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, Point, SubPath, Vec2};
|
||||
|
||||
use super::create::anchor_from_json;
|
||||
use super::draw2::usize_opt;
|
||||
@@ -544,10 +544,12 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind:
|
||||
&& before > 2
|
||||
&& picked(0)
|
||||
&& picked(before - 1)
|
||||
&& let [first, .., last] = sp.anchors.as_mut_slice()
|
||||
&& same(first, last)
|
||||
&& let (Some(&first), Some(&last)) = (sp.anchors.first(), sp.anchors.last())
|
||||
&& same(&first, &last)
|
||||
{
|
||||
first.h_in = last.h_in;
|
||||
if let Some(first) = sp.anchors.first_mut() {
|
||||
first.h_in = last.h_in;
|
||||
}
|
||||
sp.anchors.pop();
|
||||
if let Some(smooth) = join_kind {
|
||||
join_point(sp, 0, smooth);
|
||||
@@ -565,10 +567,12 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind:
|
||||
for i in (1..len).rev() {
|
||||
if picked(i - 1)
|
||||
&& picked(i)
|
||||
&& let Some([a, b]) = anchors.get_mut(i - 1..=i)
|
||||
&& same(a, b)
|
||||
&& let (Some(&a), Some(&b)) = (anchors.get(i - 1), anchors.get(i))
|
||||
&& same(&a, &b)
|
||||
{
|
||||
a.h_out = b.h_out;
|
||||
if let Some(a) = anchors.get_mut(i - 1) {
|
||||
a.h_out = b.h_out;
|
||||
}
|
||||
if let Some(slot) = gone.get_mut(i) {
|
||||
*slot = true;
|
||||
}
|
||||
@@ -603,7 +607,7 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind:
|
||||
}
|
||||
|
||||
/// [`join_point`] on anchor `ai` of `anchors` with its neighbors given by index.
|
||||
fn join_point_between(anchors: &mut [Anchor], ai: usize, prev: Option<usize>, next: Option<usize>, smooth: bool) {
|
||||
fn join_point_between(anchors: &mut Anchors, ai: usize, prev: Option<usize>, next: Option<usize>, smooth: bool) {
|
||||
let at = |j: Option<usize>| j.and_then(|j| anchors.get(j)).map(|a| a.p);
|
||||
let (prev, next) = (at(prev), at(next));
|
||||
if let Some(a) = anchors.get_mut(ai) {
|
||||
@@ -1565,7 +1569,7 @@ enum Stretch {
|
||||
/// anchor, so the two handles of a smooth anchor stay in line with it. That share is below 0 or
|
||||
/// above 1 for a handle long enough beside the span. A closed subpath with no anchor that stays
|
||||
/// moves whole when it has a focal point.
|
||||
fn stretch_weights(anchors: &[Anchor], closed: bool, roles: &[Stretch]) -> Vec<[f64; 3]> {
|
||||
fn stretch_weights(anchors: &Anchors, closed: bool, roles: &[Stretch]) -> Vec<[f64; 3]> {
|
||||
let n = anchors.len();
|
||||
let mut shares = vec![[0.0; 3]; n];
|
||||
let role = |i: usize| match roles.get(i) {
|
||||
@@ -1891,10 +1895,10 @@ mod tests {
|
||||
&& before > 2
|
||||
&& picked(0)
|
||||
&& picked(before - 1)
|
||||
&& let [first, .., last] = sp.anchors.as_mut_slice()
|
||||
&& same(first, last)
|
||||
&& let (Some(&first), Some(&last)) = (sp.anchors.first(), sp.anchors.last())
|
||||
&& same(&first, &last)
|
||||
{
|
||||
first.h_in = last.h_in;
|
||||
sp.anchors[0].h_in = last.h_in;
|
||||
sp.anchors.pop();
|
||||
if let Some(smooth) = join_kind {
|
||||
join_point(sp, 0, smooth);
|
||||
@@ -1903,10 +1907,10 @@ mod tests {
|
||||
for i in (1..sp.anchors.len()).rev() {
|
||||
if picked(i - 1)
|
||||
&& picked(i)
|
||||
&& let Some([a, b]) = sp.anchors.get_mut(i - 1..=i)
|
||||
&& same(a, b)
|
||||
&& let (Some(&a), Some(&b)) = (sp.anchors.get(i - 1), sp.anchors.get(i))
|
||||
&& same(&a, &b)
|
||||
{
|
||||
a.h_out = b.h_out;
|
||||
sp.anchors[i - 1].h_out = b.h_out;
|
||||
sp.anchors.remove(i);
|
||||
if let Some(smooth) = join_kind {
|
||||
join_point(sp, i - 1, smooth);
|
||||
|
||||
+176
-16
@@ -4,6 +4,10 @@
|
||||
//! - A raster image becomes one image at 100% of its physical size: its pixels at the resolution
|
||||
//! the file declares ([`fileio::ppi`]; 72 ppi when it declares none), linked to its file with
|
||||
//! `link` ([`super::links`]).
|
||||
//! - A PSD or PSB file placed with `layers` becomes one group of its layers as objects, embedded
|
||||
//! ([`fileio::psd_layers`]); otherwise it is an image like any other, its merged image. An
|
||||
//! embedded one brings its slices in as user slices, placed with its art (`importSlices`,
|
||||
//! [`fileio::psd_slices`]).
|
||||
//! - An SVG becomes one group of its art; so does a DXF drawing, read with the DXF options
|
||||
//! (`dxf`, [`fileio::dxfimport`]), and an HP-GL plot file (`vectorcraft_cad::hpgl`).
|
||||
//! - An EMF, WMF or PICT picture becomes one group, clipped to its frame (`crop: "crop"`) or
|
||||
@@ -45,7 +49,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SymbolBoxes};
|
||||
use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SliceOptions, SymbolBoxes};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, shapes};
|
||||
use vectorcraft_pdf::CropTo;
|
||||
|
||||
@@ -67,6 +71,8 @@ const MAX_QUEUE: usize = 100;
|
||||
const MAX_THUMBNAIL: f64 = 512.0;
|
||||
/// A text file's natural box (`file.place.info`, the place cursor): a letter page less 1 in margins.
|
||||
const TEXT_FRAME: Rect = Rect::new(0.0, 0.0, 468.0, 648.0);
|
||||
/// An encrypted PDF's box in the place cursor, which reads it without its password: a letter page.
|
||||
const LOCKED_PAGE: Rect = Rect::new(0.0, 0.0, 612.0, 792.0);
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -75,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Place…",
|
||||
["File"],
|
||||
Some("Cmd+Shift+P"),
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf and a PDF with several pages or a password and no page ask for those options first; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed",
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot p
Line truncated
|
||||
has_doc,
|
||||
place
|
||||
),
|
||||
@@ -84,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Placed File Info",
|
||||
[],
|
||||
None,
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…} (both as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}",
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}",
|
||||
always,
|
||||
info
|
||||
),
|
||||
@@ -102,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Load Place Cursor",
|
||||
[],
|
||||
None,
|
||||
"{paths?: [path…], files?: [{name, dataBase64}…], link?, template?, page?, crop?, text?, dxf?, thumbnail?: px} load the place cursor (the `place` tool) with up to 100 files (as file.place reads them): a click places the current file at 100% with its top-left corner there, a drag places it at the dragged size (aspect kept), ←/→ and ↑/↓ cycle the files, Esc discards the current one; each placement is a file.place, and the previous tool returns after the last → {count, files: [{name, format, width, height, thumbnailBase64?}], skipped: [{name, error}]}",
|
||||
"{paths?: [path…], files?: [{name, dataBase64}…], link?, template?, page?, crop?, text?, dxf?, layers?, hiddenLayers?, importSlices?, thumbnail?: px} load the place cursor (the `place` tool) with up to 100 files (as file.place reads them): a click places the current file at 100% with its top-left corner there, a drag places it at the dragged size (aspect kept), ←/→ and ↑/↓ cycle the files, Esc discards the current one; each placement is a file.place, and the previous tool returns after the last; an encrypted PDF, .ai or .ait file stays in the cursor at 612 × 792 pt (VectorCraft's own size) with needsPassword: true and no thumbnail, and a click on it in the app asks for its password (headless, its file.place fails for want of the password) → {count, files: [{name, format, width, height, thumbnailBase64?, needsPassword?}], skipped: [{name, error}]}",
|
||||
has_doc,
|
||||
queue
|
||||
),
|
||||
@@ -148,16 +154,33 @@ struct Loaded {
|
||||
board: Option<Rect>,
|
||||
}
|
||||
|
||||
/// A PSD or PSB file's slices, embedded with `importSlices`: their rectangles over the natural box
|
||||
/// of its art, and their options.
|
||||
type Slices = Vec<(Rect, SliceOptions)>;
|
||||
|
||||
/// Points per pixel of a raster image at the resolution it declares (72 ppi when none).
|
||||
pub(crate) fn pt_per_px(ppi: Option<(f64, f64)>) -> (f64, f64) {
|
||||
let (x, y) = ppi.unwrap_or((72.0, 72.0));
|
||||
(72.0 / x, 72.0 / y)
|
||||
}
|
||||
|
||||
/// [`load_sliced`] without the slices.
|
||||
fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loaded> {
|
||||
load_into(p, cmd, board, link_pdf, &mut vec![])
|
||||
}
|
||||
|
||||
/// [`load_into`], with the slices of a PSD or PSB file that `importSlices` brings in.
|
||||
fn load_sliced(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<(Loaded, Slices)> {
|
||||
let mut slices = vec![];
|
||||
let l = load_into(p, cmd, board, link_pdf, &mut slices)?;
|
||||
Ok((l, slices))
|
||||
}
|
||||
|
||||
/// The file `p` names, read into placeable art; a DXF drawing's Fit to Artboard fills `board`
|
||||
/// (unless the params name their own box). A PDF/.ai page read from a path is placed linked with
|
||||
/// Link when `link_pdf` (false for the queries, which read it embedded).
|
||||
fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loaded> {
|
||||
/// Link when `link_pdf` (false for the queries, which read it embedded). A PSD or PSB file's slices
|
||||
/// go to `slices`.
|
||||
fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_out: &mut Slices) -> Result<Loaded> {
|
||||
let src = fileio::source(p, cmd)?;
|
||||
let name = fileio::file_name(src.name);
|
||||
// An Affinity file is recognised by its signature, whatever its name says.
|
||||
@@ -237,12 +260,52 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa
|
||||
let art = Art::Vector { src: Box::new(a.doc), nodes: a.nodes, clip: a.clip };
|
||||
return Ok(Loaded { name, format, art, natural: a.frame, warnings: a.warnings, link: None, board: None });
|
||||
}
|
||||
// A PSD or PSB file placed with `layers`: its layers as objects, never linked. One without
|
||||
// layers, or whose layers can't be read, is embedded as its merged image.
|
||||
let (mut embed, mut unread) = (false, vec![]);
|
||||
let mut slices_from = None;
|
||||
if matches!(format.id, "psd" | "psb") {
|
||||
let layers = switch_or(p, "layers", false, cmd)?;
|
||||
if switch_or(p, "hiddenLayers", false, cmd)? && !layers {
|
||||
return Err(bad(cmd, "hiddenLayers applies to a PSD file placed with layers: true"));
|
||||
}
|
||||
// Slices come in with an embedded file (default on); a linked file shows its flat image.
|
||||
let linked = !layers && src.path.is_some() && bool_or(p, "link", true);
|
||||
let slices = switch_or(p, "importSlices", !linked, cmd)?;
|
||||
if slices && linked {
|
||||
return Err(bad(cmd, "importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices"));
|
||||
}
|
||||
if slices {
|
||||
slices_from = Some(&src.bytes[..]);
|
||||
}
|
||||
if layers {
|
||||
// Layers are embedded: a link shows the file's flat image.
|
||||
if switch_or(p, "link", false, cmd)? {
|
||||
return Err(bad(cmd, "layers: a linked PSD file is placed as its flat image; leave link out or give link: false"));
|
||||
}
|
||||
embed = true;
|
||||
match fileio::psd_layers(&src.bytes, opts.hidden_layers) {
|
||||
Ok(Some((doc, mut warnings))) => match psd_groups(doc) {
|
||||
Some((art, natural)) => {
|
||||
*slices_out = psd_slices(slices_from, natural, &mut warnings);
|
||||
return Ok(Loaded { name, format, art, natural, warnings, link: None, board: None });
|
||||
}
|
||||
// No layer has art: the merged image, embedded.
|
||||
None => unread = warnings,
|
||||
},
|
||||
// No layers: the merged image, embedded.
|
||||
Ok(None) => {}
|
||||
Err(e) => unread.push(format!("the layers can't be read ({e}): the file was placed as its merged image")),
|
||||
}
|
||||
}
|
||||
}
|
||||
if format.raster {
|
||||
let img = fileio::raster_image(&src.bytes)?;
|
||||
let (sx, sy) = pt_per_px(img.ppi);
|
||||
let natural = Rect::new(0.0, 0.0, img.width as f64 * sx, img.height as f64 * sy);
|
||||
let link = src.path.map(|path| super::links::link_info(path, &src.bytes));
|
||||
let warnings = fileio::size_note(&img.blob.bytes).into_iter().collect();
|
||||
let link = src.path.filter(|_| !embed).map(|path| super::links::link_info(path, &src.bytes));
|
||||
let mut warnings: Vec<String> = unread.into_iter().chain(fileio::size_note(&img.blob.bytes)).collect();
|
||||
*slices_out = psd_slices(slices_from, natural, &mut warnings);
|
||||
let clip = fileio::psdread::clipping_path(&src.bytes);
|
||||
return Ok(Loaded { name, format, art: Art::Image(img, clip), natural, warnings, link, board: None });
|
||||
}
|
||||
@@ -303,6 +366,56 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa
|
||||
Ok(Loaded { name, format, art: Art::Vector { src: Box::new(doc), nodes, clip }, natural, warnings, link: None, board })
|
||||
}
|
||||
|
||||
/// A PSD or PSB file's layers, read as `document.open` reads them into `doc`, as art to place: an
|
||||
/// image for each layer and a group for each layer group, bottom first, with the layer's name,
|
||||
/// visibility, opacity, blend mode and opacity mask. The art's natural box is the file's canvas,
|
||||
/// where the merged image would lie, and the art is clipped to the canvas when layers reach past it.
|
||||
/// None when no layer brought any art in.
|
||||
fn psd_groups(mut doc: Document) -> Option<(Art, Rect)> {
|
||||
let canvas = doc.artboards.first()?.rect;
|
||||
let nodes = psd_objects(&std::mem::take(&mut doc.layers));
|
||||
// Hidden layers count too: showing one later must not draw past the canvas.
|
||||
let symbols = doc.symbol_boxes();
|
||||
let reached = nodes.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, reach(&symbols, n)))?;
|
||||
let past = reached.union(canvas) != canvas;
|
||||
Some((Art::Vector { src: Box::new(doc), nodes, clip: past.then_some(canvas) }, canvas))
|
||||
}
|
||||
|
||||
/// The slices of the PSD or PSB file `bytes` (none without it) laid over `canvas`, the natural box
|
||||
/// of its art; their warnings go to `warnings`.
|
||||
fn psd_slices(bytes: Option<&[u8]>, canvas: Rect, warnings: &mut Vec<String>) -> Slices {
|
||||
let Some(bytes) = bytes else { return vec![] };
|
||||
let (slices, notes) = fileio::psd_slices(bytes, canvas);
|
||||
warnings.extend(notes);
|
||||
slices
|
||||
}
|
||||
|
||||
/// The bounds of `n` and every object inside it, hidden ones included.
|
||||
fn reach(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
match n.children() {
|
||||
Some(kids) => kids.iter().fold(None, |acc, k| vectorcraft_geom::union_opt(acc, reach(symbols, k))),
|
||||
None => n.geometric_bounds_with(symbols),
|
||||
}
|
||||
}
|
||||
|
||||
/// The layers a PSD import made as objects: a layer of sublayers as a group of them, and a layer
|
||||
/// holding one image as that image, each with the layer's name, visibility, opacity, blend mode,
|
||||
/// isolation and opacity mask.
|
||||
fn psd_objects(layers: &[Arc<Node>]) -> Vec<Node> {
|
||||
layers
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let mut n = (**l).clone();
|
||||
let NodeKind::Layer { children, .. } = &l.kind else { return n };
|
||||
n.kind = match &children[..] {
|
||||
[c] if matches!(c.kind, NodeKind::Image(_)) => c.kind.clone(),
|
||||
_ => NodeKind::Group { children: psd_objects(children).into_iter().map(Arc::new).collect(), clip: false },
|
||||
};
|
||||
n
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Page `page` (1-based) of the PDF/.ai/.ait file `src` (`bytes`, read from `path` when there is
|
||||
/// one) as art to place: clipped to the box `opts.crop` names, or (`bounding`) the bounds of its
|
||||
/// art; read with `opts.password`. Only the page placed is read. A .ai saved without PDF
|
||||
@@ -548,6 +661,7 @@ pub struct PlaceJob {
|
||||
pub struct PlaceRead {
|
||||
job: PlaceJob,
|
||||
loaded: Loaded,
|
||||
slices: Slices,
|
||||
}
|
||||
|
||||
impl PlaceJob {
|
||||
@@ -562,7 +676,7 @@ impl PlaceJob {
|
||||
/// the renderers' image store for the first frame that draws them
|
||||
/// ([`super::links::readable_and_kept`]).
|
||||
pub fn read(self) -> Result<PlaceRead> {
|
||||
let mut loaded = load(&self.params, PLACE, self.target, true)?;
|
||||
let (mut loaded, slices) = load_sliced(&self.params, PLACE, self.target, true)?;
|
||||
let linked = loaded.link.is_some() && bool_or(&self.params, "link", true);
|
||||
match &mut loaded.art {
|
||||
Art::Image(img, _) => {
|
||||
@@ -572,7 +686,7 @@ impl PlaceJob {
|
||||
Art::Dcs(a) => a.img.blob = super::links::readable(a.img.blob.clone(), false, true)?,
|
||||
_ => {}
|
||||
}
|
||||
Ok(PlaceRead { job: self, loaded })
|
||||
Ok(PlaceRead { job: self, loaded, slices })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -653,7 +767,7 @@ fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> {
|
||||
|
||||
/// Place the file `read` holds in the active document.
|
||||
fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
let PlaceRead { job: PlaceJob { params, old, target: read_for, .. }, mut loaded } = read;
|
||||
let PlaceRead { job: PlaceJob { params, old, target: read_for, .. }, mut loaded, slices: read_slices } = read;
|
||||
let p = ¶ms;
|
||||
let template = bool_or(p, "template", false);
|
||||
let at = at_param(p)?;
|
||||
@@ -699,7 +813,22 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
if let Art::Dcs(a) = &loaded.art {
|
||||
warnings.extend(dcs::swatch_notes(&st.doc, &a.spots));
|
||||
}
|
||||
let (id, size) = s.edit("Place", |d, sel| {
|
||||
// A PSD file's slices move and scale with its art; one that would leave the canvas is left out.
|
||||
let read_count = read_slices.len();
|
||||
let slices: Slices = read_slices
|
||||
.into_iter()
|
||||
.filter_map(|(r, o)| {
|
||||
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c);
|
||||
let placed = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c));
|
||||
super::slices::slice_rect_ok(placed).then_some((placed, o))
|
||||
})
|
||||
.collect();
|
||||
match read_count - slices.len() {
|
||||
0 => {}
|
||||
1 => warnings.push("1 slice would lie outside the canvas and was left out".into()),
|
||||
n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")),
|
||||
}
|
||||
let (id, size, slice_ids) = s.edit("Place", |d, sel| {
|
||||
let node = transformed(build(d, loaded, link), m);
|
||||
let size = node.geometric_bounds_with(&d.symbol_boxes()).unwrap_or_default();
|
||||
let (into, index) = match old {
|
||||
@@ -712,15 +841,19 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
None => (parent, usize::MAX),
|
||||
};
|
||||
let id = d.insert(into, index, node)?;
|
||||
let slice_ids: Vec<u64> = slices.into_iter().map(|(r, o)| super::slices::add_slice(d, r, o).0).collect();
|
||||
// Template art is locked: nothing to select.
|
||||
if template {
|
||||
sel.clear()
|
||||
} else {
|
||||
sel.set([id])
|
||||
}
|
||||
Ok((id, size))
|
||||
Ok((id, size, slice_ids))
|
||||
})?;
|
||||
let mut out = json!({ "ids": [id.0], "name": name, "format": format, "linked": linked, "width": size.width(), "height": size.height(), "warnings": warnings });
|
||||
if !slice_ids.is_empty() {
|
||||
out["slices"] = json!(slice_ids);
|
||||
}
|
||||
// A DCS, PSD or PSB file clipped by its clipping path: its image, which the Links commands
|
||||
// take.
|
||||
if file_clipped {
|
||||
@@ -824,7 +957,7 @@ fn read_queue(doc: u64, p: Value, queued: Vec<Value>) -> Result<QueueRead> {
|
||||
let thumbnail = p.get("thumbnail").and_then(Value::as_f64);
|
||||
let (mut entries, mut files, mut skipped) = (vec![], vec![], vec![]);
|
||||
for mut q in queued {
|
||||
for k in ["link", "template", "page", "crop", "text", "dxf"] {
|
||||
for k in ["link", "template", "page", "crop", "text", "dxf", "layers", "hiddenLayers", "importSlices"] {
|
||||
if let Some(v) = p.get(k) {
|
||||
q[k] = v.clone();
|
||||
}
|
||||
@@ -857,6 +990,14 @@ fn read_queue(doc: u64, p: Value, queued: Vec<Value>) -> Result<QueueRead> {
|
||||
}
|
||||
Err(e) => {
|
||||
let name = str_param(&q, "path").or(str_param(&q, "name")).map(fileio::file_name).unwrap_or_default();
|
||||
// An encrypted PDF stays, at a size of its own, so that a click in the app can ask
|
||||
// for its password.
|
||||
if let Some(format) = locked_pdf(&q, &e) {
|
||||
let (w, h) = (LOCKED_PAGE.width(), LOCKED_PAGE.height());
|
||||
files.push(json!({ "name": name, "format": format, "width": w, "height": h, "needsPassword": true }));
|
||||
entries.push(json!({ "params": q, "name": name, "width": w, "height": h }));
|
||||
continue;
|
||||
}
|
||||
skipped.push(json!({ "name": name, "error": e.to_string() }));
|
||||
}
|
||||
}
|
||||
@@ -864,13 +1005,29 @@ fn read_queue(doc: u64, p: Value, queued: Vec<Value>) -> Result<QueueRead> {
|
||||
Ok(QueueRead { doc, params: p, entries, files, skipped })
|
||||
}
|
||||
|
||||
/// The format id of the file `q` names when it is a PDF, `.ai` or `.ait` file (a path with one of
|
||||
/// those extensions, as the app's password dialog reads it) that opens only with a password, and
|
||||
/// reading it failed with `e` for want of that password (not for a bad option).
|
||||
fn locked_pdf(q: &Value, e: &EngineError) -> Option<&'static str> {
|
||||
if !e.to_string().contains(&vectorcraft_pdf::PdfError::NeedsPassword.to_string()) {
|
||||
return None;
|
||||
}
|
||||
let src = fileio::source(q, QUEUE).ok()?;
|
||||
if src.path.is_some() && !matches!(fileio::extension(src.name).as_str(), "pdf" | "ai" | "ait") {
|
||||
return None;
|
||||
}
|
||||
let format = fileio::detect(src.name, &src.bytes)?;
|
||||
let locked = matches!(vectorcraft_pdf::open_pdf(&src.bytes, None).map(|_| ()), Err(vectorcraft_pdf::PdfError::NeedsPassword));
|
||||
(matches!(format.id, "pdf" | "ai" | "ait") && locked).then_some(format.id)
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// `file.place.queue`'s checks (with no document open, the error `file.place.queue` gives) of
|
||||
/// `params` → what reads the files ([`QueueJob::read`]; on the
|
||||
/// desktop the Place dialog's OK with several files does this off the UI thread).
|
||||
pub fn prepare_place_queue(&self, params: &Value) -> Result<QueueJob> {
|
||||
has_doc(self).map_err(|why| EngineError::Disabled(QUEUE.into(), why))?;
|
||||
check_switches(params, &["link", "template"], QUEUE)?;
|
||||
check_switches(params, &["link", "template", "layers", "hiddenLayers", "importSlices"], QUEUE)?;
|
||||
check_numbers(params, &["thumbnail"], QUEUE)?;
|
||||
let files = queued_files(params)?;
|
||||
Ok(QueueJob { doc: self.doc()?.uid, params: params.clone(), files })
|
||||
@@ -948,7 +1105,7 @@ pub fn read_info(p: &Value) -> Result<Value> {
|
||||
check_switches(p, &["link"], "file.place.info")?;
|
||||
check_numbers(p, &["thumbnail"], "file.place.info")?;
|
||||
// A PDF/.ai page linked or not has the same size and art.
|
||||
let mut l = load(p, "file.place.info", None, false)?;
|
||||
let (mut l, slices) = load_sliced(p, "file.place.info", None, false)?;
|
||||
let natural = l.natural;
|
||||
let mut out = json!({
|
||||
"name": l.name,
|
||||
@@ -957,6 +1114,9 @@ pub fn read_info(p: &Value) -> Result<Value> {
|
||||
"height": natural.height(),
|
||||
"warnings": std::mem::take(&mut l.warnings),
|
||||
});
|
||||
if matches!(l.format.id, "psd" | "psb") {
|
||||
out["slices"] = json!(slices.len());
|
||||
}
|
||||
if let Art::Image(img, _) = &l.art {
|
||||
let (x, y) = img.ppi.unwrap_or((72.0, 72.0));
|
||||
out["pixelWidth"] = json!(img.width);
|
||||
|
||||
@@ -38,7 +38,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use roxmltree::Node;
|
||||
use craft_xml::{Canonical, Doctype, El, Limits, Names, Options};
|
||||
use vectorcraft_doc::text::Kashida;
|
||||
use vectorcraft_doc::{CharPosition, CharStyle, Justify, ParaDirection, ParaStyle, ScriptMetrics, TextRun};
|
||||
|
||||
@@ -88,6 +88,7 @@ const MAX_RUNS: usize = 100_000;
|
||||
|
||||
/// WordprocessingML's namespaces: Transitional, then Strict.
|
||||
const W: [&str; 2] = ["http://schemas.openxmlformats.org/wordprocessingml/2006/main", "http://purl.oclc.org/ooxml/wordprocessingml/main"];
|
||||
const DOCX_NS: Canonical<'static> = Canonical::new(&[("w", W[0]), ("w", W[1])]);
|
||||
|
||||
/// Is the file `name` with `bytes` a Word document: a ZIP archive named `.docx`, or one that holds
|
||||
/// `word/document.xml`?
|
||||
@@ -104,7 +105,7 @@ pub(super) fn import(bytes: &[u8], cmd: &str) -> Result<Story> {
|
||||
let main = relationship(&zip, "", "officeDocument", cmd)?.unwrap_or_else(|| "word/document.xml".into());
|
||||
let Some(xml) = part(&zip, &main, cmd)? else { return Err(bad(cmd, "not a Word document: its package has no main document part")) };
|
||||
let doc = parse(&xml, &main, cmd)?;
|
||||
if local(doc.root_element()) != Some("document") {
|
||||
if local(&doc) != Some("document") {
|
||||
return Err(bad(cmd, "not a Word document: its main part is not a WordprocessingML document"));
|
||||
}
|
||||
let folder = main.rfind('/').and_then(|i| main.get(..=i)).unwrap_or_default();
|
||||
@@ -117,7 +118,7 @@ pub(super) fn import(bytes: &[u8], cmd: &str) -> Result<Story> {
|
||||
if let Some(xml) = part(&zip, &styles, cmd)? {
|
||||
r.styles(&parse(&xml, &styles, cmd)?);
|
||||
}
|
||||
if let Some(body) = doc.root_element().children().find(|n| local(*n) == Some("body")) {
|
||||
if let Some(body) = child(&doc, "body") {
|
||||
r.block(body, 0);
|
||||
}
|
||||
r.finish(cmd)
|
||||
@@ -158,57 +159,21 @@ fn part(zip: &Archive, name: &str, cmd: &str) -> Result<Option<String>> {
|
||||
}
|
||||
|
||||
/// The XML of the part `name`.
|
||||
fn parse<'a>(xml: &'a str, name: &str, cmd: &str) -> Result<roxmltree::Document<'a>> {
|
||||
// roxmltree parses nested elements recursively.
|
||||
if nesting(xml) > MAX_NESTING {
|
||||
return Err(bad(cmd, format!("`{name}` in the Word document nests elements more than {MAX_NESTING} deep")));
|
||||
fn parse(xml: &str, name: &str, cmd: &str) -> Result<El> {
|
||||
let opts = Options {
|
||||
names: Names::Canonical(&DOCX_NS),
|
||||
doctype: Doctype::Reject,
|
||||
limits: Limits { max_depth: MAX_NESTING, max_nodes: MAX_NODES as usize, ..Limits::DEFAULT },
|
||||
..Options::default()
|
||||
}
|
||||
let opts = roxmltree::ParsingOptions { nodes_limit: MAX_NODES, ..roxmltree::ParsingOptions::default() };
|
||||
roxmltree::Document::parse_with_options(xml, opts).map_err(|e| bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")))
|
||||
}
|
||||
|
||||
/// How deep the elements of `xml` nest: start tags less end tags, at most, outside comments,
|
||||
/// CDATA sections, processing instructions, declarations and quoted attribute values.
|
||||
pub(crate) fn nesting(xml: &str) -> usize {
|
||||
let b = xml.as_bytes();
|
||||
let (mut depth, mut most, mut i) = (0usize, 0usize, 0usize);
|
||||
// The index just past the first `end` at or after `from` (the end of the text if none).
|
||||
let past = |from: usize, end: &[u8]| {
|
||||
b.get(from..).and_then(|rest| rest.windows(end.len()).position(|w| w == end)).map_or(b.len(), |at| from + at + end.len())
|
||||
};
|
||||
while let Some(at) = b.get(i..).and_then(|rest| rest.iter().position(|&c| c == b'<')) {
|
||||
let start = i + at;
|
||||
let rest = b.get(start..).unwrap_or_default();
|
||||
if rest.starts_with(b"<!--") {
|
||||
i = past(start + 4, b"-->");
|
||||
} else if rest.starts_with(b"<![CDATA[") {
|
||||
i = past(start + 9, b"]]>");
|
||||
} else if rest.starts_with(b"<?") {
|
||||
i = past(start + 2, b"?>");
|
||||
} else if rest.starts_with(b"<!") || rest.starts_with(b"</") {
|
||||
depth = depth.saturating_sub(usize::from(rest.starts_with(b"</")));
|
||||
i = past(start + 2, b">");
|
||||
} else {
|
||||
// A start tag: up to its `>` outside quotes; `/>` closes it at once.
|
||||
let mut j = start + 1;
|
||||
let mut quote = None;
|
||||
while let Some(&c) = b.get(j) {
|
||||
match (quote, c) {
|
||||
(None, b'"' | b'\'') => quote = Some(c),
|
||||
(Some(q), _) if c == q => quote = None,
|
||||
(None, b'>') => break,
|
||||
_ => {}
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
if b.get(j.saturating_sub(1)) != Some(&b'/') {
|
||||
depth += 1;
|
||||
most = most.max(depth);
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
}
|
||||
most
|
||||
.strict();
|
||||
let doc = opts.parse(xml.as_bytes()).map_err(|e| match e {
|
||||
craft_xml::Error::TooDeep(_) => bad(cmd, format!("`{name}` in the Word document nests elements more than {MAX_NESTING} deep")),
|
||||
_ => bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")),
|
||||
})?;
|
||||
crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits)
|
||||
.map_err(|e| bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")))?;
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// The part that the first relationship of part `source` (`""`: the package) whose type ends in
|
||||
@@ -220,11 +185,10 @@ fn relationship(zip: &Archive, source: &str, kind: &str, cmd: &str) -> Result<Op
|
||||
let Some(xml) = part(zip, &rels, cmd)? else { return Ok(None) };
|
||||
let doc = parse(&xml, &rels, cmd)?;
|
||||
let target = doc
|
||||
.root_element()
|
||||
.children()
|
||||
.filter(|n| n.tag_name().name() == "Relationship" && n.attribute("TargetMode") != Some("External"))
|
||||
.find(|n| n.attribute("Type").is_some_and(|t| t.rsplit('/').next() == Some(kind)))
|
||||
.and_then(|n| n.attribute("Target"));
|
||||
.elements()
|
||||
.filter(|n| n.local() == "Relationship" && n.attr("TargetMode") != Some("External"))
|
||||
.find(|n| n.attr("Type").is_some_and(|t| t.rsplit('/').next() == Some(kind)))
|
||||
.and_then(|n| n.attr("Target"));
|
||||
Ok(target.map(|t| resolve(folder, t)))
|
||||
}
|
||||
|
||||
@@ -248,22 +212,22 @@ fn resolve(folder: &str, target: &str) -> String {
|
||||
}
|
||||
|
||||
/// `n`'s local name when it is a WordprocessingML element.
|
||||
fn local<'a>(n: Node<'a, '_>) -> Option<&'a str> {
|
||||
(n.is_element() && n.tag_name().namespace().is_some_and(|ns| W.contains(&ns))).then(|| n.tag_name().name())
|
||||
fn local(n: &El) -> Option<&str> {
|
||||
n.name.strip_prefix("w:")
|
||||
}
|
||||
|
||||
/// `n`'s first WordprocessingML child element named `name`.
|
||||
fn child<'a, 'i>(n: Node<'a, 'i>, name: &str) -> Option<Node<'a, 'i>> {
|
||||
n.children().find(|c| local(*c) == Some(name))
|
||||
fn child<'a>(n: &'a El, name: &str) -> Option<&'a El> {
|
||||
n.elements().find(|c| local(c) == Some(name))
|
||||
}
|
||||
|
||||
/// `n`'s WordprocessingML attribute `name`.
|
||||
fn attr<'a>(n: Node<'a, '_>, name: &str) -> Option<&'a str> {
|
||||
n.attributes().find(|a| a.name() == name && a.namespace().is_some_and(|ns| W.contains(&ns))).map(|a| a.value())
|
||||
fn attr<'a>(n: &'a El, name: &str) -> Option<&'a str> {
|
||||
n.attrs.iter().find_map(|(k, v)| k.strip_prefix("w:").filter(|&l| l == name).map(|_| v.as_str()))
|
||||
}
|
||||
|
||||
/// An on/off property (ST_OnOff): on unless `w:val` is `false`, `0` or `off`.
|
||||
fn on(n: Node) -> bool {
|
||||
fn on(n: &El) -> bool {
|
||||
!matches!(attr(n, "val"), Some("false" | "0" | "off"))
|
||||
}
|
||||
|
||||
@@ -280,12 +244,12 @@ fn measure(v: &str, per_pt: f64) -> Option<f64> {
|
||||
}
|
||||
|
||||
/// Twentieths of a point.
|
||||
fn twips(n: Node, name: &str) -> Option<f64> {
|
||||
fn twips(n: &El, name: &str) -> Option<f64> {
|
||||
attr(n, name).and_then(|v| measure(v, 20.0))
|
||||
}
|
||||
|
||||
/// Half points.
|
||||
fn half_points(n: Node) -> Option<f64> {
|
||||
fn half_points(n: &El) -> Option<f64> {
|
||||
attr(n, "val").and_then(|v| measure(v, 2.0))
|
||||
}
|
||||
|
||||
@@ -462,21 +426,21 @@ struct Reader {
|
||||
|
||||
impl Reader {
|
||||
/// The major and minor fonts of a theme part's font scheme.
|
||||
fn theme_fonts(&mut self, doc: &roxmltree::Document) {
|
||||
fn theme_fonts(&mut self, doc: &El) {
|
||||
for (slot, scheme) in self.theme.iter_mut().zip(["majorFont", "minorFont"]) {
|
||||
*slot = doc
|
||||
.descendants()
|
||||
.find(|n| n.tag_name().name() == scheme)
|
||||
.and_then(|n| n.children().find(|c| c.tag_name().name() == "latin"))
|
||||
.and_then(|n| n.attribute("typeface"))
|
||||
*slot = std::iter::once(doc)
|
||||
.chain(doc.descendants())
|
||||
.find(|n| n.local() == scheme)
|
||||
.and_then(|n| n.elements().find(|c| c.local() == "latin"))
|
||||
.and_then(|n| n.attr("typeface"))
|
||||
.map(font_name)
|
||||
.filter(|f| !f.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// The document defaults and the styles of the styles part.
|
||||
fn styles(&mut self, doc: &roxmltree::Document) {
|
||||
for n in doc.root_element().children() {
|
||||
fn styles(&mut self, doc: &El) {
|
||||
for n in doc.elements() {
|
||||
match local(n) {
|
||||
Some("docDefaults") => {
|
||||
let props = |outer: &str, inner: &str| child(n, outer).and_then(|d| child(d, inner));
|
||||
@@ -526,7 +490,7 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// The number of the font a `w:rFonts` element names.
|
||||
fn font(&mut self, n: Node) -> Option<usize> {
|
||||
fn font(&mut self, n: &El) -> Option<usize> {
|
||||
let theme = |v: &str| self.theme.get(usize::from(v.starts_with("minor"))).and_then(Option::as_deref);
|
||||
let name = attr(n, "asciiTheme")
|
||||
.and_then(theme)
|
||||
@@ -549,9 +513,9 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// The run properties of a `w:rPr` element.
|
||||
fn run_props(&mut self, rpr: Node) -> RunProps {
|
||||
fn run_props(&mut self, rpr: &El) -> RunProps {
|
||||
let mut p = RunProps::default();
|
||||
for n in rpr.children() {
|
||||
for n in rpr.elements() {
|
||||
match local(n) {
|
||||
Some("rFonts") => p.font = self.font(n),
|
||||
Some("b") => p.bold = Some(on(n)),
|
||||
@@ -594,11 +558,11 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// The paragraphs, tables and containers of them that are `n`'s children.
|
||||
fn block(&mut self, n: Node, depth: usize) {
|
||||
fn block(&mut self, n: &El, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
for c in n.children() {
|
||||
for c in n.elements() {
|
||||
if self.full {
|
||||
return;
|
||||
}
|
||||
@@ -617,7 +581,7 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// A table: each row a paragraph, its cells separated by tabs.
|
||||
fn table(&mut self, tbl: Node, depth: usize) {
|
||||
fn table(&mut self, tbl: &El, depth: usize) {
|
||||
for row in items(tbl, "tr", depth) {
|
||||
for cell in items(row, "tc", depth) {
|
||||
self.flush();
|
||||
@@ -638,7 +602,7 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// A paragraph.
|
||||
fn paragraph(&mut self, p: Node, depth: usize) {
|
||||
fn paragraph(&mut self, p: &El, depth: usize) {
|
||||
self.flush();
|
||||
let ppr = child(p, "pPr");
|
||||
let style = ppr
|
||||
@@ -675,11 +639,11 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// The runs of a paragraph, and the containers of runs in it.
|
||||
fn inline(&mut self, n: Node, depth: usize) {
|
||||
fn inline(&mut self, n: &El, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
for c in n.children() {
|
||||
for c in n.elements() {
|
||||
match local(c) {
|
||||
Some("r") => self.run(c),
|
||||
Some("hyperlink" | "ins" | "moveTo" | "smartTag" | "customXml" | "fldSimple" | "dir" | "bdo") => self.inline(c, depth + 1),
|
||||
@@ -694,7 +658,7 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// A run.
|
||||
fn run(&mut self, r: Node) {
|
||||
fn run(&mut self, r: &El) {
|
||||
let rpr = child(r, "rPr");
|
||||
let mut chars = self.base;
|
||||
let style = rpr
|
||||
@@ -709,11 +673,10 @@ impl Reader {
|
||||
let props = self.run_props(n);
|
||||
chars.apply(&props, false);
|
||||
}
|
||||
for c in r.children() {
|
||||
for c in r.elements() {
|
||||
match local(c) {
|
||||
Some("t") => {
|
||||
// Comments and processing instructions may split the text.
|
||||
for ch in c.children().filter(|n| n.is_text()).filter_map(|n| n.text()).flat_map(str::chars) {
|
||||
for ch in c.text().chars() {
|
||||
self.put(ch, chars);
|
||||
}
|
||||
}
|
||||
@@ -907,9 +870,9 @@ fn font_name(name: &str) -> String {
|
||||
}
|
||||
|
||||
/// The paragraph properties of a `w:pPr` element.
|
||||
fn para_props(ppr: Node) -> ParaProps {
|
||||
fn para_props(ppr: &El) -> ParaProps {
|
||||
let mut p = ParaProps::default();
|
||||
for n in ppr.children() {
|
||||
for n in ppr.elements() {
|
||||
match local(n) {
|
||||
Some("jc") => {
|
||||
p.align = match attr(n, "val") {
|
||||
@@ -945,12 +908,12 @@ fn para_props(ppr: Node) -> ParaProps {
|
||||
}
|
||||
|
||||
/// `n`'s children named `name`, and those inside content controls and custom XML among them.
|
||||
fn items<'a, 'i>(n: Node<'a, 'i>, name: &str, depth: usize) -> Vec<Node<'a, 'i>> {
|
||||
fn items<'a>(n: &'a El, name: &str, depth: usize) -> Vec<&'a El> {
|
||||
let mut out = vec![];
|
||||
if depth > MAX_DEPTH {
|
||||
return out;
|
||||
}
|
||||
for c in n.children() {
|
||||
for c in n.elements() {
|
||||
match local(c) {
|
||||
Some(l) if l == name => out.push(c),
|
||||
Some("sdt") => {
|
||||
@@ -979,15 +942,6 @@ mod tests {
|
||||
assert_eq!(measure("wide", 20.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nesting_counts_elements_outside_markup_that_is_not_an_element() {
|
||||
assert_eq!(nesting(r#"<?xml version="1.0"?><a><b x="1>2" y='</c>'><c/></b><!-- <d><e> --><![CDATA[<f><g>]]></a>"#), 2);
|
||||
assert_eq!(nesting("<a><b><c>"), 3, "unclosed elements count");
|
||||
assert_eq!(nesting("</a></b><a>"), 1);
|
||||
assert_eq!(nesting("<a x=\"unterminated"), 1);
|
||||
assert_eq!(nesting(""), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targets_resolve_against_their_folder() {
|
||||
assert_eq!(resolve("", "word/document.xml"), "word/document.xml");
|
||||
|
||||
@@ -40,6 +40,9 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.image.colorMask",
|
||||
"addon.image.removeBackground",
|
||||
"addon.image.removeColorMask",
|
||||
"addon.packaging.roles",
|
||||
"addon.packaging.setRole",
|
||||
"addon.packaging.setRoleSwatch",
|
||||
"addon.pathtools.addPoints",
|
||||
"addon.pathtools.close",
|
||||
"addon.pathtools.corner",
|
||||
|
||||
@@ -486,7 +486,9 @@ fn imaged(n: &Node, which: Which) -> bool {
|
||||
let live = filters
|
||||
&& pixels == 1
|
||||
&& effects::svg_filter::writes_live(&n.appearance.effects)
|
||||
&& fx.iter().any(|f| matches!(f, RasterFx::Pixel(effects::PixelFx::Svg(s)) if s.in_points() && (!s.measured() || fx.len() == 1) && s.writes_as_svg11()));
|
||||
&& fx
|
||||
.iter()
|
||||
.any(|f| matches!(f, RasterFx::Pixel(effects::PixelFx::Svg(s)) if (!s.measured() || fx.len() == 1) && s.writes_as_svg11() && s.opens_again()));
|
||||
(pixels > 0 && !live)
|
||||
|| (fx.iter().any(|f| matches!(f, RasterFx::DropShadow { darkness: Some(_), .. })) && (cmyk || !simple_rgb_shadow_source(n, &fx)))
|
||||
}
|
||||
|
||||
@@ -8,9 +8,10 @@ use vectorcraft_doc::{Document, LockedArtboards, Node, NodeId, NodeKind};
|
||||
use vectorcraft_tools::builder::is_live_paint;
|
||||
|
||||
use super::object::can_align;
|
||||
use super::panelcmds::artboard_at;
|
||||
use super::wand::{fill_of, stroke_of};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index, ok, str_param,
|
||||
CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index_opt, ok, str_param,
|
||||
switch_or, text_param,
|
||||
};
|
||||
use crate::DocState;
|
||||
@@ -31,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"All on Active Artboard",
|
||||
["Select"],
|
||||
Some("Cmd+Alt+A"),
|
||||
"{artboard?: index (0-based; the app passes the active one; default: the first)}",
|
||||
"{artboard?: index (0-based whole number; the app passes the active one; default, or null: the first)}",
|
||||
has_doc,
|
||||
all_on_artboard
|
||||
),
|
||||
@@ -229,7 +230,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Appearance Attribute",
|
||||
["Select", "Same"],
|
||||
None,
|
||||
"{item?: appearance item index} the objects sharing an appearance attribute of the first selected object: its fill or stroke `item` (default: the Appearance panel's active item), else its first effect, else its topmost fill (compound paths as select.same.fillColor)",
|
||||
"{item?: appearance item index (0-based whole number; default, or null: the Appearance panel's active item)} the objects sharing an appearance attribute of the first selected object: its fill or stroke `item` (default: the Appearance panel's active item), else its first effect, else its topmost fill (compound paths as select.same.fillColor)",
|
||||
has_selection,
|
||||
same_attribute
|
||||
),
|
||||
@@ -428,7 +429,7 @@ fn all(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
fn all_on_artboard(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let i = p.get("artboard").and_then(Value::as_u64).map_or(0, index);
|
||||
let i = artboard_at(&st.doc, p, "artboard", "select.allOnArtboard")?.unwrap_or(0);
|
||||
let r = st.doc.artboards.get(i).map(|a| a.rect).ok_or_else(|| bad("select.allOnArtboard", "no such artboard"))?;
|
||||
let symbols = st.doc.symbol_boxes();
|
||||
let ids: Vec<NodeId> =
|
||||
@@ -1217,10 +1218,10 @@ enum Attribute {
|
||||
|
||||
fn same_attribute(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "select.same.appearanceAttribute";
|
||||
let item = index_opt(p, "item", cmd)?.or(s.appearance_item());
|
||||
let st = s.doc()?;
|
||||
let (refn, _) = same_reference(st, cmd)?;
|
||||
let ap = &refn.appearance;
|
||||
let item = p.get("item").and_then(Value::as_u64).map(index).or(s.appearance_item());
|
||||
let attr = match (item.and_then(|i| ap.items.get(i)), ap.effects.first()) {
|
||||
(Some(it), _) => Attribute::Item(it.clone()),
|
||||
(None, Some(e)) => Attribute::Effect(e.clone()),
|
||||
|
||||
@@ -234,8 +234,11 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let item = item_target(s, p, C)?.of_kind(s, false);
|
||||
let mut ids = if item == ItemTarget::Top { own_stroke_or_leaves(s, p)? } else { item.targets(s, p)? };
|
||||
let new_art = no_targets(&ids, p);
|
||||
let given = !ids.is_empty();
|
||||
// The art of a graph design in a series keeps the design's stroke.
|
||||
ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
|
||||
ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?;
|
||||
// With only design art, the weight for new art stays as it is too.
|
||||
let only_design_art = given && ids.is_empty();
|
||||
if item == ItemTarget::Top {
|
||||
// Images and symbol instances take no stroke from the panel.
|
||||
let d = &s.doc()?.doc;
|
||||
@@ -329,7 +332,9 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
// Commit the new-art template only after the complete request is validated
|
||||
// and the selected artwork edit has succeeded.
|
||||
if let Some(w) = change.weight {
|
||||
if let Some(w) = change.weight
|
||||
&& !only_design_art
|
||||
{
|
||||
s.paint.stroke_width = w;
|
||||
}
|
||||
if new_art && let Some(st) = s.new_art_stroke_mut() {
|
||||
@@ -372,7 +377,7 @@ fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result<Value> {
|
||||
}
|
||||
return Ok(json!({"objects": 0}));
|
||||
}
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
|
||||
let ids = super::appearance::drop_design_art_rows(s, ids, item, false, c)?;
|
||||
let label = if up { "Stroke Weight Up" } else { "Stroke Weight Down" };
|
||||
edit_items(s, &ids, item, None, c, label, false, |n, index| {
|
||||
if index.is_none()
|
||||
@@ -517,7 +522,7 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = item.targets(s, p)?;
|
||||
let new_art = no_targets(&ids, p);
|
||||
// The art of a graph design in a series keeps the design's stroke.
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
|
||||
let ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?;
|
||||
let arrows_and_profile = |st: &mut StrokeLayer| {
|
||||
if let Some(sc) = scale {
|
||||
st.arrow_scale = sc;
|
||||
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Swatch Options",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient} or {swatch}) or {pattern: name} replacing the swatch's colour; gradient or pattern with one of the same kind (stored as swatch.new stores it: a gradient keeps its aspect with or without start/end and holds no swatch link; a pattern is untransformed)} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}",
|
||||
"{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient} or {swatch}) or {pattern: name} replacing the swatch's colour; gradient or pattern with one of the same kind (stored as swatch.new stores it: a gradient keeps its aspect with or without start/end and holds no swatch link; a pattern is untransformed)} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). A fold line role the swatch carries (addon.packaging.roles) stays with it under its new name, and moves to a new swatch name when Global is turned off. Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}",
|
||||
has_doc,
|
||||
swatch_edit
|
||||
),
|
||||
@@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Merge Swatches",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{names: [two or more solid-colour swatches], name?: the merged swatch's name (one swatch kept)} keep the first (its name and colour) and delete the others; paints linked to them take its colour and link to it (or unlink when it isn't global), as one undo step → {name, merged: [deleted names], relinked}",
|
||||
"{names: [two or more solid-colour swatches], name?: the merged swatch's name (one swatch kept)} keep the first (its name and colour) and delete the others; paints linked to them take its colour and link to it (or unlink when it isn't global), and gradient stops linked to them drop their process plates, as one undo step. When the kept swatch is global and carries no fold line role (addon.packaging.roles), it takes the role of the first merged swatch that carried one → {name, merged: [deleted names], relinked}",
|
||||
has_doc,
|
||||
swatch_merge
|
||||
),
|
||||
@@ -688,6 +688,11 @@ impl Relink {
|
||||
/// batch, and a canceled batch preview, put back the paints the batch started with. A change is
|
||||
/// recorded with the step just made, so Undo and Redo put these paints back with the document.
|
||||
pub(super) fn map_default_paints(s: &mut Session, f: &mut LinkFn) -> Result<()> {
|
||||
map_default_paints_by(s, &mut |p| p.map_links(f))
|
||||
}
|
||||
|
||||
/// [`map_default_paints`] with `f` applied to each whole paint; `f` returns true when it changed it.
|
||||
fn map_default_paints_by(s: &mut Session, f: &mut dyn FnMut(&mut Paint) -> bool) -> Result<()> {
|
||||
if s.in_interaction() && s.batch_stash.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -699,7 +704,7 @@ pub(super) fn map_default_paints(s: &mut Session, f: &mut LinkFn) -> Result<()>
|
||||
});
|
||||
let mut changed = false;
|
||||
for p in [&mut pd.fill, &mut pd.stroke].into_iter().chain(template) {
|
||||
changed |= p.map_links(f);
|
||||
changed |= f(p);
|
||||
}
|
||||
if changed {
|
||||
super::colormgmt::record_new_art_colors(s, start)?;
|
||||
@@ -932,6 +937,8 @@ fn swatch_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let relinked = map_swatch_links(d, &mut |c, l, t| relink.apply(c, l, t));
|
||||
// A fold line role carried by the swatch follows its new name, as the strokes do.
|
||||
super::addons::role_swatch_edited(d, &name, &to, global);
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
|
||||
Ok(relinked)
|
||||
})?;
|
||||
@@ -1124,17 +1131,39 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
*l = link.clone();
|
||||
true
|
||||
};
|
||||
// A stop linked to a merged swatch loses its process plates, which printed with that ink.
|
||||
let mut unplate = |p: &Paint| {
|
||||
let mut q = p.clone();
|
||||
drop_stop_plates(&mut q, &merged_names).then_some(q)
|
||||
};
|
||||
let colorized_ok = super::paint::check_colorized(d).is_ok();
|
||||
let relinked = s.edit("Merge Swatches", |d, _| {
|
||||
take_swatches(d, merged, |_| true);
|
||||
map_all_paints(d, &mut unplate);
|
||||
let relinked = map_swatch_links(d, &mut relink);
|
||||
// The lines of a merged role swatch link to the kept swatch, which takes that role.
|
||||
super::addons::role_swatches_merged(d, merged, keep, link.is_some());
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
|
||||
Ok(relinked)
|
||||
})?;
|
||||
map_default_paints(s, &mut relink)?;
|
||||
map_default_paints_by(s, &mut |p| {
|
||||
let unplated = drop_stop_plates(p, &merged_names);
|
||||
p.map_links(&mut relink) | unplated
|
||||
})?;
|
||||
Ok(json!({"name": keep, "merged": merged, "relinked": relinked}))
|
||||
}
|
||||
|
||||
/// Clear the process plates of `p`'s gradient stops linked to a swatch in `names`. True when any
|
||||
/// stop had plates.
|
||||
fn drop_stop_plates(p: &mut Paint, names: &HashSet<&str>) -> bool {
|
||||
let Paint::Gradient(g) = p else { return false };
|
||||
g.gradient
|
||||
.stops
|
||||
.iter_mut()
|
||||
.filter(|st| st.swatch.as_deref().is_some_and(|l| names.contains(l)))
|
||||
.fold(false, |ch, st| st.plates.take().is_some() | ch)
|
||||
}
|
||||
|
||||
fn swatch_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.ungroup";
|
||||
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?.to_string();
|
||||
|
||||
Loaded 100 of 360 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user