Merge main into fix/text-a-script-throws-itself-is-not-translated

This commit is contained in:
dotCooCoo committed 2026-11-15 16:06:11 -08:00
commit 5805bbdd5a
511 files changed
+45693 -4375

No files matched your search

Generated
+155 -18
View File
@@ -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",
@@ -1010,6 +1016,14 @@ name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
[[package]]
name = "craft-gzip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b0d84cd15db39f2af9869cfb47b8b72cbeca3f20#b0d84cd15db39f2af9869cfb47b8b72cbeca3f20"
dependencies = [
"flate2",
]
[[package]]
name = "craft-i18n"
version = "0.1.0"
@@ -1033,6 +1047,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 +1134,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 +1160,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"
@@ -1156,7 +1220,7 @@ dependencies = [
[[package]]
name = "craft-vectorcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
source = "git+https://github.com/storytold/craft-libs?rev=b0d84cd15db39f2af9869cfb47b8b72cbeca3f20#b0d84cd15db39f2af9869cfb47b8b72cbeca3f20"
dependencies = [
"flate2",
"serde",
@@ -1203,6 +1267,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 +1788,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 +2836,7 @@ dependencies = [
"moxcms",
"num-traits",
"png 0.18.1",
"qoi",
"tiff",
"zune-core 0.5.3",
"zune-jpeg 0.5.15",
@@ -3200,6 +3290,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 +3495,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 +4467,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 +5852,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 +6670,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 +6683,6 @@ dependencies = [
"log",
"proptest",
"rayon",
"roxmltree 0.21.2",
"rustix 1.1.6",
"ruzstd",
"same-file",
@@ -6625,6 +6749,7 @@ dependencies = [
name = "vectorcraft-format"
version = "0.24.1"
dependencies = [
"craft-gzip",
"craft-vectorcraft-format",
"flate2",
"proptest",
@@ -6632,6 +6757,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"vectorcraft-brush",
"vectorcraft-doc",
"vectorcraft-geom 0.24.1",
"vectorcraft-testkit",
@@ -6733,6 +6859,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",
@@ -6743,7 +6870,6 @@ dependencies = [
"md-5",
"objc2-core-foundation",
"objc2-core-graphics",
"roxmltree 0.21.2",
"serde",
"serde_json",
"sha2",
@@ -6784,16 +6910,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",
@@ -6916,6 +7042,7 @@ dependencies = [
name = "vectorcraft-trace"
version = "0.24.1"
dependencies = [
"craft-image-codecs",
"image",
"kurbo 0.13.1",
"serde",
@@ -6929,6 +7056,7 @@ name = "vectorcraft-ui-egui"
version = "0.24.1"
dependencies = [
"bytemuck",
"chrono",
"craft-keymap",
"craft-ui",
"craft-update",
@@ -8369,6 +8497,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"
+8 -2
View File
@@ -21,7 +21,8 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a637
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] }
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b0d84cd15db39f2af9869cfb47b8b72cbeca3f20" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "b0d84cd15db39f2af9869cfb47b8b72cbeca3f20" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" }
@@ -30,9 +31,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" }
+2 -1
View File
@@ -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.
+4 -3
View File
@@ -24,7 +24,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
| | Value | Kind |
|---|---|---|
| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) |
| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 717/719 wired (99.7%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) |
| **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated |
| **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated |
| **To full parity** | **~360–590 h** one agent · ~95–165 h with 4–6 agents | estimated |
@@ -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.
+2 -1
View File
@@ -238,10 +238,11 @@ fn main() -> ExitCode {
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
/// (`script.listInstalled`), keeps File Info's metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
/// `VECTORCRAFT_CONFIG_DIR` apply as they do there.
fn with_stores(mut h: Headless) -> Headless {
prefs_dir::attach_scripts_dir(&mut h.session);
prefs_dir::attach_metadata_templates_dir(&mut h.session);
prefs_dir::attach_new_doc_profiles(&mut h.session);
prefs_dir::attach_profile_store(&mut h.session);
prefs_dir::attach_color_settings(&mut h.session);
+302 -50
View File
@@ -155,8 +155,18 @@ 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> {
// A list of more than MAX_URIS files (untrusted data) names none, before any file is looked at.
if paths.len() > MAX_URIS {
return None;
}
paths.into_iter().find_map(|path| {
// text/uri-list lines end in CRLF (RFC 2483), but arboard splits them on LF only.
let path = match path.to_str() {
@@ -197,6 +207,53 @@ fn read_rest(file: impl Read, mut data: Vec<u8>, limit: usize) -> Option<Vec<u8>
(data.len() <= limit).then_some(data)
}
/// The data `copy` takes off the clipboard, called only when `size` (what the clipboard reports
/// before the copy) is known and from 1 to `limit` bytes. `None` without a call otherwise, and
/// when the copy comes to more than `limit` bytes.
#[cfg_attr(not(any(windows, target_os = "macos")), allow(dead_code))]
fn copy_within(size: Option<usize>, limit: usize, copy: impl FnOnce() -> Option<Vec<u8>>) -> Option<Vec<u8>> {
size.filter(|&n| n > 0 && n <= limit)?;
copy().filter(|data| data.len() <= limit)
}
/// The most bytes of UTF-8 that `utf16` bytes of UTF-16 text come to: a code unit (2 bytes) is at
/// most 3 bytes of UTF-8, and a surrogate pair (4 bytes) is 4.
#[cfg_attr(not(windows), allow(dead_code))]
fn utf8_most(utf16: usize) -> usize {
utf16.div_ceil(2).saturating_mul(3)
}
/// Whether a Windows file list (`CF_HDROP`: a `DROPFILES` header, then file names each ended by a
/// NUL and the list by one more, in UTF-16 when the header's `fWide` is set) names at most `limit`
/// files. Counting stops at the first name past `limit`. A block too short for its header, or
/// whose names would start past its end, is not within.
#[cfg_attr(not(windows), allow(dead_code))]
fn drop_files_within(block: &[u8], limit: usize) -> bool {
let field = |at: usize| Some(u32::from_le_bytes(block.get(at..at.checked_add(4)?)?.try_into().ok()?));
let (Some(start), Some(wide)) = (field(0), field(16)) else {
return false;
};
let Some(names) = usize::try_from(start).ok().and_then(|start| block.get(start..)) else {
return false;
};
let (mut count, mut in_name) = (0usize, false);
for unit in names.chunks_exact(if wide != 0 { 2 } else { 1 }) {
if unit.iter().all(|&b| b == 0) {
if !in_name {
break;
}
in_name = false;
} else if !in_name {
in_name = true;
count += 1;
if count > limit {
return false;
}
}
}
true
}
/// The most URIs a copied file list may hold, VectorCraft's own limit: a longer list (untrusted
/// data) names no files.
const MAX_URIS: usize = 1024;
@@ -278,12 +335,13 @@ fn file_uri_path(uri: &str) -> Option<PathBuf> {
#[cfg(windows)]
mod win {
use std::num::NonZeroU32;
use std::num::{NonZeroU32, NonZeroUsize};
use clipboard_win::{formats, options::NoClear, raw};
use super::{
BITMAP, ClipboardRead, Cursor, Flavour, PNG, SVG, SystemClipboard, TEXT, copied_file, decode_png, dib_image, png_flavour, windows_formats,
BITMAP, ClipboardRead, Cursor, Flavour, MAX_BYTES, MAX_URIS, PNG, SVG, SystemClipboard, TEXT, copied_file, copy_within, decode_png,
dib_image, drop_files_within, png_flavour, utf8_most, windows_formats,
};
/// The device-independent bitmaps, the one that carries alpha first. Each is there whenever the
@@ -370,8 +428,11 @@ mod win {
let mut files = vec![];
{
let _open = clipboard_win::Clipboard::new_attempts(10).ok()?;
// None copied when the clipboard holds no file list.
let _ = raw::get_file_list_path(&mut files);
// None copied when the clipboard holds no file list, or one of more than MAX_BYTES
// or MAX_URIS files: the list is counted before its names are copied.
if copy_registered(formats::CF_HDROP, MAX_BYTES).is_some_and(|block| drop_files_within(&block, MAX_URIS)) {
let _ = raw::get_file_list_path(&mut files);
}
}
// The files are read with the clipboard closed again, not keeping other apps waiting.
copied_file(files, mimes).map(ClipboardRead::Now).or_else(|| {
@@ -390,44 +451,64 @@ mod win {
}
}
/// Read the first registered format of `mime` the clipboard holds into `data`.
fn read_registered(mime: &str, data: &mut Vec<u8>) -> bool {
formats_of(mime).filter(|id| raw::is_format_avail(*id)).any(|id| {
data.clear();
raw::get_vec(id, data).is_ok() && !data.is_empty()
/// The size the clipboard reports for format `id`, while it is open.
fn size_of(id: u32) -> Option<usize> {
raw::size(id).map(NonZeroUsize::get)
}
/// The data of format `id`, while the clipboard is open, copied only when its size is at most
/// `limit` bytes ([`copy_within`]).
fn copy_registered(id: u32, limit: usize) -> Option<Vec<u8>> {
copy_within(size_of(id), limit, || {
let mut data = vec![];
raw::get_vec(id, &mut data).ok()?;
Some(data)
})
}
/// The first registered format of `mime` the clipboard holds that is not empty and at most
/// [`MAX_BYTES`]; a larger one is skipped and the next tried.
fn read_registered(mime: &str) -> Option<Vec<u8>> {
formats_of(mime).filter(|id| raw::is_format_avail(*id)).find_map(|id| copy_registered(id, MAX_BYTES).filter(|data| !data.is_empty()))
}
/// A device-independent bitmap as a PNG flavour.
fn dib_png(dib: &[u8]) -> Option<Flavour> {
png_flavour(&dib_image(dib)?)
}
/// Copy both bitmap formats while the clipboard is open, then decode them in preference order.
pub(super) fn read_dibs(mut get: impl FnMut(u32) -> Option<Vec<u8>>) -> Option<ClipboardRead> {
let dibs: Vec<_> = DIBS.into_iter().filter_map(&mut get).collect();
/// `size` gives each format's size before `get` copies it, and a format of more than
/// [`MAX_BYTES`] is not copied ([`copy_within`]) and the next one is tried.
pub(super) fn read_dibs(mut size: impl FnMut(u32) -> Option<usize>, mut get: impl FnMut(u32) -> Option<Vec<u8>>) -> Option<ClipboardRead> {
let dibs: Vec<_> = DIBS.into_iter().filter_map(|id| copy_within(size(id), MAX_BYTES, || get(id))).collect();
(!dibs.is_empty()).then_some(ClipboardRead::Later(Box::new(move || dibs.iter().find_map(|dib| dib_png(dib)))))
}
/// One flavour, while the clipboard is open. A device-independent bitmap is copied here, and
/// the work that comes back decodes each captured format in preference order.
/// the work that comes back decodes each captured format in preference order. Text whose
/// UTF-16 block could come to more than [`MAX_BYTES`] as UTF-8 ([`utf8_most`]) is not read.
fn read_one(mime: &'static str) -> Option<ClipboardRead> {
let mut data = vec![];
let mime = match mime {
BITMAP if read_registered(PNG, &mut data) => PNG,
BITMAP => {
return read_dibs(|id| {
let mut dib = vec![];
raw::get_vec(id, &mut dib).ok()?;
Some(dib)
});
}
let (mime, mut data) = match mime {
BITMAP => match read_registered(PNG) {
Some(png) => (PNG, png),
None => {
return read_dibs(size_of, |id| {
let mut dib = vec![];
raw::get_vec(id, &mut dib).ok()?;
Some(dib)
});
}
},
TEXT => {
raw::get_string(&mut data).ok()?;
TEXT
let text = copy_within(size_of(formats::CF_UNICODETEXT).map(utf8_most), MAX_BYTES, || {
let mut text = vec![];
raw::get_string(&mut text).ok()?;
Some(text)
})?;
(TEXT, text)
}
m if read_registered(m, &mut data) => m,
_ => return None,
m => (m, read_registered(m)?),
};
// Memory blocks can be longer than the data: SVG text ends at its first NUL.
if mime == SVG
@@ -727,7 +808,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 +822,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 +894,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 +1535,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 +1550,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 +1714,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 +2054,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 +2145,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)
@@ -3092,7 +3216,7 @@ mod mac {
use objc2_app_kit::NSPasteboard;
use objc2_foundation::{NSArray, NSString};
use super::{Flavour, pasteboard_types};
use super::{Flavour, MAX_BYTES, copy_within, pasteboard_types};
/// Does the pasteboard hold one of `mimes` ([`pasteboard_types`])? Asks for its types only.
pub fn has(mimes: &[&'static str]) -> bool {
@@ -3103,13 +3227,16 @@ mod mac {
})
}
/// The pasteboard's data for `mime`, the first of its types held ([`pasteboard_types`]).
/// The pasteboard's data for `mime`, the first of its types held ([`pasteboard_types`]) that is
/// not empty and at most [`MAX_BYTES`]: its length is checked before it is copied, and a larger
/// type is skipped and the next tried.
pub fn read(mime: &str) -> Option<Flavour> {
autoreleasepool(|_| {
let pasteboard = NSPasteboard::generalPasteboard();
pasteboard_types(mime).iter().find_map(|&(t, mime)| {
let data = pasteboard.dataForType(&NSString::from_str(t))?.to_vec();
(!data.is_empty()).then_some(Flavour { mime, data })
let held = pasteboard.dataForType(&NSString::from_str(t))?;
let data = copy_within(Some(held.len()), MAX_BYTES, || Some(held.to_vec()))?;
Some(Flavour { mime, data })
})
})
}
@@ -3296,6 +3423,102 @@ mod tests {
assert!(uri_list_paths(list(MAX_URIS + 1).as_bytes()).is_empty());
}
/// A copied file list of more than 1,024 files pastes none, before any file is looked at,
/// wherever the list came from; 1,024 files paste the first that is art.
#[test]
fn a_copied_file_list_longer_than_the_limit_pastes_no_file() {
let d = dir("many");
let art = d.path().join("art.svg");
std::fs::write(&art, "<svg xmlns=\"http://www.w3.org/2000/svg\"/>").unwrap();
let missing = |n: usize| (0..n).map(|i| d.path().join(format!("gone{i}.png"))).collect::<Vec<_>>();
let last = [missing(MAX_URIS - 1), vec![art.clone()]].concat();
assert_eq!(copied_file(last, &PASTE_ORDER).map(|f| f.mime), Some(SVG));
// The art first: no file is opened past the count.
let first = [vec![art.clone()], missing(MAX_URIS)].concat();
assert!(copied_file(first, &PASTE_ORDER).is_none());
assert!(copied_file([missing(MAX_URIS), vec![art]].concat(), &PASTE_ORDER).is_none());
}
/// Clipboard data is copied only when the size the clipboard gives is from 1 byte to the limit,
/// and the copy is not asked for otherwise.
#[test]
fn clipboard_data_is_copied_only_when_its_size_fits() {
let copy = |size: Option<usize>, got: usize| {
let mut asked = false;
let data = copy_within(size, 8, || {
asked = true;
Some(vec![1; got])
});
(data.map(|d| d.len()), asked)
};
assert_eq!(copy(Some(8), 8), (Some(8), true));
assert_eq!(copy(Some(1), 1), (Some(1), true));
for size in [None, Some(0), Some(9), Some(usize::MAX)] {
assert_eq!(copy(size, 1), (None, false), "{size:?}");
}
// Data that comes to more than the limit after all is refused.
assert_eq!(copy(Some(8), 9), (None, true));
assert_eq!(MAX_BYTES, 64 << 20);
}
/// The UTF-8 that UTF-16 text comes to is bounded from the UTF-16 block's size alone, before
/// the text is converted: a block that could pass the limit as UTF-8 is not read.
#[test]
fn text_is_bounded_by_what_its_utf8_could_come_to() {
for text in ["", "a", "\u{20ac}\u{20ac}\u{20ac}", "\u{1f600}", "a\u{20ac}\u{1f600}\u{ffff}"] {
let utf16 = text.encode_utf16().count() * 2;
assert!(utf8_most(utf16) >= text.len(), "{text:?}");
}
// Every code unit at 3 bytes of UTF-8: the bound is exact.
assert_eq!(utf8_most("\u{20ac}\u{20ac}".encode_utf16().count() * 2), "\u{20ac}\u{20ac}".len());
let copied = |utf16: usize| copy_within(Some(utf8_most(utf16)), MAX_BYTES, || Some(vec![])).is_some();
assert!(copied(MAX_BYTES / 3 * 2));
assert!(!copied(MAX_BYTES / 3 * 2 + 2));
assert!(!copied(MAX_BYTES));
assert_eq!(utf8_most(usize::MAX), usize::MAX);
}
/// A Windows file list (CF_HDROP) of `names`: a DROPFILES header, the names in UTF-16 or one
/// byte a character, each ended by a NUL, and one more NUL.
fn drop_files(names: &[&str], wide: bool) -> Vec<u8> {
let mut block = vec![];
block.extend(20u32.to_le_bytes());
block.extend([0u8; 12]);
block.extend(u32::from(wide).to_le_bytes());
for name in names.iter().copied().chain([""]) {
for unit in name.encode_utf16().chain([0]) {
if wide {
block.extend(unit.to_le_bytes());
} else {
block.push(unit as u8);
}
}
}
block
}
#[test]
fn a_windows_file_list_is_counted_before_its_names_are_read() {
let names = |n: usize| (0..n).map(|i| format!("C:\\art\\{i}.svg")).collect::<Vec<_>>();
for wide in [true, false] {
let list = |n: usize| drop_files(&names(n).iter().map(String::as_str).collect::<Vec<_>>(), wide);
assert!(drop_files_within(&list(MAX_URIS), MAX_URIS), "{wide}");
assert!(!drop_files_within(&list(MAX_URIS + 1), MAX_URIS), "{wide}");
assert!(drop_files_within(&list(0), MAX_URIS), "{wide}");
// Names past the list's closing NUL are not counted.
let mut ended = list(2);
ended.extend(list(MAX_URIS + 1).get(20..).unwrap());
assert!(drop_files_within(&ended, 2), "{wide}");
// A list cut short counts the names it holds.
assert!(!drop_files_within(&list(3)[..list(3).len() - 4], 2), "{wide}");
}
// A header cut short, or names that would start past the block's end.
assert!(!drop_files_within(&drop_files(&["a"], true)[..19], MAX_URIS));
let mut past = drop_files(&["a"], true);
past[0..4].copy_from_slice(&u32::MAX.to_le_bytes());
assert!(!drop_files_within(&past, MAX_URIS));
}
#[test]
fn gnome_files_list_names_its_files_after_copy_or_cut() {
let paths = |list: &[u8]| gnome_copied_paths(list).into_iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>();
@@ -3349,19 +3572,48 @@ mod tests {
let valid = dib(40, 1, 1, 32, 0, &[], &bgra(&[RED]));
let mut captured = Vec::new();
let read = win::read_dibs(|id| {
captured.push(id);
match id {
CF_DIBV5 => Some(vec![40, 0, 0]),
CF_DIB => Some(valid.clone()),
_ => None,
}
})
let get = |id: u32| match id {
CF_DIBV5 => Some(vec![40, 0, 0]),
CF_DIB => Some(valid.clone()),
_ => None,
};
let read = win::read_dibs(
|id| get(id).map(|d| d.len()),
|id| {
captured.push(id);
get(id)
},
)
.unwrap();
assert_eq!(captured, [CF_DIBV5, CF_DIB]);
let flavour = read.flavour().unwrap();
assert_eq!(flavour.mime, PNG);
assert_eq!(pixels(&decode_png(&flavour.data).unwrap()), [RED]);
// A bitmap larger than the limit is not copied, and the other one still pastes.
captured.clear();
let read = win::read_dibs(
|id| if id == CF_DIBV5 { Some(MAX_BYTES + 1) } else { get(id).map(|d| d.len()) },
|id| {
captured.push(id);
get(id)
},
)
.unwrap();
assert_eq!(captured, [CF_DIB]);
assert_eq!(read.flavour().map(|f| f.mime), Some(PNG));
// Each format has the limit to itself: a first one at the limit that doesn't decode
// leaves the second to paste.
captured.clear();
let read = win::read_dibs(
|id| if id == CF_DIBV5 { Some(MAX_BYTES) } else { get(id).map(|d| d.len()) },
|id| {
captured.push(id);
get(id)
},
)
.unwrap();
assert_eq!(captured, [CF_DIBV5, CF_DIB]);
assert_eq!(read.flavour().map(|f| f.mime), Some(PNG));
}
#[test]
+47 -8
View File
@@ -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")]
@@ -498,6 +535,8 @@ fn main() -> std::process::ExitCode {
prefs_dir::attach_plugin_store(&mut session);
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
prefs_dir::attach_scripts_dir(&mut session);
// File Info's metadata templates live in their own folder next to the preferences.
prefs_dir::attach_metadata_templates_dir(&mut session);
prefs_dir::attach_new_doc_profiles(&mut session);
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
app.set_startup_update_check(true);
+8
View File
@@ -65,6 +65,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) {
}
}
/// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template
/// makes.
pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) {
if let Some(dir) = store_dir("Metadata Templates") {
session.attach_metadata_templates_dir(dir);
}
}
/// Have File › New start each category's documents from its profile in the `New Document
/// Profiles` folder, which `file.newProfiles.edit` makes.
pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) {
+242
View File
@@ -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");
}
}
+37 -1
View File
@@ -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]
+7
View File
@@ -120,6 +120,13 @@ impl StoredArt {
doc.number_mounted_art();
}
/// Sets the art on `doc` as [`Document::mounted_art`] with the ids it is stored with, the id
/// counter left as it is: what a save looks through, writing back only the brushes whose art it
/// changed ([`Self::write_back`]).
pub fn mount_as_stored(&self, doc: &mut Document) {
doc.mounted_art = self.entries.iter().flat_map(|e| e.art.iter().cloned()).collect();
}
/// Takes [`Document::mounted_art`] off `doc` and writes each brush whose art changed (new ids
/// included) back into its library entry: the entry at its index when that entry is as it was
/// read or reads as the brush as it was apart from its name, else the first entry that reads as
+1 -1
View File
@@ -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
View File
@@ -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)]
+4 -4
View File
@@ -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,
+20
View File
@@ -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());
}
}
-674
View File
@@ -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");
}
}
+448
View File
@@ -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
+98 -2
View File
@@ -94,6 +94,50 @@ impl Intent {
}
}
/// A color management policy (Edit → Color Settings): what opening a document does with a profile
/// it is tagged with that is not the working space of its model.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Policy {
/// The document loses the profile; its color numbers stay as they are.
Off,
/// The document keeps the profile.
#[default]
PreserveEmbedded,
/// The colors are converted from the profile into the working space, which keeps their
/// appearance, and the document loses the profile.
Convert,
/// CMYK only: the document loses the profile; its color numbers stay as they are.
PreserveNumbers,
}
impl Policy {
/// The RGB policies, in menu order.
pub const RGB: [Policy; 3] = [Policy::Off, Policy::PreserveEmbedded, Policy::Convert];
/// The CMYK policies, in menu order.
pub const CMYK: [Policy; 4] = [Policy::Off, Policy::PreserveEmbedded, Policy::Convert, Policy::PreserveNumbers];
/// Parse an id of [`Policy::id`].
pub fn parse(s: &str) -> Option<Self> {
[Policy::Off, Policy::PreserveEmbedded, Policy::Convert, Policy::PreserveNumbers].into_iter().find(|p| p.id() == s)
}
pub fn id(&self) -> &'static str {
match self {
Policy::Off => "off",
Policy::PreserveEmbedded => "preserveEmbedded",
Policy::Convert => "convert",
Policy::PreserveNumbers => "preserveNumbers",
}
}
pub fn label(&self) -> &'static str {
match self {
Policy::Off => "Off",
Policy::PreserveEmbedded => "Preserve Embedded Profiles",
Policy::Convert => "Convert to Working Space",
Policy::PreserveNumbers => "Preserve Numbers",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ProfileKind {
@@ -134,11 +178,25 @@ pub struct ColorSettings {
pub intent: Intent,
/// Black-point compensation.
pub bpc: bool,
/// The color management policy for RGB profiles (one of [`Policy::RGB`]). Settings saved
/// without one take the default.
#[serde(default)]
pub rgb_policy: Policy,
/// The color management policy for CMYK profiles. Settings saved without one take the default.
#[serde(default)]
pub cmyk_policy: Policy,
}
impl Default for ColorSettings {
fn default() -> Self {
Self { rgb: SRGB.into(), cmyk: GENERIC_CMYK.into(), intent: Intent::RelativeColorimetric, bpc: true }
Self {
rgb: SRGB.into(),
cmyk: GENERIC_CMYK.into(),
intent: Intent::RelativeColorimetric,
bpc: true,
rgb_policy: Policy::default(),
cmyk_policy: Policy::default(),
}
}
}
@@ -518,6 +576,41 @@ impl Cms {
Color::Rgb { r, g, b }
}
/// An RGB or CMYK colour of this context's space as the colour of the same model in `dest`'s
/// space that looks the same, converted with `intent` (Edit → Color Settings › Convert to
/// Working Space). RGB converts directly from profile to profile, and CMYK between two loaded
/// profiles through ProPhoto RGB ([`IccProfile::to_same_model_of`]), both with this context's
/// black-point compensation; CMYK goes through Lab when either space is built in. Grey and
/// Lab colours stay as they are.
pub fn convert_into(&self, dest: &Cms, c: &Color, intent: Intent) -> Color {
match *c {
Color::Rgb { r, g, b } => {
let icc = |s: &RgbSpace| match s {
RgbSpace::Icc(p) => Some(p.clone()),
RgbSpace::Srgb => builtin_rgb_cache(SRGB),
};
let [r, g, b] = icc(&self.rgb)
.zip(icc(&dest.rgb))
.and_then(|(s, d)| s.to_rgb_of(&d, &[r, g, b], intent, self.settings.bpc))
.unwrap_or_else(|| dest.srgb_to_rgb(self.rgb_to_srgb([r, g, b])));
Color::Rgb { r, g, b }
}
Color::Cmyk { c, m, y, k } => {
let inks = [c, m, y, k].map(|v| v.clamp(0.0, 1.0));
let direct = match (&self.cmyk, &dest.cmyk) {
(CmykSpace::Icc(s), CmykSpace::Icc(d)) => s.to_same_model_of(d, &inks, intent, self.settings.bpc),
_ => None,
};
let [c, m, y, k] = match direct.as_deref() {
Some(&[c, m, y, k]) => [c, m, y, k],
_ => dest.lab_to_cmyk(self.cmyk_to_lab(inks), intent),
};
Color::Cmyk { c, m, y, k }
}
Color::Gray { .. } | Color::Lab { .. } => *c,
}
}
/// How far (ΔE2000) the best CMYK reproduction of `c` is from `c` (0 for CMYK/grey colours).
pub fn gamut_error(&self, c: &Color) -> f32 {
match c {
@@ -966,8 +1059,11 @@ pub fn working_settings() -> ColorSettings {
}
/// Replace the working settings (Edit → Color Settings) and make them the active settings (fails,
/// leaving both unchanged, if a profile is unknown).
/// leaving both unchanged, if a profile is unknown or the RGB policy is Preserve Numbers).
pub fn set_active(settings: &ColorSettings) -> Result<(), CmsError> {
if !Policy::RGB.contains(&settings.rgb_policy) {
return Err(CmsError::Unsupported(format!("the RGB policy can't be {}", settings.rgb_policy.id())));
}
let cms = Arc::new(Cms::new(settings)?);
*WORKING.write().unwrap_or_else(|e| e.into_inner()) = Some(cms.clone());
install(cms);
+78
View File
@@ -34,6 +34,17 @@ type Xf = Option<Arc<TransformF32Executor>>;
/// generation only lets the cache drop what reloads left behind.
type DirectKey = (u64, u64, usize, bool);
/// The transforms of [`IccProfile::to_same_model_of`]: into ProPhoto RGB's primaries with linear
/// tone curves, where black-point compensation is a linear remap, and from there into the
/// destination.
struct SameModel {
into: Arc<TransformF32Executor>,
out_of: Arc<TransformF32Executor>,
/// The source's and the destination's black as luminance in the linear space (both 0 without
/// compensation).
black: [f32; 2],
}
/// A parsed ICC profile plus lazily-built transforms to/from sRGB.
pub struct IccProfile {
pub name: String,
@@ -49,6 +60,9 @@ pub struct IccProfile {
/// Direct transforms into other RGB profiles ([`Self::to_rgb_of`]), by destination, intent
/// and black-point compensation.
direct: Mutex<Vec<(DirectKey, Option<Arc<Direct>>)>>,
/// Transforms into other profiles of the same model ([`Self::to_same_model_of`]), keyed as
/// [`Self::direct`] is.
same_model: Mutex<Vec<(DirectKey, Option<Arc<SameModel>>)>>,
}
/// A transform from one profile into an RGB profile without passing through sRGB: into the
@@ -99,6 +113,7 @@ impl IccProfile {
to_srgb: Default::default(),
from_srgb: Default::default(),
direct: Mutex::new(Vec::new()),
same_model: Mutex::new(Vec::new()),
})
}
@@ -264,6 +279,69 @@ impl IccProfile {
Some(Direct { to_linear, to_dest: Some(to_dest), black })
}
/// Device values of this profile → device values of `dest`, a profile of the same model,
/// converted with `intent` through ProPhoto RGB rather than sRGB, so colours outside sRGB
/// keep their place. With `bpc` (and an intent other than absolute), this profile's black
/// maps onto the destination's black (black-point compensation). `None` when `dest` is of
/// another model or no transform can be built.
pub fn to_same_model_of(&self, dest: &IccProfile, v: &[f32], intent: Intent, bpc: bool) -> Option<Vec<f32>> {
if dest.kind != self.kind || v.len() != self.channels() {
return None;
}
let bpc = bpc && intent != Intent::AbsoluteColorimetric;
let generation = profiles_generation();
let key = (dest.id, generation, intent_index(intent), bpc);
let t = {
let mut cache = self.same_model.lock().unwrap_or_else(|e| e.into_inner());
cache.retain(|(k, _)| k.1 == generation);
match cache.iter().find(|(k, _)| *k == key) {
Some((_, t)) => t.clone(),
None => {
let t = self.build_same_model(dest, intent, bpc).map(Arc::new);
cache.push((key, t.clone()));
t
}
}
}?;
let mut lin = [0.0f32; 3];
t.into.transform(v, &mut lin).ok()?;
let [from, to] = t.black;
if from > 0.0 || to > 0.0 {
lin = lin.map(|x| to + (x - from) * (1.0 - to) / (1.0 - from));
}
let lin = lin.map(|x| x.clamp(0.0, 1.0));
let mut out = vec![0.0f32; dest.channels()];
t.out_of.transform(&lin, &mut out).ok()?;
Some(out.into_iter().map(|x| x.clamp(0.0, 1.0)).collect())
}
fn build_same_model(&self, dest: &IccProfile, intent: Intent, bpc: bool) -> Option<SameModel> {
let mut linear = rgb_space(super::PROPHOTO_RGB)?;
for trc in [&mut linear.red_trc, &mut linear.green_trc, &mut linear.blue_trc] {
*trc = Some(ToneReprCurve::Parametric(vec![1.0]));
}
linear.cicp = None;
let into = self.profile.create_transform_f32(self.layout(), &linear, Layout::Rgb, Self::opts(intent)).ok()?;
let out_of = linear.create_transform_f32(Layout::Rgb, &dest.profile, dest.layout(), Self::opts(intent)).ok()?;
let black = if bpc {
// Each profile's black: the darkest colour it reproduces, found as `build_direct`
// finds it, as luminance in the linear space.
let luminance = |p: &IccProfile, xf: &Arc<TransformF32Executor>| -> Option<f32> {
let inks = p.from_srgb([0.0; 3], Intent::RelativeColorimetric)?;
let mut lin = [0.0f32; 3];
xf.transform(&inks, &mut lin).ok()?;
let y = |c: &moxcms::Xyzd| c.y as f32;
let lum = lin[0] * y(&linear.red_colorant) + lin[1] * y(&linear.green_colorant) + lin[2] * y(&linear.blue_colorant);
Some(lum.clamp(0.0, 0.5))
};
let back = dest.profile.create_transform_f32(dest.layout(), &linear, Layout::Rgb, Self::opts(intent)).ok()?;
[luminance(self, &into)?, luminance(dest, &back)?]
} else {
[0.0; 2]
};
Some(SameModel { into, out_of, black })
}
/// Whether transforms can be built for this profile (checked at registration).
pub fn usable(&self) -> bool {
self.to_xf(Intent::RelativeColorimetric).is_some() && self.inverse_xf(Intent::RelativeColorimetric).is_some()
+36
View File
@@ -442,3 +442,39 @@ fn a_document_gets_the_same_context_for_the_same_profiles() {
let unknown = for_document(Some("no such profile"), Some(SRGB));
assert_eq!(unknown.settings(), &working_settings(), "an unknown profile or one of the other model leaves the working space");
}
/// The color management policies parse from their ids, Preserve Numbers is a CMYK policy only, and
/// settings saved before the policies existed read with the default policy.
#[test]
fn policies_parse_and_default_in_saved_settings() {
for p in Policy::CMYK {
assert_eq!(Policy::parse(p.id()), Some(p));
}
assert_eq!(Policy::parse("bogus"), None);
assert!(!Policy::RGB.contains(&Policy::PreserveNumbers));
let old: ColorSettings =
serde_json::from_str(r#"{"rgb": "sRGB IEC61966-2.1", "cmyk": "Device CMYK (uncalibrated)", "intent": "perceptual", "bpc": false}"#).unwrap();
assert_eq!((old.rgb_policy, old.cmyk_policy), (Policy::PreserveEmbedded, Policy::PreserveEmbedded));
let saved = serde_json::to_value(ColorSettings { cmyk_policy: Policy::PreserveNumbers, ..Default::default() }).unwrap();
assert_eq!((saved["rgbPolicy"].as_str(), saved["cmykPolicy"].as_str()), (Some("preserveEmbedded"), Some("preserveNumbers")));
}
/// Convert to Working Space keeps a color's appearance: an RGB color of a wide space converts into
/// sRGB, and a CMYK color of one CMYK space into another, with numbers that look the same. Grey and
/// Lab colors stay as they are.
#[test]
fn convert_into_keeps_the_appearance() {
let wide = Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap();
let working = cms();
let rgb = Color::Rgb { r: 0.25, g: 0.4, b: 0.6 };
let moved = wide.convert_into(&working, &rgb, Intent::RelativeColorimetric);
assert_ne!(moved, rgb, "the numbers change");
assert!(de(wide.display_rgb(&rgb), working.display_rgb(&moved)) < 1.0, "{rgb:?} → {moved:?}");
let ink = Color::Cmyk { c: 0.2, m: 0.4, y: 0.6, k: 0.1 };
let moved = wide.convert_into(&working, &ink, Intent::RelativeColorimetric);
assert!(matches!(moved, Color::Cmyk { .. }) && moved != ink, "{ink:?} → {moved:?}");
assert!(delta_e2000(wide.lab(&ink), working.lab(&moved)) < 3.0, "{ink:?} → {moved:?}");
for c in [Color::Gray { k: 0.3 }, Color::Lab { l: 50.0, a: 10.0, b: -20.0 }] {
assert_eq!(wide.convert_into(&working, &c, Intent::RelativeColorimetric), c);
}
}
+52
View File
@@ -274,3 +274,55 @@ fn settings_built_before_a_reload_dont_leave_the_old_transform_to_the_new_ones()
assert!(in_srgb.iter().zip(want).any(|(a, b)| (a - b).abs() > 0.05), "sRGB {in_srgb:?} vs ProPhoto {want:?}");
assert!(in_prophoto.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4), "after the reload {in_prophoto:?}, want {want:?}");
}
/// A CMYK profile converts into another CMYK profile, ink for ink, and refuses a profile
/// of another model or inks of the wrong count.
#[test]
fn cmyk_profiles_convert_into_each_other_directly() {
let generic = IccProfile::from_bytes(Some("A".into()), &icc_bytes(GENERIC_CMYK).unwrap()).unwrap();
let device = IccProfile::from_bytes(Some("B".into()), &icc_bytes(DEVICE_CMYK).unwrap()).unwrap();
let srgb = IccProfile::from_bytes(None, &icc_bytes(SRGB).unwrap()).unwrap();
let inks = [0.2, 0.4, 0.6, 0.1];
let out = generic.to_same_model_of(&device, &inks, Intent::RelativeColorimetric, false).unwrap();
assert_eq!(out.len(), 4);
assert!(out.iter().zip(inks).any(|(a, b)| (a - b).abs() > 0.01), "{out:?}");
assert!(generic.to_same_model_of(&srgb, &inks, Intent::RelativeColorimetric, false).is_none());
assert!(generic.to_same_model_of(&device, &inks[..3], Intent::RelativeColorimetric, false).is_none());
}
/// With black-point compensation, a CMYK profile's darkest ink converts into an ink as dark as a
/// darker profile's darkest ink, and a dark grey of a darker profile converts lighter into a
/// profile whose black is lighter; absolute colorimetric never compensates.
#[test]
fn cmyk_to_cmyk_compensates_the_black_point() {
let generic = IccProfile::from_bytes(Some("A".into()), &icc_bytes(GENERIC_CMYK).unwrap()).unwrap();
let device = IccProfile::from_bytes(Some("B".into()), &icc_bytes(DEVICE_CMYK).unwrap()).unwrap();
let rel = Intent::RelativeColorimetric;
let lightness = |p: &IccProfile, inks: &[f32]| lab::srgb_to_lab(p.to_srgb(inks, rel).unwrap()).l;
let black = |p: &IccProfile| p.from_srgb([0.0; 3], rel).unwrap();
// Generic CMYK's black is a dark grey, the uncalibrated profile's is black.
let (light, dark) = (lightness(&generic, &black(&generic)), lightness(&device, &black(&device)));
assert!(light > dark + 5.0, "{light} vs {dark}");
let into_device = |bpc| lightness(&device, &generic.to_same_model_of(&device, &black(&generic), rel, bpc).unwrap());
let (on, off) = (into_device(true), into_device(false));
assert!((on - dark).abs() < 1.5 && off > dark + 5.0, "with {on}, without {off}, the black {dark}");
let grey = device.from_srgb([0.2; 3], rel).unwrap();
let into_generic = |bpc| lightness(&generic, &device.to_same_model_of(&generic, &grey, rel, bpc).unwrap());
let (on, off) = (into_generic(true), into_generic(false));
assert!(on > off + 1.0, "with {on}, without {off}");
for (from, to, inks) in [(&generic, &device, black(&generic)), (&device, &generic, grey)] {
let abs = |bpc| from.to_same_model_of(to, &inks, Intent::AbsoluteColorimetric, bpc).unwrap();
assert_eq!(abs(true), abs(false));
}
// Convert to Working Space (Cms::convert_into) compensates as Color Settings say.
let device_name = register_icc(&icc_bytes(DEVICE_CMYK).unwrap(), Some("Test ICC Device CMYK".into())).unwrap().name;
let rich = Color::Cmyk { c: 0.9, m: 0.8, y: 0.8, k: 1.0 };
let convert = |bpc| {
let dest = Cms::new(&ColorSettings { cmyk: device_name.clone(), bpc, ..ColorSettings::default() }).unwrap();
icc_cmyk(bpc).convert_into(&dest, &rich, rel)
};
assert_ne!(convert(true), convert(false));
// White is untouched.
let white = generic.to_same_model_of(&device, &[0.0; 4], rel, true).unwrap();
assert!(white.iter().all(|v| *v < 0.01), "{white:?}");
}
+172 -7
View File
@@ -525,8 +525,8 @@ fn planar<R: std::io::Read + std::io::Seek>(d: &mut tiff::decoder::Decoder<R>) -
}
/// The samples of the `n` pixels of the TIFF `d` reads, `per` to a pixel (the number its color
/// type has), pixel by pixel and 8 bits each (16-bit samples to their high byte), whether the file
/// stores each pixel's samples together or one plane per channel. `None` when they don't decode to
/// type has), pixel by pixel and 8 bits each (16-bit samples rounded to the nearest), whether the
/// file stores each pixel's samples together or one plane per channel. `None` when they don't decode to
/// that many samples, which includes images whose planes together need more than the decoder's
/// limit (256 MiB of samples), and, before any decoding, files with more than
/// [`MAX_EXTRA_SAMPLES_PIXEL`] samples a pixel, files whose samples aren't unsigned integers (a
@@ -535,7 +535,7 @@ fn planar<R: std::io::Read + std::io::Seek>(d: &mut tiff::decoder::Decoder<R>) -
pub(crate) fn read_samples(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Vec<u8>> {
Some(match read_samples_at_depth(d, n, per)? {
Samples::Eight(v) => v,
Samples::Sixteen(v) => v.iter().map(|s| (s >> 8) as u8).collect(),
Samples::Sixteen(v) => v.iter().map(|&s| u8::try_from((u32::from(s) + 128) / 257).unwrap_or(u8::MAX)).collect(),
})
}
@@ -618,13 +618,25 @@ pub fn icc_color_space(icc: &[u8]) -> Option<[u8; 4]> {
icc.get(16..20)?.try_into().ok()
}
/// The ICC profile of TIFF tag 34675 (ICCProfile) of the image `d` reads; `None` without one.
/// The most bytes of an ICC profile a TIFF's tag 34675 is read with (16 MiB).
const MAX_TIFF_ICC: u64 = 16 << 20;
/// The ICC profile of TIFF tag 34675 (ICCProfile, of type UNDEFINED or BYTE) of the image `d`
/// reads, as its bytes; `None` without one and for one over [`MAX_TIFF_ICC`] bytes.
fn tiff_icc(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> Option<Vec<u8>> {
d.get_tag_u8_vec(tiff::tags::Tag::IccProfile).ok().filter(|icc| !icc.is_empty())
use tiff::tags::{Tag, Type, ValueBuffer};
let mut ifd = d.image_ifd();
let entry = ifd.find_entry(Tag::IccProfile)?;
if !matches!(entry.field_type(), Type::UNDEFINED | Type::BYTE) || entry.count() == 0 || entry.count() > MAX_TIFF_ICC {
return None;
}
let mut buf = ValueBuffer::empty(Type::UNDEFINED);
ifd.find_tag_buf(Tag::IccProfile, &mut buf).ok()??;
Some(buf.as_bytes().to_vec())
}
/// The ICC profile of TIFF `bytes`' first image (tag 34675), read with the `tiff` decoder's own
/// limits, whatever the size of the image; `None` for other images and TIFFs without one.
/// The ICC profile of TIFF `bytes`' first image (tag 34675), up to [`MAX_TIFF_ICC`] bytes whatever
/// the size of the image; `None` for other images, TIFFs without one and a longer one.
pub fn tiff_icc_profile(bytes: &[u8]) -> Option<Vec<u8>> {
let (_, mut d) = tiff(bytes)?;
tiff_icc(&mut d)
@@ -638,6 +650,75 @@ fn jpeg_icc(bytes: &[u8]) -> Option<Vec<u8>> {
d.icc_profile().filter(|icc| !icc.is_empty())
}
/// The bytes after an `ICC_PROFILE` APP2 segment's length: its name, then the segment's number and
/// the count of segments.
const ICC_SEGMENT: &[u8; 12] = b"ICC_PROFILE\0";
/// JPEG `bytes` carrying `icc` in place of the ICC profile they carry, if any: every
/// `ICC_PROFILE` APP2 segment before the scan taken out, `icc` written as numbered APP2 segments
/// after the leading application segments, and the other segments and the scan as they are. `None`
/// for bytes whose segments before the scan can't be read, an empty `icc`, and one longer than 255
/// segments hold.
pub fn jpeg_with_icc(bytes: &[u8], icc: &[u8]) -> Option<Vec<u8>> {
// A segment's length counts itself (2 bytes) and the name, number and count (14).
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)?;
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()?;
segments.extend_from_slice(&[0xFF, 0xE2]);
segments.extend_from_slice(&len.to_be_bytes());
segments.extend_from_slice(ICC_SEGMENT);
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);
let mut at = 2;
// The segments before the scan (SOS), each with its length; a marker without one ends them.
// Fill bytes (0xFF) before a marker are left out.
loop {
while bytes.get(at..at + 2) == Some(&[0xFF, 0xFF]) {
at += 1;
}
let (Some(&0xFF), Some(&marker)) = (bytes.get(at), bytes.get(at + 1)) else { return None };
let app = (0xE0..=0xEF).contains(&marker);
if !app && let Some(s) = icc_segments.take() {
out.extend_from_slice(&s);
}
if matches!(marker, 0xDA | 0xD8 | 0xD9 | 0x01 | 0xD0..=0xD7) {
break;
}
let len = usize::from(u16::from_be_bytes(bytes.get(at + 2..at + 4)?.try_into().ok()?));
let segment = bytes.get(at..(at + 2).checked_add(len)?).filter(|_| len >= 2)?;
if !(marker == 0xE2 && segment.get(4..16) == Some(ICC_SEGMENT.as_slice())) {
out.extend_from_slice(segment);
}
at += segment.len();
}
out.extend_from_slice(bytes.get(at..)?);
Some(out)
}
/// `icc` when it is a profile of CMYK colors, which the samples of a CMYK image are in.
fn cmyk_icc(icc: Option<Vec<u8>>) -> Option<Vec<u8>> {
icc.filter(|icc| icc_color_space(icc) == Some(*b"CMYK"))
@@ -746,6 +827,14 @@ impl ImageBlob {
Some(Self::new("image/tiff", tiff))
}
/// [`ImageBlob::cmyk_tiff`], carrying `icc` as tag 34675 (ICCProfile) when it is a profile of
/// CMYK colors; any other profile is left out. The caller checks the rest of the profile.
pub fn cmyk_tiff_with_icc(inks: &Inks, icc: Option<&[u8]>) -> Option<Self> {
let icc = icc.filter(|icc| icc_color_space(icc) == Some(*b"CMYK"));
let tiff = write_cmyk_tiff(inks.width, inks.height, SampleSlice::Eight(&inks.data), None, icc)?;
Some(Self::new("image/tiff", tiff))
}
/// Does the image hold CMYK samples (a four-component JPEG or a CMYK TIFF)? Reads only its
/// header.
pub fn is_cmyk(&self) -> bool {
@@ -1968,6 +2057,35 @@ mod tests {
assert_eq!(rgb.get_pixel(1, 0).0, [0, 255, 255]);
}
/// A CMYK TIFF written with a CMYK profile carries it byte for byte as tag 34675; a profile of
/// other colors, and none, leave the TIFF untagged. The inks are the same either way.
#[test]
fn a_cmyk_tiff_carries_the_cmyk_profile_it_is_given() {
let profile = |space: &[u8; 4]| {
let mut icc = vec![0u8; 128];
icc[0..4].copy_from_slice(&128u32.to_be_bytes());
icc[16..20].copy_from_slice(space);
icc[36..40].copy_from_slice(b"acsp");
icc
};
let cmyk = profile(b"CMYK");
let b = ImageBlob::cmyk_tiff_with_icc(&inks(), Some(&cmyk)).unwrap();
assert_eq!(b.cmyk_icc_profile(), Some(cmyk), "the profile, byte for byte");
assert_eq!(b.cmyk(), Some(inks()));
// Read back up to 16 MiB; a longer one isn't read.
for (len, read) in [(16 << 20, true), ((16 << 20) + 1, false)] {
let mut big = profile(b"CMYK");
big.resize(len, 0);
let b = ImageBlob::cmyk_tiff_with_icc(&inks(), Some(&big)).unwrap();
assert_eq!(b.cmyk_icc_profile().is_some_and(|p| p == big), read, "{len} bytes");
}
for icc in [Some(profile(b"RGB ")), None] {
let b = ImageBlob::cmyk_tiff_with_icc(&inks(), icc.as_deref()).unwrap();
assert_eq!(tiff_icc_profile(&b.bytes), None, "{icc:?}");
assert_eq!(b.cmyk(), Some(inks()));
}
}
#[test]
fn a_header_gives_the_size_without_the_samples() {
assert_eq!(ImageBlob::cmyk_tiff(&inks()).unwrap().header_size(), Some((3, 2)));
@@ -2031,6 +2149,53 @@ mod tests {
}
}
/// A CMYK JPEG given a profile carries it in place of its own, its samples as they were; a
/// profile longer than 255 segments hold, an empty one and bytes that aren't a JPEG give none.
#[test]
fn a_cmyk_jpeg_carries_the_profile_it_is_given() {
let profile = |len: usize, mark: u8| {
let mut icc = vec![mark; len];
icc[16..20].copy_from_slice(b"CMYK");
icc
};
let px: Vec<u8> = (0..16 * 16).flat_map(|_| [10u8, 40, 100, 20]).collect();
let mut jpg = Vec::new();
let mut e = jpeg_encoder::Encoder::new(&mut jpg, 100);
e.add_icc_profile(&profile(300_000, 1)).unwrap();
e.encode(&px, 16, 16, jpeg_encoder::ColorType::Cmyk).unwrap();
let inks = ImageBlob::new("image/jpeg", jpg.clone()).cmyk().unwrap();
// One segment holds 65,519 bytes of a profile.
for len in [128, 65_519, 65_520, 300_000, 1 << 20] {
let icc = profile(len, 2);
let b = ImageBlob::new("image/jpeg", jpeg_with_icc(&jpg, &icc).unwrap());
assert!(b.cmyk_icc_profile() == Some(icc), "{len} bytes");
assert!(b.cmyk() == Some(inks.clone()), "{len} bytes: the samples as they were");
}
// A profile segment after the quantization table is taken out too.
let dqt = jpg.windows(2).position(|w| w == [0xFF, 0xDB]).unwrap();
let after = dqt + 2 + usize::from(u16::from_be_bytes([jpg[dqt + 2], jpg[dqt + 3]]));
let mut late = jpg.clone();
let stale = profile(128, 3);
let segment = [&[0xFF, 0xE2, 0, 144][..], ICC_SEGMENT, &[1, 1], &stale].concat();
late.splice(after..after, segment);
let icc = profile(128, 2);
let b = jpeg_with_icc(&late, &icc).unwrap();
assert_eq!(b.windows(ICC_SEGMENT.len()).filter(|w| *w == ICC_SEGMENT).count(), 1, "one profile segment");
assert!(ImageBlob::new("image/jpeg", b).cmyk_icc_profile() == Some(icc));
// Fill bytes before the quantization table's marker are passed over.
let mut filled = jpg.clone();
filled.splice(dqt..dqt, [0xFF; 3]);
assert!(ImageBlob::new("image/jpeg", filled.clone()).cmyk() == Some(inks.clone()), "the decoder reads it");
let icc = profile(128, 2);
let b = ImageBlob::new("image/jpeg", jpeg_with_icc(&filled, &icc).unwrap());
assert!(b.cmyk_icc_profile() == Some(icc), "fill bytes");
assert!(b.cmyk() == Some(inks.clone()), "fill bytes: the samples as they were");
assert!(jpeg_with_icc(&jpg, &profile(255 * 65_519, 2)).is_some(), "255 segments");
assert!(jpeg_with_icc(&jpg, &profile(255 * 65_519 + 1, 2)).is_none(), "256 segments");
assert!(jpeg_with_icc(&jpg, &[]).is_none(), "empty");
assert!(jpeg_with_icc(&ImageBlob::cmyk_tiff(&inks).unwrap().bytes, &profile(128, 2)).is_none(), "a TIFF");
}
#[test]
fn other_images_are_not_cmyk() {
let mut png = Vec::new();
+301 -73
View File
@@ -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
@@ -504,8 +511,9 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab
/// [`hit_test`] passing over the nodes `skip` names (and their contents), and with
/// `editable_only` over the objects of layers and sublayers on a locked artboard, and over all of
/// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art
/// ([`Node::geometric_bounds_with`]).
/// ([`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();
@@ -1055,9 +1063,18 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill),
})
}
NodeKind::Text(_) | NodeKind::PlacedDocument(_) | NodeKind::SymbolInstance { .. } => {
NodeKind::Text(_) | NodeKind::PlacedDocument(_) => {
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`]). 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 !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)
}
// A blend or an envelope is hit within its bounds, and outside them where its evaluated
// art paints: a blend's keys and steps on a spine can reach past the keys and the spine,
// and the strokes of an envelope's distorted contents past its bounds.
@@ -1105,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
@@ -1164,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
@@ -1211,64 +1239,231 @@ 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>> {
struct Find<'a> {
art: &'a InstanceArt<'a>,
p: Point,
opt: HitOptions,
symbols: &'a SymbolBoxes<'a>,
}
impl Find<'_> {
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>, opt: HitOptions) -> bool {
self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, opt, self.symbols).is_some())
}
fn skips_guide(&self, n: &Node) -> bool {
self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
}
/// `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) -> bool {
if !n.visible || n.locked || n.is_template() || self.skips_guide(n) {
return false;
}
let outline = outline || previews_off(n);
let opt = HitOptions { outline, ..self.opt };
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole, opt) };
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
return self.hit(n, whole, opt);
}
let whole = self.art.whole(n, whole);
if n.clips()
&& let Some(first) = children.first()
{
let Some(clip) = self.art.place_unclipped(first, whole) else { return false };
if self.opt.clip_outlines && first.visible && !first.locked && !self.skips_guide(first) && clip_outline(&clip, self.p, opt).is_some()
{
path.push(0);
return true;
}
if !clip_contains(&clip, self.p, outline) {
return false;
}
}
for (i, c) in children.iter().enumerate().rev() {
// A Shaper group's original shapes are not drawn; symbol art has no isolation scope.
if shaper_hides(n, i, None) {
continue;
}
let Ok(i) = u32::try_from(i) else { continue };
path.push(i);
if self.find(c, path, whole, outline) {
return true;
}
path.pop();
}
false
}
}
let _walk = ArtWalk::open();
let art = InstanceArt::of(doc, inst)?;
let symbols = doc.symbol_boxes();
let mut path = vec![];
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None, outline).then_some(path)
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false };
find.find(&art.art, &mut path, None, outline).map(|_| path)
}
/// The walk of a symbol instance's placed art that [`symbol_part_at`] and [`instance_art_hit`] make.
struct FindPart<'a> {
art: &'a InstanceArt<'a>,
p: Point,
opt: HitOptions,
symbols: &'a SymbolBoxes<'a>,
/// For [`instance_art_hit`]: locked and template objects of the art count, as the canvas draws
/// them, and clipping paths are not picked by their outline.
whole_instance: bool,
}
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> {
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 {
self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
}
/// 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) || ArtWalk::used_up() {
return None;
}
let outline = outline || previews_off(n);
let opt = HitOptions { outline, ..self.opt };
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole, opt) };
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()
{
let clip = self.art.place_unclipped(first, whole)?;
if !self.whole_instance
&& self.opt.clip_outlines
&& first.visible
&& !first.locked
&& !self.skips_guide(first)
&& let Some(kind) = clip_outline(&clip, self.p, opt)
{
path.push(0);
return Some(kind);
}
if !clip_contains(&clip, self.p, outline) {
return None;
}
}
for (i, c) in children.iter().enumerate().rev() {
// A Shaper group's original shapes are not drawn; symbol art has no isolation scope.
if shaper_hides(n, i, None) {
continue;
}
let Ok(i) = u32::try_from(i) else { continue };
path.push(i);
if let Some(kind) = self.find(c, path, whole, outline) {
return Some(kind);
}
path.pop();
}
None
}
}
/// What a click at `p` hits of symbol instance `n`'s art where the canvas draws it (`None` in
/// 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`]), 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() || !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
@@ -1435,7 +1630,8 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
/// Objects (children of layers, or of `scope` in isolation mode) touched by a marquee rect, leaving
/// out those on a locked artboard ([`crate::LockedArtboards::holds_id`]). Symbol instances are measured
/// by their art ([`Node::geometric_bounds_with`]). The art of a clip group or of a layer with a
/// by their art ([`Node::geometric_bounds_with`]), and outside that box, except in outline, they are
/// touched where the live geometry effects of a clipping path in their art show it. The art of a clip group or of a layer with a
/// clipping mask counts only when the marquee meets the region its clipping path clips to, and then
/// only within that region's bounds. In isolation mode the clipping mask of the isolated container,
/// or of the parent of the single object isolated, does not limit the marquee, as it does not limit
@@ -1463,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)) {
@@ -1573,14 +1770,45 @@ 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 box with no width or no height (an instance of a symbol that draws a straight
// line) is touched where the marquee crosses it.
_ => n.geometric_bounds_with(s).is_some_and(|b| {
let crosses = (b.width() == 0.0 || b.height() == 0.0) && b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
b.intersect(r).area() > 0.0 || r.contains(b.origin()) || crosses
}),
// 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. 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),
}
}
/// Does the marquee `r` touch the box of `n`? A box with no width or no height (an instance of
/// a symbol that draws a straight line) is touched where the marquee crosses it.
fn box_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool {
n.geometric_bounds_with(s).is_some_and(|b| {
let crosses = (b.width() == 0.0 || b.height() == 0.0) && b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
b.intersect(r).area() > 0.0 || r.contains(b.origin()) || crosses
})
}
/// 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`]), 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() && !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>) {
match &n.kind {
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
+389
View File
@@ -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);
@@ -1852,6 +1922,325 @@ fn a_symbol_part_follows_the_region_its_clipping_layers_effects_give_it() {
assert!(symbol_part_outline(&d, n, &[0, 1]).unwrap().elements().is_empty(), "nothing is drawn, so nothing is outlined");
}
/// A symbol instance whose art holds a clip group or a clipping layer with a live effect that moves
/// its clipping path is clicked, and touched by a marquee, where the moved region shows the art past
/// the art's box: inside a group, nested in another symbol's art, moved and scaled. In Outline view,
/// below a layer whose Preview is off, where the art is hidden and where no region is left, only the
/// box counts.
#[test]
fn a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art() {
use vectorcraft_geom::Affine;
set_clip_region(moved_clip_region);
// `effect` on the clipping path of a clip group (a clipping layer with `layer`), whose art is
// shown when `shown`; `xf` places the instance, which with `nest` shows a symbol whose art holds
// an instance of the clipped symbol. The instance is in a group: the group, the instance.
let build = |effect: &str, xf: Affine, nest: bool, shown: bool, layer: bool| {
let mut d = Document::new(600.0, 400.0);
let l = d.layers[0].id;
let (mut mask, mut art) = half_clipped(&mut d);
mask.appearance.effects.push(crate::Effect { id: effect.into(), ..test_move() });
art.visible = shown;
let mut clip = if layer {
let mut layer = Node::layer(d.alloc_id(), "Masked", crate::LayerColor::Preset(2));
if let NodeKind::Layer { children, .. } = &mut layer.kind {
*children = vec![Arc::new(mask), Arc::new(art)];
}
layer
} else {
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) });
let mut symbol = "Clipped";
if nest {
let inner = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Clipped".into(), xf: Affine::IDENTITY });
let root = Node::group(d.alloc_id(), vec![Arc::new(inner)]);
d.symbols.push(crate::Symbol { dynamic: false, name: "Outer".into(), art: Arc::new(root) });
symbol = "Outer";
}
let (g, inst) = (d.alloc_id(), d.alloc_id());
let instance = Node::new(inst, NodeKind::SymbolInstance { symbol: symbol.into(), xf });
d.insert(Some(l), 0, Node::group(g, vec![Arc::new(instance)])).unwrap();
(d, g, inst)
};
let opt = HitOptions::default();
let outline = HitOptions { outline: true, ..opt };
let at = |d: &Document, x: f64, y: f64, opt: HitOptions| hit_test(d, Point::new(x, y), opt).map(|h| h.leaf);
// Across the art's top edge in the moved region, and past the art's right end.
let (edge, past) = (Rect::new(140.0, -5.0, 160.0, 5.0), Rect::new(240.0, -5.0, 260.0, 5.0));
for layer in [false, true] {
let (d, g, inst) = build("test.move", Affine::IDENTITY, false, true, layer);
assert_eq!(at(&d, 150.0, 50.0, opt), Some(inst), "in the moved region, layer {layer}");
assert_eq!(hit_test(&d, Point::new(150.0, 50.0), opt).map(|h| h.top_object(None)), Some(g));
assert_eq!(at(&d, 50.0, 50.0, opt), Some(inst), "in the box");
assert_eq!(at(&d, 250.0, 50.0, opt), None, "past the art");
assert_eq!(at(&d, 150.0, 150.0, opt), None, "below the art");
assert_eq!(at(&d, 150.0, 50.0, outline), None, "Outline view draws the plain clipping path");
assert_eq!(marquee(&d, edge, None, false), [g], "layer {layer}");
assert_eq!(marquee(&d, edge, None, true), [inst], "layer {layer}");
assert!(marquee(&d, past, None, false).is_empty());
assert!(marquee_in_view(&d, edge, None, false, true).is_empty(), "Outline view");
}
// Preview off for the layer the instance is on.
let (mut d, _, _) = build("test.move", Affine::IDENTITY, false, true, false);
if let NodeKind::Layer { preview, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind {
*preview = false;
}
assert_eq!(at(&d, 150.0, 50.0, opt), None, "Preview off");
assert!(marquee(&d, edge, None, false).is_empty(), "Preview off");
// Moved, scaled (the region moves 100 pt from the placed clipping path) and nested.
let (d, _, inst) = build("test.move", Affine::translate((10.0, 20.0)), false, true, false);
assert_eq!(at(&d, 160.0, 70.0, opt), Some(inst), "moved");
let (d, _, inst) = build("test.move", Affine::scale(2.0), false, true, false);
assert_eq!(at(&d, 250.0, 100.0, opt), Some(inst), "scaled");
assert_eq!(at(&d, 350.0, 100.0, opt), None, "scaled, past the region");
let (d, g, inst) = build("test.move", Affine::IDENTITY, true, true, false);
assert_eq!(at(&d, 150.0, 50.0, opt), Some(inst), "nested");
assert_eq!(marquee(&d, edge, None, false), [g], "nested");
// Hidden art, and an effect that leaves no region: clicks find only the box. The marquee still
// touches the moved clipping path on the edge of its region, as in a clip group, unless no
// region is left.
for (effect, shown) in [("test.move", false), ("test.empty", true)] {
let (d, g, inst) = build(effect, Affine::IDENTITY, false, shown, false);
assert_eq!(at(&d, 150.0, 50.0, opt), None, "{effect}, shown {shown}");
assert_eq!(at(&d, 50.0, 50.0, opt), Some(inst), "{effect}, shown {shown}: in the box");
let touched: &[NodeId] = if shown { &[] } else { &[g] };
assert_eq!(marquee(&d, edge, None, false), touched, "{effect}, shown {shown}");
}
}
/// A click on the stroke of a symbol's art where it paints past the instance's box selects the
/// instance; past the stroke, and in Outline view, it does not.
#[test]
fn a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box() {
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
// A 20 pt stroke reaches 10 pt past the 0..100 square.
let look = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 20.0);
let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look);
let art = Node::group(d.alloc_id(), vec![Arc::new(square)]);
d.symbols.push(crate::Symbol { dynamic: false, name: "Stroked".into(), art: Arc::new(art) });
let inst = d.alloc_id();
let xf = vectorcraft_geom::Affine::IDENTITY;
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Stroked".into(), xf })).unwrap();
let at = |x: f64, opt: HitOptions| hit_test(&d, Point::new(x, 50.0), opt).map(|h| h.leaf);
assert_eq!(at(108.0, HitOptions::default()), Some(inst), "on the stroke past the box");
assert_eq!(at(50.0, HitOptions::default()), Some(inst), "in the box");
assert_eq!(at(116.0, HitOptions::default()), None, "past the stroke");
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.
+34 -4
View File
@@ -80,16 +80,22 @@ pub fn spot_color(doc: &Document, name: &str) -> Option<Color> {
/// A colour's swatch link and tint (`(swatch name, tint 0..1)`), as the colour visitors pass it.
pub type Link<'a> = Option<(&'a str, f32)>;
/// An ink amount clamped to 0..1; an amount that is not a finite number prints no ink.
fn ink_amount(v: f32) -> f32 {
if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }
}
/// Separate one colour into inks. A colour linked to a spot swatch prints on that plate only, at
/// its tint; one linked to the Registration swatch prints its tint on every plate.
/// its tint; one linked to the Registration swatch prints its tint on every plate. A tint that is
/// not a finite number prints no ink.
pub fn inks(doc: &Document, c: &Cms, color: &Color, link: Link, intent: Intent) -> Inks {
if let Some((REGISTRATION, tint)) = link {
return Inks { cmyk: [tint.clamp(0.0, 1.0); 4], spot: None, registration: true };
return Inks { cmyk: [ink_amount(tint); 4], spot: None, registration: true };
}
if let Some((name, tint)) = link
&& doc.swatch(name).is_some_and(|s| s.spot && s.paint.color().is_some())
{
return Inks { cmyk: [0.0; 4], spot: Some((name.to_string(), tint.clamp(0.0, 1.0))), registration: false };
return Inks { cmyk: [0.0; 4], spot: Some((name.to_string(), ink_amount(tint))), registration: false };
}
Inks { cmyk: c.to_cmyk(color, intent), spot: None, registration: false }
}
@@ -104,7 +110,7 @@ pub type StopPlates = Option<[f32; 4]>;
pub fn stop_inks(doc: &Document, c: &Cms, color: &Color, link: Link, plates: StopPlates, intent: Intent) -> Inks {
let mut ink = inks(doc, c, color, link, intent);
if let (Some(p), Some(_)) = (plates, &ink.spot) {
ink.cmyk = p.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 });
ink.cmyk = p.map(ink_amount);
}
ink
}
@@ -227,6 +233,30 @@ mod tests {
}
}
#[test]
fn a_spot_or_registration_tint_that_is_not_a_finite_number_prints_no_ink() {
let d = gold_doc();
let c = vectorcraft_color::cms::active();
let look = Color::cmyk(0.25, 0.1, 0.8, 0.05);
let ink = |link: Link| inks(&d, &c, &look, link, Intent::RelativeColorimetric);
for t in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
let spot = ink(Some(("Gold", t)));
assert_eq!(spot, Inks { cmyk: [0.0; 4], spot: Some(("Gold".into(), 0.0)), registration: false }, "{t}");
assert_eq!((spot.on_plate("Gold"), spot.on_plate("Cyan")), (0.0, 0.0), "{t}");
let reg = ink(Some((REGISTRATION, t)));
assert_eq!(reg, Inks { cmyk: [0.0; 4], spot: None, registration: true }, "{t}");
assert_eq!((reg.on_plate("Gold"), reg.on_plate("Black")), (0.0, 0.0), "{t}");
// A stop's process plates still print beside a spot tint that prints nothing.
let stop = stop_inks(&d, &c, &look, Some(("Gold", t)), Some([0.25, 0.0, 0.4, 0.0]), Intent::RelativeColorimetric);
assert_eq!((stop.cmyk, stop.on_plate("Gold")), ([0.25, 0.0, 0.4, 0.0], 0.0), "{t}");
}
// Finite tints outside 0..1 are clamped.
assert_eq!(ink(Some(("Gold", 2.0))).on_plate("Gold"), 1.0);
assert_eq!(ink(Some(("Gold", -1.0))).on_plate("Gold"), 0.0);
assert_eq!(ink(Some((REGISTRATION, 2.0))).cmyk, [1.0; 4]);
assert_eq!(ink(Some((REGISTRATION, -1.0))).cmyk, [0.0; 4]);
}
#[test]
fn gradient_stops_pass_their_plates_and_freeform_points_are_visited() {
let mut stop = GradientStop::new(0.0, Color::cmyk(0.25, 0.1, 0.8, 0.05));
+3 -1
View File
@@ -28,6 +28,7 @@ pub mod shared;
mod symbol_export_type;
mod symbol_nine_slice;
pub mod symbol_overrides;
mod symbol_pixel_aligned;
mod symbol_registration;
pub use inline::{SYMBOL_HALF, SYMBOL_SIZES};
pub use shared::Shared;
@@ -37,6 +38,7 @@ pub use symbol_nine_slice::{
SymbolNineSlice, charge_symbol_art,
};
pub use symbol_overrides::SymbolOverride;
pub use symbol_pixel_aligned::SYMBOL_PIXEL_ALIGNED;
pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration};
pub mod links;
pub mod live;
@@ -128,7 +130,7 @@ pub use text::{
RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap,
VerticalAlign, WrapShape,
};
pub use text::{CharClass, CompositeFont, CompositePart, CompositeParts};
pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet};
pub use trace::TraceView;
pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables};
pub use vectorcraft_color as color;
+37 -4
View File
@@ -105,8 +105,13 @@ impl Document {
n += shared(&self.para_styles, &newer.para_styles, styles);
n += shared(&self.composite_fonts, &newer.composite_fonts, |c| {
let part = |p: &crate::CompositePart| p.font.capacity() + p.style.capacity();
let custom = |f: &crate::CompositeFont| {
vec_bytes(&f.custom) + f.custom.iter().map(|s| s.name.capacity() + s.characters.capacity() + part(&s.part)).sum::<usize>()
};
vec_bytes(c)
+ c.iter().map(|f| f.name.capacity() + crate::CharClass::ALL.into_iter().map(|k| part(f.parts.get(k))).sum::<usize>()).sum::<usize>()
+ c.iter()
.map(|f| f.name.capacity() + crate::CharClass::ALL.into_iter().map(|k| part(f.parts.get(k))).sum::<usize>() + custom(f))
.sum::<usize>()
});
n += shared(&self.saved_selections, &newer.saved_selections, |s| {
vec_bytes(s) + s.iter().map(|s: &SavedSelection| s.name.capacity() + vec_bytes(&s.objects)).sum::<usize>()
@@ -276,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, .. }
@@ -293,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>() }
}
+29 -1
View File
@@ -228,7 +228,11 @@ impl Node {
/// grown by the farthest a stroke in the art can reach. For an instance placed through 9-slice
/// guides, that box also holds the art box placed by each cell's map
/// ([`crate::NineSliceMap::placement_bounds`]). An instance whose art holds an instance of a
/// symbol with 9-slice guides at any depth is measured as its art placed by its transform.
/// symbol with 9-slice guides at any depth is measured as its art placed by its transform. An
/// instance whose art holds a clipping path with live geometry effects also takes in the region
/// they give it ([`crate::hit::set_clip_region`]): moved with the instance when it only moves its
/// art, otherwise placed by it and grown by as far as the region reaches past the art, times √2
/// and the larger of 1 and the Frobenius norm of the transform's linear part.
pub fn reach_bounds_with(&self, symbols: &SymbolBoxes) -> Option<Rect> {
symbols.quickly(|| self.reach(Some(symbols)))
}
@@ -268,6 +272,30 @@ impl Node {
NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => {
vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c)))
}
// The live geometry effects of the clipping paths in the art can draw it past its box.
NodeKind::SymbolInstance { symbol, xf } => {
let Some((s, art, region)) = symbols.and_then(|s| {
let a = s.art(symbol)?;
Some((s, a, a.reshaped?))
}) else {
return self.visual(symbols);
};
let map = s.document().symbol_slice_map_of(symbol, art.geometric, *xf);
let placed = if moves_only(*xf) && map.is_none() {
xf.transform_rect_bbox(region)
} else {
// An effect can reach a fixed distance past the art or a distance in proportion
// to its size, as `SymbolBoxes::effects_reach` estimates it.
let g = art.geometric;
let all = region.union(g);
let past = [g.x0 - region.x0, region.x1 - g.x1, g.y0 - region.y0, region.y1 - g.y1].into_iter().fold(0.0_f64, f64::max);
let [a, b, c, d, _, _] = xf.as_coeffs();
let grow = past * std::f64::consts::SQRT_2 * (a * a + b * b + c * c + d * d).sqrt().max(1.0);
map.map_or_else(|| xf.transform_rect_bbox(all), |m| m.placement_bounds(all)).inflate(grow, grow)
};
let o = self.appearance.outset();
vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o)))
}
_ => self.visual(symbols),
}
}
+8
View File
@@ -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 {
+59 -2
View File
@@ -49,6 +49,13 @@ pub struct Selection {
/// it when no object is selected to align to it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_guide: Option<NodeId>,
/// The key anchor for Align: one of two or more anchor points selected with Direct Selection,
/// the last one a Shift-click added (path, anchor in [`Self::anchors`]). Align and Distribute
/// move the other selected points relative to it, and it stays in place. Never set with `key`
/// or `key_guide`; [`Self::prune`] clears it when the point is no longer a selected anchor, or
/// fewer than two points are selected.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_anchor: Option<(NodeId, AnchorRef)>,
/// The new art on a locked artboard that this selection keeps editable
/// ([`Document::new_art`]). Undo, Redo and a failed batch restore it with the selection, and
/// the engine then sets the document's from it. Editing state, never saved.
@@ -98,6 +105,7 @@ impl Selection {
self.slices.clear();
self.guides.clear();
self.key_guide = None;
self.key_anchor = None;
self.symbol_part = None;
self.on_path_member = None;
}
@@ -113,9 +121,15 @@ impl Selection {
self.set([instance]);
self.symbol_part = Some(SymbolPart { instance, path });
}
/// Is there a key for Align: an object or a guide?
/// Is there a key for Align: an object, a guide or an anchor point?
pub fn has_key(&self) -> bool {
self.key.is_some() || self.key_guide.is_some()
self.key.is_some() || self.key_guide.is_some() || self.key_anchor.is_some()
}
/// Where the key anchor ([`Self::key_anchor`]) is. `None` without one, or when the point is
/// gone from its path.
pub fn key_anchor_point(&self, doc: &Document) -> Option<vectorcraft_geom::Point> {
let (id, (si, ai)) = self.key_anchor?;
Some(doc.node(id)?.path_data()?.subpaths.get(si)?.anchors.get(ai)?.p)
}
pub fn set(&mut self, ids: impl IntoIterator<Item = NodeId>) {
self.clear();
@@ -143,6 +157,9 @@ impl Selection {
if self.key == Some(id) {
self.key = None;
}
if self.key_anchor.is_some_and(|(k, _)| k == id) {
self.key_anchor = None;
}
}
/// [`Self::remove`] for each of `ids`, going through the selected objects once.
pub fn remove_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
@@ -162,6 +179,9 @@ impl Selection {
if self.key.is_some_and(|k| ids.contains(&k)) {
self.key = None;
}
if self.key_anchor.is_some_and(|(k, _)| ids.contains(&k)) {
self.key_anchor = None;
}
}
/// Select slices `ids` (see [`Selection::slices`]) and nothing else.
pub fn set_slices(&mut self, ids: impl IntoIterator<Item = NodeId>) {
@@ -271,6 +291,40 @@ impl Selection {
if self.key.is_some() || self.objects.is_empty() || self.key_guide.is_some_and(|k| !self.guides.contains(&k)) {
self.key_guide = None;
}
// A key anchor needs its point on its path and selected as an anchor point (not as a
// selected segment's end), with another point selected too: another anchor, or a path
// selected whole (Align and Distribute act on path points only). It takes the place of a
// key object or key guide.
let path_of = |o: &NodeId| found.get(o).and_then(|p| doc.node_at(p)).and_then(|n| n.path_data());
let whole_path = |o: &NodeId| !self.anchors.contains_key(o) && path_of(o).is_some_and(|path| path.anchors().next().is_some());
// Selected anchor points that are on their paths, counted up to two.
let points = || {
self.anchors
.iter()
.flat_map(|(o, set)| {
let path = path_of(o);
set.iter().filter(move |&&(si, ai)| path.is_some_and(|p| p.subpaths.get(si).is_some_and(|sp| ai < sp.anchors.len())))
})
.take(2)
.count()
};
let anchor_kept = self.key_anchor.is_some_and(|(id, (si, ai))| {
self.objects.contains(&id)
&& !self.segments.contains_key(&id)
&& self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai)))
&& found
.get(&id)
.and_then(|p| doc.node_at(p))
.and_then(|n| n.path_data())
.is_some_and(|path| path.subpaths.get(si).is_some_and(|sp| ai < sp.anchors.len()))
&& (points() >= 2 || self.objects.iter().any(whole_path))
});
if anchor_kept {
self.key = None;
self.key_guide = None;
} else {
self.key_anchor = None;
}
// A selected part needs its instance selected alone, with no guides, its symbol dynamic
// and the object still in the symbol's art as a path, compound path or type, where neither
// it nor a group or layer around it is hidden, locked or a template.
@@ -348,6 +402,9 @@ impl Selection {
if self.key.is_some_and(|k| gone.contains(&k)) {
self.key = None;
}
if self.key_anchor.is_some_and(|(k, _)| gone.contains(&k)) {
self.key_anchor = None;
}
}
/// Target `id` (see [`Selection::target`]): a layer gets its visible, unlocked art selected
/// (the art of its sublayers too), anything else is selected itself.
+80
View File
@@ -0,0 +1,80 @@
//! Symbol Options › Align to Pixel Grid: a symbol whose instances stay on the pixel grid at their
//! actual size wherever they are placed
//! (<https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28>).
//!
//! Stored under [`SYMBOL_PIXEL_ALIGNED`] keyed by symbol name; a symbol that is not pixel-aligned
//! (the default) is left out of the map.
use std::collections::HashSet;
use crate::Document;
/// Document unknown key: `{ symbolName: true }` for each pixel-aligned symbol.
pub const SYMBOL_PIXEL_ALIGNED: &str = "symbolPixelAligned";
impl Document {
/// Whether symbol `name` has Symbol Options › Align to Pixel Grid on (default: off).
pub fn symbol_pixel_aligned(&self, name: &str) -> bool {
self.unknown.get(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.get(name)).and_then(serde_json::Value::as_bool).unwrap_or(false)
}
/// Turn Align to Pixel Grid on or off for symbol `name`. Off removes the symbol from the map,
/// and the map goes when it is empty.
pub fn set_symbol_pixel_aligned(&mut self, name: &str, on: bool) {
if on {
let m = self.unknown.entry(SYMBOL_PIXEL_ALIGNED.to_string()).or_insert_with(|| serde_json::json!({}));
if let Some(o) = m.as_object_mut() {
o.insert(name.into(), serde_json::json!(true));
}
return;
}
let Some(o) = self.unknown.get_mut(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.as_object_mut()) else { return };
o.remove(name);
if o.is_empty() {
self.unknown.remove(SYMBOL_PIXEL_ALIGNED);
}
}
/// Move the stored setting when a symbol is renamed.
pub fn rename_symbol_pixel_aligned(&mut self, from: &str, to: &str) {
if from == to {
return;
}
let on = self.symbol_pixel_aligned(from);
self.set_symbol_pixel_aligned(from, false);
self.set_symbol_pixel_aligned(to, on);
}
/// The names of the pixel-aligned symbols the document holds (empty for most documents).
pub fn pixel_aligned_symbols(&self) -> HashSet<String> {
let Some(o) = self.unknown.get(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.as_object()) else { return HashSet::new() };
o.iter()
.filter(|(name, v)| v.as_bool() == Some(true) && self.symbols.iter().any(|s| &s.name == *name))
.map(|(name, _)| name.clone())
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_setting_is_off_by_default_and_follows_a_rename() {
let mut d = Document::new(100.0, 100.0);
let art = std::sync::Arc::new(crate::Node::group(d.alloc_id(), vec![]));
d.symbols.push(crate::Symbol { dynamic: false, name: "A".into(), art });
assert!(!d.symbol_pixel_aligned("A"));
assert!(d.unknown.get(SYMBOL_PIXEL_ALIGNED).is_none());
d.set_symbol_pixel_aligned("A", true);
assert!(d.symbol_pixel_aligned("A"));
assert_eq!(d.pixel_aligned_symbols(), HashSet::from(["A".to_string()]));
d.symbols[0].name = "B".into();
d.rename_symbol_pixel_aligned("A", "B");
assert!(!d.symbol_pixel_aligned("A"));
assert!(d.symbol_pixel_aligned("B"));
d.set_symbol_pixel_aligned("B", false);
assert!(d.unknown.get(SYMBOL_PIXEL_ALIGNED).is_none());
assert!(d.pixel_aligned_symbols().is_empty());
}
}
+17 -1
View File
@@ -47,6 +47,11 @@ pub(crate) struct ArtBox {
/// Whether the art holds an instance of a symbol with 9-slice guides, or of a symbol whose art
/// holds one at any depth.
pub(crate) sliced: bool,
/// The box of the regions that the live geometry effects of the clipping paths in the art give
/// them ([`crate::hit::set_clip_region`]), and of the instances in the art whose art has such
/// regions, each measured by [`Node::reach_bounds_with`]. `None` when nothing in the art has
/// one.
pub(crate) reshaped: Option<Rect>,
}
/// The art boxes of a document's symbols, which [`Node::geometric_bounds_with`],
@@ -562,7 +567,18 @@ fn art_box(art: &Arc<Node>, symbols: &SymbolBoxes) -> Option<ArtBox> {
sliced |= symbols.doc.symbol_nine_slice(symbol).is_some() || symbols.art(symbol).is_some_and(|a| a.sliced);
}
});
Some(ArtBox { geometric, visual, reach, effects, brush, sliced })
let mut reshaped = None;
if effects {
art.walk(&mut |n| {
let b = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if symbols.art(symbol).is_some_and(|a| a.reshaped.is_some()) => n.reach(Some(symbols)),
_ if n.clips() => n.children().and_then(|c| c.first()).and_then(|c| crate::hit::reshaped_clip_box(c)),
_ => None,
};
reshaped = vectorcraft_geom::union_opt(reshaped, b.filter(finite));
});
}
Some(ArtBox { geometric, visual, reach, effects, brush, sliced, reshaped })
}
#[cfg(test)]
+5 -5
View File
@@ -18,12 +18,12 @@ 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, CharClass, CompositeFont, CompositePart,
CompositeParts,
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass,
CompositeClass, CompositeClasses, CompositeFont, CompositePart, CompositeParts, CustomCharSet,
};
pub use para_style::{
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, KinsokuShoriType, LeadingModel,
@@ -35,7 +35,7 @@ pub use tabs_lists::{
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign,
TabStop,
};
pub use wrap::{resolve_wrap, wrap_work};
pub use wrap::{resolve_wrap, wrap_sources, wrap_work};
/// A text object. `runs` split into paragraphs at `\n`.
///
+26 -2
View File
@@ -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 =
+247 -26
View File
@@ -1,11 +1,16 @@
//! Type › Composite Fonts…: a font made of other fonts, one for each class of character (the
//! Kanji font is the base; kana, punctuation, symbols, Roman letters and numerals each take a font
//! of their own, sized, raised and scaled against it). Type set in a composite font names it as its
//! family; the layout sets each character in its class's font.
//! of their own, sized, raised and scaled against it). Custom character sets give characters the
//! user picks a font of their own too, ahead of their class; of two sets that list a character,
//! the later one sets it. Type set in a composite font names it as its family; the layout sets each
//! character in its set's or its class's font.
//!
//! Behavior reference (public documentation):
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>.
//! Which characters fall in which class, the ranges and the defaults are VectorCraft's own.
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>,
//! custom character sets:
//! <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348>.
//! Which characters fall in which class, the ranges, the limits and the defaults are VectorCraft's
//! own.
use serde::{Deserialize, Serialize};
@@ -179,12 +184,76 @@ impl CompositeParts {
}
}
/// A custom character set of a composite font: characters chosen by the user, set in a part of
/// their own instead of their class's part.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CustomCharSet {
/// The set's name, unique in its composite font in any case.
pub name: String,
/// The set's characters, each once, in the order they were added.
#[serde(default)]
pub characters: String,
/// The font, style, size, baseline and scales its characters take.
#[serde(flatten)]
pub part: CompositePart,
}
impl CustomCharSet {
/// An empty set named `name`, its characters set in `part`.
pub fn new(name: impl Into<String>, part: CompositePart) -> Self {
Self { name: name.into(), characters: String::new(), part }
}
/// Whether `c` can be in a custom character set: not a control character, and in the Basic
/// Multilingual Plane (U+0000 to U+FFFF).
pub fn takes(c: char) -> bool {
!c.is_control() && (c as u32) <= 0xFFFF
}
/// The character a Unicode code names: hexadecimal digits, optionally after `U+` or `0x`
/// (`3042`, `U+3042`). `None` for anything else or a code [`Self::takes`] refuses.
pub fn char_from_code(code: &str) -> Option<char> {
let code = code.trim();
let hex = ["U+", "u+", "0x", "0X"].iter().find_map(|p| code.strip_prefix(p)).unwrap_or(code);
if hex.is_empty() || hex.len() > 6 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
return None;
}
u32::from_str_radix(hex, 16).ok().and_then(char::from_u32).filter(|&c| Self::takes(c))
}
}
/// Where a composite font sets a character: the part of one of its six classes, or the part of
/// one of its custom character sets (an index into [`CompositeFont::custom`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CompositeClass {
Fixed(CharClass),
Custom(usize),
}
/// The custom character set each character of a composite font's sets falls in
/// ([`CompositeFont::classes`]): the last set that lists it.
#[derive(Clone, Debug, Default)]
pub struct CompositeClasses {
custom: std::collections::HashMap<char, usize>,
}
impl CompositeClasses {
/// Where the composite font sets `c`: the last custom set that lists it, else its class.
pub fn of(&self, c: char) -> CompositeClass {
self.custom.get(&c).map_or(CompositeClass::Fixed(CharClass::of(c)), |&i| CompositeClass::Custom(i))
}
}
/// A composite font (Type › Composite Fonts…), saved with the document. Its name is the family
/// that type set in it names.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CompositeFont {
pub name: String,
pub parts: CompositeParts,
/// Custom character sets, checked before the classes. A character two sets list is set in the
/// later set's part.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub custom: Vec<CustomCharSet>,
}
/// The size a part can take, in percent of the type's size.
@@ -197,11 +266,40 @@ pub const COMPOSITE_SCALE: std::ops::RangeInclusive<f64> = 10.0..=400.0;
pub const COMPOSITE_NAME_MAX: usize = 255;
/// The most composite fonts a document or a file keeps.
pub const COMPOSITE_FONTS_MAX: usize = 256;
/// The most custom character sets a composite font keeps.
pub const CUSTOM_SETS_MAX: usize = 64;
/// The most characters a custom character set keeps.
pub const CUSTOM_CHARS_MAX: usize = 8192;
impl CompositeFont {
/// A composite font named `name` setting every class in `font` and `style`.
pub fn new(name: impl Into<String>, font: impl Into<String>, style: impl Into<String>) -> Self {
Self { name: name.into(), parts: CompositeParts::all(CompositePart::new(font, style)) }
Self { name: name.into(), parts: CompositeParts::all(CompositePart::new(font, style)), custom: Vec::new() }
}
/// The part that sets the characters of `class`, `None` for a custom set the font doesn't have.
pub fn part(&self, class: CompositeClass) -> Option<&CompositePart> {
match class {
CompositeClass::Fixed(c) => Some(self.parts.get(c)),
CompositeClass::Custom(i) => self.custom.get(i).map(|s| &s.part),
}
}
/// Where this font sets character `c`: the last custom set that lists it, else its class. For
/// many characters, [`Self::classes`] looks each up faster.
pub fn class_of(&self, c: char) -> CompositeClass {
self.custom.iter().rposition(|s| s.characters.contains(c)).map_or(CompositeClass::Fixed(CharClass::of(c)), CompositeClass::Custom)
}
/// The custom set each character of this font's sets falls in, to look up many characters.
pub fn classes(&self) -> CompositeClasses {
let mut custom = std::collections::HashMap::new();
for (i, s) in self.custom.iter().enumerate() {
for c in s.characters.chars() {
custom.insert(c, i);
}
}
CompositeClasses { custom }
}
/// Do `a` and `b` name the same composite font: equal in any case?
@@ -223,36 +321,50 @@ impl CompositeFont {
}
/// Why this composite font can't be used, if it can't: a name [`Self::clean_name`] refuses, a
/// part without a font, a value out of its range, or a scale or Scale at Center on a class
/// that has none.
/// part without a font, a value out of its range, a scale or Scale at Center on a class that
/// has none, or a custom character set [`Self::check_custom`] refuses.
pub fn check(&self) -> Result<(), String> {
if Self::clean_name(&self.name).as_deref() != Some(self.name.as_str()) {
return Err(format!("`{}` can't name a composite font", self.name));
}
for class in CharClass::ALL {
let p = self.parts.get(class);
let k = class.key();
if p.font.trim().is_empty() {
return Err(format!("{k}: give a font"));
check_part(self.parts.get(class), class.key(), class.scales(), class == CharClass::Kana)?;
}
self.check_custom()
}
/// Why this font's custom character sets can't be used, if they can't: more than
/// [`CUSTOM_SETS_MAX`], a name [`Self::clean_name`] refuses or two sets share (in any case), a
/// character [`CustomCharSet::takes`] refuses or a set lists twice, more than
/// [`CUSTOM_CHARS_MAX`] characters in a set, or a part [`Self::check`] would refuse. A set's
/// characters can be scaled across and up; only kana are scaled at the center.
pub fn check_custom(&self) -> Result<(), String> {
if self.custom.len() > CUSTOM_SETS_MAX {
return Err(format!("a composite font keeps at most {CUSTOM_SETS_MAX} character sets"));
}
let mut names = std::collections::HashSet::new();
for s in &self.custom {
let name = &s.name;
if Self::clean_name(name).as_deref() != Some(name.as_str()) {
return Err(format!("`{name}` can't name a character set"));
}
let within = |v: f64, r: &std::ops::RangeInclusive<f64>| v.is_finite() && r.contains(&v);
if !within(p.size, &COMPOSITE_SIZE) {
return Err(format!("{k}: size must be {} to {}%", COMPOSITE_SIZE.start(), COMPOSITE_SIZE.end()));
if !names.insert(name.to_lowercase()) {
return Err(format!("two character sets are named `{name}`"));
}
if !within(p.baseline, &COMPOSITE_BASELINE) {
return Err(format!("{k}: baseline must be {} to {}%", COMPOSITE_BASELINE.start(), COMPOSITE_BASELINE.end()));
}
for v in [p.h_scale, p.v_scale] {
if !within(v, &COMPOSITE_SCALE) {
return Err(format!("{k}: scale must be {} to {}%", COMPOSITE_SCALE.start(), COMPOSITE_SCALE.end()));
let mut seen = std::collections::HashSet::new();
for (n, c) in s.characters.chars().enumerate() {
if n == CUSTOM_CHARS_MAX {
return Err(format!("`{name}`: a character set keeps at most {CUSTOM_CHARS_MAX} characters"));
}
if v != 100.0 && !class.scales() {
return Err(format!("{k}: only kana, roman and numerals can be scaled"));
let code = c as u32;
if !CustomCharSet::takes(c) {
return Err(format!("`{name}`: U+{code:04X} is a control character or past U+FFFF"));
}
if !seen.insert(c) {
return Err(format!("`{name}`: U+{code:04X} is listed twice"));
}
}
if p.scale_at_center && class != CharClass::Kana {
return Err(format!("{k}: only kana can be scaled at the center"));
}
check_part(&s.part, name, true, false)?;
}
Ok(())
}
@@ -264,9 +376,41 @@ impl CompositeFont {
let mut names = std::collections::HashSet::new();
let mut kept: Vec<CompositeFont> =
fonts.iter().filter(|f| f.check().is_ok() && names.insert(f.name.to_lowercase())).take(COMPOSITE_FONTS_MAX).cloned().collect();
kept.retain(|f| CharClass::ALL.iter().all(|&c| !names.contains(&f.parts.get(c).font.to_lowercase())));
kept.retain(|f| f.part_fonts().all(|font| !names.contains(&font.to_lowercase())));
(kept.len() != fonts.len()).then_some(kept)
}
/// The fonts of the parts, each class's then each custom set's.
pub fn part_fonts(&self) -> impl Iterator<Item = &str> {
CharClass::ALL.into_iter().map(|c| self.parts.get(c).font.as_str()).chain(self.custom.iter().map(|s| s.part.font.as_str()))
}
}
/// Why part `p` (of the class or set named `k`) can't be used, if it can't: no font, a value out
/// of its range, a scale when `scales` is false, or Scale at Center when `center` is false.
fn check_part(p: &CompositePart, k: &str, scales: bool, center: bool) -> Result<(), String> {
if p.font.trim().is_empty() {
return Err(format!("{k}: give a font"));
}
let within = |v: f64, r: &std::ops::RangeInclusive<f64>| v.is_finite() && r.contains(&v);
if !within(p.size, &COMPOSITE_SIZE) {
return Err(format!("{k}: size must be {} to {}%", COMPOSITE_SIZE.start(), COMPOSITE_SIZE.end()));
}
if !within(p.baseline, &COMPOSITE_BASELINE) {
return Err(format!("{k}: baseline must be {} to {}%", COMPOSITE_BASELINE.start(), COMPOSITE_BASELINE.end()));
}
for v in [p.h_scale, p.v_scale] {
if !within(v, &COMPOSITE_SCALE) {
return Err(format!("{k}: scale must be {} to {}%", COMPOSITE_SCALE.start(), COMPOSITE_SCALE.end()));
}
if v != 100.0 && !scales {
return Err(format!("{k}: only kana, roman and numerals can be scaled"));
}
}
if p.scale_at_center && !center {
return Err(format!("{k}: only kana can be scaled at the center"));
}
Ok(())
}
#[cfg(test)]
@@ -341,4 +485,81 @@ mod tests {
spaced.name = " Mixed".into();
assert!(spaced.check().is_err());
}
/// A character a custom set lists falls in that set ahead of its class, the later of two sets
/// that list it wins, and the quick lookup agrees with the one-character one.
#[test]
fn custom_sets_take_their_characters_before_the_classes() {
let mut f = CompositeFont::new("Mixed", "Inter", "Regular");
let mut a = CustomCharSet::new("Marks", CompositePart::new("Source Sans 3", "Bold"));
a.characters = "※A".into();
let mut b = CustomCharSet::new("Letters", CompositePart::new("Inter", "Italic"));
b.characters = "AB".into();
f.custom = vec![a, b];
let classes = f.classes();
for (c, want) in [
('※', CompositeClass::Custom(0)),
('A', CompositeClass::Custom(1)),
('B', CompositeClass::Custom(1)),
('C', CompositeClass::Fixed(CharClass::Roman)),
('漢', CompositeClass::Fixed(CharClass::Kanji)),
] {
assert_eq!(f.class_of(c), want, "{c:?}");
assert_eq!(classes.of(c), want, "{c:?}");
}
assert_eq!(f.part(CompositeClass::Custom(0)).map(|p| p.style.as_str()), Some("Bold"));
assert_eq!(f.part(CompositeClass::Custom(2)), None);
assert_eq!(f.check(), Ok(()));
// Read and written with the part's fields beside the set's name and characters.
let json = serde_json::to_value(&f).unwrap();
assert_eq!(json["custom"][1]["characters"], "AB");
assert_eq!(json["custom"][1]["style"], "Italic");
assert_eq!(serde_json::from_value::<CompositeFont>(json).unwrap(), f);
// A font without sets is written as before.
assert!(serde_json::to_value(CompositeFont::new("Plain", "Inter", "Regular")).unwrap().get("custom").is_none());
}
/// Set names, characters and limits are checked; sets scale like Roman letters.
#[test]
fn custom_sets_check_their_names_and_characters() {
let ok = CompositeFont::new("Mixed", "Inter", "Regular");
let with = |sets: Vec<(&str, &str)>, edit: fn(&mut CompositePart)| {
let mut f = ok.clone();
for (name, chars) in sets {
let mut s = CustomCharSet::new(name, CompositePart::new("Inter", "Regular"));
s.characters = chars.into();
edit(&mut s.part);
f.custom.push(s);
}
f.check()
};
let none = |_: &mut CompositePart| {};
assert_eq!(with(vec![("Empty", "")], none), Ok(()));
assert_eq!(with(vec![("Wide", "AB")], |p| p.h_scale = 80.0), Ok(()));
assert!(with(vec![("Wide", "AB")], |p| p.scale_at_center = true).is_err());
assert!(with(vec![("Big", "A")], |p| p.size = 401.0).is_err());
assert!(with(vec![("Same", "A"), ("same", "B")], none).unwrap_err().contains("two character sets"));
assert!(with(vec![(" Pad", "A")], none).is_err());
assert!(with(vec![("Twice", "ABA")], none).unwrap_err().contains("U+0041 is listed twice"));
assert!(with(vec![("Tab", "A\t")], none).unwrap_err().contains("U+0009"));
assert!(with(vec![("Astral", "𠀋")], none).unwrap_err().contains("U+2000B"));
let many: String = (0x4E00u32..).filter_map(char::from_u32).take(CUSTOM_CHARS_MAX + 1).collect();
let mut f = ok.clone();
f.custom.push(CustomCharSet { name: "Many".into(), characters: many, part: CompositePart::new("Inter", "Regular") });
assert!(f.check().unwrap_err().contains("at most"));
let mut f = ok.clone();
f.custom = (0..=CUSTOM_SETS_MAX).map(|i| CustomCharSet::new(format!("S{i}"), CompositePart::new("Inter", "Regular"))).collect();
assert!(f.check().is_err());
}
/// Codes are hexadecimal, with or without `U+` or `0x`, inside the Basic Multilingual Plane.
#[test]
fn custom_set_codes_name_characters() {
assert_eq!(CustomCharSet::char_from_code("3042"), Some('あ'));
assert_eq!(CustomCharSet::char_from_code(" U+203B "), Some('※'));
assert_eq!(CustomCharSet::char_from_code("0x41"), Some('A'));
for bad in ["", "U+", "zz", "20000B", "D800", "0009", "1F600", "1234567", "+41"] {
assert_eq!(CustomCharSet::char_from_code(bad), None, "{bad:?}");
}
}
}
+4
View File
@@ -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 {
+34 -4
View File
@@ -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
+36
View File
@@ -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]
+58 -34
View File
@@ -4,7 +4,7 @@ use std::sync::Arc;
use vectorcraft_geom::{PathData, shapes};
use super::{TextKind, WrapShape};
use super::{TextKind, TextObject, WrapShape};
use crate::{Document, Node, NodeId, NodeKind};
/// Outline of a wrap object in document coordinates: its paths, or its bounds for other art.
@@ -82,6 +82,57 @@ pub fn wrap_work(doc: &Document) -> usize {
total
}
/// Each area text object of `layer`, from the top down, with the wrap objects above it in the
/// layer whose outlines aren't empty, topmost first, each with the shape its outline makes in
/// document coordinates. Each wrap object's outline is made once.
fn each_text<'a>(layer: &'a Node, mut f: impl FnMut(&'a Node, &[(&'a Node, WrapShape)])) {
let mut items = vec![];
collect(layer, &mut items);
let mut above: Vec<(&Node, WrapShape)> = vec![];
for it in items.iter().rev() {
match it {
Item::Wrap(n) => {
let mut pd = PathData::default();
outline(n, &mut pd);
if !pd.is_empty() {
above.push((n, WrapShape { path: pd, wrap: n.extras().wrap.unwrap_or_default() }));
}
}
Item::Text(n) => f(n, &above),
}
}
}
/// The wrap shapes of text object `t` (text space) from `above`, the wrap objects above it as
/// [`each_text`] gives them: bottom first.
fn shapes_of(t: &TextObject, above: &[(&Node, WrapShape)]) -> Vec<WrapShape> {
let inv = t.xf.inverse();
above
.iter()
.rev()
.map(|(_, s)| {
let mut path = s.path.clone();
path.transform(inv);
WrapShape { path, wrap: s.wrap }
})
.collect()
}
/// Each area text object on `doc`'s layers that [`resolve_wrap`] gives wrap shapes, with the wrap
/// objects whose outlines make them, bottom first, and those shapes (text space), as
/// [`resolve_wrap`] works them out. The copying is [`wrap_work`].
pub fn wrap_sources<'a>(doc: &'a Document, mut f: impl FnMut(&'a Node, Vec<&'a Node>, Vec<WrapShape>)) {
for layer in &doc.layers {
each_text(layer, |n, above| {
if let NodeKind::Text(t) = &n.kind
&& !above.is_empty()
{
f(n, above.iter().rev().map(|(s, _)| *s).collect(), shapes_of(t, above));
}
});
}
}
/// Resolve the wrap shapes (`TextObject::wrap`, text space) of each area text object from the
/// outlines of the wrap objects above it in its layer. With `before`, the layers it holds unchanged
/// are skipped; without it, every layer is resolved. Returns the area text objects whose shapes
@@ -95,41 +146,14 @@ pub fn resolve_wrap(before: Option<&Document>, doc: &mut Document) -> Vec<NodeId
{
continue;
}
let mut items = vec![];
collect(layer, &mut items);
if items.is_empty() {
continue;
}
// From the top down, each wrap object's outline is made once; each area text object takes
// those above it, bottom first.
let mut above: Vec<WrapShape> = vec![];
for it in items.iter().rev() {
match it {
Item::Wrap(n) => {
let mut pd = PathData::default();
outline(n, &mut pd);
if !pd.is_empty() {
above.push(WrapShape { path: pd, wrap: n.extras().wrap.unwrap_or_default() });
}
}
Item::Text(n) => {
let NodeKind::Text(t) = &n.kind else { continue };
let inv = t.xf.inverse();
let shapes: Vec<WrapShape> = above
.iter()
.rev()
.map(|s| {
let mut path = s.path.clone();
path.transform(inv);
WrapShape { path, wrap: s.wrap }
})
.collect();
if shapes != t.wrap {
updates.push((n.id, shapes));
}
each_text(layer, |n, above| {
if let NodeKind::Text(t) = &n.kind {
let shapes = shapes_of(t, above);
if shapes != t.wrap {
updates.push((n.id, shapes));
}
}
}
});
}
let mut changed = Vec::with_capacity(updates.len());
for (id, shapes) in updates {
+34 -6
View File
@@ -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)
+122
View File
@@ -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}");
}
+8 -8
View File
@@ -210,22 +210,22 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
CLASSIC_EXTRUDE,
"Extrude & Bevel (Classic)…",
&["Effect", "3D and Materials", "3D (Classic)"],
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.",
json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","drawHiddenFaces":false}),
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.",
json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false}),
),
g(
CLASSIC_REVOLVE,
"Revolve (Classic)…",
&["Effect", "3D and Materials", "3D (Classic)"],
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000"}),
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}),
),
g(
CLASSIC_ROTATE,
"Rotate (Classic)…",
&["Effect", "3D and Materials", "3D (Classic)"],
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none (black; the color the art darkens toward; none keeps the paint), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.",
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"diffuse","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000"}),
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none (black; the color the art darkens toward; none keeps the paint), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.",
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"diffuse","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}),
),
g(
"convertToShape.rectangle",
@@ -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
+52 -51
View File
@@ -367,9 +367,14 @@ fn compound_shape_art_in(doc: Option<&Document>, n: &Node, hook: Option<OutlineH
fn styled(src: &Node, path: PathData, outline: bool) -> Node {
let mut appearance = Appearance { items: src.appearance.items.clone(), ..Default::default() };
if outline {
let fill = src.appearance.fill_paint();
let paint = if fill.is_none() { src.appearance.stroke_paint() } else { fill };
appearance = Appearance { items: vec![AppearanceItem::Stroke(StrokeLayer::new(paint, 1.0))], ..Default::default() };
// The edges take the paint, opacity, blend mode and overprint of the top fill that paints,
// or of the top stroke that paints when no fill does.
let layer = top_painting_fill(&src.appearance).or_else(|| src.appearance.items.iter().rev().find(|i| paints(i)));
let mut stroke = StrokeLayer::new(layer.map_or(Paint::None, |i| i.paint().clone()), 1.0);
if let Some(i) = layer {
(stroke.opacity, stroke.blend, stroke.overprint) = (i.opacity(), i.blend(), i.overprint());
}
appearance = Appearance { items: vec![AppearanceItem::Stroke(stroke)], ..Default::default() };
}
let mut n = Node::path(src.id, path, appearance);
n.opacity = src.opacity;
@@ -504,7 +509,8 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
.iter()
.filter_map(|l| {
let (path, rule) = geometry(l)?;
Some((l.id, crate::trap::TrapSource { path, rule, fill: l.appearance.fill_paint() }))
let fill = top_painting_fill(&l.appearance).map_or(Paint::None, |i| i.paint().clone());
Some((l.id, crate::trap::TrapSource { path, rule, fill }))
})
.unzip();
let made = crate::trap::traps(&srcs, &crate::trap::TrapOptions::from_params(&e.params));
@@ -580,7 +586,8 @@ fn mixing_rate(params: &Value) -> f64 {
}
fn fill_cmyk(src: &Node) -> Option<[f32; 4]> {
let paint = src.appearance.fill_paint();
// The top fill that paints: a hidden fill adds no color.
let paint = top_painting_fill(&src.appearance)?.paint().clone();
let color = paint.color()?;
let tinted = match paint {
Paint::Solid { tint, .. } => color.tinted(tint),
@@ -637,6 +644,11 @@ fn is_container(n: &Node) -> bool {
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })
}
/// The top fill of `a` that paints: hidden fills and fills of no paint are skipped.
fn top_painting_fill(a: &Appearance) -> Option<&AppearanceItem> {
a.items.iter().rev().find(|i| i.is_fill() && paints(i))
}
/// Does `item` paint anything?
pub fn paints(item: &AppearanceItem) -> bool {
item.visible()
@@ -742,45 +754,28 @@ fn item_art(id: NodeId, item: &AppearanceItem, shapes: &[(PathData, FillRule)],
}
/// The members of a container that [`take_held_guides`] visits, by index, each with the same for
/// its own members. A ruler guide's entry is empty; a container's is not.
/// its own members. A ruler guide's entry is empty, whether its container is a layer or a group; a
/// container's is not.
#[derive(Default)]
struct HeldGuides(Vec<(usize, HeldGuides)>);
/// The members of `n` holding or leading to the ruler guides of sublayers, found by looking at each
/// member at every depth once: the ruler guides (`is_guide`) of `n` when it is a layer, each
/// sublayer holding one directly or in its sublayers, and each member of another kind with such a
/// sublayer among its members or its groups' members. With them, whether `n` is a layer holding a
/// ruler guide directly or in its sublayers. The other members of a layer holding none are not
/// looked into, unless the layer is the one whose sublayers are gathered (`top`).
fn held_guides(n: &Node, top: bool, is_guide: &impl Fn(&Node) -> bool) -> (bool, HeldGuides) {
let layer = n.is_layer();
let (mut holds, mut held, mut other) = (false, vec![], vec![]);
/// The members of `n` that are ruler guides (`is_guide`), and those holding one at any depth, in
/// order. Every member at every depth is looked at once: a sublayer or group with no guide of its
/// own is still looked into, and a guide directly in a group counts as one in a layer does. A
/// member holding no guide gets no entry.
fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> HeldGuides {
let mut held = vec![];
for (i, c) in n.children().into_iter().flatten().enumerate() {
if is_guide(c) {
if layer {
holds = true;
held.push((i, HeldGuides::default()));
}
} else if c.is_layer() {
let (sub_holds, inner) = held_guides(c, false, is_guide);
if sub_holds {
holds = true;
held.push((i, inner));
}
} else {
other.push((i, c));
held.push((i, HeldGuides::default()));
continue;
}
let inner = held_guides(c, is_guide);
if !inner.0.is_empty() {
held.push((i, inner));
}
}
if !layer || holds || top {
for (i, c) in other {
let (_, inner) = held_guides(c, false, is_guide);
if !inner.0.is_empty() {
held.push((i, inner));
}
}
held.sort_unstable_by_key(|(i, _)| *i);
}
(layer && holds, HeldGuides(held))
HeldGuides(held)
}
/// Move the ruler guides of `n` and of its members that [`held_guides`] found (`held`) to `out`:
@@ -818,15 +813,14 @@ fn take_held_guides(n: &mut Node, held: HeldGuides, out: &mut Vec<Arc<Node>>, hi
out.append(&mut deeper);
}
/// Move the ruler guides of the sublayers among the members of `n`, and among its groups'
/// members, to `out`, in order: a sublayer's own guides, then those of its members. A guide taken
/// from a hidden or locked sublayer, or from one inside such a sublayer or group, is hidden or
/// locked itself. Each member at every depth is looked at once at most (`is_guide`), and only
/// containers holding one are copied.
/// Move the ruler guides of `n` and those held at any depth by the sublayers and groups among its
/// members to `out`, in order: a container's own guides, then those of its members. A sublayer or
/// group with no guide of its own still gives up those of its members. A guide taken from a hidden
/// or locked sublayer or group, or from one inside such a container, is hidden or locked itself.
/// Each member at every depth is looked at once (`is_guide`), and only containers holding a guide
/// are copied.
fn take_sublayer_guides(n: &mut Node, out: &mut Vec<Arc<Node>>, is_guide: &impl Fn(&Node) -> bool) {
let (_, mut held) = held_guides(n, true, is_guide);
// The ruler guides of `n` itself stay where they are.
held.0.retain(|(_, inner)| !inner.0.is_empty());
let held = held_guides(n, is_guide);
take_held_guides(n, held, out, false, false);
}
@@ -850,12 +844,15 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
return None;
}
let mut m = n.clone();
// A layer's ruler guides take no part: they go back above the evaluated art at the end.
let mut guides = m.children_mut().map(|ch| ch.split_off(Node::guide_run_start(ch))).unwrap_or_default();
// So do its sublayers' guides, which would otherwise go with the art the effects replace or
// copy: they stay on this layer, hidden and locked as their sublayers were.
if m.is_layer() && (pathfinder || !fx.is_empty()) {
// Its ruler guides take no part: they go back above the evaluated art at the end. With effects
// that replace or copy the art, so do its guides among the art and those in its sublayers and
// groups, which would otherwise go with that art: they stay on `n`, in order, hidden and
// locked as their containers were.
let mut guides = vec![];
if pathfinder || !fx.is_empty() {
take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide);
} else if let Some(ch) = m.children_mut() {
guides = ch.split_off(Node::guide_run_start(ch));
}
if pathfinder {
let hook = |c: &Node| crate::outline_object(doc, c);
@@ -868,7 +865,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.
+236 -8
View File
@@ -1,6 +1,6 @@
use super::*;
use vectorcraft_color::{BlendMode, Color, Paint};
use vectorcraft_doc::{CharStyle, Effect, NodeId, TextObject};
use vectorcraft_doc::{CharStyle, Effect, FillLayer, NodeId, TextObject};
use vectorcraft_geom::{Point, Rect, shapes};
/// Type tests need glyph outlines, which only the optional craft-fonts build input provides.
@@ -71,6 +71,33 @@ fn trap_effect_adds_an_overprinting_strip_above_the_members() {
assert_eq!(fill.paint.color(), Some(yellow));
}
/// Trap takes each member's top fill that paints: a hidden fill on top is skipped, and a member
/// whose only fill is hidden does not take part.
#[test]
fn trap_skips_a_hidden_fill() {
let yellow = Color::cmyk(0.0, 0.0, 1.0, 0.0);
let blue = Color::cmyk(1.0, 0.6, 0.0, 0.0);
let mut hidden = FillLayer::new(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
hidden.visible = false;
let trap = |members: Vec<Arc<Node>>| {
let mut g = Node::group(NodeId(10), members);
let params = serde_json::json!({"thickness": 1.0, "tintReduction": 100});
g.appearance.effects.push(Effect { id: crate::trap::TRAP.into(), params, visible: true });
pathfinder_children(None, &g, None).unwrap()
};
let mut covered = (*sq(1, 0.0, yellow)).clone();
covered.appearance.items.push(AppearanceItem::Fill(hidden.clone()));
let out = trap(vec![Arc::new(covered), sq(2, 10.0, blue)]);
assert_eq!(out.len(), 3, "both squares and one trap");
assert_eq!(out[2].appearance.fill().unwrap().paint.color(), Some(yellow));
let only_hidden = Node::path(
NodeId(1),
shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)),
Appearance { items: vec![AppearanceItem::Fill(hidden)], ..Default::default() },
);
assert_eq!(trap(vec![Arc::new(only_hidden), sq(2, 10.0, blue)]).len(), 2, "no trap");
}
#[test]
fn hard_mix_takes_the_highest_of_each_cmyk_channel_and_drops_strokes() {
let mut g = two_overlapping_cmyk_squares();
@@ -87,6 +114,72 @@ fn soft_mix_blends_cmyk_bottom_to_top_and_drops_strokes() {
assert!((c - 0.3).abs() < 0.02 && (m - 0.43).abs() < 0.02 && (y - 0.35).abs() < 0.02 && (k - 0.05).abs() < 0.02, "{c} {m} {y} {k}");
}
/// Soft Mix and Hard Mix mix the top fill that paints: a hidden fill above it adds no color.
#[test]
fn mixes_skip_a_hidden_fill() {
for effect in ["pathfinder.softMix", "pathfinder.hardMix"] {
let mut plain = two_overlapping_cmyk_squares();
plain.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"mixingRate": 50.0}), visible: true });
let mut covered = plain.clone();
let NodeKind::Group { children, .. } = &mut covered.kind else { panic!("group") };
let mut hidden = FillLayer::new(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
hidden.visible = false;
for c in children.iter_mut() {
Arc::make_mut(c).appearance.items.push(AppearanceItem::Fill(hidden.clone()));
}
assert_eq!(overlap_cmyk(&covered), overlap_cmyk(&plain), "{effect}");
}
}
/// Outline strokes each edge with the top fill that paints, keeping that fill's opacity, blend
/// mode and overprint. A hidden fill or a fill of no paint gives the edges nothing; with no fill
/// that paints, the edges take the top stroke that paints, which skips hidden and 0 pt strokes.
#[test]
fn outline_edges_keep_the_fill_layers_opacity_blend_and_overprint() {
use vectorcraft_doc::StrokeLayer;
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
let mut fill = FillLayer::new(red.clone());
(fill.opacity, fill.blend, fill.overprint) = (0.5, BlendMode::Multiply, true);
let mut hidden = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
hidden.visible = false;
let mut stroke = StrokeLayer::new(blue.clone(), 2.0);
(stroke.opacity, stroke.blend, stroke.overprint) = (0.5, BlendMode::Multiply, true);
let mut hidden_stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 2.0);
hidden_stroke.visible = false;
let zero_stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 0.0);
let look = |items: Vec<AppearanceItem>| Appearance { items, ..Default::default() };
let (f, s) = (AppearanceItem::Fill, AppearanceItem::Stroke);
let cases = [
(look(vec![f(fill.clone())]), Some(red.clone())),
(look(vec![f(fill.clone()), f(hidden.clone())]), Some(red.clone())),
(look(vec![f(fill.clone()), f(FillLayer::new(Paint::None))]), Some(red.clone())),
(look(vec![f(hidden.clone())]), None),
(look(vec![s(stroke.clone())]), Some(blue.clone())),
(look(vec![f(hidden.clone()), s(stroke.clone())]), Some(blue.clone())),
(look(vec![s(stroke.clone()), s(hidden_stroke), s(zero_stroke.clone())]), Some(blue.clone())),
(look(vec![s(zero_stroke)]), None),
];
for (appearance, want) in cases {
let member = Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), appearance));
let mut g = Node::group(NodeId(10), vec![member, sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0))]);
g.appearance.effects.push(Effect { id: "pathfinder.outline".into(), params: serde_json::json!({}), visible: true });
let out = pathfinder_children(None, &g, None).unwrap();
let edges: Vec<_> = out.iter().filter(|n| n.id == NodeId(1)).collect();
assert!(!edges.is_empty(), "{out:#?}");
for n in edges {
let [AppearanceItem::Stroke(s)] = n.appearance.items.as_slice() else { panic!("one stroke: {n:#?}") };
match &want {
Some(paint) => {
assert_eq!(&s.paint, paint);
assert_eq!((s.opacity, s.blend, s.overprint), (0.5, BlendMode::Multiply, true), "{s:#?}");
}
None => assert!(s.paint.is_none() && s.opacity == 1.0, "{s:#?}"),
}
}
}
}
#[test]
fn shape_modes_follow_the_pathfinder_panel() {
let add = pathfinder_children(None, &group_with("pathfinder.add"), None).unwrap();
@@ -1808,7 +1901,7 @@ fn a_sublayers_ruler_guide_in_a_hidden_or_locked_group_stays_hidden_or_locked()
}
/// Gathering the ruler guides of nested sublayers, and of a sublayer inside nested groups, looks
/// at each member at every depth once at most, and takes the same guides, in the same order and
/// at each member at every depth once, and takes the same guides, in the same order and
/// state, as a layer's effects keep.
#[test]
fn gathering_sublayer_ruler_guides_looks_at_each_member_once() {
@@ -1840,7 +1933,7 @@ fn gathering_sublayer_ruler_guides_looks_at_each_member_once() {
groups.locked = depth == 3;
}
let free = Arc::new(Node::group(NodeId(500), vec![sq(501, 0.0, Color::BLACK), sq(502, 5.0, Color::BLACK)]));
// A sublayer with no guide: the art in its group is not looked at.
// A sublayer with no guide, its group holding none either.
let quiet = Node::group(NodeId(601), vec![sq(602, 0.0, Color::BLACK), sq(603, 5.0, Color::BLACK)]);
let quiet = Arc::new(layer(600, vec![Arc::new(quiet)]));
let mut root = layer(10, vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(chain), Arc::new(groups), free.clone(), quiet.clone(), guide(20)]);
@@ -1858,15 +1951,16 @@ fn gathering_sublayer_ruler_guides_looks_at_each_member_once() {
};
let mut taken = vec![];
take_sublayer_guides(&mut m, &mut taken, &is_guide);
assert_eq!(looked.get(), members(&root) - 2, "each member is looked at once, none in the quiet sublayer's group");
assert_eq!(state(&taken), expected, "a sublayer's own guides, then its sublayers', each once");
assert!(Arc::ptr_eq(&taken[0], &first_guide), "a guide with nothing to change is not copied");
assert!(!Arc::ptr_eq(&taken[1], &second_guide), "a guide made hidden is copied");
assert_eq!(looked.get(), members(&root), "each member is looked at once, those of guide-free containers included");
assert_eq!(taken[0].id, NodeId(20), "the layer's own guide comes first");
assert_eq!(state(&taken[1..]), expected, "a sublayer's own guides, then its sublayers', each once");
assert!(Arc::ptr_eq(&taken[1], &first_guide), "a guide with nothing to change is not copied");
assert!(!Arc::ptr_eq(&taken[2], &second_guide), "a guide made hidden is copied");
assert!(second_guide.visible, "the guide as it was stays as it was");
let ch = m.children().unwrap();
assert_eq!(ch.len(), 5, "the layer's own guide is taken");
assert!(Arc::ptr_eq(&ch[3], &free), "a member with no sublayer guide is not copied");
assert!(Arc::ptr_eq(&ch[4], &quiet), "a sublayer with no guide is not copied");
assert!(ch[5].is_ruler_guide(), "the layer's own guide stays where it is");
let ids = |n: &Node| n.children().into_iter().flatten().map(|c| c.id).collect::<Vec<_>>();
assert_eq!(ids(&ch[1]), [NodeId(102), NodeId(301)], "the sublayer's art stays, in order");
assert_eq!(ids(&root.children().unwrap()[1]), [NodeId(102), NodeId(301), NodeId(201)], "the source keeps its guides");
@@ -1892,6 +1986,140 @@ fn gathering_sublayer_ruler_guides_looks_at_each_member_once() {
}
}
/// Where each ruler guide in `n` is, at every depth, with its position, visibility and lock.
fn ruler_guides_in(n: &Node, out: &mut Vec<(NodeId, NodeKind, bool, bool)>) {
for c in n.children().into_iter().flatten() {
if c.is_ruler_guide() {
out.push((c.id, c.kind.clone(), c.visible, c.locked));
}
ruler_guides_in(c, out);
}
}
/// A ruler guide in a layer inside a group inside a sublayer that holds no guide of its own, at
/// any depth of that pattern, survives its layer's Pathfinder effect or Transform copies once, last
/// in the layer, hidden or locked when any container on its way was.
#[test]
fn a_ruler_guide_below_a_guide_free_sublayer_and_a_group_survives_its_layers_effects() {
use vectorcraft_doc::LayerColor;
let layer = |id, children: Vec<Arc<Node>>, (hidden, locked): (bool, bool)| {
let mut l = Node::layer(NodeId(id), "Sub", LayerColor::Preset(1));
if let Some(ch) = l.children_mut() {
*ch = children;
}
(l.visible, l.locked) = (!hidden, locked);
Arc::new(l)
};
let group = |id, children: Vec<Arc<Node>>, (hidden, locked): (bool, bool)| {
let mut g = Node::group(NodeId(id), children);
(g.visible, g.locked) = (!hidden, locked);
Arc::new(g)
};
let kind = NodeKind::RulerGuide { vertical: false, pos: 7.0, artboard: None };
let states = [(false, false), (true, false), (false, true)];
for (effect, params) in [("pathfinder.add", serde_json::json!({})), ("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}))] {
for depth in 1..=3_u64 {
for sub in states {
for grp in states {
for inner in states {
// Layer 10 → sublayer → group → … → layer holding the guide, the pattern
// repeated `depth` times; only the innermost layer holds a guide.
let mut n = layer(900, vec![sq(901, 0.0, Color::BLACK), Arc::new(Node::new(NodeId(20), kind.clone()))], inner);
for d in (0..depth).rev() {
let (s, g) = if d == 0 { (sub, grp) } else { ((false, false), (false, false)) };
n = group(700 + d, vec![sq(710 + d, 5.0, Color::BLACK), n], g);
n = layer(800 + d, vec![n, sq(810 + d, 2.0, Color::BLACK)], s);
}
let mut root = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0));
if let Some(ch) = root.children_mut() {
*ch = vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), n];
}
root.appearance.effects.push(Effect { id: effect.into(), params: params.clone(), visible: true });
let art = evaluate_container(None, &root).unwrap();
let (hidden, locked) = (sub.0 || grp.0 || inner.0, sub.1 || grp.1 || inner.1);
let mut all = vec![];
ruler_guides_in(&art, &mut all);
let case = format!("{effect}, depth {depth}, sublayer {sub:?}, group {grp:?}, layer {inner:?}");
assert_eq!(all, [(NodeId(20), kind.clone(), !hidden, locked)], "{case}: the guide, once, unchanged");
let last = art.children().and_then(|c| c.last()).unwrap();
assert_eq!(last.id, NodeId(20), "{case}: last in the layer");
}
}
}
}
}
}
/// A ruler guide directly in a group, in a layer or in a group with a Pathfinder effect or
/// Transform copies, survives that effect once, last in the container, hidden or locked as its
/// groups were. So does one among a group's art rather than after it.
#[test]
fn a_ruler_guide_in_a_group_survives_its_containers_effects() {
use vectorcraft_doc::LayerColor;
let kind = NodeKind::RulerGuide { vertical: true, pos: 4.0, artboard: None };
let guide = || Arc::new(Node::new(NodeId(20), kind.clone()));
for (effect, params) in [("pathfinder.add", serde_json::json!({})), ("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}))] {
for (hidden, locked) in [(false, false), (true, false), (false, true)] {
let mut inner = Node::group(NodeId(12), vec![sq(2, 5.0, Color::BLACK), guide(), sq(3, 8.0, Color::BLACK)]);
(inner.visible, inner.locked) = (!hidden, locked);
let outer = Arc::new(Node::group(NodeId(11), vec![Arc::new(inner)]));
let fx = Effect { id: effect.into(), params: params.clone(), visible: true };
let mut l = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0));
if let Some(ch) = l.children_mut() {
*ch = vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), outer.clone()];
}
l.appearance.effects.push(fx.clone());
let mut g = Node::group(NodeId(13), vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), outer]);
g.appearance.effects.push(fx.clone());
for (what, n) in [("layer", l), ("group", g)] {
let art = evaluate_container(None, &n).unwrap();
let mut all = vec![];
ruler_guides_in(&art, &mut all);
let case = format!("{effect} on a {what}, hidden {hidden}, locked {locked}");
assert_eq!(all, [(NodeId(20), kind.clone(), !hidden, locked)], "{case}: the guide, once, unchanged");
assert_eq!(art.children().and_then(|c| c.last()).map(|c| c.id), Some(NodeId(20)), "{case}: last");
}
}
// A group's guide placed before its art.
let mut g = Node::group(NodeId(13), vec![guide(), sq(1, 0.0, Color::BLACK), sq(2, 5.0, Color::BLACK)]);
g.appearance.effects.push(Effect { id: effect.into(), params: params.clone(), visible: true });
let art = evaluate_container(None, &g).unwrap();
let mut all = vec![];
ruler_guides_in(&art, &mut all);
assert_eq!(all, [(NodeId(20), kind.clone(), true, false)], "{effect}: a group's leading guide, once");
assert_eq!(art.children().and_then(|c| c.last()).map(|c| c.id), Some(NodeId(20)), "{effect}: moved last");
}
}
/// The ruler guides of a layer or group with a Pathfinder effect or Transform copies, one among
/// its art and one after it, go after the evaluated art in the order they were in.
#[test]
fn a_containers_ruler_guides_keep_their_order_through_its_effects() {
use vectorcraft_doc::LayerColor;
let guide = |id| Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: false, pos: 3.0, artboard: None }));
for (effect, params) in [("pathfinder.add", serde_json::json!({})), ("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}))] {
let members = || vec![sq(1, 0.0, Color::BLACK), guide(20), sq(2, 5.0, Color::BLACK), guide(21)];
let fx = Effect { id: effect.into(), params: params.clone(), visible: true };
let mut l = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0));
if let Some(ch) = l.children_mut() {
*ch = members();
}
l.appearance.effects.push(fx.clone());
let mut g = Node::group(NodeId(11), members());
g.appearance.effects.push(fx);
for (what, n) in [("layer", l), ("group", g)] {
let art = evaluate_container(None, &n).unwrap();
let mut all = vec![];
ruler_guides_in(&art, &mut all);
let ids = all.iter().map(|(id, ..)| *id).collect::<Vec<_>>();
assert_eq!(ids, [NodeId(20), NodeId(21)], "{effect} on a {what}: the guides, in order");
let ch = art.children().unwrap();
let tail = ch[ch.len() - 2..].iter().map(|c| c.id).collect::<Vec<_>>();
assert_eq!(tail, [NodeId(20), NodeId(21)], "{effect} on a {what}: last, in order");
}
}
}
/// A group's own Fill + Offset Path below its contents follows the outline of a clip group among
/// its members, its clipping path, not the clipped art it hides outside that path (#7289).
#[test]
+4 -1
View File
@@ -81,7 +81,10 @@ pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_par
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, without_geometry};
pub use raster::{
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_map, staged_effects,
without_geometry,
};
pub use reshape::{
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry,
has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outer_effects, outline_art,
+16
View File
@@ -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
View File
@@ -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>();
+2 -2
View File
@@ -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),
+1 -1
View File
@@ -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.
+103 -10
View File
@@ -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;
}
}
@@ -606,18 +606,104 @@ fn transform_step(e: &Effect) -> Option<Affine> {
(copies == 0 && !flag(&p, "random", false)).then(|| map.with_translation(Vec2::ZERO))
}
/// The Transform effects of `effects` that move the image of its last visible Rasterize effect
/// instead of the art it is made from: the indices of the visible Transform effects listed after
/// it that move the art, when from the first visible Transform effect after it on every visible
/// effect is a Transform effect that moves the art once (no copies, not at random). Effects apply
/// in the order they are listed, so the image is made of the art before those Transform effects
/// and moves with them, its pixel grid and room around the art included. `None` when there is no
/// such Transform effect, or the effects after the Rasterize effect hold anything else from there
/// on.
pub fn rasterize_stage(effects: &[Effect]) -> Option<Vec<usize>> {
let r = effects.iter().rposition(|e| e.visible && e.id == RASTERIZE)?;
let first = r + 1 + effects.get(r + 1..)?.iter().position(|e| e.visible && e.id == "distort.transform")?;
let mut at = vec![];
for (i, e) in effects.iter().enumerate().skip(first).filter(|(_, e)| e.visible) {
if e.id != "distort.transform" || transform_step(e).is_none() {
return None;
}
if crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).0 != Affine::IDENTITY {
at.push(i);
}
}
(!at.is_empty()).then_some(at)
}
/// `effects` with the Transform effects at `at` hidden ([`rasterize_stage`]): what the image of
/// the Rasterize effect before them is made from.
pub fn staged_effects(effects: &[Effect], at: &[usize]) -> Vec<Effect> {
let mut out = effects.to_vec();
for &i in at {
if let Some(e) = out.get_mut(i) {
e.visible = false;
}
}
out
}
/// The map the Transform effects at `at` of `effects` ([`rasterize_stage`]) move the Rasterize
/// image by, for `staged`, the geometry the effects before them make: each one's map about its
/// reference point on the bounds of the geometry it takes, as the geometry pass applies it, the
/// last one outermost. `None` when `staged` is empty or the map is not a number.
pub fn stage_map(effects: &[Effect], at: &[usize], staged: &vectorcraft_geom::PathData) -> Option<Affine> {
let mut cur = staged.clone();
let mut b = staged.bounds()?;
let mut map = Affine::IDENTITY;
for &i in at {
let e = effects.get(i)?;
let (m, _) = crate::distort::transform_map(b, &merged_params(&e.id, &e.params), 0);
map = m * map;
cur = cur.transformed(m);
b = cur.bounds().unwrap_or(b);
}
map.is_finite().then_some(map)
}
/// Does raster effect `id` follow the Transform effects listed after it ([`followed`])? An SVG
/// filter does not, and neither does Rasterize, whose image keeps its own pixel grid and room
/// around the art.
/// around the art: the image moves with those Transform effects instead ([`rasterize_stage`]).
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;
}
@@ -625,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);
}
}
+49 -4
View File
@@ -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();
+56 -7
View File
@@ -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)]
+48 -1
View File
@@ -23,7 +23,7 @@ const RANGES: [(&str, f64, f64, bool); 13] = [
("blendSteps", 1.0, 256.0, true),
];
const FLAGS: [&str; 2] = ["cap", "lightBehind"];
const FLAGS: [&str; 3] = ["cap", "lightBehind", "preserveSpotColors"];
/// The surface Revolve (Classic)'s parameters `p` sweep: Revolve's angle, cap, offset, edge,
/// rotation and perspective, built unshaded, since the classic surfaces light its faces.
@@ -118,6 +118,52 @@ mod tests {
}
}
/// With Preserve Spot Colors, a fill linked to a spot swatch stays linked on every face: the
/// highlight lowers its tint, and the shadow is black multiplied and overprinting over it.
#[test]
fn preserve_spot_colors_keeps_the_swatch_on_every_face() {
let ink = Color::cmyk(0.0, 1.0, 0.0, 0.2);
let spot = |params: Value| {
let mut n = profile();
*n.appearance = Appearance::basic(Paint::Solid { color: ink, swatch: Some("Ink".into()), tint: 0.5 }, Paint::None, 0.0);
n.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &params).unwrap());
crate::revolve_art(&n).unwrap()
};
let art = spot(json!({"preserveSpotColors": true}));
let mut darkened = 0;
for face in faces(&art) {
let mut fills = face.appearance.items.iter().filter_map(|i| match i {
AppearanceItem::Fill(f) => Some(f),
AppearanceItem::Stroke(_) => None,
});
match fills.next().map(|f| &f.paint) {
Some(Paint::Solid { color, swatch: Some(name), tint }) => {
assert_eq!(name, "Ink");
assert!(*tint > 0.0 && *tint <= 0.5, "{tint}");
assert_eq!(*color, ink.tinted(*tint / 0.5), "the color is the swatch at the face's tint");
}
other => panic!("the face keeps its swatch: {other:?}"),
}
if let Some(shadow) = fills.next() {
assert!(matches!(shadow.paint.color(), Some(Color::Gray { .. })), "{:?}", shadow.paint);
assert_eq!((shadow.blend, shadow.overprint), (vectorcraft_doc::color::BlendMode::Multiply, true));
darkened += 1;
}
}
assert!(darkened > 0, "faces turned from the light are darkened");
// Off, and with a custom shading color, the faces are process mixes again.
for params in [json!({}), json!({"preserveSpotColors": true, "shadingColor": "custom", "shadingCustom": "#336699"})] {
let art = spot(params.clone());
let linked = faces(&art)
.iter()
.filter(|f| {
f.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if matches!(f.paint, Paint::Solid { swatch: Some(_), .. })))
})
.count();
assert!(linked < faces(&art).len(), "{params}: shaded faces lose the swatch");
}
}
#[test]
fn angle_offset_edge_and_cap_shape_the_surface() {
let full = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})).visual_bounds().unwrap();
@@ -207,6 +253,7 @@ mod tests {
(json!({"rotationY": -181}), "`rotationY` must be between -180 and 180"),
(json!({"blendSteps": 2.5}), "`blendSteps` must be a whole number"),
(json!({"lightBehind": 1}), "`lightBehind` must be true or false"),
(json!({"preserveSpotColors": "on"}), "`preserveSpotColors` must be true or false"),
(json!({"surface": "glossy"}), "`surface` must be one of"),
(json!({"shadingColor": "white"}), "`shadingColor` must be one of"),
(json!({"shadingCustom": "red"}), "`shadingCustom` must be a #rrggbb color"),
+88 -66
View File
@@ -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),
+41 -5
View File
@@ -102,7 +102,7 @@ const RANGES: [(&str, f64, f64, bool); 13] = [
("blendSteps", 1.0, 256.0, true),
];
const FLAGS: [&str; 4] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces"];
const FLAGS: [&str; 5] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces", "preserveSpotColors"];
/// Check Extrude & Bevel (Classic)'s parameters `p` (its defaults filled in): every key is one of
/// its parameters, numbers are in range, flags are true or false, and `surface`, `shadingColor` and
@@ -127,7 +127,7 @@ const ROTATE_RANGES: [(&str, f64, f64, bool); 9] = [
/// Check Rotate (Classic)'s parameters `p` (its defaults filled in) as [`validate`] checks Extrude &
/// Bevel (Classic)'s, with `surface` No Shading or Diffuse only.
pub fn validate_rotate(p: &Value) -> Result<(), String> {
validate_classic(CLASSIC_ROTATE, p, &ROTATE_RANGES, &["lightBehind"])?;
validate_classic(CLASSIC_ROTATE, p, &ROTATE_RANGES, &["lightBehind", "preserveSpotColors"])?;
if p.get("surface").is_some_and(|v| !v.as_str().is_some_and(|s| ROTATE_SURFACES.contains(&s))) {
return Err(format!("`surface` must be one of {}", ROTATE_SURFACES.join(", ")));
}
@@ -192,6 +192,35 @@ fn shaded(c: Color, tone: f64, spec: f64, shade: Option<Color>) -> Color {
Color::rgb(r, g, b)
}
/// Whether Preserve Spot Colors applies with parameters `p`: `preserveSpotColors` is on and the
/// shading color is not Custom, which cannot keep a spot color.
fn preserves_spot_colors(p: &Value) -> bool {
flag(p, "preserveSpotColors", false) && text(p, "shadingColor", "black") != "custom"
}
/// A face of `paint`, a color linked to a swatch, with Preserve Spot Colors: the swatch at a lower
/// tint for the highlight `spec`, its link kept so a spot color stays on its own plate, and, where
/// tone `tone` is below full light and the faces darken (`shade`), black over it at `1 - tone`,
/// multiplied and overprinting, so it prints on the black plate. `seam` is the width of the seam
/// stroke each layer draws around the face.
fn linked_face(paint: &Paint, tone: f64, spec: f64, shade: Option<Color>, seam: f64) -> Vec<AppearanceItem> {
let Paint::Solid { color, swatch, tint } = paint else { return vec![] };
let keep = (1.0 - spec).clamp(0.0, 1.0) as f32;
let fill = Paint::Solid { color: color.tinted(keep), swatch: swatch.clone(), tint: tint * keep };
let mut items = vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))];
if shade.is_some() && tone < 1.0 {
let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32));
let mut layer = FillLayer::new(black.clone());
layer.blend = BlendMode::Multiply;
layer.overprint = true;
let mut edge = crate::lighting::seam_stroke(black, seam);
edge.blend = BlendMode::Multiply;
edge.overprint = true;
items.extend([AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)]);
}
items
}
/// The width of the stroke [`surface`] draws around `face` with parameters `p`: a wire edge on
/// Wireframe, else the seam between faces.
pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 {
@@ -200,14 +229,17 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 {
/// One solid's faces in paint `paint`, as a group with the paint's opacity and blend mode, one child
/// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by
/// its tone and highlight. A gradient with transparent stops is shaded opaque and then masked by
/// its own transparency, so the shading follows the gradient's coverage.
/// 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; 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()
@@ -229,6 +261,10 @@ pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32
AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam)),
]
}
// Preserve Spot Colors: a color linked to a swatch stays a tint of that swatch.
Some(_) if preserve && matches!(paint, Paint::Solid { swatch: Some(_), .. }) && !paint.is_registration() => {
linked_face(paint, tone, spec, shade, seam)
}
Some(c) => {
let fill = Paint::solid(shaded(c, tone, spec, shade));
vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))]
+13
View File
@@ -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.
+117 -2
View File
@@ -1,5 +1,5 @@
use serde_json::json;
use vectorcraft_doc::{Document, NodeId, StrokeLayer};
use vectorcraft_doc::{Document, FillLayer, NodeId, StrokeLayer};
use vectorcraft_geom::{Affine, BezPath, Point, Shape};
use super::*;
@@ -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
@@ -2015,6 +2072,62 @@ fn a_member_in_a_transparent_gradient_keeps_the_shared_face_order() {
}
}
/// The fills of each face of `art`: the first is the face's paint, a second the shadow over it.
fn face_fills(art: &Node) -> Vec<Vec<FillLayer>> {
faces(art)
.iter()
.map(|f| {
f.appearance
.items
.iter()
.filter_map(|i| match i {
AppearanceItem::Fill(f) => Some(f.clone()),
AppearanceItem::Stroke(_) => None,
})
.collect()
})
.collect()
}
#[test]
fn classic_preserve_spot_colors_keeps_a_linked_fill_on_every_face() {
let ink = Color::cmyk(0.0, 1.0, 0.0, 0.2);
let art = |params: Value| {
let mut n = classic(params);
n.appearance.items = vec![AppearanceItem::Fill(FillLayer::new(Paint::Solid { color: ink, swatch: Some("Ink".into()), tint: 1.0 }))];
solid_art(&n).unwrap()
};
let lit = json!({"preserveSpotColors": true, "highlightIntensity": 100, "highlightSize": 100, "lightHeight": 60});
let (mut highlighted, mut shaded) = (false, false);
for layers in face_fills(&art(lit)) {
let Paint::Solid { color, swatch: Some(name), tint } = &layers[0].paint else { panic!("the swatch is kept: {layers:?}") };
assert_eq!(name, "Ink");
assert_eq!(*color, ink.tinted(*tint), "the color is the swatch at the face's tint");
highlighted |= *tint < 1.0;
if let Some(shadow) = layers.get(1) {
let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) };
assert!(k > 0.0 && k <= 1.0, "{k}");
assert_eq!((shadow.blend, shadow.overprint, shadow.opacity), (BlendMode::Multiply, true, 1.0));
shaded = true;
}
assert!(layers.len() <= 2, "{layers:?}");
}
assert!(highlighted && shaded, "the highlight lowers the tint and the shadow adds black");
// No shading color: the highlight only, as tints of the swatch.
for layers in face_fills(&art(json!({"preserveSpotColors": true, "shadingColor": "none"}))) {
assert!(matches!(&layers[..], [f] if matches!(&f.paint, Paint::Solid { swatch: Some(_), .. })), "{layers:?}");
}
// Off, or with a custom shading color, shaded faces are process mixes, as before.
for params in [json!({}), json!({"preserveSpotColors": true, "shadingColor": "custom", "shadingCustom": "#3366cc"})] {
let unlinked = face_fills(&art(params.clone())).iter().filter(|l| matches!(l[0].paint, Paint::Solid { swatch: None, .. })).count();
assert!(unlinked > 0, "{params}");
}
// An unlinked fill is shaded as it is with the option off.
let off: Vec<[f32; 3]> = classic_faces(json!({})).iter().map(fill_rgb).collect();
let on: Vec<[f32; 3]> = classic_faces(json!({"preserveSpotColors": true})).iter().map(fill_rgb).collect();
assert_eq!(off, on);
}
#[test]
fn classic_parameters_are_checked() {
let n = classic(json!({}));
@@ -2034,6 +2147,7 @@ fn classic_parameters_are_checked() {
(json!({"highlightSize": "big"}), "`highlightSize` must be a number"),
(json!({"cap": "yes"}), "`cap` must be true or false"),
(json!({"drawHiddenFaces": 1}), "`drawHiddenFaces` must be true or false"),
(json!({"preserveSpotColors": "yes"}), "`preserveSpotColors` must be true or false"),
(json!({"bevel": "fancy"}), "bevel must be none or one of"),
(json!({"twist": 10}), "unknown parameter `twist`"),
(json!({"lights": []}), "lights must contain one to ten lights"),
@@ -2110,6 +2224,7 @@ fn classic_rotate_parameters_are_checked() {
(json!({"lightIntensity": 101}), "`lightIntensity` must be between 0 and 100 (got 101)"),
(json!({"blendSteps": 0}), "`blendSteps` must be a whole number between 1 and 256 (got 0)"),
(json!({"lightBehind": 1}), "`lightBehind` must be true or false"),
(json!({"preserveSpotColors": null}), "`preserveSpotColors` must be true or false"),
(json!({"highlightSize": 50}), "unknown parameter `highlightSize`"),
(json!({"drawHiddenFaces": true}), "unknown parameter `drawHiddenFaces`"),
(json!({"shadow": true}), "unknown parameter `shadow`"),
+122
View File
@@ -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, &params) {
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, &params), 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}");
}
}
}
}
+218 -34
View File
@@ -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;
+150 -1
View File
@@ -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 }));
+1
View File
@@ -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 }
+285 -2
View File
@@ -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 }
@@ -117,13 +118,71 @@ fn a_hidden_shadow_follows_the_transform_it_loses() {
assert!(close(drawn_shadow(&[shown]), (20.0, 20.0, 8.0)));
}
/// Rasterize keeps its room around the art: its image keeps its own pixel grid.
/// Rasterize keeps its room around the art: its image keeps its own pixel grid, and the Transform
/// effect moves the image instead ([`crate::rasterize_stage`]).
#[test]
fn rasterize_before_a_transform_keeps_its_options() {
let rasterize = fx(crate::RASTERIZE, json!({"addAround": 6}));
let effects = [rasterize.clone(), transform(json!({"scaleH": 200, "scaleV": 200}))];
assert_eq!(crate::raster::followed(&effects)[0], rasterize);
assert_eq!(crate::raster::without_geometry(&effects), vec![rasterize]);
assert_eq!(crate::rasterize_stage(&effects), Some(vec![1]));
}
/// The Transform effects after the last Rasterize effect move its image when, from the first of
/// them on, every visible effect is a Transform effect that moves the art once. Hidden ones, and
/// ones with Transform Objects off, leave the image where it is.
#[test]
fn rasterize_following_ignores_hidden_and_objects_off() {
let rasterize = || fx(crate::RASTERIZE, json!({}));
let scale = || transform(json!({"scaleH": 200, "scaleV": 200}));
let mut hidden = scale();
hidden.visible = false;
let off = transform(json!({"scaleH": 200, "objects": false}));
let roughen = fx("distort.roughen", json!({}));
let shadow = shadow(5.0, 5.0, 2.0);
let cases: Vec<(Vec<Effect>, Option<Vec<usize>>)> = vec![
(vec![rasterize(), hidden.clone()], None),
(vec![rasterize(), off.clone()], None),
(vec![rasterize(), hidden, off, scale()], Some(vec![3])),
(vec![rasterize(), transform(json!({"moveH": 10})), scale()], Some(vec![1, 2])),
// Effects before the first Transform effect go into the image; anything after it holds
// the image back.
(vec![rasterize(), roughen.clone(), shadow.clone(), scale()], Some(vec![3])),
(vec![rasterize(), scale(), roughen], None),
(vec![rasterize(), scale(), shadow], None),
(vec![rasterize(), transform(json!({"scaleH": 200, "copies": 2}))], None),
(vec![rasterize(), transform(json!({"scaleH": 200, "random": true}))], None),
// The Transform effect before the Rasterize effect moves the art.
(vec![scale(), rasterize()], None),
(vec![scale(), rasterize(), rasterize(), scale()], Some(vec![3])),
];
for (effects, want) in cases {
let ids: Vec<&str> = effects.iter().map(|e| e.id.as_str()).collect();
assert_eq!(crate::rasterize_stage(&effects), want, "{ids:?}");
}
// What the image is made from hides those Transform effects; the rest stay as they are.
let effects = [rasterize(), scale()];
let staged = crate::staged_effects(&effects, &[1]);
assert_eq!((staged[0].visible, staged[1].visible), (true, false));
}
/// The map that moves the image is each Transform effect's map about its reference point on the
/// bounds of the geometry it takes, in order.
#[test]
fn the_image_moves_by_each_transform_about_the_art_it_takes() {
let staged = shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0));
let effects = [fx(crate::RASTERIZE, json!({})), transform(json!({"scaleH": 200, "scaleV": 200})), transform(json!({"moveH": 5}))];
let map = crate::stage_map(&effects, &[1, 2], &staged).unwrap();
// Twice the size about the center (20, 20), then 5 pt to the right.
let want = Affine::translate((5.0, 0.0)) * Affine::translate((20.0, 20.0)) * Affine::scale(2.0) * Affine::translate((-20.0, -20.0));
assert!(map.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "{map:?}");
// The second Transform effect turns about the center of what the first one made.
let effects = [fx(crate::RASTERIZE, json!({})), transform(json!({"moveH": 100})), transform(json!({"rotate": 90}))];
let map = crate::stage_map(&effects, &[1, 2], &staged).unwrap();
let c = map * Point::new(20.0, 20.0);
assert!((c.x - 120.0).abs() < 1e-9 && (c.y - 20.0).abs() < 1e-9, "{c:?}");
assert_eq!(crate::stage_map(&effects, &[1, 2], &PathData::default()), None);
}
/// An SVG filter keeps its options: it paints in its own user space.
@@ -378,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]
+123
View File
@@ -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:?}");
}
+1 -1
View File
@@ -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 }
+2
View File
@@ -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;
+77 -17
View File
@@ -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 })
+3
View File
@@ -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());
+114 -41
View File
@@ -9,7 +9,7 @@ mod tests;
mod text;
use serde_json::{Map, Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_doc::{Document, LockedArtboards, Node, NodeId, NodeKind};
use vectorcraft_geom::{PathData, SubPath};
use vectorcraft_pathops::addons as po;
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Simplify Anchors (Keep Shape)…",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step; open ends stay, and locked and hidden paths are left out → {ids, before, after} anchor counts",
"{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step when a path changes; open ends stay; from the selection, locked and hidden paths are left out, and named by `ids`, the paths of the objects, groups and layers it names are taken even when locked or hidden, but not those on a locked artboard; a changed path loses its selected anchors and segments → {ids, before, after} anchor counts",
has_selection,
simplify
),
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Deep Ungroup…",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step; each object keeps the opacity of the groups it was in; locked and hidden groups stay whole, and locked and hidden objects stay locked or hidden and are not selected → {ids (the objects selected: those left, or with no group to take apart the selection as it was), ungrouped (groups)}",
"{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step when a group goes; each object keeps the opacity of the groups it was in; from the selection, locked and hidden groups stay whole; named by `ids`, the groups it names and the groups in the groups and layers it names are ungrouped even when locked or hidden (a named layer stays), but not those on a locked artboard, and their objects become hidden or locked when a group was; locked and hidden objects stay locked or hidden and are not selected → {ids (the objects selected: those left, or with no group to take apart the selection as it was), ungrouped (groups)}",
has_selection,
deep_ungroup
),
@@ -82,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Rejoin Path Pieces…",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{gap?: pt 0..6 (0.1), ids?: [id…] (default: the selection)} weld the open paths under the objects whose ends lie within the gap of each other back into paths: an end joins one other end, the one the path turns least to go on into, pieces may run either way, and a chain whose ends meet closes; each path takes the place and paint of its topmost piece, as one undo step → {ids, joined (paths made), removed (pieces merged into them)}",
"{gap?: pt 0..6 (0.1), ids?: [id…] (default: the selection)} weld the open paths under the objects whose ends lie within the gap of each other back into paths: an end joins one other end, the one the path turns least to go on into, pieces may run either way, and a chain whose ends meet closes; each path takes the place and paint of its topmost piece, as one undo step when a path is made; from the selection, locked and hidden paths are left out, and named by `ids`, they are taken, but not those on a locked artboard; only pieces alike in being hidden (by themselves or a group or layer above them) and in being locked join; locked and hidden paths made are not selected → {ids, joined (paths made), removed (pieces merged into them)}",
has_selection,
rejoin
),
@@ -91,9 +91,28 @@ pub fn specs() -> Vec<CommandSpec> {
v
}
/// The paths (not guides) under `roots`, compound path members included; locked and hidden
/// paths, and those in locked or hidden groups, stay out.
fn paths_under(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
/// Whether a request names its objects with `ids` (present and not null) rather than taking the
/// selection.
fn named(p: &Value) -> bool {
p.get("ids").is_some_and(|v| !v.is_null())
}
/// Keep the items of `items` whose object (`id`) a command acts on: when `named`, every one not on
/// a locked artboard, locked and hidden ones (and ones in a locked or hidden group or layer)
/// included; else only those that can be edited.
fn retain_targets<T>(d: &Document, items: &mut Vec<T>, named: bool, id: impl Fn(&T) -> NodeId) {
if named {
let locks = d.locked_artboards();
items.retain(|t| !locks.holds_id(id(t)));
} else {
let editable = d.editable();
items.retain(|t| editable(id(t)));
}
}
/// The paths (not guides) under `roots`, compound path members included, that a command acts on
/// ([`retain_targets`]).
fn paths_under(d: &Document, roots: &[NodeId], named: bool) -> Vec<NodeId> {
let mut out = vec![];
for n in roots.iter().filter_map(|id| d.node(*id)) {
n.walk(&mut |c| {
@@ -102,8 +121,7 @@ fn paths_under(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
}
});
}
let editable = d.editable();
out.retain(|id| editable(*id));
retain_targets(d, &mut out, named, |id| *id);
out
}
@@ -116,7 +134,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
let protect = switch_or(p, "protectCorners", false, C)?;
let roots = checked_ids_or_selection(s, p, C)?;
let d = &s.doc()?.doc;
let ids = paths_under(d, &roots);
let ids = paths_under(d, &roots, named(p));
let paths: Vec<(NodeId, &PathData)> = ids.iter().filter_map(|id| Some((*id, d.node(*id)?.path_data()?))).collect();
let before: usize = paths.iter().map(|(_, p)| p.anchor_count()).sum();
if before > MAX_ANCHORS {
@@ -258,10 +276,11 @@ fn ungroupable(n: &Node, clips: bool) -> bool {
}
/// `n` with every level of grouping Deep Ungroup takes apart removed, into `out`; `count` counts
/// the groups. Members take on the opacity of the groups they were in, and a clipping path
/// becomes a plain path. A locked or hidden group stays whole.
fn flatten(n: Node, clips: bool, out: &mut Vec<Node>, count: &mut usize) {
if !ungroupable(&n, clips) || n.locked || !n.visible {
/// the groups. Members take on the opacity of the groups they were in, are hidden when one of them
/// was hidden and locked when one of them was locked, and a clipping path becomes a plain path. A
/// locked or hidden group stays whole unless `named`.
fn flatten(n: Node, clips: bool, named: bool, out: &mut Vec<Node>, count: &mut usize) {
if !ungroupable(&n, clips) || (!named && (n.locked || !n.visible)) {
out.push(n);
return;
}
@@ -276,26 +295,57 @@ fn flatten(n: Node, clips: bool, out: &mut Vec<Node>, count: &mut usize) {
*clipping = false;
}
c.opacity *= n.opacity;
flatten(c, clips, out, count);
c.visible &= n.visible;
c.locked |= n.locked;
flatten(c, clips, named, out, count);
}
}
/// The outermost groups Deep Ungroup takes apart in layer `n`, its sublayers included, in paint
/// order, leaving out those on a locked artboard.
fn groups_in_layer(d: &Document, n: &Node, clips: bool, out: &mut Vec<NodeId>) {
let locks = d.locked_artboards();
fn visit(n: &Node, clips: bool, locks: &LockedArtboards, out: &mut Vec<NodeId>) {
for c in n.children().into_iter().flatten() {
if c.is_layer() {
visit(c, clips, locks, out);
} else if ungroupable(c, clips) && !locks.holds_id(c.id) {
out.push(c.id);
}
}
}
visit(n, clips, &locks, out);
}
fn deep_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.cleanup.deepUngroup";
let clips = switch_or(p, "includeClipGroups", false, C)?;
let roots = checked_ids_or_selection(s, p, C)?;
let named = named(p);
let mut roots = checked_ids_or_selection(s, p, C)?;
let d = &s.doc()?.doc;
// Locked and hidden objects, and those in locked or hidden groups, stay as they are.
let roots: Vec<NodeId> = {
let editable = d.editable();
roots.into_iter().filter(|id| editable(*id)).collect()
};
// From the selection, locked and hidden objects, and those in locked or hidden groups, stay as
// they are; named, only those on a locked artboard do.
retain_targets(d, &mut roots, named, |id| *id);
// A named layer stays: the groups in it, and in its sublayers, are taken apart.
let mut groups = vec![];
for id in roots {
match d.node(id) {
Some(n) if named && n.is_layer() => {
let at = groups.len();
groups_in_layer(d, n, clips, &mut groups);
if groups.len() == at {
groups.push(id);
}
}
_ => groups.push(id),
}
}
let (mut items, mut selected, mut count) = (vec![], vec![], 0);
for id in &roots {
for id in &groups {
match d.node(*id).filter(|n| ungroupable(n, clips)) {
Some(n) => {
let mut out = vec![];
flatten(n.clone(), clips, &mut out, &mut count);
flatten(n.clone(), clips, named, &mut out, &mut count);
selected.extend(out.iter().map(|n| n.id));
items.push((*id, out));
}
@@ -304,7 +354,7 @@ fn deep_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
}
// With no group to take apart, the document, the selection and the undo history stay as they
// are, and the reply lists the selection.
if items.is_empty() {
if count == 0 {
selected = s.doc()?.selection.objects.to_vec();
} else {
selected = s.edit("Deep Ungroup", move |d, sel| {
@@ -319,26 +369,39 @@ fn deep_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "ids": selected.iter().map(|i| i.0).collect::<Vec<_>>(), "ungrouped": count }))
}
/// One path Rejoin Path Pieces takes: its id, its subpath, and whether it and every group and layer
/// above it are visible, and whether they are all unlocked.
type Piece = (NodeId, SubPath, (bool, bool));
/// The open single-subpath paths under `roots` that Rejoin Path Pieces takes, in paint order
/// (compound path members, clipping paths and guides stay out).
fn pieces(d: &Document, roots: &[NodeId]) -> Vec<(NodeId, SubPath)> {
fn visit(n: &Node, out: &mut Vec<(NodeId, SubPath)>) {
/// (compound path members, clipping paths and guides stay out; [`retain_targets`]).
fn pieces(d: &Document, roots: &[NodeId], named: bool) -> Vec<Piece> {
fn visit(n: &Node, above: (bool, bool), out: &mut Vec<Piece>) {
let state = (above.0 && n.visible, above.1 && !n.locked);
match &n.kind {
NodeKind::Path { path, guide: false, clipping: false, .. } => {
if let [sp] = path.subpaths.as_slice()
&& !sp.closed
{
out.push((n.id, sp.clone()));
out.push((n.id, sp.clone(), state));
}
}
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| visit(c, out)),
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| visit(c, state, out)),
_ => {}
}
}
let mut out = vec![];
roots.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, &mut out));
let editable = d.editable();
out.retain(|(id, _)| editable(*id));
for (id, n) in roots.iter().filter_map(|id| Some((*id, d.node(*id)?))) {
// The groups and layers above the root, and their state.
let above = d.ancestry(id).unwrap_or_default();
let above = above.split_last().map_or(&[][..], |(_, up)| up);
if above.last().and_then(|i| d.node(*i)).is_some_and(|parent| matches!(parent.kind, NodeKind::Compound { .. })) {
continue;
}
let state = above.iter().filter_map(|i| d.node(*i)).fold((true, true), |(v, u), a| (v && a.visible, u && !a.locked));
visit(n, state, &mut out);
}
retain_targets(d, &mut out, named, |piece| piece.0);
out
}
@@ -349,18 +412,26 @@ fn rejoin(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "`gap` must be from 0 to 6 pt"));
}
let roots = checked_ids_or_selection(s, p, C)?;
let found = pieces(&s.doc()?.doc, &roots);
let found = pieces(&s.doc()?.doc, &roots, named(p));
if found.len() > MAX_OBJECTS {
return Err(EngineError::Other("Rejoin Path Pieces: too many paths to rejoin at once".into()));
}
let subpaths: Vec<SubPath> = found.iter().map(|(_, sp)| sp.clone()).collect();
// Each chain becomes its topmost piece (the last in paint order); the others go.
// Only pieces alike in being shown and in being unlocked join, so that a joined path neither
// shows hidden art nor hides shown art, nor locks or unlocks a piece.
let (mut kept, mut gone) = (vec![], vec![]);
for j in po::rejoin(&subpaths, gap) {
let ids: Vec<NodeId> = j.members.iter().filter_map(|&m| found.get(m).map(|f| f.0)).collect();
let Some(&top) = j.members.iter().max().and_then(|&m| found.get(m).map(|f| &f.0)) else { continue };
gone.extend(ids.into_iter().filter(|id| *id != top));
kept.push((top, j.path));
for state in [(true, true), (true, false), (false, true), (false, false)] {
let part: Vec<&Piece> = found.iter().filter(|f| f.2 == state).collect();
if part.is_empty() {
continue;
}
let subpaths: Vec<SubPath> = part.iter().map(|f| f.1.clone()).collect();
// Each chain becomes its topmost piece (the last in paint order); the others go.
for j in po::rejoin(&subpaths, gap) {
let ids: Vec<NodeId> = j.members.iter().filter_map(|&m| part.get(m).map(|f| f.0)).collect();
let Some(top) = j.members.iter().max().and_then(|&m| part.get(m).map(|f| f.0)) else { continue };
gone.extend(ids.into_iter().filter(|id| *id != top));
kept.push((top, j.path));
}
}
if !kept.is_empty() {
let ids: Vec<NodeId> = kept.iter().map(|k| k.0).collect();
@@ -369,7 +440,9 @@ fn rejoin(s: &mut Session, p: &Value) -> Result<Value> {
set_path(d, *id, PathData::single(sp.clone()));
}
d.remove_many(&gone)?;
sel.set(ids);
// Locked and hidden paths, and those in locked or hidden groups, are not selected.
let editable = d.editable();
sel.set(ids.into_iter().filter(|id| editable(*id)));
Ok(())
})?;
}
+268 -12
View File
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind};
use vectorcraft_doc::{Appearance, LayerColor, Node, NodeId, NodeKind};
use vectorcraft_geom::{FillRule, Rect};
use crate::Session;
@@ -123,18 +123,100 @@ fn simplify_leaves_locked_and_hidden_paths_alone() {
assert_eq!(r["before"], 16);
assert!(anchors(&s, ids[0]) < 16);
assert_eq!((anchors(&s, ids[1]), anchors(&s, ids[2])), (16, 16));
// Named by `ids`, or in a locked group, a path stays too, with no undo step.
let steps = undo_steps(&s);
s.execute("addon.cleanup.simplify", &json!({"ids": [ids[1].0, ids[2].0]})).unwrap();
assert_eq!((anchors(&s, ids[1]), anchors(&s, ids[2])), (16, 16));
assert_eq!(undo_steps(&s), steps);
// In a selected locked group, a path stays too, with no undo step.
change(&mut s, ids[1], |n| n.locked = false);
change(&mut s, g, |n| n.locked = true);
let steps = undo_steps(&s);
let r = s.execute("addon.cleanup.simplify", &json!({"ids": [g.0]})).unwrap();
let r = s.execute("addon.cleanup.simplify", &json!({})).unwrap();
assert_eq!((r["before"].as_u64(), r["after"].as_u64()), (Some(0), Some(0)));
assert_eq!(anchors(&s, ids[1]), 16);
assert_eq!(undo_steps(&s), steps);
// Named by `ids`, the locked group's paths, its hidden one included, are simplified.
let r = s.execute("addon.cleanup.simplify", &json!({"ids": [g.0]})).unwrap();
assert_eq!(r["ids"], json!([ids[0].0, ids[1].0, ids[2].0]));
assert!(anchors(&s, ids[1]) < 16 && anchors(&s, ids[2]) < 16);
assert_eq!(undo_steps(&s), steps + 1);
}
/// A path of 16 anchors at (`x`, `y`): an ellipse with anchors added twice.
fn ellipse16(s: &mut Session, x: f64, y: f64) -> NodeId {
let e = id_of(&s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": 50, "height": 50})).unwrap());
select(s, &[e]);
s.execute("object.path.addAnchorPoints", &json!({})).unwrap();
s.execute("object.path.addAnchorPoints", &json!({})).unwrap();
e
}
/// Simplify Anchors takes the locked and hidden paths `ids` names, those in the locked or hidden
/// groups and layers it names (their locked and hidden members too) and a hidden compound path's
/// member, as one undo step, without selecting them; from the selection it leaves them alone, and a
/// path on a locked artboard stays even when named.
#[test]
fn simplify_named_locked_and_hidden_paths() {
let mut s = session();
let locked = ellipse16(&mut s, 10.0, 10.0);
let hidden = ellipse16(&mut s, 70.0, 10.0);
change(&mut s, locked, |n| n.locked = true);
change(&mut s, hidden, |n| n.visible = false);
// A locked group with a hidden member, and a hidden group with a locked member.
let in_locked = ellipse16(&mut s, 130.0, 10.0);
let locked_group = wrap(&mut s, in_locked, |c| NodeKind::Group { children: c, clip: false });
change(&mut s, locked_group, |n| n.locked = true);
change(&mut s, in_locked, |n| n.visible = false);
let in_hidden = ellipse16(&mut s, 190.0, 10.0);
let hidden_group = wrap(&mut s, in_hidden, |c| NodeKind::Group { children: c, clip: false });
change(&mut s, hidden_group, |n| n.visible = false);
change(&mut s, in_hidden, |n| n.locked = true);
// A member of a hidden compound path.
let member = ellipse16(&mut s, 250.0, 10.0);
let compound = wrap(&mut s, member, |c| NodeKind::Compound { children: c, rule: FillRule::NonZero });
change(&mut s, compound, |n| n.visible = false);
// A path in a locked layer, named itself.
let layer = id_of(&s.execute("layer.new", &json!({})).unwrap());
let in_layer = ellipse16(&mut s, 10.0, 100.0);
let on_board = ellipse16(&mut s, 10.0, 200.0);
change(&mut s, layer, |n| n.locked = true);
let all = [locked, hidden, in_locked, in_hidden, member, in_layer];
select(&mut s, &[locked, hidden, locked_group, hidden_group, compound]);
let steps = undo_steps(&s);
let r = s.execute("addon.cleanup.simplify", &json!({})).unwrap();
assert_eq!(r["ids"], json!([]), "from the selection, none is taken");
assert_eq!(undo_steps(&s), steps);
assert!(all.iter().all(|id| anchors(&s, *id) == 16));
select(&mut s, &[]);
s.edit("Select Anchors", |_, sel| {
sel.anchors.insert(locked, [(0, 1)].into());
Ok(())
})
.unwrap();
let steps = undo_steps(&s);
let r = s.execute("addon.cleanup.simplify", &json!({"ids": [locked.0, hidden.0, locked_group.0, hidden_group.0, member.0, in_layer.0]})).unwrap();
assert_eq!(r["ids"], json!(all.iter().map(|i| i.0).collect::<Vec<_>>()));
assert_eq!(r["before"], 16 * 6);
assert_eq!(r["after"].as_u64(), Some(all.iter().map(|id| anchors(&s, *id) as u64).sum::<u64>()));
assert!(all.iter().all(|id| anchors(&s, *id) < 16), "{r}");
assert_eq!(undo_steps(&s), steps + 1);
let sel = &s.doc().unwrap().selection;
assert!(sel.objects.is_empty() && sel.anchors.is_empty(), "nothing is selected, and the changed path's anchors are not");
let n = node(&s, in_hidden).unwrap();
assert!(n.locked && n.visible && !node(&s, hidden_group).unwrap().visible);
s.execute("edit.undo", &json!({})).unwrap();
assert!(all.iter().all(|id| anchors(&s, *id) == 16));
s.execute("edit.redo", &json!({})).unwrap();
assert!(all.iter().all(|id| anchors(&s, *id) < 16));
// Nothing left to remove: no undo step.
let steps = undo_steps(&s);
s.execute("addon.cleanup.simplify", &json!({"ids": [locked.0]})).unwrap();
assert_eq!(undo_steps(&s), steps);
// On a locked artboard, a named path stays as it is.
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let steps = undo_steps(&s);
let r = s.execute("addon.cleanup.simplify", &json!({"ids": [on_board.0]})).unwrap();
assert_eq!((r["ids"].clone(), anchors(&s, on_board), undo_steps(&s)), (json!([]), 16, steps));
}
/// Each kind: what makes the issue in a fresh document (beside a clean rectangle).
@@ -610,14 +692,15 @@ fn deep_ungroup_keeps_hidden_art_hidden_and_locked_art_locked() {
assert!(!d.node(hidden).unwrap().visible && d.node(b).unwrap().visible);
assert!(d.node(locked).unwrap().locked && d.node(e).unwrap().locked);
assert_eq!(s.doc().unwrap().selection.objects, [a]);
// Named by `ids`, a locked group stays as it is, with no undo step.
// Named by `ids`, a locked group is taken apart as one undo step; its member becomes locked
// and is not selected.
let steps = undo_steps(&s);
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [locked.0]})).unwrap();
assert_eq!(r["ungrouped"], 0);
assert!(node(&s, locked).is_some());
assert_eq!(undo_steps(&s), steps);
assert_eq!(r["ungrouped"], 1);
assert!(node(&s, locked).is_none() && node(&s, c).unwrap().locked);
assert_eq!(undo_steps(&s), steps + 1);
assert_eq!(r["ids"], json!([]));
// With nothing ungrouped, the selection stays and the reply lists it.
assert_eq!(r["ids"], json!([a.0]));
let f = rect(&mut s, 130.0, 10.0, 20.0, 20.0);
select(&mut s, &[a]);
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [f.0]})).unwrap();
@@ -625,6 +708,108 @@ fn deep_ungroup_keeps_hidden_art_hidden_and_locked_art_locked() {
assert_eq!(s.doc().unwrap().selection.objects, [a]);
}
/// Put `ids` inside a new container that `kind` makes of its members.
fn wrap_all(s: &mut Session, ids: &[NodeId], kind: fn(Vec<std::sync::Arc<Node>>) -> NodeKind) -> NodeId {
s.edit("t", |d, _| {
let w = d.alloc_id();
Ok(d.wrap(ids, |c| Node::new(w, kind(c)))?)
})
.unwrap()
}
fn plain_group(c: Vec<std::sync::Arc<Node>>) -> NodeKind {
NodeKind::Group { children: c, clip: false }
}
fn sublayer(c: Vec<std::sync::Arc<Node>>) -> NodeKind {
NodeKind::Layer { color: LayerColor::Preset(0), template: false, printable: true, children: c, clip: false, preview: true, dim_images: None }
}
/// Named by `ids`, Deep Ungroup takes apart locked and hidden groups, those nested in a group it
/// names and those in a layer it names (its sublayers included, the layer staying), as one undo
/// step; their members become locked or hidden as the groups were, keep the groups' opacity and are
/// not selected. From the selection those groups stay whole, as do a clipping group and a group on a
/// locked artboard even when named.
#[test]
fn deep_ungroup_named_locked_and_hidden_groups() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0);
let locked = wrap_all(&mut s, &[a], plain_group);
let hidden = wrap_all(&mut s, &[b], plain_group);
change(&mut s, locked, |n| n.locked = true);
change(&mut s, hidden, |n| {
n.visible = false;
n.opacity = 0.5;
});
select(&mut s, &[locked, hidden]);
let steps = undo_steps(&s);
let r = s.execute("addon.cleanup.deepUngroup", &json!({})).unwrap();
assert_eq!((r["ungrouped"].clone(), undo_steps(&s)), (json!(0), steps), "from the selection, they stay whole");
assert!(node(&s, locked).is_some() && node(&s, hidden).is_some());
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [locked.0, hidden.0]})).unwrap();
assert_eq!((r["ungrouped"].clone(), r["ids"].clone()), (json!(2), json!([])));
assert_eq!(undo_steps(&s), steps + 1);
assert!(node(&s, locked).is_none() && node(&s, hidden).is_none());
let (na, nb) = (node(&s, a).unwrap(), node(&s, b).unwrap());
assert!(na.locked && na.visible && !nb.visible && !nb.locked);
assert_eq!(nb.opacity, 0.5);
assert!(s.doc().unwrap().selection.objects.is_empty());
s.execute("edit.undo", &json!({})).unwrap();
assert!(node(&s, locked).is_some() && !node(&s, a).unwrap().locked && node(&s, b).unwrap().visible);
s.execute("edit.redo", &json!({})).unwrap();
assert!(node(&s, locked).is_none() && node(&s, a).unwrap().locked);
// Locked and hidden groups nested in a named group that can be edited.
let c = rect(&mut s, 70.0, 10.0, 20.0, 20.0);
let e = rect(&mut s, 100.0, 10.0, 20.0, 20.0);
let f = rect(&mut s, 130.0, 10.0, 20.0, 20.0);
let inner_locked = wrap_all(&mut s, &[e], plain_group);
let inner_hidden = wrap_all(&mut s, &[f], plain_group);
change(&mut s, inner_locked, |n| n.locked = true);
change(&mut s, inner_hidden, |n| n.visible = false);
let outer = wrap_all(&mut s, &[c, inner_locked, inner_hidden], plain_group);
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [outer.0]})).unwrap();
assert_eq!((r["ungrouped"].clone(), r["ids"].clone()), (json!(3), json!([c.0])));
assert!(node(&s, e).unwrap().locked && !node(&s, f).unwrap().visible);
assert_eq!(s.doc().unwrap().selection.objects, [c]);
// In a named layer and its sublayer; the layers and a clipping group stay.
let layer = id_of(&s.execute("layer.new", &json!({})).unwrap());
let g = rect(&mut s, 10.0, 100.0, 20.0, 20.0);
let h = rect(&mut s, 40.0, 100.0, 20.0, 20.0);
let layer_locked = wrap_all(&mut s, &[g], plain_group);
change(&mut s, layer_locked, |n| n.locked = true);
let layer_hidden = wrap_all(&mut s, &[h], plain_group);
change(&mut s, layer_hidden, |n| n.visible = false);
let sub = wrap_all(&mut s, &[layer_hidden], sublayer);
let clipped = rect(&mut s, 100.0, 100.0, 10.0, 10.0);
let clip = rect(&mut s, 95.0, 95.0, 30.0, 30.0);
select(&mut s, &[clipped, clip]);
s.execute("object.clippingMask.make", &json!({})).unwrap();
let clip_group = s.doc().unwrap().selection.objects[0];
let steps = undo_steps(&s);
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [layer.0]})).unwrap();
assert_eq!((r["ungrouped"].clone(), undo_steps(&s)), (json!(2), steps + 1));
assert!(node(&s, layer_locked).is_none() && node(&s, layer_hidden).is_none());
assert!(node(&s, layer).is_some() && node(&s, clip_group).is_some());
assert!(node(&s, g).unwrap().locked && !node(&s, h).unwrap().visible);
assert_eq!(s.doc().unwrap().doc.parent_of(h), Some(sub));
// On a locked artboard, a named group stays whole, with the selection as it was.
let k = rect(&mut s, 10.0, 200.0, 20.0, 20.0);
let on_board = wrap_all(&mut s, &[k], plain_group);
let off_board = rect(&mut s, 500.0, 10.0, 20.0, 20.0);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
select(&mut s, &[off_board]);
let steps = undo_steps(&s);
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [on_board.0]})).unwrap();
assert_eq!((r["ungrouped"].clone(), r["ids"].clone(), undo_steps(&s)), (json!(0), json!([off_board.0]), steps));
assert!(node(&s, on_board).is_some());
assert_eq!(s.doc().unwrap().selection.objects, [off_board]);
}
#[test]
fn rejoin_joins_pieces_within_the_gap_only() {
let mut s = session();
@@ -646,3 +831,74 @@ fn rejoin_joins_pieces_within_the_gap_only() {
assert!(s.execute("addon.cleanup.rejoin", &bad).is_err(), "{bad}");
}
}
/// Named by `ids`, Rejoin Path Pieces takes locked and hidden pieces (in a locked group or layer
/// too) and joins only pieces alike in being hidden and in being locked, whichever is topmost, as one
/// undo step; a locked or hidden path it makes is not selected. From the selection it takes only
/// pieces that can be edited, and compound path members and pieces on a locked artboard stay out.
#[test]
fn rejoin_named_locked_and_hidden_pieces() {
let mut s = session();
let a = line(&mut s, &[(10.0, 10.0), (50.0, 10.0)]);
let b = line(&mut s, &[(50.05, 10.0), (90.0, 10.0)]);
let g = wrap_all(&mut s, &[a, b], plain_group);
change(&mut s, g, |n| n.locked = true);
select(&mut s, &[g]);
let steps = undo_steps(&s);
let r = s.execute("addon.cleanup.rejoin", &json!({})).unwrap();
assert_eq!((r["joined"].clone(), undo_steps(&s)), (json!(0), steps), "from the selection, none is taken");
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [g.0]})).unwrap();
assert_eq!((r["joined"].clone(), r["removed"].clone(), r["ids"].clone()), (json!(1), json!(1), json!([b.0])));
assert_eq!(undo_steps(&s), steps + 1);
assert!(node(&s, a).is_none() && anchors(&s, b) == 3);
assert!(s.doc().unwrap().selection.objects.is_empty(), "the locked path is not selected");
s.execute("edit.undo", &json!({})).unwrap();
assert!(node(&s, a).is_some() && anchors(&s, b) == 2);
s.execute("edit.redo", &json!({})).unwrap();
assert!(node(&s, a).is_none() && anchors(&s, b) == 3);
// A shown piece and two hidden ones, the hidden on top: only the hidden pair joins.
let c = line(&mut s, &[(10.0, 40.0), (50.0, 40.0)]);
let e = line(&mut s, &[(50.05, 40.0), (90.0, 40.0)]);
let h = line(&mut s, &[(90.05, 40.0), (130.0, 40.0)]);
change(&mut s, e, |n| n.visible = false);
change(&mut s, h, |n| n.visible = false);
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [c.0, e.0, h.0]})).unwrap();
assert_eq!((r["joined"].clone(), r["removed"].clone(), r["ids"].clone()), (json!(1), json!(1), json!([h.0])));
assert!(node(&s, e).is_none() && anchors(&s, c) == 2 && anchors(&s, h) == 3);
assert!(!node(&s, h).unwrap().visible && node(&s, c).unwrap().visible);
assert!(s.doc().unwrap().selection.objects.is_empty(), "the hidden path is not selected");
// An unlocked piece under a locked one, and a hidden piece under a shown one: none joins.
let k = line(&mut s, &[(10.0, 70.0), (50.0, 70.0)]);
let m = line(&mut s, &[(50.05, 70.0), (90.0, 70.0)]);
let n = line(&mut s, &[(10.0, 100.0), (50.0, 100.0)]);
let o = line(&mut s, &[(50.05, 100.0), (90.0, 100.0)]);
change(&mut s, m, |x| x.locked = true);
change(&mut s, n, |x| x.visible = false);
let steps = undo_steps(&s);
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [k.0, m.0, n.0, o.0]})).unwrap();
assert_eq!((r["joined"].clone(), r["removed"].clone(), undo_steps(&s)), (json!(0), json!(0), steps));
assert!([k, m, n, o].iter().all(|id| anchors(&s, *id) == 2));
// Named pieces in a locked layer join; members of a compound path stay out.
let layer = id_of(&s.execute("layer.new", &json!({})).unwrap());
let p = line(&mut s, &[(10.0, 130.0), (50.0, 130.0)]);
let q = line(&mut s, &[(50.05, 130.0), (90.0, 130.0)]);
let u = line(&mut s, &[(10.0, 160.0), (50.0, 160.0)]);
let v = line(&mut s, &[(50.05, 160.0), (90.0, 160.0)]);
wrap_all(&mut s, &[u, v], |c| NodeKind::Compound { children: c, rule: FillRule::NonZero });
let w = line(&mut s, &[(10.0, 200.0), (50.0, 200.0)]);
let x = line(&mut s, &[(50.05, 200.0), (90.0, 200.0)]);
change(&mut s, layer, |l| l.locked = true);
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [p.0, q.0, u.0, v.0]})).unwrap();
assert_eq!((r["joined"].clone(), r["ids"].clone()), (json!(1), json!([q.0])));
assert!(node(&s, p).is_none() && anchors(&s, u) == 2 && anchors(&s, v) == 2);
// On a locked artboard, named pieces stay as they are.
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let steps = undo_steps(&s);
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [w.0, x.0]})).unwrap();
assert_eq!((r["joined"].clone(), undo_steps(&s)), (json!(0), steps));
assert!(node(&s, w).is_some() && node(&s, x).is_some());
}
+18
View File
@@ -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:?}");
+6 -6
View File
@@ -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
+19 -2
View File
@@ -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()
}
};
+6 -6
View File
@@ -19,8 +19,8 @@ use super::edit::{outermost, selected_roots};
use super::pathops::{remove_each, separate};
use super::swatch::{anchor, names_param};
use super::{
CommandSpec, Result, Session, bad, check_numbers, cmd, color_param, find_command, has_doc, has_selection, id_param, named_ids, number_or, ok,
str_param, switch_or,
CommandSpec, Result, Session, bad, check_numbers, cmd, color_param, find_command, has_doc, has_selection, named_ids, number_or, ok, str_param,
switch_or,
};
use crate::EngineError;
@@ -180,7 +180,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Paintbrush",
[],
None,
"{…params as path.freehand, brush?: name} paint a freehand stroke with a brush; without `brush` (or with null) the plain path is drawn; a `brush` that names no brush in the document, or a `style` other than \"pencil\" or \"brush\", is an error and nothing is drawn → {id}",
"{…params as path.freehand, brush?: name} paint a freehand stroke with a brush; without `brush` (or with null) the plain path is drawn; a `brush` that names no brush in the document, a `style` other than \"pencil\" or \"brush\", a `brush` for a path with no stroke (a continued or redrawn path without one, or a new filled \"pencil\" path while the stroke is None) and an unknown key are errors and nothing is drawn; the path and its brush are one undo step → {id}",
has_doc,
brush_freehand
),
@@ -190,7 +190,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Symbols",
[],
None,
"{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic}], current}",
"{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic, alignToPixelGrid: bool}], current}",
has_doc,
symbol_list
),
@@ -199,7 +199,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Symbol…",
[],
None,
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions → {name, id, registration, exportType, nineSlice, type}",
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}",
has_selection,
symbol_new
),
@@ -208,7 +208,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Symbol Options…",
[],
None,
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}",
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}",
has_doc,
symbol_options
),
+7 -14
View File
@@ -1,7 +1,6 @@
use super::{
AppearanceItem, Arc, BTreeSet, Bristle, Brush, BrushKind, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, Result, Session, Value,
anchor, bad, brush, check_numbers, find_command, id_param, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown,
str_param,
anchor, bad, brush, check_numbers, find_command, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown, str_param,
};
// ---------- brushes ----------
@@ -729,9 +728,10 @@ pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "ids": ids_json(&out) }))
}
/// Paints a `path.freehand` stroke with the brush `brush` names. A `brush` left out or null draws
/// the plain path; a `brush` that is not a string or names no brush in the document, and a `style`
/// other than "pencil" or "brush", is an error before anything is drawn.
/// Paints a `path.freehand` stroke with the brush `brush` names, in one undo step with the path.
/// A `brush` left out or null draws the plain path; a `brush` that is not a string or names no
/// brush in the document, a `style` other than "pencil" or "brush", and a `brush` for a path with
/// no stroke are errors before anything is drawn.
pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "brush.freehand";
let name = match crate::cmd::text_param(p, "brush", C)? {
@@ -745,13 +745,6 @@ pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
Some(v) => return Err(bad(C, format!("`style` must be \"pencil\" or \"brush\", not {v}"))),
}
let spec = find_command("path.freehand").ok_or_else(|| EngineError::UnknownCommand("path.freehand".into()))?;
let r = crate::cmd::run_checked(s, spec, p)?;
let (Some(name), Some(id)) = (name, id_param(&r, "id")) else { return Ok(r) };
s.edit("Paintbrush", |d, _| {
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
st.brush = Some(name.clone());
}
Ok(())
})?;
Ok(r)
let checked = crate::schemas::check(spec, p, s.replaying())?;
crate::cmd::draw2::freehand_brushed(s, checked.as_ref().unwrap_or(p), name.as_deref())
}
+42 -9
View File
@@ -69,6 +69,15 @@ fn nine_slice_param(p: &Value, cmd: &str, current: Option<SymbolNineSlice>) -> R
})
}
/// `alignToPixelGrid` (Symbol Options › Align to Pixel Grid): `None` when it is not given; any
/// value other than true or false, null included, is an error.
fn pixel_grid_param(p: &Value, cmd: &str) -> Result<Option<bool>> {
match p.get("alignToPixelGrid") {
None => Ok(None),
Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(cmd, "alignToPixelGrid must be true or false")),
}
}
fn nine_slice_json(d: &Document, name: &str) -> Value {
d.symbol_nine_slice(name).map_or(Value::Null, SymbolNineSlice::to_value)
}
@@ -187,6 +196,7 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
"exportType": d.symbol_export_type(&sym.name).id(),
"nineSlice": nine_slice_json(d, &sym.name),
"type": type_id(sym.dynamic),
"alignToPixelGrid": d.symbol_pixel_aligned(&sym.name),
})
})
.collect();
@@ -239,6 +249,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
let export = export_type_param(p, C)?.unwrap_or_default();
let nine = nine_slice_param(p, C, None)?.flatten();
let dynamic = type_param(p, C)?.unwrap_or(false);
let pixel = pixel_grid_param(p, C)?.unwrap_or(false);
// Keep the art where it was: the geometric centre stays at `c`, whatever the registration is.
let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg);
let id = s.edit("New Symbol", |d, sel| {
@@ -249,6 +260,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
d.set_symbol_registration(&name, reg);
d.set_symbol_export_type(&name, export);
d.set_symbol_nine_slice(&name, nine);
d.set_symbol_pixel_aligned(&name, pixel);
let id = instance_in_place(d, &ids, &name, place)?;
sel.set([id]);
Ok(id)
@@ -260,6 +272,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
"exportType": export.id(),
"nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value),
"type": type_id(dynamic),
"alignToPixelGrid": pixel,
}))
}
@@ -270,9 +283,15 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
let reg = registration_param(p, C)?;
let nine = nine_slice_param(p, C, s.doc()?.doc.symbol_nine_slice(&name))?;
let dynamic = type_param(p, C)?;
let pixel = pixel_grid_param(p, C)?;
let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() {
return Err(bad(C, "pass newName, registration, exportType, nineSlice and/or type"));
match pixel {
None => return Err(bad(C, "pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid")),
// Align to Pixel Grid alone, already as asked: nothing changes and no undo step is added.
Some(on) if on == s.doc()?.doc.symbol_pixel_aligned(&name) => return Ok(options_json(&s.doc()?.doc, &name)),
Some(_) => {}
}
}
if let Some(ref n) = new_name
&& n != &name
@@ -324,6 +343,7 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
d.rename_symbol_registration(&name, n);
d.rename_symbol_export_type(&name, n);
d.rename_symbol_nine_slice(&name, n);
d.rename_symbol_pixel_aligned(&name, n);
if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) {
d.unknown.insert(CURRENT_SYMBOL.into(), json!(n));
}
@@ -352,16 +372,26 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
sym.dynamic = dynamic;
fit_overrides(d, &instances_of(d, Some(&final_name)));
}
// Turning it on snaps the art and the instances at actual size when the edit ends
// (`object::refresh_pixel_aligned`).
if let Some(on) = pixel {
d.set_symbol_pixel_aligned(&final_name, on);
}
Ok(())
})?;
let d = &s.doc()?.doc;
Ok(json!({
"name": final_name,
"registration": d.symbol_registration(&final_name).0,
"exportType": d.symbol_export_type(&final_name).id(),
"nineSlice": nine_slice_json(d, &final_name),
"type": type_id(d.symbols.iter().any(|x| x.name == final_name && x.dynamic)),
}))
Ok(options_json(&s.doc()?.doc, &final_name))
}
/// What `symbol.options` answers for symbol `name`.
fn options_json(d: &Document, name: &str) -> Value {
json!({
"name": name,
"registration": d.symbol_registration(name).0,
"exportType": d.symbol_export_type(name).id(),
"nineSlice": nine_slice_json(d, name),
"type": type_id(d.symbols.iter().any(|x| x.name == name && x.dynamic)),
"alignToPixelGrid": d.symbol_pixel_aligned(name),
})
}
fn resolve_symbol(d: &Document, p: &Value, cmd: &str) -> Result<String> {
@@ -702,6 +732,7 @@ pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result<Value> {
d.set_symbol_registration(name, SymbolRegistration::CENTER);
d.clear_symbol_export_type(name);
d.set_symbol_nine_slice(name, None);
d.set_symbol_pixel_aligned(name, false);
if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) {
d.unknown.remove(CURRENT_SYMBOL);
}
@@ -725,6 +756,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
let reg = d.symbol_registration(&name);
let export = d.symbol_export_type(&name);
let nine = d.symbol_nine_slice(&name);
let pixel = d.symbol_pixel_aligned(&name);
s.edit("Duplicate Symbol", |d, _| {
let art = d.reid(&sym.art);
d.symbols.push(Symbol { dynamic: sym.dynamic, name: new.clone(), art: Arc::new(art) });
@@ -732,6 +764,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
d.set_symbol_registration(&new, reg);
d.set_symbol_export_type(&new, export);
d.set_symbol_nine_slice(&new, nine);
d.set_symbol_pixel_aligned(&new, pixel);
Ok(())
})?;
Ok(json!({ "name": new, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) }))
+3 -3
View File
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Bucket",
[],
None,
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the face alone) | \"connected\" (a double-click: also each face reached across edges that are hidden or draw no stroke, as a flood from the face; a stroked edge, a hidden face or a Gap Detection gap stops it) | \"samePaint\" (a triple-click: also every face of the group whose fill is match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it, the `fill` of a face's appearance; scope samePaint only; default: the face's fill), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces; when every face it reaches already has the paint, nothing changes (no undo step, and the recent colors stay as they are) → {group, face, count (faces reached)}",
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the face alone) | \"connected\" (a double-click: also each face reached across edges that are hidden or draw no stroke, as a flood from the face; a stroked edge, a hidden face or a Gap Detection gap stops it) | \"samePaint\" (a triple-click: also every face of the group whose fill is match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it, the `fill` of a face's appearance; scope samePaint only; default: the face's fill), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces: each face reached has its fills replaced by one fill with the paint, shown, fully opaque and blending normally, in the place of its topmost fill (none leaves one fill of none), and its strokes and its own opacity stay as they are; when every face it reaches already has only that one fill, nothing changes (no undo step, and the recent colors stay as they are) → {group, face, count (faces reached)}",
has_doc,
lp_fill
),
@@ -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 takes the paint and width in its topmost stroke that is shown, or in a new stroke above the others when it has none; when every edge it reaches already has the paint and the width there, 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 of the group's edges, each given once, counted as drawing with stroke paint match whatever they draw with, such as another edge a double-click's clicks painted; any other id is an error), 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\", 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\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; 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)
),
+96 -40
View File
@@ -525,16 +525,17 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
Some(gid) => {
let (fid, targets) = targets_in(&s.doc()?.doc, gid)?;
let count = targets.len();
// Faces that already have the paint stay as they are: when every face has it, nothing
// changes and no undo step is recorded.
// Faces that already have only the fill the bucket would leave ([`bucket_keeps`]) stay as
// they are: when every face does, nothing changes and no undo step is recorded.
let d = &s.doc()?.doc;
let unpainted: Vec<NodeId> = targets.into_iter().filter(|t| d.node(*t).is_none_or(|f| f.appearance.fill_paint() != paint)).collect();
let unpainted: Vec<NodeId> =
targets.into_iter().filter(|t| d.node(*t).is_none_or(|f| !bucket_keeps(&f.appearance, true, &paint, 0.0))).collect();
if unpainted.is_empty() {
return Ok(json!({ "group": gid.0, "face": fid.0, "count": count }));
}
s.edit("Live Paint Bucket", |d, _| {
for target in unpainted {
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
bucket_paint(&mut d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance, true, &paint, 0.0);
}
Ok((gid, fid, count))
})?
@@ -544,7 +545,7 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
let (fid, targets) = targets_in(d, gid)?;
let count = targets.len();
for target in targets {
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
bucket_paint(&mut d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance, true, &paint, 0.0);
}
Ok((gid, fid, count))
})?,
@@ -566,32 +567,40 @@ 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")))?;
// Each id in `through` is an edge of the group, given once.
let group_edges: std::collections::HashSet<NodeId> = b::edges(n).iter().map(|e| e.id).collect();
let mut seen = std::collections::HashSet::new();
if let Some(id) = through.iter().find(|id| !group_edges.contains(id) || !seen.insert(**id)) {
return Err(bad(C, format!("through: {id} is not an edge of {g}, or is given twice")));
}
let start = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
let eid = start.id;
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(),
};
let count = targets.len();
// An edge whose shown stroke already has the paint and the width (or that has no shown stroke
// and gets none) stays as it is; when every edge does, nothing changes and no undo step is
// recorded.
let changed: Vec<NodeId> = targets
.into_iter()
.filter(|t| {
d.node(*t).is_none_or(|e| match shown_stroke(e) {
Some(st) => !(st.paint == paint && st.width == width),
None => !paint.is_none(),
})
})
.collect();
// An edge that already has only the stroke the bucket would leave ([`bucket_keeps`]) stays
// as it is; when every edge does, nothing changes and no undo step is recorded.
let changed: Vec<NodeId> =
targets.into_iter().filter(|t| d.node(*t).is_none_or(|e| !bucket_keeps(&e.appearance, false, &paint, width))).collect();
(eid, count, changed)
};
if changed.is_empty() {
@@ -599,14 +608,7 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
}
s.edit("Live Paint Bucket", |d, _| {
for target in &changed {
let e = d.node_mut(*target).ok_or(EngineError::NoNode(*target))?;
match shown_stroke_mut(e) {
Some(st) => {
st.paint = paint.clone();
st.width = width;
}
None => e.appearance.items.push(super::AppearanceItem::Stroke(super::StrokeLayer::new(paint.clone(), width))),
}
bucket_paint(&mut d.node_mut(*target).ok_or(EngineError::NoNode(*target))?.appearance, false, &paint, width);
}
Ok(())
})?;
@@ -614,22 +616,76 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "group": g.0, "edge": eid.0, "count": count }))
}
/// The stroke `livePaint.strokeEdge` paints on Live Paint edge `e`: its topmost stroke that is
/// shown. None when it has no stroke or every stroke is hidden; the command then adds a stroke
/// above the others.
fn shown_stroke(e: &Node) -> Option<&super::StrokeLayer> {
e.appearance.items.iter().rev().find_map(|i| match i {
super::AppearanceItem::Stroke(s) if s.visible => Some(s),
_ => None,
})
/// Whether the Live Paint Bucket leaves appearance `a` as it is when it paints its fills (`fill`)
/// or strokes with `paint` (a stroke at `width`): it has exactly one row of that kind, shown, fully
/// opaque, blending normally and with the paint (a stroke also with the width, unless the paint is
/// none), or it has no row of that kind and the paint is none.
fn bucket_keeps(a: &Appearance, fill: bool, paint: &super::Paint, width: f64) -> bool {
let mut rows = a.items.iter().filter(|i| i.is_fill() == fill);
match (rows.next(), rows.next()) {
(None, _) => paint.is_none(),
(Some(row), None) => {
row.visible()
&& row.opacity() == 1.0
&& row.blend() == vectorcraft_color::BlendMode::Normal
&& row.paint() == paint
&& match row {
AppearanceItem::Fill(_) => true,
AppearanceItem::Stroke(st) => paint.is_none() || st.width == width,
}
}
(Some(_), Some(_)) => false,
}
}
/// [`shown_stroke`], to change.
fn shown_stroke_mut(e: &mut Node) -> Option<&mut super::StrokeLayer> {
e.appearance.items.iter_mut().rev().find_map(|i| match i {
super::AppearanceItem::Stroke(s) if s.visible => Some(s),
_ => None,
})
/// Paint the fills (`fill`) or strokes of appearance `a` with `paint` (a stroke at `width`), as the
/// Live Paint Bucket does: every row of that kind is replaced by one row, shown, fully opaque and
/// blending normally, in the place of the topmost row of that kind. The new row keeps the other
/// settings (a stroke's dashes, caps and arrowheads, a row's effects) of the topmost row of that
/// kind that is shown, or of the topmost one when every row is hidden. Rows of the other kind stay
/// as they are. With no row of that kind, a fill is added below the strokes and a stroke above the
/// fills.
fn bucket_paint(a: &mut Appearance, fill: bool, paint: &super::Paint, width: f64) {
let of_kind = |i: &AppearanceItem| i.is_fill() == fill;
let Some(top) = a.items.iter().rposition(of_kind) else {
if fill {
a.set_fill(paint.clone());
} else {
a.items.push(AppearanceItem::Stroke(super::StrokeLayer::new(paint.clone(), width)));
}
return;
};
let base = a.items.iter().rposition(|i| of_kind(i) && i.visible()).unwrap_or(top);
let Some(mut row) = a.items.get(base).cloned() else { return };
match &mut row {
AppearanceItem::Fill(f) => {
f.paint = paint.clone();
f.opacity = 1.0;
f.blend = vectorcraft_color::BlendMode::Normal;
f.visible = true;
}
AppearanceItem::Stroke(st) => {
st.paint = paint.clone();
st.width = width;
st.opacity = 1.0;
st.blend = vectorcraft_color::BlendMode::Normal;
st.visible = true;
}
}
let mut row = Some(row);
a.items = std::mem::take(&mut a.items)
.into_iter()
.enumerate()
.filter_map(|(i, item)| {
if i == top {
row.take()
} else if of_kind(&item) {
None
} else {
Some(item)
}
})
.collect();
}
/// Every fill and stroke row of face or edge `n`, bottom first, as `livePaint.info` lists them. A
+127 -18
View File
@@ -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 ----------
@@ -22,6 +23,22 @@ fn is_trace_group(n: &Node) -> bool {
&& n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_))))
}
/// The name of the group that holds an Abutting trace's seam fills (see [`tr::TraceResult::seams`]).
const SEAM_FILLS_NAME: &str = "Seam Fills";
/// Whether `n` can be a trace's seam fills group: a group named as one, or a group of stroked paths
/// without fills, so that it is still found after it is renamed or its strokes are edited. (Auto
/// Grouping groups hold filled paths.)
fn is_seam_fills(n: &Node) -> bool {
let stroke_only = |m: &Arc<Node>| {
matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
&& m.appearance.fill_paint() == Paint::None
&& m.appearance.stroke_paint() != Paint::None
};
matches!(n.kind, NodeKind::Group { clip: false, .. })
&& (n.name.as_deref() == Some(SEAM_FILLS_NAME) || n.children().is_some_and(|c| !c.is_empty() && c.iter().all(stroke_only)))
}
const LIVE_PATHFINDER_BY_COLOR: &str = "byColor can't regroup a trace with a live Pathfinder effect: expand without byColor";
/// The `view` param ([`TraceView`] id), if given.
@@ -393,11 +410,15 @@ fn by_color_param(cmd: &str, p: &Value) -> Result<bool> {
/// (by the boxes of everything they paint, effects included, within one point); otherwise it
/// starts another group of that paint, which keeps the stacking order of those items. Items
/// farther apart can still share antialiased pixels at small view or raster-export scales, so
/// their edge pixels may change. A group among `items` (Auto Grouping) is refused.
/// their edge pixels may change. The seam fills' group, when it is the lowest item, stays as it is,
/// under every other group. Any other group among `items` (Auto Grouping) is refused.
fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Vec<Arc<Node>>> {
use std::collections::{BTreeMap, HashMap};
use std::ops::Bound::{Excluded, Unbounded};
use vectorcraft_color::tint_percent;
// The seam fills come first, under every path: kept there, they move under nothing.
let mut items = items;
let seams: Vec<Arc<Node>> = if items.first().is_some_and(|n| is_seam_fills(n)) { items.drain(..1).collect() } else { vec![] };
// Grouped by the paint: unlinked (its #rrggbb), linked (the swatch and its exact tint), a
// gradient, or another paint (its label). The name is apart from it: a swatch may be named as
// a color's `#rrggbb` or as "Gradients".
@@ -517,25 +538,31 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve
}
}
}
Ok(groups
let groups: Vec<Arc<Node>> = groups
.into_iter()
.map(|run| {
let mut g = Node::group(d.alloc_id(), run.members);
g.name = Some(run.name);
Arc::new(g)
})
.collect())
.collect();
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.
@@ -604,21 +631,25 @@ 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(&params).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 })
}
/// What a trace made of an image: the size in pixels it was decoded at, and the paths.
/// What a trace made of an image: the size in pixels it was decoded at, the paths, and their seam
/// fills ([`seams_within`]).
pub struct Traced {
inputs: TraceInputs,
raster: (u32, u32),
res: tr::TraceResult,
seams: Vec<tr::TracedPath>,
}
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);
}
@@ -627,6 +658,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) {
@@ -636,7 +669,18 @@ fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64
tr::TraceError::Cancelled => EngineError::Cancelled,
e => EngineError::Other(e.to_string()),
})?;
Ok(Traced { inputs: inputs.clone(), raster: (raster.width, raster.height), res })
let seams = seams_within(&res, params, MAX_TRACE_ANCHORS);
Ok(Traced { inputs: inputs.clone(), raster: (raster.width, raster.height), res, seams })
}
/// The seam fills of `res`, traced with `params` ([`tr::seam_fills`]), while the paths and the seam
/// fills together stay within `max` anchors: the seam fills have at most as many anchors as the
/// paths, so a trace whose paths have more than half of `max` gets none.
fn seams_within(res: &tr::TraceResult, params: &tr::TraceParams, max: usize) -> Vec<tr::TracedPath> {
if res.anchor_count() > max / 2 {
return vec![];
}
tr::seam_fills(&res.paths, params)
}
/// An Image Trace made away from its command, off the UI thread (#3098). [`TraceRun::prepare`]
@@ -691,17 +735,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> {
@@ -716,7 +773,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
s.note_journal("savedPreset", recorded);
}
// A trace handed in for these very inputs ([`TraceRun`]), else one made now.
let Traced { raster, res, .. } = match s.trace_hand_off.take() {
let Traced { raster, res, seams: seam_fills, .. } = match s.trace_hand_off.take() {
Some(traced) if traced.inputs == inputs => traced,
_ => trace_now(&inputs, &trace, &|_, _| true)?,
};
@@ -729,6 +786,13 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
let xf = img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy);
// Document units per raster pixel (stroke widths).
let unit = xf.determinant().abs().sqrt();
// Seam fills: document units per raster pixel along the direction the image is stretched most,
// so that a stroke covers its pixels across an edge at any angle.
let seam_unit = {
let [a, b, c, d, _, _] = xf.as_coeffs();
let (t, det) = (a * a + b * b + c * c + d * d, a * d - b * c);
((t + (t * t - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt()
};
let (npaths, anchors, colors) = (res.paths.len(), res.anchor_count(), res.palette.len());
let label = if expand { "Image Trace (Make and Expand)" } else { "Image Trace" };
// A library color fills with the swatch's displayed color (its model kept), unlinked.
@@ -754,8 +818,38 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
hidden.visible = false;
children.push(Arc::new(hidden));
}
let paint_of = |tp: &tr::TracedPath| {
let solid =
by_color.get(&tp.color).map_or_else(|| Paint::solid(Color::rgb8(tp.color[0], tp.color[1], tp.color[2])), |paint| (*paint).clone());
// Gradients: a path the tracer found to be a linear gradient is filled with it.
tp.gradient.as_ref().map_or(solid, |g| traced_gradient(g, xf))
};
// Abutting: the seam fills, in a group of their own under every path.
let seams: Vec<Arc<Node>> = seam_fills
.iter()
.filter_map(|tp| {
let width = tp.stroke?;
let mut n = shape_node(d, tp.path.transformed(xf), None);
n.appearance = Appearance {
items: vec![AppearanceItem::Stroke(StrokeLayer {
cap: LineCap::Butt,
join: LineJoin::Round,
..StrokeLayer::new(paint_of(tp), width * seam_unit)
})],
..Default::default()
}
.into();
Some(Arc::new(n))
})
.collect();
if !seams.is_empty() {
let mut g = Node::group(d.alloc_id(), seams);
g.name = Some(SEAM_FILLS_NAME.into());
children.push(Arc::new(g));
}
let mut traced = Vec::with_capacity(res.paths.len());
for tp in res.paths {
let paint = paint_of(&tp);
let path = tp.path.transformed(xf);
let mut n = shape_node(d, path, None);
// Shapes: a path the tracer found to be a shape is that live shape.
@@ -764,10 +858,6 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
*path = shape.to_path();
*live = Some(Box::new(shape));
}
let solid =
by_color.get(&tp.color).map_or_else(|| Paint::solid(Color::rgb8(tp.color[0], tp.color[1], tp.color[2])), |paint| (*paint).clone());
// Gradients: a path the tracer found to be a linear gradient is filled with it.
let paint = tp.gradient.as_ref().map_or(solid, |g| traced_gradient(g, xf));
n.appearance = match tp.stroke {
// Traced lines: round corners, and ends round or square as the tracer found them.
Some(width) => Appearance {
@@ -1103,9 +1193,28 @@ mod color_group_tests {
#[cfg(test)]
mod trace_limit_tests {
use super::{MAX_TRACE_ANCHORS, keep_warnings, trace_warnings};
use super::{MAX_TRACE_ANCHORS, keep_warnings, seams_within, trace_warnings};
use vectorcraft_trace as tr;
#[test]
fn seam_fills_count_against_the_anchor_limit() {
// Two colors side by side, the edge between them anti-aliased: one seam fill along it.
let img = tr::Raster::from_fn(24, 16, |x, _| {
let share = (10.4 - f64::from(x)).clamp(0.0, 1.0);
let mix = |a: f64, b: f64| (a * share + b * (1.0 - share)).round() as u8;
[mix(200.0, 30.0), mix(40.0, 90.0), mix(50.0, 200.0), 255]
});
let params = tr::TraceParams { mode: tr::Mode::Color, colors: 2, method: tr::Method::Abutting, ..tr::TraceParams::default() };
let res = tr::trace(&img, &params);
let all = tr::seam_fills(&res.paths, &params);
assert!(!all.is_empty(), "{res:?}");
let anchors = res.anchor_count();
// Twice the paths' anchors leaves room for any seam fills.
assert_eq!(seams_within(&res, &params, 2 * anchors), all);
// One anchor short of that: none.
assert_eq!(seams_within(&res, &params, 2 * anchors - 1), []);
}
#[test]
fn keep_warnings_name_matched_colors_that_produce_no_paths() {
let params = tr::TraceParams { keep_colors: vec!["#ff0000".into()], ..tr::TraceParams::default() };
+37 -2
View File
@@ -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));
}
@@ -762,6 +766,8 @@ pub struct SymbolOptions {
pub export_type: SymbolExportType,
/// 9-slice guides (`None`: 9-slice scaling off).
pub nine_slice: Option<SymbolNineSlice>,
/// Align to Pixel Grid.
pub pixel_aligned: bool,
}
impl SymbolOptions {
@@ -772,6 +778,7 @@ impl SymbolOptions {
registration: d.symbol_registration(name),
export_type: d.symbol_export_type(name),
nine_slice: d.symbol_nine_slice(name),
pixel_aligned: d.symbol_pixel_aligned(name),
}
}
@@ -781,6 +788,7 @@ impl SymbolOptions {
d.set_symbol_registration(name, self.registration);
d.set_symbol_export_type(name, self.export_type);
d.set_symbol_nine_slice(name, self.nine_slice);
d.set_symbol_pixel_aligned(name, self.pixel_aligned);
}
}
@@ -1031,10 +1039,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 +1120,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
+12 -1
View File
@@ -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) })
+129 -3
View File
@@ -16,7 +16,7 @@ use std::collections::BTreeMap;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::cms::{self, ColorSettings, Intent, Model, ProofTarget};
use vectorcraft_color::cms::{self, ColorSettings, Intent, Model, Policy, ProofTarget};
use vectorcraft_color::recolor::Neutral;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::ColorMode;
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Color Settings…",
["Edit"],
Some("Cmd+Shift+K"),
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool} set the working spaces → {rgb, cmyk, intent, bpc, profiles: [{name, kind, builtin}]}. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\"} set the working spaces and the color management policies → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, profiles: [{name, kind, builtin}]}. A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
always,
color_settings
),
@@ -163,12 +163,26 @@ fn on_param(p: &Value, key: &str, cmd: &str) -> Result<Option<bool>> {
switch_or(p, key, false, cmd).map(Some)
}
/// The policy `p` gives for `key`, one of `allowed`, or `None` when `p` leaves it out.
fn policy_param(p: &Value, key: &str, allowed: &[Policy], cmd: &str) -> Result<Option<Policy>> {
let Some(v) = text_param(p, key, cmd)? else { return Ok(None) };
match Policy::parse(v).filter(|x| allowed.contains(x)) {
Some(x) => Ok(Some(x)),
None => {
let ids: Vec<&str> = allowed.iter().map(Policy::id).collect();
Err(bad(cmd, format!("`{key}` must be one of {}", ids.join(", "))))
}
}
}
fn settings_json(st: &ColorSettings) -> Value {
json!({
"rgb": st.rgb,
"cmyk": st.cmyk,
"intent": st.intent.id(),
"bpc": st.bpc,
"rgbPolicy": st.rgb_policy.id(),
"cmykPolicy": st.cmyk_policy.id(),
"profiles": cms::profiles().iter().map(|p| json!({"name": p.name, "kind": p.kind, "builtin": p.builtin})).collect::<Vec<_>>(),
})
}
@@ -205,6 +219,12 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
st.intent = i;
}
st.bpc = switch_or(p, "bpc", st.bpc, C)?;
if let Some(v) = policy_param(p, "rgbPolicy", &Policy::RGB, C)? {
st.rgb_policy = v;
}
if let Some(v) = policy_param(p, "cmykPolicy", &Policy::CMYK, C)? {
st.cmyk_policy = v;
}
if st != before {
cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?;
// Saved for the next start when the app attached a settings file (#6335).
@@ -530,7 +550,12 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
if !convert {
return 0;
}
let conv = mode_converter(mode, intent, grays);
convert_colors(d, &mode_converter(mode, intent, grays))
}
/// Every color of `d` that [`set_color_mode`] converts, converted with `conv` → how many colors of
/// the art changed, as [`set_color_mode`] counts them.
fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Color) -> usize {
for sw in d.swatches_iter_mut() {
match &mut sw.paint {
Paint::Solid { color, .. } => *color = conv(color),
@@ -538,6 +563,11 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
for st in &mut g.gradient.stops {
st.color = conv(&st.color);
}
if let Some(freeform) = &mut g.freeform {
for point in &mut freeform.points {
point.color = conv(&point.color);
}
}
}
_ => {}
}
@@ -621,6 +651,102 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
in_art
}
/// Apply the color management policies of Edit → Color Settings to `d`, a document being opened:
/// each RGB or CMYK profile it is tagged with that is not the working space of its model is kept
/// (Preserve Embedded Profiles), taken off with the color numbers kept (Off, Preserve Numbers), or
/// taken off after the colors of that model were converted from it into the working space with the
/// working intent (Convert to Working Space). A profile that is not available here is taken off
/// by Off and Preserve Numbers and kept by Convert to Working Space, which has nothing to convert
/// from. → a note for each profile, and whether `d` changed.
pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec<String>, bool) {
let working = cms::working_settings();
let (rgb, cmyk) = doc_profiles(d);
let mut notes = Vec::new();
// What each model's policy does with its profile: `None` keeps it; `Some` takes it off, after
// converting the colors from the profile it holds.
let mut decide = |label: &str, tag: Option<String>, working: &str, policy: Policy, kind: cms::ProfileKind| -> Option<Option<String>> {
let tag = tag.filter(|t| t != working)?;
let available = cms::profile(&tag).is_some_and(|p| p.kind == kind);
match policy {
Policy::PreserveEmbedded => None,
Policy::Off | Policy::PreserveNumbers => {
notes.push(format!(
"the {label} profile “{tag}” the file is tagged with was not used: Color Settings' {label} policy is {}",
policy.label()
));
Some(None)
}
Policy::Convert if available => {
notes.push(format!(
"the {label} colors were converted from the profile “{tag}” the file is tagged with into the working space “{working}”"
));
Some(Some(tag))
}
Policy::Convert => {
notes.push(format!("the {label} profile “{tag}” the file is tagged with is not available, so its colors were not converted"));
None
}
}
};
let rgb_do = decide("RGB", rgb, &working.rgb, working.rgb_policy, cms::ProfileKind::Rgb);
let cmyk_do = decide("CMYK", cmyk, &working.cmyk, working.cmyk_policy, cms::ProfileKind::Cmyk);
if rgb_do.is_none() && cmyk_do.is_none() {
return (notes, false);
}
let (from_rgb, from_cmyk) = (rgb_do.clone().flatten(), cmyk_do.clone().flatten());
if from_rgb.is_some() || from_cmyk.is_some() {
let source = cms::for_document(from_rgb.as_deref(), from_cmyk.as_deref());
let dest = cms::working();
let intent = working.intent;
let (rgb_on, cmyk_on) = (from_rgb.is_some(), from_cmyk.is_some());
let conv = |c: &Color| match c {
Color::Rgb { .. } if rgb_on => source.convert_into(&dest, c, intent),
Color::Cmyk { .. } if cmyk_on => source.convert_into(&dest, c, intent),
_ => *c,
};
convert_colors(d, &conv);
convert_setting_colors(d, &conv);
}
if rgb_do.is_some() {
d.color_profiles.rgb = None;
}
if cmyk_do.is_some() {
d.color_profiles.cmyk = None;
}
(notes, true)
}
/// The colors of `d` outside its art that [`convert_colors`] leaves, converted with `conv`: each
/// artboard's background, the transparency grid and simulated paper colors of Document Setup, and
/// the fill and stroke of the character and paragraph styles.
fn convert_setting_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Color) {
for c in d.artboards.iter_mut().filter_map(|a| a.color.as_mut()) {
*c = conv(c);
}
for c in &mut d.setup.grid_colors {
*c = conv(c);
}
// A tint of a global swatch is the converted swatch's color at its tint, which
// [`convert_colors`] already gave it.
let bases = global_bases(d);
let mut f = |c: &Color, link: proof::Link| mode_color(c, link, &bases, conv);
for styles in [&mut d.char_styles, &mut d.para_styles] {
if !styles.iter().any(|s| s.attrs.contains_key("fill") || s.attrs.contains_key("stroke")) {
continue;
}
for def in styles.iter_mut() {
for key in ["fill", "stroke"] {
let Some(value) = def.attrs.get_mut(key) else { continue };
let Ok(mut paint) = serde_json::from_value::<Paint>(value.clone()) else { continue };
map_paint_colors(&mut paint, &mut f);
if let Ok(v) = serde_json::to_value(&paint) {
*value = v;
}
}
}
}
}
/// [`proof::map_node_colors`] over `n`'s subtree, then [`map_more_colors`].
fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
proof::map_node_colors(n, f);
+67 -15
View File
@@ -1,15 +1,18 @@
//! Type › Composite Fonts…: the document's composite fonts ([`vectorcraft_doc::CompositeFont`]),
//! which set each class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals) in a
//! font of its own. Type names a composite font as its family, and the font menus list them first.
//! The font database holds the active document's composite fonts ([`sync`]); a file exported here
//! carries them to another document.
//! font of its own, and the characters of each custom character set in the set's font. Type names
//! a composite font as its family, and the font menus list them first. The font database holds the
//! active document's composite fonts ([`sync`]); a file exported here carries them to another
//! document.
//!
//! Behavior reference (public documentation):
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>.
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>,
//! custom character sets:
//! <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348>.
use serde_json::{Map, Value, json};
use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX};
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts};
use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX};
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet};
use vectorcraft_text::FontDb;
use super::fileio::{read_file_head, write_file};
@@ -26,6 +29,10 @@ const MAX_FILE_BYTES: usize = 4 << 20;
/// The keys a part may give.
const PART_KEYS: [&str; 7] = ["font", "style", "size", "baseline", "hScale", "vScale", "scaleAtCenter"];
/// The keys a custom character set may give: its name and characters, then its part's values
/// (a set is never scaled at the center).
const SET_KEYS: [&str; 8] = ["name", "characters", "font", "style", "size", "baseline", "hScale", "vScale"];
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
@@ -33,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Composite Fonts",
[],
None,
"{} the active document's composite fonts → {fonts: [{name, parts: {kanji, kana, punctuation, symbols, roman, numerals: {font, style, size: % of the type size, baseline: % of the type size (positive raises), hScale: %, vScale: %, scaleAtCenter?: bool}}}]}",
"{} the active document's composite fonts → {fonts: [{name, parts: {kanji, kana, punctuation, symbols, roman, numerals: {font, style, size: % of the type size, baseline: % of the type size (positive raises), hScale: %, vScale: %, scaleAtCenter?: bool}}, custom?: [{name, characters, font, style, size, baseline, hScale, vScale}]}]}",
has_doc,
list
),
@@ -42,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Composite Fonts…",
["Type"],
None,
"{fonts: [{name, parts: {kanji: {font, style?: \"Regular\", size?: % 10..400 = 100, baseline?: % -100..100 = 0}, kana?, punctuation?, symbols?, roman?, numerals?: {font, style?, size?, baseline?, hScale?, vScale?: % 10..400 = 100, scaleAtCenter?: bool = false}}}]} replace the active document's composite fonts (Type › Composite Fonts…'s OK), as one undo step, none when nothing changes. A composite font sets each class of character in its part's font: kanji (the base: ideographs, full-width letters and digits and anything no other class takes), kana (hiragana and katakana, both widths), punctuation (East Asian and full-width punctuation, quotes and dashes), symbols (arrows, math, shapes and other symbols), roman (half-width letters, their punctuation and spaces) and numerals (the digits 0 to 9); a part left out is the kanji part. size and baseline are percent of the type's size, hScale and vScale scale kana, roman and numerals only, and scaleAtCenter (kana only) scales them from the em box's center instead of the baseline. Names are trimmed, unique in any case, at most 255 characters, and may not name an installed font; a part's font may not be a composite font; at most 256. Type set in a composite font names it as its family (text.setStyle {font: name}), and the font menus list composite fonts first. A font taken out stays named by its type, which then shows as missing → {fonts}",
"{fonts: [{name, parts: {kanji: {font, style?: \"Regular\", size?: % 10..400 = 100, baseline?: % -100..100 = 0}, kana?, punctuation?, symbols?, roman?, numerals?: {font, style?, size?, baseline?, hScale?, vScale?: % 10..400 = 100, scaleAtCenter?: bool = false}}, custom?: [{name, characters?: string = \"\", font?, style?, size?, baseline?, hScale?, vScale?}]}]} replace the active document's composite fonts (Type › Composite Fonts…'s OK), as one undo step, none when nothing changes. A composite font sets each class of character in its part's font: kanji (the base: ideographs, full-width letters and digits and anything no other class takes), kana (hiragana and katakana, both widths), punctuation (East Asian and full-width punctuation, quotes and dashes), symbols (arrows, math, shapes and other symbols), roman (half-width letters, their punctuation and spaces) and numerals (the digits 0 to 9); a part left out is the kanji part. size and baseline are percent of the type's size, hScale and vScale scale kana, roman and numerals only, and scaleAtCenter (kana only) scales them from the em box's center instead of the baseline. custom lists custom character sets: each sets the characters it lists in its own font, style, size, baseline and scales (values left out are the kanji part's), ahead of their class; a character two sets list is set by the later one. A set's name is trimmed and unique in the font in any case; its characters are each listed once, at most 8192, none a control character or past U+FFFF; at most 64 sets. Names are trimmed, unique in any case, at most 255 characters, and may not name an installed font; a part's font may not be a composite font; at most 256. Type set in a composite font names it as its family (text.setStyle {font: name}), and the font menus list composite fonts first. A font taken out stays named by its type, which then shows as missing → {fonts}",
has_doc,
set
),
@@ -51,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Composite Fonts",
[],
None,
"{path?: .vccomposite file, names?: [name] (default: all), fonts?: [{name, parts}] (as type.compositeFonts.set takes them)} write the active document's composite fonts (all, or those named, any case), or the fonts given, to a file type.compositeFonts.import reads; without path the file's text comes back as data → {path, count} | {data, count}",
"{path?: .vccomposite file, names?: [name] (default: all), fonts?: [{name, parts}] (as type.compositeFonts.set takes them)} write the active document's composite fonts (all, or those named, any case), or the fonts given, to a file type.compositeFonts.import reads (a file over 4 MB is refused); without path the file's text comes back as data → {path, count} | {data, count}",
has_doc,
export
),
@@ -121,8 +128,8 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
/// copy of the Kanji part, and keys or values a part can't take refused.
fn parse_font(v: &Value, c: &str) -> Result<CompositeFont> {
let o = v.as_object().ok_or_else(|| bad(c, "each font must be {name, parts}"))?;
if let Some(k) = o.keys().find(|k| !["name", "parts"].contains(&k.as_str())) {
return Err(bad(c, format!("unknown key `{k}`; a font takes name and parts")));
if let Some(k) = o.keys().find(|k| !["name", "parts", "custom"].contains(&k.as_str())) {
return Err(bad(c, format!("unknown key `{k}`; a font takes name, parts and custom")));
}
let raw = o.get("name").and_then(Value::as_str).ok_or_else(|| bad(c, "each font needs a name"))?;
let name = CompositeFont::clean_name(raw)
@@ -140,7 +147,17 @@ fn parse_font(v: &Value, c: &str) -> Result<CompositeFont> {
serde_json::from_value(p.clone()).map(Some).map_err(|e| bad(c, format!("`{name}`: {}: {e}", class.key())))
};
let kanji = part(CharClass::Kanji)?.ok_or_else(|| bad(c, format!("`{name}`: give the kanji part")))?;
let mut f = CompositeFont { name: name.clone(), parts: CompositeParts::all(kanji) };
let custom = match o.get("custom") {
None => Vec::new(),
Some(Value::Array(sets)) => {
if sets.len() > CUSTOM_SETS_MAX {
return Err(bad(c, format!("`{name}`: a composite font keeps at most {CUSTOM_SETS_MAX} character sets")));
}
sets.iter().map(|s| parse_set(s, &name, &kanji, c)).collect::<Result<Vec<_>>>()?
}
Some(_) => return Err(bad(c, format!("`{name}`: custom must be a list of character sets"))),
};
let mut f = CompositeFont { name: name.clone(), parts: CompositeParts::all(kanji), custom };
for class in CharClass::ALL.into_iter().skip(1) {
if let Some(p) = part(class)? {
*f.parts.get_mut(class) = p;
@@ -150,6 +167,38 @@ fn parse_font(v: &Value, c: &str) -> Result<CompositeFont> {
Ok(f)
}
/// Custom character set `v` of composite font `font` from command parameters or a file: its name
/// trimmed, the part values it leaves out those of `kanji`, and keys or values it can't take
/// refused. [`CompositeFont::check`] checks its characters and values.
fn parse_set(v: &Value, font: &str, kanji: &CompositePart, c: &str) -> Result<CustomCharSet> {
let o = v.as_object().ok_or_else(|| bad(c, format!("`{font}`: each character set must be {{name, characters, font…}}")))?;
if let Some(k) = o.keys().find(|k| !SET_KEYS.contains(&k.as_str())) {
return Err(bad(c, format!("`{font}`: unknown key `{k}` in a character set")));
}
let raw = o.get("name").and_then(Value::as_str).ok_or_else(|| bad(c, format!("`{font}`: each character set needs a name")))?;
let name = CompositeFont::clean_name(raw)
.ok_or_else(|| bad(c, format!("`{raw}` can't name a character set (1 to {COMPOSITE_NAME_MAX} characters, no control characters)")))?;
let characters = match o.get("characters") {
None => String::new(),
Some(Value::String(s)) => s.clone(),
Some(_) => return Err(bad(c, format!("`{font}`: `{name}`: characters must be a string"))),
};
// Checked here as well as by `check`, so a huge list is refused before it is copied again.
if characters.chars().nth(CUSTOM_CHARS_MAX).is_some() {
return Err(bad(c, format!("`{font}`: `{name}`: a character set keeps at most {CUSTOM_CHARS_MAX} characters")));
}
let mut part = serde_json::to_value(kanji).map_err(|e| bad(c, e.to_string()))?;
if let Some(p) = part.as_object_mut() {
for k in &SET_KEYS[2..] {
if let Some(given) = o.get(*k) {
p.insert(k.to_string(), given.clone());
}
}
}
let part: CompositePart = serde_json::from_value(part).map_err(|e| bad(c, format!("`{font}`: `{name}`: {e}")))?;
Ok(CustomCharSet { name, characters, part })
}
/// Error unless `fonts` can stand together in a document: names unique in any case, none naming
/// an installed font, no part set in a composite font, and at most [`COMPOSITE_FONTS_MAX`].
fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> {
@@ -167,10 +216,10 @@ fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> {
}
}
for f in fonts {
for class in CharClass::ALL {
let font = &f.parts.get(class).font;
let classes = CharClass::ALL.into_iter().map(|class| (class.key(), &f.parts.get(class).font));
for (part, font) in classes.chain(f.custom.iter().map(|s| (s.name.as_str(), &s.part.font))) {
if names.contains(&font.to_lowercase()) || db.composite_font(font).is_some() {
return Err(bad(c, format!("`{}`: {} is set in `{font}`, a composite font", f.name, class.key())));
return Err(bad(c, format!("`{}`: {} is set in `{font}`, a composite font", f.name, part)));
}
}
}
@@ -260,6 +309,9 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
let mut file = Map::new();
file.insert("compositeFonts".into(), json!(fonts));
let text = serde_json::to_string_pretty(&file).map_err(|e| bad(C, e.to_string()))?;
if text.len() > MAX_FILE_BYTES {
return Err(bad(C, "the composite fonts make a file larger than 4 MB, which Import can't read; export fewer of them"));
}
match path {
Some(path) => {
write_file(path, text.as_bytes())?;
@@ -856,3 +856,127 @@ fn composite_fonts_export_and_import() {
assert!(s.execute("type.compositeFonts.export", &json!({"path": " "})).is_err());
let _ = std::fs::remove_dir_all(&dir);
}
/// `font(name)` with two custom character sets: "Marks" (x and A) in Inter at 150%, and "A only"
/// (A) in Source Sans 3, which sets A since it comes later.
fn font_with_sets(name: &str) -> Value {
let mut v = font(name);
v["custom"] = json!([
{"name": " Marks ", "characters": "xA", "font": "Inter", "size": 150, "hScale": 90},
{"name": "A only", "characters": "A"},
]);
v
}
/// Custom character sets are set with the font as one undo step, take values they leave out from
/// the Kanji part, set the characters they list ahead of their class (the later set winning), are
/// saved with the document, and measure type again when they change.
#[test]
fn custom_character_sets_set_their_characters() {
let mut s = session();
let before = steps(&s);
let r = s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets")]})).unwrap();
assert_eq!(r["fonts"][0]["custom"][0]["name"], "Marks");
assert_eq!(steps(&s), before + 1);
let f = s.doc().unwrap().doc.composite_fonts[0].clone();
assert_eq!(f.custom.len(), 2);
assert_eq!((f.custom[0].part.font.as_str(), f.custom[0].part.size, f.custom[0].part.h_scale), ("Inter", 150.0, 90.0));
assert_eq!((f.custom[1].part.font.as_str(), f.custom[1].part.size), ("Source Sans 3", 100.0));
// The same sets again change nothing.
s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets")]})).unwrap();
assert_eq!(steps(&s), before + 1);
let back = vectorcraft_format::load(&vectorcraft_format::save_file(&s.doc().unwrap().doc)).unwrap();
assert_eq!(*back.composite_fonts, *s.doc().unwrap().doc.composite_fonts);
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "xAB", "size": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("text.setStyle", &json!({"ids": [id], "font": "CF Sets"})).unwrap();
let db = vectorcraft_text::FontDb::global();
let face = |family: &str| db.face(family, "Regular").unwrap().id();
let lay = vectorcraft_text::layout(db, &text(&s, id));
let fonts: Vec<u32> = lay.glyphs.iter().map(|g| g.font_id).collect();
assert_eq!(fonts, [face("Inter"), face("Source Sans 3"), face("JetBrains Mono")]);
// Taking x out of Marks sets it in its class's font again, measured in the same step.
let wide = text(&s, id).cached_bounds.unwrap().width();
let mut fewer = font_with_sets("CF Sets");
fewer["custom"][0]["characters"] = json!("A");
s.execute("type.compositeFonts.set", &json!({"fonts": [fewer]})).unwrap();
assert!(text(&s, id).cached_bounds.unwrap().width() < wide - 1.0);
s.execute("edit.undo", &json!({})).unwrap();
assert!((text(&s, id).cached_bounds.unwrap().width() - wide).abs() < 1e-6);
}
/// Bad custom character sets are refused with an error and no undo step.
#[test]
fn bad_custom_character_sets_are_refused() {
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets Base")]})).unwrap();
let before = steps(&s);
let with = |f: &dyn Fn(&mut Value)| {
let mut v = font_with_sets("CF Sets Refused");
f(&mut v);
json!({"fonts": [v]})
};
let many: String = (0x4E00u32..).filter_map(char::from_u32).take(8193).collect();
let sets: Vec<Value> = (0..65).map(|i| json!({"name": format!("S{i}")})).collect();
for bad in [
with(&|v| v["custom"] = json!("Marks")),
with(&|v| v["custom"] = Value::Null),
with(&|v| v["custom"][0]["characters"] = Value::Null),
with(&|v| v["custom"][0] = json!("Marks")),
with(&|v| v["custom"][0]["name"] = json!(" ")),
with(&|v| {
v["custom"][0].as_object_mut().unwrap().remove("name");
}),
with(&|v| v["custom"][1]["name"] = json!("marks")),
with(&|v| v["custom"][0]["characters"] = json!(["※"])),
with(&|v| v["custom"][0]["characters"] = json!("※※")),
with(&|v| v["custom"][0]["characters"] = json!("A\n")),
with(&|v| v["custom"][0]["characters"] = json!("😀")),
with(&|v| v["custom"][0]["characters"] = json!(many.clone())),
with(&|v| v["custom"] = json!(sets.clone())),
with(&|v| v["custom"][0]["size"] = json!(5)),
with(&|v| v["custom"][0]["size"] = json!("50")),
with(&|v| v["custom"][0]["scaleAtCenter"] = json!(true)),
with(&|v| v["custom"][0]["scaleAtCenter"] = json!(false)),
with(&|v| v["custom"][0]["font"] = json!("")),
with(&|v| v["custom"][0]["font"] = json!("CF Sets Base")),
with(&|v| v["custom"][0]["width"] = json!(3)),
] {
let e = s.execute("type.compositeFonts.set", &bad);
assert!(e.is_err(), "accepted {bad}");
assert_eq!(names(&s), ["CF Sets Base"]);
assert_eq!(steps(&s), before);
}
// A set without characters is kept: it sets nothing.
let ok = with(&|v| v["custom"][0]["characters"] = json!(""));
s.execute("type.compositeFonts.set", &ok).unwrap();
assert_eq!(s.doc().unwrap().doc.composite_fonts[0].custom[0].characters, "");
}
/// Export writes the custom character sets and Import reads them back; a file whose set is bad is
/// refused.
#[test]
fn custom_character_sets_export_and_import() {
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets IO")]})).unwrap();
let data = s.execute("type.compositeFonts.export", &json!({})).unwrap();
let mut t = session();
t.execute("type.compositeFonts.import", &json!({"data": data["data"]})).unwrap();
assert_eq!(*t.doc().unwrap().doc.composite_fonts, *s.doc().unwrap().doc.composite_fonts);
let text = data["data"].as_str().unwrap().replace("\"A only\"", "\"marks\"");
let mut u = session();
assert!(u.execute("type.compositeFonts.import", &json!({"data": text})).is_err());
assert!(names(&u).is_empty());
// Fonts whose file would be larger than Import reads are refused.
let full: String = (0x4E00u32..).filter_map(char::from_u32).take(8192).collect();
let sets: Vec<Value> = (0..64).map(|i| json!({"name": format!("S{i}"), "characters": full})).collect();
let big: Vec<Value> = (0..3)
.map(|i| {
let mut f = font(&format!("CF Sets Big {i}"));
f["custom"] = json!(sets);
f
})
.collect();
let e = s.execute("type.compositeFonts.export", &json!({"fonts": big})).unwrap_err();
assert!(e.to_string().contains("4 MB"), "{e}");
}
+45 -11
View File
@@ -26,7 +26,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Ellipse",
[],
None,
"{x, y, width, height, rotation?: deg clockwise about the centre (0: upright)} → {id}",
"{x, y, width, height, rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}",
has_doc,
ellipse
),
@@ -53,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Flare",
[],
None,
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?} → {id}",
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: places the rings along the path anew, keeping their count and sizes)} → {id}",
has_doc,
flare
),
@@ -362,10 +362,28 @@ fn rectangle(s: &mut Session, p: &Value) -> Result<Value> {
add_art_turned(s, label, path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0))
}
/// The most anchors `shape.ellipse` draws, as many as a polygon's sides.
const MAX_ELLIPSE_ANCHORS: u64 = 1000;
fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
let r = rect_of(p, "shape.ellipse")?;
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: rect_transform(r, p, "shape.ellipse")? };
add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0))
// One message for every number that is not a whole count in range (a fraction, a negative,
// 0, 1, too many); a value that is not a number gets `number_or`'s.
let (key, min, max) = ("anchors", 2, MAX_ELLIPSE_ANCHORS);
let n = number_or(p, key, 4.0, "shape.ellipse")?;
if n.fract() != 0.0 || !(min as f64..=max as f64).contains(&n) {
return Err(bad("shape.ellipse", format!("`{key}` must be a whole number between {min} and {max} (got {n})")));
}
let x = n as u64;
let xf = rect_transform(r, p, "shape.ellipse")?;
let rotation = f64_or(p, "rotation", 0.0);
if x != 4 {
// Another count is a plain path: a live ellipse always has 4 anchors.
let path = shapes::ellipse_with_anchors(Rect::new(0.0, 0.0, r.width(), r.height()), x as u32).transformed(xf);
return add_art_turned(s, "Ellipse", path_kind(path, None), rotation);
}
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf };
add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation)
}
/// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or
@@ -429,6 +447,7 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
"direction",
"pathLength",
"seed",
"ringSeed",
];
check_numbers(p, &numbers, "shape.flare")?;
let pct = |k: &str, d: f64| (f64_or(p, k, d) / 100.0).clamp(0.0, 10.0);
@@ -450,14 +469,28 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
c + vectorcraft_geom::Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0)
}
};
// Deterministic pseudo-random sizes (same parameters → same flare).
let mut seed = p.get("seed").and_then(Value::as_u64).unwrap_or(0x2545_f491_4f6c_dd1d) | 1;
let mut rnd = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed >> 11) as f64 / (1u64 << 53) as f64
// Deterministic pseudo-random sizes (same parameters → same flare). `ringSeed` places the rings
// along the path from a sequence of its own; their count and sizes and the other parts stay.
let seed_of = |key: &str| match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => v.as_u64().map(Some).ok_or_else(|| bad("shape.flare", format!("`{key}` must be a whole number of at least 0, not {v}"))),
};
// The generator's state is odd (never 0).
let random = |mut state: u64| {
move || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
(state >> 11) as f64 / (1u64 << 53) as f64
}
};
let mut rnd = random(seed_of("seed")?.unwrap_or(0x2545_f491_4f6c_dd1d) | 1);
// Each `ringSeed` below 2^53 (what a JSON number holds exactly) gets a state of its own.
let ring_seed = match seed_of("ringSeed")? {
Some(r) if r >= 1 << 53 => return Err(bad("shape.flare", format!("`ringSeed` must be below 2^53, not {r}"))),
r => r,
};
let mut ring_at = ring_seed.map(|r| random((r << 1) | 1));
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, vectorcraft_color::Color::WHITE) };
let radial = |centre: Point, radius: f64, stops: Vec<GradientStop>| {
let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops));
@@ -495,6 +528,7 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
// Rings along the path to the end point (Largest = % of the average ring size).
for _ in 0..rings {
let t = rnd();
let t = ring_at.as_mut().map_or(t, |next| next());
let at = c + (end - c) * t;
let rr = (r * largest * (0.25 + rnd() * 0.75)).max(0.5);
let solid = rnd() < 0.5;
+2 -1
View File
@@ -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));
+6 -7
View File
@@ -631,13 +631,12 @@ impl LiquifyStroke {
}
let msg = (!ids.is_empty()).then(|| {
let n = ids.len();
format!(
"{} left {n} object{} under the brush as {} ({}): it reshapes paths only",
self.prm.kind.label(),
if n == 1 { "" } else { "s" },
if n == 1 { "it was" } else { "they were" },
kinds.join(", ")
)
let (tool, kinds) = (self.prm.kind.label(), kinds.join(", "));
if n == 1 {
format!("{tool} left {n} object under the brush as it was ({kinds}): it reshapes paths only")
} else {
format!("{tool} left {n} objects under the brush as they were ({kinds}): it reshapes paths only")
}
});
(ids, msg)
}
+30 -9
View File
@@ -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
),
@@ -269,6 +270,33 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
super::fileinfo::file_info
),
cmd!(
"file.info.saveTemplate",
"Save Metadata Template…",
[],
None,
"{name?: save into the metadata templates folder as <name>.xmp (a name with characters file systems reject, a dot at either end, or a device name is an error (spaces at either end are dropped); the same name replaces that template), path?: save to this file instead (not both), fields?: {File Info fields as file.info takes them} save these instead of the document's (default: the document's File Info)} write the File Info as an XMP metadata template: title (only one of its own, not Untitled-N), author, authorTitle, description, keywords, rating (1–5), copyrightStatus, copyrightNotice and copyrightUrl, each where it has a value; the dates are left out → {name, path} (with name), {path} (with path), or {data: the XMP text} with neither",
has_doc,
super::fileinfo::save_template
),
cmd!(
"file.info.applyTemplate",
"Import Metadata Template…",
[],
None,
"{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text (exactly one of the three; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)",
has_doc,
super::fileinfo::apply_template
),
cmd!(
query "file.info.templates",
"Metadata Templates",
[],
None,
"{create?: false (true: make the folder when it is missing)} the metadata templates in the metadata templates folder next to the preferences, sorted by name, at most 1,000 → {templates: [{name, file: the file name, path}], folder?: the folder (left out for a request that may not read it, in runs without preferences and on the web, where the list is empty)}",
super::always,
super::fileinfo::templates
),
]
}
@@ -767,15 +795,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")),
+1
View File
@@ -33,3 +33,4 @@ mod smooth;
pub use commands::specs;
pub(super) use common::{ids_json, replace_with_pieces, usize_opt};
pub(super) use cut::{components, erase_outline};
pub(super) use freehand::freehand_brushed;
+1 -1
View File
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Eraser",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
has_doc,
erase_region
),
+76 -6
View File
@@ -3,9 +3,10 @@ use super::common::{
samples_param, sibling_with, size_pressure, target_paths, usize_opt,
};
use super::{
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Result, Session,
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session,
SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
};
use kurbo::{CubicBez, Line, PathSeg};
use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Variation};
use vectorcraft_doc::StrokeLayer;
use vectorcraft_tools::draw2::MIN_BRUSH_SIZE;
@@ -46,8 +47,8 @@ pub(in super::super) fn components(pd: &PathData) -> Vec<PathData> {
/// The pieces of `sp` where `remove(point)` is false. `None` when nothing is removed. Each segment
/// is sampled at least every `step` pt (and at least 24 times), so a removed stretch at least
/// `step` long is found.
fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Option<Vec<SubPath>> {
/// `step` long is found, and also at the parameters `extra` gives for it.
fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool, extra: &dyn Fn(CubicBez) -> Vec<f64>) -> Option<Vec<SubPath>> {
let nseg = sp.segment_count();
if nseg == 0 {
return sp.anchors.first().filter(|a| remove(a.p)).map(|_| vec![]);
@@ -64,6 +65,13 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio
let edge = (c.p1 - c.p0).hypot().max((c.p2 - c.p1).hypot()).max((c.p3 - c.p2).hypot());
let wanted = (3.0 * edge / step).ceil();
let samples = if wanted.is_finite() && wanted > K as f64 { (wanted as usize).min(MAX_SAMPLES) } else { K };
let mut ts: Vec<f64> = (1..=samples).map(|k| k as f64 / samples as f64).collect();
let more = extra(c);
if !more.is_empty() {
ts.extend(more.into_iter().filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0));
ts.sort_by(f64::total_cmp);
ts.dedup();
}
let mut prev_t = 0.0;
let mut prev_rm = remove(c.eval(0.0));
let mut start = if prev_rm { None } else { Some(0.0) };
@@ -73,8 +81,7 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio
runs.push(std::mem::take(&mut cur));
}
}
for k in 1..=samples {
let t = k as f64 / samples as f64;
for t in ts {
let rm = remove(c.eval(t));
if rm != prev_rm {
let (mut lo, mut hi) = (prev_t, t);
@@ -146,10 +153,15 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio
/// every `step` pt (`f64::INFINITY` for the fixed sampling). Returns the new geometry per output
/// object (one object per piece when the path had a single subpath), or None if unchanged.
pub(in super::super) fn erase_outline(pd: &PathData, step: f64, remove: &dyn Fn(Point) -> bool) -> Option<Vec<PathData>> {
erase_outline_at(pd, step, remove, &|_| vec![])
}
/// [`erase_outline`], also sampling each segment at the parameters `extra` gives for it.
fn erase_outline_at(pd: &PathData, step: f64, remove: &dyn Fn(Point) -> bool, extra: &dyn Fn(CubicBez) -> Vec<f64>) -> Option<Vec<PathData>> {
let mut changed = false;
let mut subs = vec![];
for sp in &pd.subpaths {
match cut_subpath(sp, step, remove) {
match cut_subpath(sp, step, remove, extra) {
Some(pieces) => {
changed = true;
subs.extend(pieces);
@@ -274,6 +286,12 @@ pub(super) fn knife(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.eraseRegion";
if let Some(rect) = p.get("rect").filter(|v| !v.is_null()) {
if p.get("points").is_some_and(|v| !v.is_null()) {
return Err(bad(C, "give `points` or `rect`, not both"));
}
return erase_rect(s, marquee_param(rect, C)?);
}
let samples = samples_param(p, "points", C)?;
let size = number_or(p, "size", 10.0, C)?;
if !(size.is_finite() && size > 0.0) {
@@ -325,6 +343,58 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
apply_plan(s, "Eraser", plan)
}
/// `path.eraseRegion`'s `rect: [x, y, width, height]`: four finite numbers, with a width and a
/// height above 0.
fn marquee_param(v: &Value, cmd: &str) -> Result<Rect> {
const SHAPE: &str = "rect is [x, y, width, height] in points, with a width and a height above 0";
let n: Vec<f64> = match v.as_array() {
Some(a) if a.len() == 4 => a.iter().map(Value::as_f64).collect::<Option<_>>().ok_or_else(|| bad(cmd, SHAPE))?,
_ => return Err(bad(cmd, SHAPE)),
};
let [x, y, w, h] = [n[0], n[1], n[2], n[3]];
if !(n.iter().all(|v| v.is_finite()) && w > 0.0 && h > 0.0 && (x + w).is_finite() && (y + h).is_finite()) {
return Err(bad(cmd, SHAPE));
}
Ok(Rect::new(x, y, x + w, y + h))
}
/// `path.eraseRegion` with a marquee: everything inside `r` is erased from the paths (selected, or
/// all). Closed paths lose the rectangle's area, and open paths are cut where they cross its edges.
fn erase_rect(s: &mut Session, r: Rect) -> Result<Value> {
let region =
PathData::single(SubPath::polyline(&[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)], true));
let inside = |q: Point| q.x >= r.x0 && q.x <= r.x1 && q.y >= r.y0 && q.y <= r.y1;
// An open path is sampled at least every half of the rectangle's shorter side, and also where
// each segment crosses the rectangle's edges and halfway between those crossings, so a stretch
// inside the rectangle is found however long the segment is.
let step = r.width().min(r.height()) / 2.0;
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)];
let crossings = |c: CubicBez| {
let mut ts: Vec<f64> = (0..4)
.flat_map(|k| PathSeg::Cubic(c).intersect_line(Line::new(corners[k], corners[(k + 1) % 4])))
.map(|x| x.segment_t)
.filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0)
.collect();
ts.sort_by(f64::total_cmp);
let mids: Vec<f64> = [0.0].iter().chain(&ts).zip(ts.iter().chain(&[1.0])).map(|(a, b)| 0.5 * (a + b)).collect();
ts.extend(mids);
ts
};
let st = s.doc()?;
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r)? {
if pd.is_closed() {
if po::area(&po::boolean(&pd, rule, &region, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
continue;
}
plan.push((id, components(&po::boolean(&pd, rule, &region, FillRule::NonZero, BoolOp::Difference))));
} else if let Some(pieces) = erase_outline_at(&pd, step, &inside, &crossings) {
plan.push((id, pieces));
}
}
apply_plan(s, "Eraser", plan)
}
/// The variation modes `path.eraseRegion` takes for each of `angleMode`, `roundnessMode` and
/// `sizeMode`.
const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\"";
+82 -12
View File
@@ -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() {
@@ -157,6 +157,34 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -
}
pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
freehand_brushed(s, p, None)
}
/// The object a brush on path `id` paints: the compound path a member path is in, else the path.
fn brush_target(d: &Document, id: NodeId) -> NodeId {
d.parent_of(id).filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id)
}
/// Whether `ap` has a stroke a brush can paint: a stroke whose paint is not None.
fn can_brush(ap: &Appearance) -> bool {
ap.stroke().is_some_and(|st| !st.paint.is_none())
}
fn no_stroke(name: &str) -> EngineError {
bad("brush.freehand", format!("cannot apply brush `{name}`: path has no stroke"))
}
/// Sets brush `name` on the stroke of object `id` of `d`.
fn set_brush(d: &mut Document, id: NodeId, name: &str) {
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
st.brush = Some(name.to_string());
}
}
/// `path.freehand`, with the stroke painted with brush `brush_name` (one `brush.freehand` has
/// checked) in the same undo step as the path. A path without a stroke is an error before
/// anything changes.
pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&str>) -> Result<Value> {
const C: &str = "path.freehand";
let samples = samples_param(p, "points", C)?;
if samples.iter().any(|q| !within_input_bound(q.pt)) {
@@ -173,6 +201,8 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol);
let closed = switch_or(p, "closed", false, C)?;
let brush = str_param(p, "style") == Some("brush");
// The undo step's name: a stroke painted with a brush is a Paintbrush stroke, whatever its style.
let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" };
let keep_selected = switch_or(p, "keepSelected", true, C)?;
let filled = switch_or(p, "fill", false, C)?;
if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) {
@@ -180,6 +210,12 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
let at_start = str_param(ext, "end") == Some("start");
let (pd, _) = path_of(&s.doc()?.doc, id)?;
let si = pd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "path has no open end"))?;
let target = brush_target(&s.doc()?.doc, id);
if let Some(name) = brush_name
&& !s.doc()?.doc.node(target).is_some_and(|n| can_brush(&n.appearance))
{
return Err(no_stroke(name));
}
let mut sp = pd.subpaths[si].clone();
let old_len = subpath_len(&sp);
if at_start {
@@ -191,6 +227,21 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
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, 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, sel| {
set_brush(d, target, name);
if keep_selected {
sel.set([id]);
} else {
sel.remove(id);
}
Ok(())
})?;
}
return Ok(json!({ "id": id.0 }));
}
// A stroke that ends on an open end of another path connects the two: (that path, its last
@@ -271,12 +322,12 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
// 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
@@ -290,7 +341,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
let drawn = old.extended(old_len, &pen, drawn_len - old_len);
if connect.is_some() { drawn.extended(drawn_len, &other, other_len) } else { drawn }
});
s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| {
s.edit(label, |d, sel| {
let reverse = at_start && !sp.closed;
if reverse {
sp.reverse();
@@ -326,6 +377,9 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
{
if reverse { joined.reversed() } else { joined }.write(st);
}
if let Some(name) = brush_name {
set_brush(d, target, name);
}
if keep_selected {
sel.set([id]);
} else {
@@ -346,11 +400,19 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
// were, measured along the old path; fit them to the new length if strokes drawn with a
// pen get redrawn.
if let Some((si, sp)) = redraw_section(&pd, &pts, fit_tol, within) {
s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| {
// A member path of a compound path is redrawn in it: the compound path is what is
// selected, and what a brush paints.
let whole = brush_target(&s.doc()?.doc, id);
if let Some(name) = brush_name
&& !s.doc()?.doc.node(whole).is_some_and(|n| can_brush(&n.appearance))
{
return Err(no_stroke(name));
}
s.edit(label, |d, sel| {
*path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| bad(C, "no such subpath"))? = sp;
// A member path of a compound path is redrawn in it: the compound path is what is
// selected.
let whole = d.parent_of(id).filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id);
if let Some(name) = brush_name {
set_brush(d, whole, name);
}
if keep_selected {
sel.set([whole]);
} else {
@@ -373,7 +435,15 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(st) = look.appearance.stroke_mut() {
pen.write(st);
}
let out = insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected)?;
if let Some(name) = brush_name {
if !can_brush(&look.appearance) {
return Err(no_stroke(name));
}
if let Some(st) = look.appearance.stroke_mut() {
st.brush = Some(name.to_string());
}
}
let out = insert_look(s, label, path_kind(PathData::single(sp)), look, None, keep_selected)?;
if !keep_selected {
// A new stroke with Keep selected off leaves nothing selected: Illustrator starts the stroke
// by dropping the earlier selection, it does not keep it (#5752).
+75 -24
View File
@@ -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]);
}
+1 -1
View File
@@ -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)
),
+64 -29
View File
@@ -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.
+8 -5
View File
@@ -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))
Loaded 100 of 511 files, more files were not shown because too many files have changed in this diff. Show more