mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-20 01:14:23 +01:00
Merge remote-tracking branch 'upstream/main' into feat-4936-spell-check
# Conflicts: # crates/engine/src/cmd.rs # docs/gaps.md # docs/roadmap.md # docs/target-app-parity.md # docs/type-parity.md
This commit is contained in:
commit
82181ff0b1
710 files changed
+87638
-4693
No files matched your search
@@ -368,6 +368,18 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `crates/engine/tests/fixtures/jpeg2000/checker.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `3de9c2bb5b8aaec241d939b795002a68eb3d50e41d51c43368000804ad3de057` |
|
||||
| `crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `76fa51ab8ccbc2534098b26b8e7fe16dd886e2b6298ba52d06a6b1bde9b61d9e` |
|
||||
| `crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `1b1aeed8975d3cdc832da6ecf5855852d07d0c490105121e61a8aefb31af009b` |
|
||||
| `crates/engine/tests/fixtures/heif/quadrants.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 32 red, green, blue and white quadrants encoded with libheif's `heif-enc` 1.23.2 (x265); SHA-256 `122d14963fe899daa736cd216902cf4fc8f2192b3a0ba81f94004adcd71a0ff5` |
|
||||
| `crates/engine/tests/fixtures/heif/quadrants-alpha.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the quadrants with a transparent right half, encoded with `heif-enc` 1.23.2; SHA-256 `55b5a537401ead742714c3a1bc526559ec8c1ba97cdb7f43ac63f4037167475b` |
|
||||
| `crates/engine/tests/fixtures/heif/quadrants-10bit.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the quadrants at 10 bits, encoded with `heif-enc` 1.23.2; SHA-256 `11014848c6a838e5799d87e034eff1b06b816712ed70ba451bd582d72741774f` |
|
||||
| `crates/engine/tests/fixtures/heif/quadrants-grid.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 128 × 128 quadrants as a 2 × 2 grid of 64 × 64 tiles, encoded with `heif-enc` 1.23.2; SHA-256 `5802f8715110954eb9c58d4bdcc10d1200426a48cf726f1b88dfb60da825ba7a` |
|
||||
| `crates/engine/tests/fixtures/heif/quadrants-300ppi.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the quadrants with EXIF resolution tags of 300 ppi, encoded with `heif-enc` 1.23.2; SHA-256 `6a344a6de04fc5fceaee46b6e0028b12478c90bdcb6f6f14ed8c86a44cb203d7` |
|
||||
| `crates/engine/tests/fixtures/heif/wide-rotated.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 16 red and blue halves stored with a quarter-turn rotation, encoded with `heif-enc` 1.23.2; SHA-256 `e3a2c3a9beb4066c13d6deb8e1311805c6aac485fde8784f1ee317dd95b89973` |
|
||||
| `crates/engine/tests/fixtures/heif/wide-rotated-300x150.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the rotated halves with EXIF resolution tags of 300 ppi across and 150 ppi down, encoded with `heif-enc` 1.23.2; SHA-256 `79ad7945cd2c1ea9d3e70ac9b93d9a162fd8ce37541a0f3de44e12f04745921d` |
|
||||
| `crates/engine/tests/fixtures/heif/tones.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 32 quadrants of four mid tones, encoded with `heif-enc` 1.23.2; SHA-256 `29ed7d75fbfbc4c298eb2da3a6b62625a150cd6bfe5b7ff1d847437501b1b4b1` |
|
||||
| `crates/engine/tests/fixtures/heif/tones-p3-nclx.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the tones labeled Display P3 in an `nclx` color box, encoded with `heif-enc` 1.23.2; SHA-256 `baeb32ffa58ac1ac29a00c9e388b9281f4acb4695c4681e4933d0ad061447101` |
|
||||
| `crates/engine/tests/fixtures/heif/tones-p3-icc.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the tones with VectorCraft's own Display P3 ICC profile (`vectorcraft_color::cms::icc_bytes`), encoded with `heif-enc` 1.23.2; SHA-256 `472e1a123b9515926a8985a04c3f680387e8c410dbf8f7ff0cfb8cb99c89e93b` |
|
||||
| `crates/engine/tests/fixtures/heif/tones-p3-icc-only.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the tones with VectorCraft's own Display P3 ICC profile as their only color box, encoded with `heif-enc` 1.23.2; SHA-256 `2654fdd21e56641107db20b3f4d0a66a86420ac040d42ddf55e20f7e789d5c55` |
|
||||
| `crates/engine/tests/fixtures/heif/quadrants-grid16.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 32 quadrants as a 2 × 2 grid of 16 × 16 tiles, each cropped from a 64 × 64 picture, encoded with `heif-enc` 1.23.2; SHA-256 `bd114ee66cdac10142729dc9dddfa1cd96993a5cefa54c2f25b65496652f007f` |
|
||||
|
||||
## Assets embedded by the PDF backend
|
||||
|
||||
|
||||
Generated
+246
-18
@@ -1070,7 +1070,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -1453,7 +1453,7 @@ dependencies = [
|
||||
"itertools",
|
||||
"log",
|
||||
"profiling",
|
||||
"resvg",
|
||||
"resvg 0.45.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2297,6 +2297,15 @@ version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "heic-rs"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8883c3bfa6b4ff19a40e52a6dc051c5612cbe21bf408fc6d4875e8dfd777cb66"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.5.3"
|
||||
@@ -2846,6 +2855,182 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-bitstream"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b480e752277e29eb4054f69546887a9b84656fe78c08f54ba5850ced98a378fe"
|
||||
dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-coding"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cd972bcd125e776f1eb241ac50e39f956095a1c2770c64736c968f8946bd9a3c"
|
||||
dependencies = [
|
||||
"jxl-bitstream",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-color"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f316b1358c1711755b3ee8e8cb5c4a1dad12e796233088a7a513440782de80b2"
|
||||
dependencies = [
|
||||
"jxl-bitstream",
|
||||
"jxl-coding",
|
||||
"jxl-grid",
|
||||
"jxl-image",
|
||||
"jxl-oxide-common",
|
||||
"jxl-threadpool",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-frame"
|
||||
version = "0.13.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2d967c6fd669c7c01060b5022d8835fa82fd46b06ffc98b549f17600a097c2b3"
|
||||
dependencies = [
|
||||
"jxl-bitstream",
|
||||
"jxl-coding",
|
||||
"jxl-grid",
|
||||
"jxl-image",
|
||||
"jxl-modular",
|
||||
"jxl-oxide-common",
|
||||
"jxl-threadpool",
|
||||
"jxl-vardct",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-grid"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "01671307879a033bfa52e6e8784b941aca770b3f3a7d33830b455b6844f793fb"
|
||||
dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-image"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c5f752d62577c702a94dbbce4045caf08cb58639e8a4d56464b40ecf33ffe565"
|
||||
dependencies = [
|
||||
"jxl-bitstream",
|
||||
"jxl-grid",
|
||||
"jxl-oxide-common",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-jbr"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e35d032bcec660647828527ff42c6f5776d2fd44b8357f9f6d9ac6dc07218e46"
|
||||
dependencies = [
|
||||
"brotli-decompressor",
|
||||
"jxl-bitstream",
|
||||
"jxl-frame",
|
||||
"jxl-grid",
|
||||
"jxl-image",
|
||||
"jxl-modular",
|
||||
"jxl-oxide-common",
|
||||
"jxl-threadpool",
|
||||
"jxl-vardct",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-modular"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2a2f045b24c738dd91d482be385512b512721ae08a671bd4b27bf1c47f215235"
|
||||
dependencies = [
|
||||
"jxl-bitstream",
|
||||
"jxl-coding",
|
||||
"jxl-grid",
|
||||
"jxl-oxide-common",
|
||||
"jxl-threadpool",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-oxide"
|
||||
version = "0.12.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d36c662923f47586880211f3bc7c0d83fb3a9b410d278c7bde93450748abeef3"
|
||||
dependencies = [
|
||||
"brotli-decompressor",
|
||||
"jxl-bitstream",
|
||||
"jxl-color",
|
||||
"jxl-frame",
|
||||
"jxl-grid",
|
||||
"jxl-image",
|
||||
"jxl-jbr",
|
||||
"jxl-oxide-common",
|
||||
"jxl-render",
|
||||
"jxl-threadpool",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-oxide-common"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b62394c5021b3a9e7e0dbb2d639d555d019090c9946c39f6d3b09d390db4157b"
|
||||
dependencies = [
|
||||
"jxl-bitstream",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-render"
|
||||
version = "0.12.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d34386bfdb6a19b5a30cc9beb4d475d537422c31ae8c39bb69640fcce3fcaf19"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"jxl-bitstream",
|
||||
"jxl-coding",
|
||||
"jxl-color",
|
||||
"jxl-frame",
|
||||
"jxl-grid",
|
||||
"jxl-image",
|
||||
"jxl-modular",
|
||||
"jxl-oxide-common",
|
||||
"jxl-threadpool",
|
||||
"jxl-vardct",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-threadpool"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "25f15eb830aa77a7f21148d72e153562a26bfe570139bd4922eab1908dd499d3"
|
||||
dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-vardct"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce72a18c6d3a47172ab6c479be2bdb56f22066b5d7092663f03b4490820b4511"
|
||||
dependencies = [
|
||||
"jxl-bitstream",
|
||||
"jxl-coding",
|
||||
"jxl-grid",
|
||||
"jxl-modular",
|
||||
"jxl-oxide-common",
|
||||
"jxl-threadpool",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "keyboard-types"
|
||||
version = "0.8.3"
|
||||
@@ -4440,11 +4625,29 @@ dependencies = [
|
||||
"pico-args",
|
||||
"rgb",
|
||||
"svgtypes 0.15.3",
|
||||
"tiny-skia",
|
||||
"tiny-skia 0.11.4",
|
||||
"usvg 0.45.1",
|
||||
"zune-jpeg 0.4.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "resvg"
|
||||
version = "0.48.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"gif 0.14.2",
|
||||
"image-webp",
|
||||
"log",
|
||||
"pico-args",
|
||||
"rgb",
|
||||
"svgtypes 0.16.1",
|
||||
"tiny-skia 0.12.0",
|
||||
"usvg 0.48.1",
|
||||
"zune-jpeg 0.5.15",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rfd"
|
||||
version = "0.17.2"
|
||||
@@ -4729,7 +4932,7 @@ checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec"
|
||||
dependencies = [
|
||||
"log",
|
||||
"smithay-client-toolkit 0.19.2",
|
||||
"tiny-skia",
|
||||
"tiny-skia 0.11.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5595,6 +5798,21 @@ dependencies = [
|
||||
"tiny-skia-path 0.11.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tiny-skia"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea"
|
||||
dependencies = [
|
||||
"arrayref",
|
||||
"arrayvec",
|
||||
"bytemuck",
|
||||
"cfg-if",
|
||||
"log",
|
||||
"png 0.18.1",
|
||||
"tiny-skia-path 0.12.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tiny-skia-path"
|
||||
version = "0.11.4"
|
||||
@@ -6237,7 +6455,9 @@ version = "0.21.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
"resvg 0.48.1",
|
||||
"serde_json",
|
||||
"svgtypes 0.16.1",
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-geom",
|
||||
@@ -6258,10 +6478,15 @@ dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"hayro-jpeg2000",
|
||||
"heic-rs",
|
||||
"image",
|
||||
"jxl-color",
|
||||
"jxl-grid",
|
||||
"jxl-oxide",
|
||||
"kurbo 0.13.1",
|
||||
"log",
|
||||
"proptest",
|
||||
"rayon",
|
||||
"roxmltree 0.21.2",
|
||||
"rustix 1.1.6",
|
||||
"ruzstd",
|
||||
@@ -6289,6 +6514,8 @@ dependencies = [
|
||||
"vectorcraft-tools",
|
||||
"vectorcraft-trace",
|
||||
"wat",
|
||||
"zune-core 0.5.3",
|
||||
"zune-jpegxl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6296,6 +6523,7 @@ name = "vectorcraft-eps"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-pdf",
|
||||
"encoding_rs",
|
||||
"fax",
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -6304,6 +6532,7 @@ dependencies = [
|
||||
"memchr",
|
||||
"ruzstd",
|
||||
"serde_json",
|
||||
"skrifa 0.47.0",
|
||||
"vectorcraft-brush",
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
@@ -6349,6 +6578,7 @@ dependencies = [
|
||||
name = "vectorcraft-js"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"proptest",
|
||||
"unicode-general-category",
|
||||
]
|
||||
@@ -6434,6 +6664,8 @@ dependencies = [
|
||||
name = "vectorcraft-plugins"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-vectorcraft-format",
|
||||
"image",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -6492,7 +6724,7 @@ dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
"proptest",
|
||||
"resvg",
|
||||
"resvg 0.45.1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"simplecss",
|
||||
@@ -8004,7 +8236,6 @@ dependencies = [
|
||||
"nix",
|
||||
"typed-path",
|
||||
"windows-sys 0.61.2",
|
||||
"zopfli",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8019,18 +8250,6 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
|
||||
[[package]]
|
||||
name = "zopfli"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"crc32fast",
|
||||
"log",
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zune-core"
|
||||
version = "0.4.12"
|
||||
@@ -8061,6 +8280,15 @@ dependencies = [
|
||||
"zune-core 0.5.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zune-jpegxl"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4"
|
||||
dependencies = [
|
||||
"zune-core 0.5.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zvariant"
|
||||
version = "5.15.1"
|
||||
|
||||
+14
-1
@@ -23,7 +23,7 @@ craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63
|
||||
# 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 = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -100,12 +100,25 @@ ruzstd = { version = "0.9.1", default-features = false, features = ["std"] }
|
||||
hayro-ccitt = "0.3"
|
||||
# Substring search for the EPS reader's PostScript `search`.
|
||||
memchr = "2"
|
||||
# The WHATWG Encoding Standard's legacy encodings: names in legacy .ai files read in the code page
|
||||
# the user picks (Mac OS Roman, Korean, Japanese, Chinese).
|
||||
encoding_rs = "0.8.42"
|
||||
jpeg-encoder = { version = "0.6", default-features = false, features = ["std"] }
|
||||
gif = { version = "0.14", default-features = false, features = ["std", "raii_no_panic"] }
|
||||
# CMYK image samples (vectorcraft-doc's cmyk module): the image crate's own TIFF and JPEG
|
||||
# decoders, read directly (the image crate converts CMYK to RGB).
|
||||
tiff = "0.11"
|
||||
zune-jpeg = "0.5"
|
||||
# JPEG XL decoder (pure Rust, MIT OR Apache-2.0): File › Open and Place read `.jxl` images. It is
|
||||
# built without its default `rayon` feature and decodes on one thread.
|
||||
jxl-oxide = { version = "0.12.6", default-features = false }
|
||||
# jxl-oxide's color conversions, run on colors after their alpha is divided out.
|
||||
jxl-color = "0.11.0"
|
||||
# jxl-oxide's buffer allocation error, told apart from other decoding errors.
|
||||
jxl-grid = "0.6.2"
|
||||
# Tests: a lossless JPEG XL encoder (pure Rust, MIT OR Apache-2.0 OR Zlib) for the `.jxl` test files.
|
||||
zune-jpegxl = { version = "0.5.2", default-features = false, features = ["std"] }
|
||||
zune-core = "0.5"
|
||||
|
||||
# ui
|
||||
egui = "0.37"
|
||||
|
||||
@@ -237,7 +237,7 @@ and what's next; [`docs/target-app-parity.md`](docs/target-app-parity.md) the fu
|
||||
(92.5% of menu items do something), feature depth is ~75%, and we estimate ~65% ready for real work for a mainstream illustrator (~62% across all tracked features): everyday
|
||||
vector illustration is close to usable: drawing and path tools,
|
||||
Pathfinder and Shape Builder, paint, gradients, appearance and transparency, type with styles, threading and Hebrew/Arabic bidirectional layout, and
|
||||
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out and PSD/PSB in as their merged image, Print, Package).
|
||||
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out and PSD/PSB in as their merged image, JPEG XL in, Print, Package).
|
||||
Affinity documents (`.af` from Affinity 3, `.afdesign`, `.afpub` and, by their content, `.afphoto` from Affinity 1 and 2) open
|
||||
and place natively: layers, groups, artboards and pages, curves and shapes, fills, gradients and strokes, clipping
|
||||
and masks, text with each paragraph's indents, spacing and leading, tables (as text frames and lines), master
|
||||
|
||||
+5
-1
@@ -4,6 +4,7 @@
|
||||
- Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged.
|
||||
|
||||
- Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged.
|
||||
- UI: Window → Help Bar toggles the tool-help strip separately from the status bar and saves visibility with workspaces. Scores and estimates unchanged.
|
||||
|
||||
- PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document.
|
||||
- PDF.W1: PDF export and print composition use the shared optional writer for configuration, metadata, font preparation and guarded finalization; drawing and output policy remain app-owned.
|
||||
@@ -14,7 +15,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
|
||||
VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs
|
||||
on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON
|
||||
@@ -34,6 +35,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
|
||||
|
||||
| | Value | Kind |
|
||||
|---|---|---|
|
||||
| 2026-11-03 | minor | Docked Tools stays between left-side panels and the canvas; redocking accepts canvas and window edges. Requested layout choice; scores and estimates unchanged. |
|
||||
| **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 depth** (weighted by use, scored by behaviour) | **~75%** | estimated |
|
||||
| **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated |
|
||||
@@ -134,6 +136,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; 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-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.
|
||||
@@ -223,6 +226,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-02 | minor | Selection QoL: saved marquee modes, screen drag direction with a 3 px dead zone, and translated mode/E feedback (#5313); VectorCraft addition, scores and estimates unchanged. |
|
||||
| 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged |
|
||||
| 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. |
|
||||
| 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. |
|
||||
|
||||
@@ -16,7 +16,7 @@ workspace = true
|
||||
[dependencies]
|
||||
vectorcraft-color = { workspace = true }
|
||||
vectorcraft-doc = { workspace = true }
|
||||
vectorcraft-engine = { workspace = true, features = ["bundled-fonts"] }
|
||||
vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] }
|
||||
vectorcraft-format = { workspace = true }
|
||||
vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-svg = { workspace = true }
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
//! `vectorcraft-cli`: VectorCraft from the command line.
|
||||
//!
|
||||
//! ```text
|
||||
//! vectorcraft-cli --safe-mode SUBCOMMAND ...
|
||||
//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
|
||||
//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300]
|
||||
//! vectorcraft-cli commands
|
||||
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
|
||||
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
|
||||
//! vectorcraft-cli info FILE
|
||||
//! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5]
|
||||
//! vectorcraft-cli perf [--paths 50000] [--deep]
|
||||
@@ -72,6 +73,11 @@ const USAGE: &str = "\
|
||||
vectorcraft-cli — VectorCraft automation
|
||||
|
||||
USAGE:
|
||||
vectorcraft-cli --safe-mode SUBCOMMAND ...
|
||||
Run any subcommand without plug-ins: none loads or runs, and plug-in commands report that
|
||||
Safe Mode is on. Plug-ins stay installed. `--safe-mode mcp` serves a headless session and
|
||||
does not take --connect.
|
||||
|
||||
vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
|
||||
Run the MCP server on stdio. Default: connect to a running app at 127.0.0.1:7979
|
||||
(vectorcraft --control 7979), falling back to a headless in-process session.
|
||||
@@ -95,7 +101,7 @@ USAGE:
|
||||
vectorcraft-cli commands
|
||||
Print the command catalogue as JSON.
|
||||
|
||||
vectorcraft-cli convert IN OUT [--scale N] [--ppi N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
|
||||
vectorcraft-cli convert IN OUT [--scale N] [--ppi N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
|
||||
Open IN (any readable format) and export OUT in the format its extension picks (see Writable
|
||||
formats). Raster resolution: --ppi, else 72 times --scale, else the document's raster effects
|
||||
resolution; other formats leave them out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard
|
||||
@@ -108,7 +114,10 @@ USAGE:
|
||||
IN left things out (hidden text, art or layers it could not read; the notes say which) unless
|
||||
--replace-lossy is given. --editing-data opens a .ai or an EPS with editing data from its editing copy
|
||||
even where that draws differently from its PDF part or page (which can be older), as long as
|
||||
it can be read. A PDF OUT omits the embedded native document unless --preserve-editing is
|
||||
it can be read. --legacy-name-encoding reads the names in a .ai's or an EPS's editing data
|
||||
that aren't UTF-8 (layers, objects, artboards, colors, gradients, patterns, graphic styles,
|
||||
swatches, brushes, symbols, variables and data sets, and data sets' text values) in
|
||||
windows-1252 (the default), macintosh, windows-949, shift_jis, gbk or big5. A PDF OUT omits the embedded native document unless --preserve-editing is
|
||||
given (the app's Save As PDF still defaults to keeping it). With --preserve-editing, when the
|
||||
attachment is written the result's warnings say so (it is left out, with its own warning, for
|
||||
--artboard or a --range without every artboard).
|
||||
@@ -128,12 +137,17 @@ USAGE:
|
||||
Render FILE (any readable format) fitted to WxH (default 2880x1800) and print ms per frame
|
||||
(warm), multithreaded and single-threaded.
|
||||
|
||||
vectorcraft-cli perf [--paths N] [--deep]
|
||||
vectorcraft-cli perf [--paths N] [--deep] [--native-io [--artboards 1..4]]
|
||||
Check the performance budgets (render, pan, hit test, save/load, SVG, Pathfinder, handle
|
||||
and segment drags) on a synthetic N-path document (default 50000). Exits non-zero if a
|
||||
budget is exceeded, unless the report says the machine is busy. --deep also times work with
|
||||
no budget yet and prints memory use (the working set on Windows), with the peak so far on
|
||||
Windows and Linux.
|
||||
--native-io instead measures the application's native save/open commands (one warmup,
|
||||
five samples, no disk I/O), including preview, PDF, compression and API base64 costs.
|
||||
It reports the default and explicit PDF opt-out, with and without preview/compression;
|
||||
--artboards repeats the same artwork
|
||||
on 1 to 4 overlapping artboards. This mode allows at most 50000 paths.
|
||||
";
|
||||
|
||||
/// The usage text plus the formats `document.open` reads and `document.export` writes.
|
||||
@@ -175,12 +189,18 @@ fn main() -> ExitCode {
|
||||
#[cfg(target_os = "macos")]
|
||||
mac_fonts::install();
|
||||
prefs_dir::install_fonts();
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let mut args: Vec<String> = std::env::args().skip(1).collect();
|
||||
// Before any subcommand attaches the plug-in folder.
|
||||
let safe_mode = args.first().is_some_and(|a| a == "--safe-mode");
|
||||
if safe_mode {
|
||||
args.remove(0);
|
||||
vectorcraft_engine::cmd::plugin::start_in_safe_mode();
|
||||
}
|
||||
let r = match args.first().map(String::as_str) {
|
||||
// `commands` and `info` take no options, so `--help` or `-h` anywhere after them prints the
|
||||
// usage. The other subcommands check for it themselves.
|
||||
Some("commands" | "info") if help_requested(&args[1..], &[]) => help(),
|
||||
Some("mcp") => mcp(&args[1..]),
|
||||
Some("mcp") => mcp(&args[1..], safe_mode),
|
||||
Some("run") => run(&args[1..]),
|
||||
Some("commands") => commands(),
|
||||
Some("convert") => convert(&args[1..]),
|
||||
@@ -213,7 +233,9 @@ fn with_stores(mut h: Headless) -> Headless {
|
||||
h
|
||||
}
|
||||
|
||||
fn mcp(args: &[String]) -> Result<(), String> {
|
||||
/// `mcp`. With `--safe-mode` (`safe_mode`) it serves a headless session: a running app loads its own
|
||||
/// plug-ins, so `--connect` is refused and the default does not connect.
|
||||
fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
|
||||
if help_requested(args, &["--connect", "--automation-read-root", "--automation-write-root"]) {
|
||||
return help();
|
||||
}
|
||||
@@ -240,6 +262,9 @@ fn mcp(args: &[String]) -> Result<(), String> {
|
||||
if headless && connect.is_some() {
|
||||
return Err("use either --connect or --headless".into());
|
||||
}
|
||||
if safe_mode && connect.is_some() {
|
||||
return Err("--safe-mode runs a headless session without plug-ins; a running app loads its own: start it with `vectorcraft --safe-mode --control <port>`".into());
|
||||
}
|
||||
let read: Vec<&Path> = read_roots.iter().map(Path::new).collect();
|
||||
let write: Vec<&Path> = write_roots.iter().map(Path::new).collect();
|
||||
let roots = AutomationRoots::new(&read, &write)?;
|
||||
@@ -252,7 +277,7 @@ fn mcp(args: &[String]) -> Result<(), String> {
|
||||
file_access::confine_process(roots.clone());
|
||||
eprintln!("vectorcraft-cli: files confined: {}", roots.describe());
|
||||
Box::new(Headless::with_document().with_automation_roots(Some(roots)))
|
||||
} else if headless {
|
||||
} else if headless || safe_mode {
|
||||
Box::new(with_stores(Headless::with_document()))
|
||||
} else if let Some(addr) = connect {
|
||||
// Explicit address: fail loudly if the app isn't there.
|
||||
@@ -280,8 +305,20 @@ fn commands() -> Result<(), String> {
|
||||
}
|
||||
|
||||
fn convert(args: &[String]) -> Result<(), String> {
|
||||
let valued =
|
||||
["--scale", "-s", "--ppi", "--artboard", "-a", "--range", "-r", "--decimals", "--ai-version", "--hidden-objects", "--transparent-images"];
|
||||
let valued = [
|
||||
"--scale",
|
||||
"-s",
|
||||
"--ppi",
|
||||
"--artboard",
|
||||
"-a",
|
||||
"--range",
|
||||
"-r",
|
||||
"--decimals",
|
||||
"--ai-version",
|
||||
"--hidden-objects",
|
||||
"--transparent-images",
|
||||
"--legacy-name-encoding",
|
||||
];
|
||||
if help_requested(args, &valued) {
|
||||
return help();
|
||||
}
|
||||
@@ -290,6 +327,9 @@ fn convert(args: &[String]) -> Result<(), String> {
|
||||
(None::<f64>, None::<u64>, None::<String>, false, false, false, false);
|
||||
let mut ppi = None::<f64>;
|
||||
let mut decimals = None::<u64>;
|
||||
// The encoding of a legacy `.ai`'s names that aren't UTF-8, passed on as `document.open`'s
|
||||
// `legacyNameEncoding`; the engine checks it.
|
||||
let mut legacy_names = None::<String>;
|
||||
// Legacy `.ai` options, passed on as the export's own (`aiVersion`, `hiddenObjects`,
|
||||
// `transparentImages`); the engine checks their values.
|
||||
let mut legacy: Vec<(&str, String)> = vec![];
|
||||
@@ -312,6 +352,9 @@ fn convert(args: &[String]) -> Result<(), String> {
|
||||
"--replace-lossy" => replace_lossy = true,
|
||||
"--editing-data" => editing_data = true,
|
||||
"--preserve-editing" => preserve_editing = true,
|
||||
"--legacy-name-encoding" => {
|
||||
legacy_names = Some(it.next().cloned().ok_or("--legacy-name-encoding needs an encoding such as windows-949")?);
|
||||
}
|
||||
"--ai-version" => legacy.push(("aiVersion", it.next().cloned().ok_or("--ai-version needs 7 or pdf")?)),
|
||||
"--hidden-objects" => legacy.push(("hiddenObjects", it.next().cloned().ok_or("--hidden-objects needs layer, omit or visible")?)),
|
||||
"--transparent-images" => legacy.push(("transparentImages", it.next().cloned().ok_or("--transparent-images needs flatten or omit")?)),
|
||||
@@ -324,8 +367,14 @@ fn convert(args: &[String]) -> Result<(), String> {
|
||||
return Err("a .ait template holds every artboard: --artboard and --range don't apply".into());
|
||||
}
|
||||
let mut h = Headless::new();
|
||||
let opened = if editing_data {
|
||||
let params = json!({"path": input, "editingData": "always"});
|
||||
let opened = if editing_data || legacy_names.is_some() {
|
||||
let mut params = json!({"path": input});
|
||||
if editing_data {
|
||||
params["editingData"] = json!("always");
|
||||
}
|
||||
if let Some(e) = &legacy_names {
|
||||
params["legacyNameEncoding"] = json!(e);
|
||||
}
|
||||
h.call("engine.execute", json!({"command": "document.open", "params": params})).map_err(|e| format!("open {input}: {e}"))?
|
||||
} else {
|
||||
h.call("app.open", json!({"path": input})).map_err(|e| format!("open {input}: {e}"))?
|
||||
|
||||
@@ -64,6 +64,61 @@ fn median_ms(runs: usize, mut f: impl FnMut()) -> f64 {
|
||||
v.get(v.len() / 2).copied().unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// Exercise the application's native save/open commands, including previews, PDF output,
|
||||
/// compression and API base64 conversion. Session setup and validation are outside timing.
|
||||
/// Five measured runs follow one warmup; no filesystem or GPU window is involved.
|
||||
fn native_io(doc: &Document) -> Result<(), String> {
|
||||
for (label, compatible, preview) in [
|
||||
("default options", None, false),
|
||||
("PDF disabled", Some(false), false),
|
||||
("preview+gzip", None, true),
|
||||
("preview+gzip, PDF disabled", Some(false), true),
|
||||
] {
|
||||
let mut session = vectorcraft_engine::Session::new();
|
||||
session.add_document(doc.clone(), None);
|
||||
let mut params = json!({"format":"vectorcraft","modified":null,"preview":preview,"compress":preview});
|
||||
if let Some(value) = compatible {
|
||||
params["pdfCompatible"] = json!(value);
|
||||
}
|
||||
let (mut saves, mut opens) = (Vec::new(), Vec::new());
|
||||
let (mut size, mut has_pdf, mut compressed) = (0, false, false);
|
||||
for run in 0..6 {
|
||||
let start = Instant::now();
|
||||
let saved = session.execute("file.saveAs", ¶ms).map_err(|e| e.to_string())?;
|
||||
let save_ms = start.elapsed().as_secs_f64() * 1000.0;
|
||||
let data = saved["dataBase64"].as_str().ok_or("native save returned no dataBase64")?;
|
||||
let bytes = vectorcraft_format::base64_decode(data).ok_or("native save returned invalid base64")?;
|
||||
size = bytes.len();
|
||||
has_pdf = vectorcraft_format::pdf_content(&bytes).is_some();
|
||||
if compatible == Some(false) && has_pdf {
|
||||
return Err("native save ignored the explicit PDF opt-out".into());
|
||||
}
|
||||
compressed = vectorcraft_format::is_compressed(&bytes);
|
||||
if compressed != preview || vectorcraft_format::preview(&bytes).is_some() != preview {
|
||||
return Err("native save did not apply the requested preview/compression options".into());
|
||||
}
|
||||
let args = json!({"name":"perf.vectorcraft","dataBase64":data});
|
||||
let mut opened = vectorcraft_engine::Session::new();
|
||||
let start = Instant::now();
|
||||
opened.execute("document.open", &args).map_err(|e| e.to_string())?;
|
||||
let open_ms = start.elapsed().as_secs_f64() * 1000.0;
|
||||
if opened.doc().map_err(|e| e.to_string())?.doc.artboards.len() != doc.artboards.len() {
|
||||
return Err("native round trip changed the artboard count".into());
|
||||
}
|
||||
if run > 0 {
|
||||
saves.push(save_ms);
|
||||
opens.push(open_ms);
|
||||
}
|
||||
}
|
||||
saves.sort_by(f64::total_cmp);
|
||||
opens.sort_by(f64::total_cmp);
|
||||
let save = saves.get(2).copied().ok_or("no save measurements")?;
|
||||
let open = opens.get(2).copied().ok_or("no open measurements")?;
|
||||
outln!(" native {label}: save {save:.2} ms, open {open:.2} ms, {size} bytes, PDF {has_pdf}, compressed {compressed}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 1-minute load average (macOS / Linux), if available.
|
||||
#[cfg(not(windows))]
|
||||
fn load_average() -> Option<f64> {
|
||||
@@ -393,19 +448,36 @@ fn deep(n: usize) -> Result<(), String> {
|
||||
}
|
||||
|
||||
pub fn run(args: &[String]) -> Result<(), String> {
|
||||
if crate::help_requested(args, &["--paths"]) {
|
||||
if crate::help_requested(args, &["--paths", "--artboards"]) {
|
||||
return crate::help();
|
||||
}
|
||||
let mut n = 50_000usize;
|
||||
let mut want_deep = false;
|
||||
let mut want_native = false;
|
||||
let mut artboards = None::<usize>;
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
match a.as_str() {
|
||||
"--deep" => want_deep = true,
|
||||
"--native-io" => want_native = true,
|
||||
"--artboards" => {
|
||||
artboards =
|
||||
Some(it.next().and_then(|v| v.parse().ok()).filter(|n| (1..=4).contains(n)).ok_or("--artboards needs a number from 1 to 4")?)
|
||||
}
|
||||
"--paths" => n = it.next().and_then(|v| v.parse().ok()).ok_or("--paths needs a number")?,
|
||||
other => return Err(format!("unknown perf option `{other}`")),
|
||||
}
|
||||
}
|
||||
if want_native && n > 50_000 {
|
||||
return Err("--native-io allows at most 50000 paths".into());
|
||||
}
|
||||
if want_native && want_deep {
|
||||
return Err("--native-io and --deep are separate measurement modes".into());
|
||||
}
|
||||
if artboards.is_some() && !want_native {
|
||||
return Err("--artboards requires --native-io".into());
|
||||
}
|
||||
let artboards = artboards.unwrap_or(1);
|
||||
let cores = std::thread::available_parallelism().map_or(1, |c| c.get());
|
||||
// The figure is the 1-minute load average, or on Windows the cores busy over one second.
|
||||
#[cfg(not(windows))]
|
||||
@@ -418,8 +490,20 @@ pub fn run(args: &[String]) -> Result<(), String> {
|
||||
outln!("WARNING: the machine is busy; wall-clock timings below are not trustworthy.");
|
||||
}
|
||||
let t = Instant::now();
|
||||
let doc = synthetic(n)?;
|
||||
let mut doc = synthetic(n)?;
|
||||
outln!(" (built in {:.0} ms)", t.elapsed().as_secs_f64() * 1000.0);
|
||||
if want_native {
|
||||
let first = doc.artboards.first().cloned().ok_or("synthetic document has no artboard")?;
|
||||
// Overlapping artboards intentionally repeat the same paths on every PDF page.
|
||||
for index in 1..artboards {
|
||||
let mut page = first.clone();
|
||||
page.id = first.id.checked_add(index as u32).ok_or("artboard id overflow")?;
|
||||
page.name = format!("Perf {}", index + 1);
|
||||
doc.artboards.push(page);
|
||||
}
|
||||
outln!(" application native I/O: {artboards} overlapping artboard(s), one warmup + five samples; medians; no disk I/O");
|
||||
return native_io(&doc);
|
||||
}
|
||||
|
||||
let mut rows: Vec<(&str, f64, f64)> = vec![];
|
||||
let opts = RenderOptions::default();
|
||||
@@ -513,6 +597,24 @@ pub fn run(args: &[String]) -> Result<(), String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn native_io_exercises_the_application_save_and_open_commands() {
|
||||
native_io(&synthetic(3).unwrap()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_io_rejects_conflicting_modes_and_excessive_workloads() {
|
||||
for (args, expected) in [
|
||||
(vec!["--native-io", "--deep"], "separate measurement modes"),
|
||||
(vec!["--native-io", "--paths", "50001"], "at most 50000"),
|
||||
(vec!["--native-io", "--artboards", "5"], "1 to 4"),
|
||||
(vec!["--artboards", "1"], "requires --native-io"),
|
||||
(vec!["--artboards", "2"], "requires --native-io"),
|
||||
] {
|
||||
assert!(run(&args.into_iter().map(str::to_owned).collect::<Vec<_>>()).unwrap_err().contains(expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn busy_share_leaves_out_idle_time() {
|
||||
// In one second four processors log 40,000,000 ticks of 100 ns of kernel and user time,
|
||||
|
||||
@@ -283,6 +283,22 @@ fn mcp_headless_over_stdio() {
|
||||
assert_eq!(replies[3]["result"]["content"][0]["type"], "image");
|
||||
}
|
||||
|
||||
/// `--safe-mode mcp` serves a headless session without plug-ins: it refuses `--connect`, and by
|
||||
/// default it does not connect to an app listening on the default address, which loads its own
|
||||
/// plug-ins.
|
||||
#[test]
|
||||
fn safe_mode_mcp_does_not_connect_to_a_running_app() {
|
||||
let out = Command::new(BIN).args(["--safe-mode", "mcp", "--connect", "127.0.0.1:9"]).env("VECTORCRAFT_NO_PREFS", "1").output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success() && err.contains("--safe-mode runs a headless session"), "{err}");
|
||||
// Something listening on the default address, as a running app does; a running app or another
|
||||
// program already holding it serves as well.
|
||||
let _app = std::net::TcpListener::bind(vectorcraft_mcp::DEFAULT_ADDR);
|
||||
let out = Command::new(BIN).args(["--safe-mode", "mcp"]).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success() && err.contains("MCP server on stdio (headless)"), "{err}");
|
||||
}
|
||||
|
||||
/// `mcp --automation-read-root` / `--automation-write-root` (#832): the flags are checked before the
|
||||
/// server starts, and the process then reads and writes only inside its roots.
|
||||
#[test]
|
||||
|
||||
@@ -14,7 +14,7 @@ name = "vectorcraft-web"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
vectorcraft-engine = { workspace = true, features = ["bundled-fonts"] }
|
||||
vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] }
|
||||
vectorcraft-ui-egui = { workspace = true }
|
||||
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
|
||||
|
||||
@@ -15,7 +15,7 @@ wgpu = ["eframe/wgpu", "dep:winsafe"]
|
||||
accessibility = ["eframe/accesskit"]
|
||||
|
||||
[dependencies]
|
||||
vectorcraft-engine = { workspace = true, features = ["bundled-fonts"] }
|
||||
vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] }
|
||||
vectorcraft-ui-egui = { workspace = true }
|
||||
vectorcraft-text = { workspace = true }
|
||||
# Shared across the Craft suite: decides who draws the window frame per desktop (compositor vs app)
|
||||
|
||||
@@ -8,6 +8,7 @@ use super::windows_stylus;
|
||||
use super::{App, VectorcraftApp, file_access, window};
|
||||
#[cfg(target_os = "macos")]
|
||||
use super::{mac_menu, mac_window, open_documents};
|
||||
use vectorcraft_ui_egui::dialogs::safe_mode;
|
||||
|
||||
/// The parts of [`App::raw_input_hook`] that every window needs, for the OS windows of floating
|
||||
/// panels: a click or Escape that closes the macOS menu bar's open menu, and the pen barrel
|
||||
@@ -91,6 +92,9 @@ impl eframe::App for App {
|
||||
}
|
||||
fn on_exit(&mut self) {
|
||||
file_access::unconfined(|| save_prefs(&self.app));
|
||||
// A ready update installs once the process has exited. The macOS exit below skips
|
||||
// dropping the app, so the helper is started here.
|
||||
self.app.start_pending_update();
|
||||
end_before_teardown(self.frames);
|
||||
}
|
||||
}
|
||||
@@ -113,16 +117,26 @@ impl App {
|
||||
vectorcraft_ui_egui::background::wait_all(&mut self.app);
|
||||
return;
|
||||
}
|
||||
// An app that stays in Safe Mode leaves later launches to start their own app with plug-ins.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
if safe_mode::staying_on(&self.app) {
|
||||
single_instance::resign();
|
||||
}
|
||||
// Files from the Finder and the Dock (macOS) or from later launches (#4892) wait while a file
|
||||
// dialog is open: what asked for it runs again on its document when it answers.
|
||||
if !self.app.file_dialog_open() {
|
||||
// dialog is open: what asked for it runs again on its document when it answers. They also
|
||||
// wait for the choice about a stopped plug-in, so they open after the plug-ins it loads, as
|
||||
// do the command line's files held back for it. Files later launches handed over before the
|
||||
// choice ended in Safe Mode open in a new app with plug-ins.
|
||||
if !self.app.file_dialog_open() && !safe_mode::choosing(&self.app) {
|
||||
let held = std::mem::take(&mut self.held_files);
|
||||
#[cfg(target_os = "macos")]
|
||||
let files = open_documents::take();
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let files = single_instance::take();
|
||||
let files = single_instance::take_for_frame(safe_mode::staying_on(&self.app), single_instance::launch_with_plug_ins);
|
||||
if !files.is_empty() {
|
||||
bring_window_forward(ctx);
|
||||
}
|
||||
open_files(&mut self.app, held);
|
||||
open_files(&mut self.app, files);
|
||||
}
|
||||
let (now, zoom) = (ctx.input(|i| i.time), ctx.zoom_factor());
|
||||
@@ -151,13 +165,15 @@ impl App {
|
||||
/// On macOS with accessibility, end the process once the app has saved what it keeps on quitting,
|
||||
/// before eframe tears the window down (#661). AccessKit then gives the window's content view back
|
||||
/// its own class, which AppKit's Touch Bar support was observing it under, and AppKit aborts the
|
||||
/// app as it quits on Macs with a Touch Bar. Nothing after the window is needed on a normal quit.
|
||||
/// app as it quits on Macs with a Touch Bar. On a normal quit, only the launch marker is needed
|
||||
/// after the window, so it is ended here as `main` ends it after the window on other platforms.
|
||||
/// Not while the window is still starting up (`frames` below [`gpu::STARTUP_FRAMES`]): a graphics
|
||||
/// failure then starts the app again on another adapter (#651).
|
||||
#[allow(unused_variables)]
|
||||
fn end_before_teardown(frames: u64) {
|
||||
#[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))]
|
||||
if frames >= gpu::STARTUP_FRAMES {
|
||||
safe_mode::end_launch();
|
||||
log::info!("quitting");
|
||||
log::logger().flush();
|
||||
std::process::exit(0);
|
||||
@@ -172,6 +188,16 @@ pub(crate) fn bring_window_forward(ctx: &egui::Context) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
|
||||
}
|
||||
|
||||
/// Open the command line's `files` now, or, while the choice about a stopped plug-in is up
|
||||
/// ([`safe_mode::choosing`]), return them to open once it is made, with the plug-ins it loads.
|
||||
pub(crate) fn open_or_hold(app: &mut VectorcraftApp, files: Vec<String>) -> Vec<String> {
|
||||
if safe_mode::choosing(app) {
|
||||
return files;
|
||||
}
|
||||
open_files(app, files);
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Open files handed to the app (command line, macOS Finder and Dock, later launches) as documents. A file that
|
||||
/// can't be opened is reported to the user and on stderr; the others still open.
|
||||
pub(crate) fn open_files(app: &mut VectorcraftApp, files: Vec<String>) {
|
||||
|
||||
@@ -310,7 +310,7 @@ fn pci_ids(device_id: &str) -> Option<(u32, u32)> {
|
||||
let field = |key: &str| {
|
||||
device_id.split(['\\', '&']).find_map(|part| {
|
||||
let (name, hex) = part.split_at_checked(key.len())?;
|
||||
if name.eq_ignore_ascii_case(key) { u32::from_str_radix(hex, 16).ok() } else { None }
|
||||
if name.eq_ignore_ascii_case(key) && hex.bytes().all(|b| b.is_ascii_hexdigit()) { u32::from_str_radix(hex, 16).ok() } else { None }
|
||||
})
|
||||
};
|
||||
Some((field("VEN_")?, field("DEV_")?))
|
||||
|
||||
@@ -820,3 +820,10 @@ fn crashes_are_forgotten_in_another_version_or_under_another_preference() {
|
||||
assert_eq!(record.crashed.len(), CRASHED_LIMIT);
|
||||
assert_eq!(record.crashed.last().map(|c| c.key.as_str()), Some("Dx12:10de:0013"));
|
||||
}
|
||||
|
||||
/// `u32::from_str_radix` accepts a leading `+`; a device id with one is not a PCI id.
|
||||
#[test]
|
||||
fn pci_ids_reject_a_sign_in_the_hex_digits() {
|
||||
assert_eq!(pci_ids("PCI\\VEN_+10DE&DEV_2204"), None);
|
||||
assert_eq!(pci_ids("PCI\\VEN_10DE&DEV_+2204"), None);
|
||||
}
|
||||
+107
-39
@@ -1,7 +1,10 @@
|
||||
//! VectorCraft desktop app.
|
||||
//!
|
||||
//! Usage: `vectorcraft [--control <port> [--automation-read-root <dir>]... [--automation-write-root <dir>]...]
|
||||
//! [--in-window-menus] [--new-instance] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`)
|
||||
//! [--in-window-menus] [--new-instance] [--safe-mode] [--] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`)
|
||||
//!
|
||||
//! Any other argument starting with '-' (not `-` alone) is an error; after `--`, every argument is
|
||||
//! a file.
|
||||
//!
|
||||
//! Files given while VectorCraft already runs open in that window, unless `--new-instance` is given
|
||||
//! (Windows and Linux; `single_instance`).
|
||||
@@ -65,6 +68,7 @@ mod xwayland;
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_engine::cmd::fileio;
|
||||
use vectorcraft_engine::file_access::{self, AutomationRoots};
|
||||
use vectorcraft_ui_egui::dialogs::safe_mode;
|
||||
use vectorcraft_ui_egui::graphics::GraphicsLoss;
|
||||
use vectorcraft_ui_egui::picks::PickRequest;
|
||||
use vectorcraft_ui_egui::{ClipboardProbeFactory, FilePick, Services, VectorcraftApp};
|
||||
@@ -77,7 +81,7 @@ mod titlebar;
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
use app::bring_window_forward;
|
||||
use app::native_input_hook;
|
||||
use app::open_files;
|
||||
use app::open_or_hold;
|
||||
use host_services::services;
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
use prefs::{KEEP_UI_PREFS, decode_saved_prefs, keep_prefs_copy, prefs_bytes};
|
||||
@@ -92,7 +96,9 @@ use titlebar::custom_titlebar_from;
|
||||
use titlebar::opted_into_system_title_bar;
|
||||
#[cfg(windows)]
|
||||
use titlebar::set_taskbar_icon;
|
||||
use titlebar::{custom_titlebar, native_options};
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
use titlebar::{app_draws_frame, opted_into_app_title_bar, start_frame, system_title_bar_applies};
|
||||
use titlebar::{custom_titlebar, native_options, titlebar_from_env};
|
||||
|
||||
struct App {
|
||||
app: VectorcraftApp,
|
||||
@@ -111,6 +117,8 @@ struct App {
|
||||
pending_maximize: bool,
|
||||
/// Frames left to retry [`window::apply_pending_maximize`].
|
||||
maximize_tries: u8,
|
||||
/// The command line's files, held back until the choice about a stopped plug-in is made.
|
||||
held_files: Vec<String>,
|
||||
/// The time and UI zoom of the last monitor list ([`window::monitors_due`]).
|
||||
monitors_listed: Option<(f64, f32)>,
|
||||
}
|
||||
@@ -132,13 +140,89 @@ Options:
|
||||
(or VECTORCRAFT_IN_WINDOW_MENUS=1)
|
||||
--new-instance Open the files in a new window even when VectorCraft
|
||||
already runs (Windows and Linux)
|
||||
--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
|
||||
--version Print the version and exit
|
||||
-h, --help Print this help and exit
|
||||
-- Treat every argument after it as a file
|
||||
|
||||
Any other argument starting with '-' is an error.
|
||||
|
||||
Without a window (converting, scripting, the MCP server), use vectorcraft-cli:
|
||||
vectorcraft-cli --help
|
||||
";
|
||||
|
||||
/// The command line's options other than the automation roots and the control port.
|
||||
struct CommandLine {
|
||||
files: Vec<String>,
|
||||
in_window_menus: bool,
|
||||
new_instance: bool,
|
||||
/// `--safe-mode`: no plug-in loads or runs in this launch.
|
||||
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.
|
||||
fn read_command_line(
|
||||
mut args: impl Iterator<Item = String>,
|
||||
control: &mut automation_args::ControlArg,
|
||||
roots_args: &mut automation_args::AutomationArgs,
|
||||
) -> 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");
|
||||
let mut new_instance = false;
|
||||
let mut safe_mode = false;
|
||||
let mut unknown = None;
|
||||
while let Some(a) = args.next() {
|
||||
// After `--`, every argument is a file, even one whose name starts with '-'.
|
||||
if a == "--" {
|
||||
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) }) {
|
||||
Ok(true) => continue,
|
||||
Ok(false) => {}
|
||||
Err(e) => {
|
||||
eprintln!("vectorcraft: {e}");
|
||||
return Err(std::process::ExitCode::FAILURE);
|
||||
}
|
||||
}
|
||||
match a.as_str() {
|
||||
"--in-window-menus" => in_window_menus = true,
|
||||
"--new-instance" => new_instance = true,
|
||||
"--safe-mode" => safe_mode = true,
|
||||
"--version" => {
|
||||
println!("vectorcraft {}", env!("CARGO_PKG_VERSION"));
|
||||
return Err(std::process::ExitCode::SUCCESS);
|
||||
}
|
||||
// Before anything starts, like `--version`: from a terminal or an agent's shell the app
|
||||
// used to open (or hang without a display) instead (#2110).
|
||||
"--help" | "-h" => {
|
||||
// Not `print!`, which panics when standard output is closed (`| head -0`):
|
||||
// there is nothing left to tell then.
|
||||
let _ = std::io::Write::write_all(&mut std::io::stdout(), USAGE.as_bytes());
|
||||
return Err(std::process::ExitCode::SUCCESS);
|
||||
}
|
||||
// The process serial number older macOS versions pass to an app the Finder starts.
|
||||
#[cfg(target_os = "macos")]
|
||||
_ if a.starts_with("-psn_") => {}
|
||||
// An option this version doesn't know (a typo such as `--safe-mod`) is an error, not a
|
||||
// file to open. Reported after the loop, so a later `--help` or `--version` still wins.
|
||||
_ if a.starts_with('-') && a != "-" => {
|
||||
unknown.get_or_insert(a);
|
||||
}
|
||||
_ => files.push(a),
|
||||
}
|
||||
}
|
||||
if let Some(a) = unknown {
|
||||
eprintln!("vectorcraft: unknown option {a}; see vectorcraft --help, or put -- before a file whose name starts with '-'");
|
||||
return Err(std::process::ExitCode::FAILURE);
|
||||
}
|
||||
Ok(CommandLine { files, in_window_menus, new_instance, safe_mode })
|
||||
}
|
||||
|
||||
fn main() -> std::process::ExitCode {
|
||||
// Windows: the update helper is a copy of this program started with `--finish-update`.
|
||||
#[cfg(windows)]
|
||||
@@ -154,37 +238,11 @@ 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 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");
|
||||
let mut new_instance = false;
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(a) = args.next() {
|
||||
match roots_args.consume(&a, &mut args).and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) }) {
|
||||
Ok(true) => continue,
|
||||
Ok(false) => {}
|
||||
Err(e) => {
|
||||
eprintln!("vectorcraft: {e}");
|
||||
return std::process::ExitCode::FAILURE;
|
||||
}
|
||||
}
|
||||
match a.as_str() {
|
||||
"--in-window-menus" => in_window_menus = true,
|
||||
"--new-instance" => new_instance = true,
|
||||
"--version" => {
|
||||
println!("vectorcraft {}", env!("CARGO_PKG_VERSION"));
|
||||
return std::process::ExitCode::SUCCESS;
|
||||
}
|
||||
// Before anything starts, like `--version`: from a terminal or an agent's shell the app
|
||||
// used to open (or hang without a display) instead (#2110).
|
||||
"--help" | "-h" => {
|
||||
// Not `print!`, which panics when standard output is closed (`| head -0`):
|
||||
// there is nothing left to tell then.
|
||||
let _ = std::io::Write::write_all(&mut std::io::stdout(), USAGE.as_bytes());
|
||||
return std::process::ExitCode::SUCCESS;
|
||||
}
|
||||
_ => files.push(a),
|
||||
}
|
||||
}
|
||||
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) {
|
||||
Ok(command_line) => command_line,
|
||||
Err(code) => return code,
|
||||
};
|
||||
let automation_args::AutomationArgs { read_roots, write_roots, .. } = roots_args;
|
||||
// After the arguments: `--control` and `--version` win over a bad environment value.
|
||||
let control_port = match control.port {
|
||||
@@ -202,10 +260,10 @@ 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"))]
|
||||
let instance = match single_instance::start(control_port.is_some(), new_instance, &files) {
|
||||
match single_instance::start(control_port.is_some(), new_instance, safe_mode_flag, &files) {
|
||||
single_instance::Start::Forwarded => return std::process::ExitCode::SUCCESS,
|
||||
single_instance::Start::Running(primary) => primary,
|
||||
};
|
||||
single_instance::Start::Running(primary) => single_instance::hold(primary),
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
let _ = new_instance;
|
||||
vectorcraft_ui_egui::i18n::detect_system_lang_in_background();
|
||||
@@ -396,10 +454,15 @@ fn main() -> std::process::ExitCode {
|
||||
let mut session = Session::new();
|
||||
// The profiles loaded before come back before the preferences name any of them.
|
||||
prefs_dir::attach_profile_store(&mut session);
|
||||
// Before any plug-in loads: this launch's marker in the Launch folder next to the
|
||||
// preferences (none for runs without preferences), and Safe Mode.
|
||||
let launch_dir = prefs_path().filter(|_| prefs_enabled()).and_then(|p| Some(p.parent()?.join("Launch")));
|
||||
let stopped = safe_mode::begin_launch(launch_dir.as_deref(), safe_mode_flag);
|
||||
prefs_dir::attach_plugin_store(&mut session);
|
||||
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
|
||||
app.set_startup_update_check(true);
|
||||
load_prefs(&mut app, saved);
|
||||
safe_mode::after_start(&mut app, stopped);
|
||||
// The saved PDF presets live in their own folder (also read by vectorcraft-cli),
|
||||
// which takes over from the copy the preferences file used to hold.
|
||||
prefs_dir::attach_pdf_preset_store(&mut app.session);
|
||||
@@ -466,7 +529,9 @@ fn main() -> std::process::ExitCode {
|
||||
let (loss, ctx) = (graphics_loss.clone(), cc.egui_ctx.clone());
|
||||
rs.device.set_device_lost_callback(move |reason, msg| loss.report(&ctx, format!("{reason:?}: {msg}")));
|
||||
}
|
||||
app.titlebar_from_env = titlebar_from_env();
|
||||
app.custom_titlebar = custom_titlebar;
|
||||
app.desktop_frame = !custom_titlebar;
|
||||
if let Some(port) = control_port {
|
||||
let rx = control_server::start(port, cc.egui_ctx.clone());
|
||||
app = app.with_control(rx).with_automation_roots(roots.clone());
|
||||
@@ -491,7 +556,7 @@ fn main() -> std::process::ExitCode {
|
||||
single_instance::set_ui(&cc.egui_ctx);
|
||||
}
|
||||
app.services.native_input_hook = native_input_hook(&app);
|
||||
file_access::unconfined(|| open_files(&mut app, files));
|
||||
let held_files = file_access::unconfined(|| open_or_hold(&mut app, files));
|
||||
// The first frame is due from now (`gpu::watch_first_frame`).
|
||||
#[cfg(feature = "wgpu")]
|
||||
created.ready();
|
||||
@@ -507,6 +572,7 @@ fn main() -> std::process::ExitCode {
|
||||
winit_window,
|
||||
pending_maximize,
|
||||
maximize_tries: 8,
|
||||
held_files,
|
||||
monitors_listed: None,
|
||||
}))
|
||||
}),
|
||||
@@ -515,7 +581,9 @@ fn main() -> std::process::ExitCode {
|
||||
// The window is gone: later launches start their own app, including the one a graphics
|
||||
// failure starts again below.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
drop(instance);
|
||||
single_instance::resign();
|
||||
// The process ends normally from here: this launch didn't stop while a plug-in was loading.
|
||||
safe_mode::end_launch();
|
||||
#[cfg(feature = "wgpu")]
|
||||
let outcome = gpu::finish(outcome, &startup);
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
|
||||
@@ -168,6 +168,11 @@ fn same_lasting(a: &serde_json::Value, b: &serde_json::Value) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fields that a read fills in from other fields when the file lacks them
|
||||
/// (`vectorcraft_ui_egui::layout_migration`): `help_bar` follows `status_bar`. A save writes them
|
||||
/// whenever the file lacks them, so the next read does not fill them in again from a changed field.
|
||||
const DERIVED: &[&str] = &["help_bar"];
|
||||
|
||||
/// `on_disk` with what changed from `base` to `mine` put over it: each top-level field of the UI
|
||||
/// state, and each engine preference (`engine_prefs`) on its own, so two windows that change
|
||||
/// different settings keep both. A field both changed takes this window's value (it saves last).
|
||||
@@ -219,6 +224,13 @@ fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: se
|
||||
}
|
||||
}
|
||||
}
|
||||
for key in DERIVED {
|
||||
if !out.contains_key(*key)
|
||||
&& let Some(v) = mine.get(*key)
|
||||
{
|
||||
out.insert((*key).to_string(), v.clone());
|
||||
}
|
||||
}
|
||||
if use_mine {
|
||||
match mine.get("action_set") {
|
||||
Some(v) => {
|
||||
@@ -383,6 +395,20 @@ mod tests {
|
||||
assert!(!same_lasting(&base, &mine));
|
||||
}
|
||||
|
||||
/// A file from before the Help Bar setting: the read shows the Help Bar with the status bar.
|
||||
/// After the status bar is hidden and the Help Bar left showing, the save writes `help_bar`,
|
||||
/// so the next read does not hide it with the status bar. A value on disk is kept.
|
||||
#[test]
|
||||
fn a_help_bar_setting_the_file_lacks_is_saved() {
|
||||
let base = json!({"status_bar": true, "help_bar": true});
|
||||
let mine = json!({"status_bar": false, "help_bar": true});
|
||||
let on_disk = json!({"status_bar": true});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"status_bar": false, "help_bar": true}));
|
||||
// Another window saved its own Help Bar setting: it stays.
|
||||
let on_disk = json!({"status_bar": true, "help_bar": false});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"status_bar": false, "help_bar": false}));
|
||||
}
|
||||
|
||||
/// One window deleted the first Actions set and saved; this one made the second set current.
|
||||
/// The saved index follows that set to its place in the merged list.
|
||||
#[test]
|
||||
|
||||
@@ -12,8 +12,12 @@
|
||||
//! as its own app, which replaces a stale file. Nothing received is ever run.
|
||||
//!
|
||||
//! Runs that start many apps side by side (`--control`, `VECTORCRAFT_NO_PREFS`) neither forward
|
||||
//! nor listen, and `--new-instance` opens a launch's files in an app of its own. macOS hands files
|
||||
//! opened from Finder to the running app itself (`open_documents`), so this is off there.
|
||||
//! nor listen, and neither does a `--safe-mode` launch, which opens its files in an app of its own
|
||||
//! and leaves later launches to start theirs with plug-ins. `--new-instance` opens a launch's files
|
||||
//! in an app of its own. An app that stays in Safe Mode after the choice about a stopped plug-in
|
||||
//! stops listening ([`resign`]), and files later launches handed it before then open in a new app
|
||||
//! with plug-ins ([`take_for_frame`]). macOS hands files opened from Finder to the running app itself
|
||||
//! (`open_documents`), so this is off there.
|
||||
|
||||
use std::fs::{self, OpenOptions};
|
||||
use std::hash::{BuildHasher as _, RandomState};
|
||||
@@ -43,6 +47,8 @@ const CLIENT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// Paths handed over by later launches that the UI hasn't opened yet.
|
||||
static PENDING: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
||||
/// This app while it is the one later launches hand their files to ([`hold`]).
|
||||
static HELD: Mutex<Option<Primary>> = Mutex::new(None);
|
||||
/// The UI to wake when files arrive (unset until the window exists; the first frame opens them).
|
||||
static UI: OnceLock<egui::Context> = OnceLock::new();
|
||||
|
||||
@@ -56,23 +62,46 @@ pub enum Start {
|
||||
|
||||
/// Hand `files` to the app already running, or become the app later launches hand theirs to.
|
||||
/// `automation`: started with `--control`.
|
||||
pub fn start(automation: bool, new_instance: bool, files: &[String]) -> Start {
|
||||
pub fn start(automation: bool, new_instance: bool, safe_mode: bool, files: &[String]) -> Start {
|
||||
if automation || !prefs_enabled() {
|
||||
return Start::Running(None);
|
||||
}
|
||||
let Some(path) = prefs_path().and_then(|p| Some(p.parent()?.join(FILE_NAME))) else { return Start::Running(None) };
|
||||
start_at(&path, new_instance, safe_mode, files)
|
||||
}
|
||||
|
||||
/// [`start`] with the endpoint file `path`. A launch with `--new-instance` or `--safe-mode` keeps
|
||||
/// its files and runs as its own app: a running app would open them with its plug-ins loaded. A
|
||||
/// `--safe-mode` launch never becomes the app later launches hand their files to, which would open
|
||||
/// them without plug-ins.
|
||||
fn start_at(path: &Path, new_instance: bool, safe_mode: bool, files: &[String]) -> Start {
|
||||
if safe_mode {
|
||||
return Start::Running(None);
|
||||
}
|
||||
// With nothing to hand over, the same exchange only asks whether an app is running.
|
||||
let send: &[String] = if new_instance { &[] } else { files };
|
||||
match forward(&path, send) {
|
||||
match forward(path, send) {
|
||||
Ok(()) if send.is_empty() => Start::Running(None),
|
||||
Ok(()) => Start::Forwarded,
|
||||
Err(e) => {
|
||||
log::debug!("no running VectorCraft to hand files to ({e})");
|
||||
Start::Running(listen(&path, queue))
|
||||
Start::Running(listen(path, queue))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep `primary` ([`start`]'s) until [`resign`].
|
||||
pub fn hold(primary: Option<Primary>) {
|
||||
*HELD.lock().unwrap_or_else(PoisonError::into_inner) = primary;
|
||||
}
|
||||
|
||||
/// Later launches start their own app from now on: the endpoint file goes. The app calls it when
|
||||
/// its window is gone, and when it stays in Safe Mode after the choice about a stopped plug-in.
|
||||
pub fn resign() {
|
||||
let primary = HELD.lock().unwrap_or_else(PoisonError::into_inner).take();
|
||||
drop(primary);
|
||||
}
|
||||
|
||||
/// Wake `ctx` when files arrive from later launches.
|
||||
pub fn set_ui(ctx: &egui::Context) {
|
||||
// Set once; a second call would hand over the same context.
|
||||
@@ -84,6 +113,43 @@ pub fn take() -> Vec<String> {
|
||||
std::mem::take(&mut *PENDING.lock().unwrap_or_else(PoisonError::into_inner))
|
||||
}
|
||||
|
||||
/// The paths later launches handed over since the last call, to open in this app. An app that
|
||||
/// stays in Safe Mode (`safe_mode`) resigns and hands them to a new app with plug-ins (`launch`,
|
||||
/// [`launch_with_plug_ins`] in the app) instead: they arrived while it was the primary, before the
|
||||
/// choice about a stopped plug-in ended in Safe Mode, or just before it resigned. When `launch`
|
||||
/// fails (logged), they open here.
|
||||
pub fn take_for_frame(safe_mode: bool, launch: impl FnOnce(&[String]) -> io::Result<()>) -> Vec<String> {
|
||||
let files = take();
|
||||
if !safe_mode {
|
||||
return files;
|
||||
}
|
||||
// First, so the new app becomes the primary instead of handing the files back.
|
||||
resign();
|
||||
if files.is_empty() {
|
||||
return files;
|
||||
}
|
||||
match launch(&files) {
|
||||
Ok(()) => Vec::new(),
|
||||
Err(e) => {
|
||||
log::warn!("couldn't start VectorCraft with plug-ins for the files another launch opened: {e}");
|
||||
files
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Start this program again, with plug-ins, on `files`.
|
||||
pub fn launch_with_plug_ins(files: &[String]) -> io::Result<()> {
|
||||
app_with_plug_ins(&std::env::current_exe()?, files).spawn().map(drop)
|
||||
}
|
||||
|
||||
/// The command [`launch_with_plug_ins`] runs: `exe -- files…`, so a file whose name starts with '-'
|
||||
/// stays a file.
|
||||
fn app_with_plug_ins(exe: &Path, files: &[String]) -> std::process::Command {
|
||||
let mut command = std::process::Command::new(exe);
|
||||
command.arg("--").args(files);
|
||||
command
|
||||
}
|
||||
|
||||
fn queue(files: Vec<String>) {
|
||||
PENDING.lock().unwrap_or_else(PoisonError::into_inner).extend(files);
|
||||
if let Some(ctx) = UI.get() {
|
||||
@@ -263,6 +329,13 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Held by the tests that use the process-wide [`HELD`] and [`PENDING`], one at a time.
|
||||
static GLOBALS: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn globals() -> std::sync::MutexGuard<'static, ()> {
|
||||
GLOBALS.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
struct TestDir(tempfile::TempDir);
|
||||
|
||||
impl std::ops::Deref for TestDir {
|
||||
@@ -313,6 +386,72 @@ mod tests {
|
||||
assert!(!path.exists(), "the endpoint file goes with the app");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_instance_or_safe_mode_launch_keeps_its_files() {
|
||||
let (path, _dir, file) = folder("own");
|
||||
let (primary, rx) = primary(&path);
|
||||
for (new_instance, safe_mode) in [(true, false), (false, true)] {
|
||||
let start = start_at(&path, new_instance, safe_mode, std::slice::from_ref(&file));
|
||||
assert!(matches!(start, Start::Running(None)), "runs as its own app (new instance {new_instance}, Safe Mode {safe_mode})");
|
||||
}
|
||||
assert!(matches!(start_at(&path, false, false, std::slice::from_ref(&file)), Start::Forwarded));
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), std::slice::from_ref(&file));
|
||||
assert!(rx.try_recv().is_err(), "only the plain launch handed its file over");
|
||||
drop(primary);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_safe_mode_launch_leaves_later_launches_their_own_app() {
|
||||
let _globals = globals();
|
||||
let (path, _dir, file) = folder("safe-mode-alone");
|
||||
// With no app running, a Safe Mode launch runs without listening.
|
||||
assert!(matches!(start_at(&path, false, true, std::slice::from_ref(&file)), Start::Running(None)));
|
||||
assert!(!path.exists(), "a Safe Mode launch records no endpoint");
|
||||
// A plain launch after it starts its own app and takes later launches' files.
|
||||
let Start::Running(Some(primary)) = start_at(&path, false, false, std::slice::from_ref(&file)) else {
|
||||
panic!("the plain launch runs and listens")
|
||||
};
|
||||
assert!(path.exists());
|
||||
// An app that stays in Safe Mode after the choice gives that up.
|
||||
hold(Some(primary));
|
||||
resign();
|
||||
assert!(!path.exists(), "the endpoint file goes with resign");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_handed_to_an_app_staying_in_safe_mode_go_to_a_new_app_with_plug_ins() {
|
||||
let _globals = globals();
|
||||
// Nothing left over from a test that failed.
|
||||
resign();
|
||||
drop(take());
|
||||
let (path, _dir, file) = folder("safe-mode-later");
|
||||
let Start::Running(Some(primary)) = start_at(&path, false, false, &[]) else { panic!("the first launch listens") };
|
||||
hold(Some(primary));
|
||||
// A later launch handed its file over while the choice about a stopped plug-in was up.
|
||||
queue(vec![file.clone()]);
|
||||
let mut launched = Vec::new();
|
||||
let here = take_for_frame(true, |files| {
|
||||
launched = files.to_vec();
|
||||
Ok(())
|
||||
});
|
||||
assert!(here.is_empty(), "nothing opens in the Safe Mode app");
|
||||
assert_eq!(launched, std::slice::from_ref(&file), "a new app with plug-ins opens it");
|
||||
assert!(!path.exists(), "the app resigned before starting the new one");
|
||||
// When the new app can't start, the file opens here rather than being lost.
|
||||
queue(vec![file.clone()]);
|
||||
assert_eq!(take_for_frame(true, |_| Err(io::Error::other("no program"))), std::slice::from_ref(&file));
|
||||
// An app with plug-ins opens what it is handed.
|
||||
queue(vec![file.clone()]);
|
||||
assert_eq!(take_for_frame(false, |_| panic!("no new app")), [file]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_new_app_takes_every_name_as_a_file() {
|
||||
let command = app_with_plug_ins(Path::new("vectorcraft"), &["-a.svg".to_owned(), "b.svg".to_owned()]);
|
||||
let args: Vec<_> = command.get_args().collect();
|
||||
assert_eq!(args, ["--", "-a.svg", "b.svg"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_token_garbage_and_oversized_messages_are_refused() {
|
||||
let (path, _dir, file) = folder("refused");
|
||||
|
||||
@@ -36,6 +36,33 @@ fn shortcut_overrides_from_an_earlier_version_load() {
|
||||
assert!(km.problems().iter().any(|p| format!("{p:?}") == r#"UnknownCommand { key: "test.unknown" }"#), "reported");
|
||||
}
|
||||
|
||||
/// The command line's files wait for the choice about a stopped plug-in, so they open with the
|
||||
/// plug-ins it loads; with no choice up they open at once.
|
||||
#[test]
|
||||
fn command_line_files_wait_for_the_choice_about_a_stopped_plug_in() {
|
||||
let temp = tempfile::Builder::new().prefix("vectorcraft-held-files-").tempdir().unwrap();
|
||||
let file = temp.path().join("a.svg");
|
||||
std::fs::write(&file, r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>"#).unwrap();
|
||||
let files = vec![file.to_string_lossy().into_owned()];
|
||||
// The files the app reads to open them.
|
||||
let read = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
|
||||
let reads = read.clone();
|
||||
let services = vectorcraft_ui_egui::Services {
|
||||
read: Some(Box::new(move |p: &str| {
|
||||
reads.borrow_mut().push(p.to_owned());
|
||||
std::fs::read(p).map_err(|e| e.to_string())
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), services);
|
||||
app.ui.stopped_plugin = Some(serde_json::json!({"id": "test.held", "name": "Held"}));
|
||||
assert_eq!(open_or_hold(&mut app, files.clone()), files, "held while the choice is up");
|
||||
assert!(read.borrow().is_empty(), "nothing opened before the choice");
|
||||
app.ui.stopped_plugin = None;
|
||||
assert!(open_or_hold(&mut app, files.clone()).is_empty());
|
||||
assert_eq!(*read.borrow(), files, "opened with no choice up");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_files_unminimizes_and_focuses_the_window() {
|
||||
let ctx = egui::Context::default();
|
||||
@@ -164,6 +191,134 @@ fn the_system_title_bar_preference_keeps_the_window_decorations() {
|
||||
assert_eq!(super::native_options(true).viewport.decorations, Some(false));
|
||||
}
|
||||
|
||||
/// Preferences › User Interface › VectorCraft Title Bar on Every Desktop gives the app frame where
|
||||
/// the probe chose the desktop's (KDE, X11, a window opened through XWayland); without it the probe
|
||||
/// decides, and `VECTORCRAFT_TITLEBAR` set to `app`, `system` or `desktop` takes precedence over
|
||||
/// both.
|
||||
#[test]
|
||||
fn the_app_title_bar_preference_gives_the_app_frame_on_desktop_frames() {
|
||||
assert!(!super::opted_into_app_title_bar(None), "no preferences: the default");
|
||||
let off = ui_state_with_prefs(serde_json::json!({"appTitleBar": false}));
|
||||
assert!(!super::opted_into_app_title_bar(Some(&off)));
|
||||
let on = ui_state_with_prefs(serde_json::json!({"appTitleBar": true}));
|
||||
assert!(super::opted_into_app_title_bar(Some(&on)));
|
||||
|
||||
// (probed_app, overridden, forced_to_x11): without the preference, then with it.
|
||||
let cases = [
|
||||
((false, None, false), false, true), // KDE, Sway, X11: the desktop frame
|
||||
((true, None, false), true, true), // GNOME on Wayland: the app frame either way
|
||||
((true, None, true), false, true), // GNOME, the window opened through XWayland
|
||||
((false, Some(true), false), true, true), // VECTORCRAFT_TITLEBAR=app
|
||||
((false, Some(true), true), true, true), // VECTORCRAFT_TITLEBAR=app, the window opened through XWayland
|
||||
((true, Some(false), false), false, false), // VECTORCRAFT_TITLEBAR=desktop takes precedence over the preference
|
||||
((false, Some(false), true), false, false),
|
||||
];
|
||||
for ((probed_app, overridden, forced_to_x11), without, with) in cases {
|
||||
assert_eq!(super::app_draws_frame(probed_app, overridden, forced_to_x11, false), without, "{probed_app} {overridden:?} {forced_to_x11}");
|
||||
assert_eq!(super::app_draws_frame(probed_app, overridden, forced_to_x11, true), with, "{probed_app} {overridden:?} {forced_to_x11}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame a start uses: the preference turns the desktop frame the probe chose into the app frame
|
||||
/// with the default window buttons, a probed app frame keeps its own buttons, and the desktop frame
|
||||
/// stays where the app frame is not drawn. System Title Bar takes precedence over the preference.
|
||||
#[test]
|
||||
fn the_start_frame_applies_the_app_title_bar_preference() {
|
||||
use craft_window::{Button, Frame, Layout};
|
||||
let gnome = Layout { left: vec![Button::Close], right: vec![] };
|
||||
let cases = [
|
||||
// (probed, overridden, forced_to_x11, opted_into_app), expected
|
||||
((Frame::Desktop, None, false, false), Frame::Desktop),
|
||||
((Frame::Desktop, None, false, true), Frame::App(Layout::default())),
|
||||
((Frame::Desktop, None, true, true), Frame::App(Layout::default())),
|
||||
((Frame::App(gnome.clone()), None, false, false), Frame::App(gnome.clone())),
|
||||
((Frame::App(gnome.clone()), None, true, false), Frame::Desktop),
|
||||
((Frame::App(gnome.clone()), None, true, true), Frame::App(gnome.clone())),
|
||||
((Frame::Desktop, Some(false), false, true), Frame::Desktop),
|
||||
((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(gnome.clone())),
|
||||
];
|
||||
for ((probed, overridden, forced_to_x11, opted_into_app), expected) in cases {
|
||||
let label = format!("{probed:?} {overridden:?} {forced_to_x11} {opted_into_app}");
|
||||
assert_eq!(super::start_frame(probed, overridden, forced_to_x11, opted_into_app), expected, "{label}");
|
||||
}
|
||||
// With both preferences on, System Title Bar takes precedence: the desktop draws the frame.
|
||||
let both = super::start_frame(Frame::Desktop, None, false, true);
|
||||
assert!(!super::custom_titlebar_from(&both, true), "System Title Bar takes precedence over the app title bar preference");
|
||||
}
|
||||
|
||||
/// `VECTORCRAFT_TITLEBAR` chooses the frame for the run it is set in, with System Title Bar off and
|
||||
/// on. The saved preference still decides while the variable is unset.
|
||||
#[test]
|
||||
fn the_titlebar_variable_takes_precedence_over_system_title_bar() {
|
||||
use craft_window::Frame;
|
||||
assert!(super::system_title_bar_applies(true, false));
|
||||
assert!(!super::system_title_bar_applies(true, true));
|
||||
assert!(!super::system_title_bar_applies(false, false));
|
||||
assert!(!super::system_title_bar_applies(false, true));
|
||||
// VECTORCRAFT_TITLEBAR=app with System Title Bar on: VectorCraft draws its own title bar.
|
||||
let frame = super::start_frame(Frame::Desktop, Some(true), false, false);
|
||||
assert_eq!(super::custom_titlebar_from(&frame, super::system_title_bar_applies(true, true)), !cfg!(target_os = "macos"));
|
||||
// VECTORCRAFT_TITLEBAR=desktop with System Title Bar off keeps the desktop's frame.
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
{
|
||||
let frame = super::start_frame(Frame::App(craft_window::Layout::default()), Some(false), false, false);
|
||||
assert!(!super::custom_titlebar_from(&frame, super::system_title_bar_applies(false, true)));
|
||||
}
|
||||
}
|
||||
|
||||
/// `VECTORCRAFT_TITLEBAR` read from the environment at startup, with System Title Bar off and on.
|
||||
/// The variable is process-wide and read once, so each value runs in a separate test process.
|
||||
#[test]
|
||||
fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
|
||||
const CHILD: &str = "VECTORCRAFT_TEST_TITLEBAR_CHILD";
|
||||
if std::env::var_os(CHILD).is_none() {
|
||||
for value in ["app", "system", "desktop", "unknown"] {
|
||||
// Linux and the BSDs: hold `spawning` while the child starts, so it does not keep a
|
||||
// copy of a GPU start test's locked start file (see `CHILD_SPAWN`).
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
let spawning = super::spawning();
|
||||
let child = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "tests::the_titlebar_variable_decides_the_frame_before_the_window_opens", "--nocapture"])
|
||||
.env(CHILD, "1")
|
||||
.env("VECTORCRAFT_TITLEBAR", value)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn();
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
drop(spawning);
|
||||
let output = child.unwrap().wait_with_output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"VECTORCRAFT_TITLEBAR={value}\n{}\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let value = std::env::var("VECTORCRAFT_TITLEBAR").unwrap();
|
||||
let not_read = cfg!(any(target_os = "macos", target_os = "windows"));
|
||||
assert_eq!(super::titlebar_from_env(), !not_read && value != "unknown", "VECTORCRAFT_TITLEBAR={value}");
|
||||
let off = ui_state_with_prefs(serde_json::json!({"systemTitleBar": false}));
|
||||
let on = ui_state_with_prefs(serde_json::json!({"systemTitleBar": true}));
|
||||
for (saved, opted_into_system) in [(None, false), (Some(&off), false), (Some(&on), true)] {
|
||||
let custom = super::custom_titlebar(saved);
|
||||
let expected = match value.as_str() {
|
||||
_ if not_read => !cfg!(target_os = "macos") && !opted_into_system,
|
||||
"app" => true,
|
||||
"system" | "desktop" => false,
|
||||
// Not a value the variable takes: System Title Bar decides when it is on. Otherwise the
|
||||
// `craft-window` probe decides, the same with System Title Bar off as with no saved
|
||||
// preferences.
|
||||
_ if opted_into_system => false,
|
||||
_ => super::custom_titlebar(None),
|
||||
};
|
||||
assert_eq!(custom, expected, "{value}, preference {opted_into_system}");
|
||||
assert_eq!(super::native_options(custom).viewport.decorations, Some(!custom), "{value}, preference {opted_into_system}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The file extensions the macOS bundle declares: its document types and its own exported type.
|
||||
fn plist_extensions(plist: &str) -> Vec<&str> {
|
||||
["<key>CFBundleTypeExtensions</key>", "<key>public.filename-extension</key>"]
|
||||
|
||||
@@ -41,11 +41,66 @@ pub(crate) const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos");
|
||||
|
||||
/// Whether the user asked for the system title bar in Preferences › User Interface › System Title
|
||||
/// Bar. Read from the saved preferences before the window opens; a missing or unreadable value is
|
||||
/// `false` (the default). This preference forces the desktop/native frame back on.
|
||||
/// `false` (the default). This preference forces the desktop/native frame back on unless
|
||||
/// `VECTORCRAFT_TITLEBAR` is set to `app`, `system` or `desktop` ([`system_title_bar_applies`]).
|
||||
pub(crate) fn opted_into_system_title_bar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
|
||||
saved.map(|ui| ui.engine_prefs.get("systemTitleBar").and_then(serde_json::Value::as_bool).unwrap_or(false)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the user asked for VectorCraft's own title bar in Preferences › User Interface ›
|
||||
/// VectorCraft Title Bar on Every Desktop (Linux and the BSDs). Read like
|
||||
/// [`opted_into_system_title_bar`]; a missing or unreadable value is `false` (the default).
|
||||
pub(crate) fn opted_into_app_title_bar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
|
||||
saved.map(|ui| ui.engine_prefs.get("appTitleBar").and_then(serde_json::Value::as_bool).unwrap_or(false)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the app draws the frame on this start, before the System Title Bar preference is
|
||||
/// applied ([`custom_titlebar_from`]). `probed_app` is the `craft-window` probe's answer and
|
||||
/// `overridden` its `VECTORCRAFT_TITLEBAR` override. In order: the override decides when the
|
||||
/// variable is set to `app`, `system` or `desktop`;VectorCraft Title Bar on Every Desktop (`opted_into_app`) gives the app frame; a window
|
||||
/// that opens through XWayland (`forced_to_x11`) gets the desktop frame; otherwise the probe
|
||||
/// decides.
|
||||
pub(crate) fn app_draws_frame(probed_app: bool, overridden: Option<bool>, forced_to_x11: bool, opted_into_app: bool) -> bool {
|
||||
match overridden {
|
||||
Some(app) => app,
|
||||
None => opted_into_app || (probed_app && !forced_to_x11),
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame this start uses, before the System Title Bar preference is applied
|
||||
/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. A probed
|
||||
/// app frame keeps its window-button layout; an app frame the probe did not choose gets the default
|
||||
/// layout, since `custom_titlebar_from` reads only which frame it is.
|
||||
pub(crate) fn start_frame(probed: craft_window::Frame, overridden: Option<bool>, forced_to_x11: bool, opted_into_app: bool) -> craft_window::Frame {
|
||||
let probed_app = matches!(probed, craft_window::Frame::App(_));
|
||||
match (app_draws_frame(probed_app, overridden, forced_to_x11, opted_into_app), probed) {
|
||||
(true, frame @ craft_window::Frame::App(_)) => frame,
|
||||
(true, craft_window::Frame::Desktop) => craft_window::Frame::App(craft_window::Layout::default()),
|
||||
(false, _) => craft_window::Frame::Desktop,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `craft-window` probe's answer for this process (its override variable is
|
||||
/// `VECTORCRAFT_TITLEBAR`). The probe runs once; on a Wayland session it opens a connection.
|
||||
fn probed_choice() -> &'static craft_window::Choice {
|
||||
static CHOICE: std::sync::OnceLock<craft_window::Choice> = std::sync::OnceLock::new();
|
||||
CHOICE.get_or_init(|| craft_window::Choice::probe(craft_window::Prefix::new("VECTORCRAFT")))
|
||||
}
|
||||
|
||||
/// Whether `VECTORCRAFT_TITLEBAR` chose this window's frame (Linux and the BSDs), so Preferences ›
|
||||
/// User Interface › System Title Bar and VectorCraft Title Bar on Every Desktop do not apply while
|
||||
/// it is set to `app`, `system` or `desktop`. Always `false` on macOS and Windows.
|
||||
pub(crate) fn titlebar_from_env() -> bool {
|
||||
cfg!(not(any(target_os = "macos", target_os = "windows"))) && probed_choice().overridden().is_some()
|
||||
}
|
||||
|
||||
/// Whether System Title Bar decides this start: `opted_into_system` unless `VECTORCRAFT_TITLEBAR`
|
||||
/// is set to `app`, `system` or `desktop` (`from_env`), which chooses the frame for the run it is
|
||||
/// set in.
|
||||
pub(crate) fn system_title_bar_applies(opted_into_system: bool, from_env: bool) -> bool {
|
||||
opted_into_system && !from_env
|
||||
}
|
||||
|
||||
/// Whether this start draws its own title bar, given the frame the shared `craft-window` crate
|
||||
/// decided and the user's System Title Bar preference.
|
||||
///
|
||||
@@ -53,9 +108,10 @@ pub(crate) fn opted_into_system_title_bar(saved: Option<&vectorcraft_ui_egui::Ui
|
||||
/// ([`craft_window::Frame::Desktop`]) on macOS, Windows, X11 and any Wayland compositor with
|
||||
/// server-side decorations (KDE, Sway, Hyprland, COSMIC); the app draws it
|
||||
/// ([`craft_window::Frame::App`]) only where the compositor leaves it to the app (GNOME's Mutter),
|
||||
/// or when `VECTORCRAFT_TITLEBAR` overrides the probe. VectorCraft draws its own title bar exactly
|
||||
/// or when `VECTORCRAFT_TITLEBAR` set to `app`, `system` or `desktop` overrides the probe. VectorCraft draws its own title bar exactly
|
||||
/// when `craft-window` says the app owns the frame **and** the user has not opted into the system
|
||||
/// title bar; the preference always forces the native frame back on.
|
||||
/// title bar; the preference forces the native frame back on unless `VECTORCRAFT_TITLEBAR` is set
|
||||
/// to one of those values ([`system_title_bar_applies`]).
|
||||
///
|
||||
/// macOS and Windows keep today's behavior and are decided by [`CUSTOM_TITLEBAR`] rather than the
|
||||
/// probe: `craft-window` returns `Frame::Desktop` for both (the OS always draws a frame), but
|
||||
@@ -77,29 +133,34 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
|
||||
|
||||
/// Whether this start draws its own title bar. Probes the shared `craft-window` crate once (its
|
||||
/// override variable is `VECTORCRAFT_TITLEBAR`) and combines its decision with the saved System
|
||||
/// Title Bar preference. Call once at startup, before [`native_options`].
|
||||
/// Title Bar preference, which does not apply while the variable is set to `app`, `system` or
|
||||
/// `desktop`. Call once at startup,
|
||||
/// before [`native_options`].
|
||||
///
|
||||
/// On Linux, Preferences › Performance › Linux Display Server › X11 opens the window through
|
||||
/// XWayland (below). A GNOME/Wayland probe would say `Frame::App` there, but the window really runs
|
||||
/// on X11, whose window manager draws the frame — so when XWayland is being forced, keep the native
|
||||
/// frame, the same as a real X11 session. An explicit `VECTORCRAFT_TITLEBAR` override still wins.
|
||||
/// frame, the same as a real X11 session. A recognized `VECTORCRAFT_TITLEBAR` override still wins,
|
||||
/// and so does VectorCraft Title Bar on Every Desktop ([`app_draws_frame`]).
|
||||
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
|
||||
let choice = craft_window::Choice::probe(craft_window::Prefix::new("VECTORCRAFT"));
|
||||
let opted_into_system = opted_into_system_title_bar(saved);
|
||||
let choice = probed_choice();
|
||||
let opted_into_system = system_title_bar_applies(opted_into_system_title_bar(saved), titlebar_from_env());
|
||||
// macOS and Windows never read VectorCraft Title Bar on Every Desktop (`custom_titlebar_from`
|
||||
// ignores the frame there).
|
||||
let opted_into_app = cfg!(not(any(target_os = "macos", target_os = "windows"))) && opted_into_app_title_bar(saved);
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
// When the window will actually open on X11 (XWayland) — the user asked for it *and* the X11
|
||||
// libraries are present, the same two conditions the launch path checks below — that run is
|
||||
// effectively X11, so keep the native frame. If the libraries are missing, startup stays on
|
||||
// Wayland, so the probe's own decision (app-drawn on GNOME) must stand.
|
||||
let forced_to_x11 = {
|
||||
let pref = saved.and_then(|ui| ui.engine_prefs.get("linuxDisplayServer")).and_then(serde_json::Value::as_str);
|
||||
// `overridden() == None` means the probe decided (no VECTORCRAFT_TITLEBAR). When the window
|
||||
// will actually open on X11 (XWayland) — the user asked for it *and* the X11 libraries are
|
||||
// present, the same two conditions the launch path checks below — that run is effectively
|
||||
// X11, so keep the native frame. If the libraries are missing, startup stays on Wayland, so
|
||||
// the probe's own decision (app-drawn on GNOME) must stand.
|
||||
let forced_to_x11 = xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) && xwayland::x11_libraries_found();
|
||||
if choice.overridden().is_none() && forced_to_x11 {
|
||||
return custom_titlebar_from(&craft_window::Frame::Desktop, opted_into_system);
|
||||
}
|
||||
}
|
||||
custom_titlebar_from(choice.frame(), opted_into_system)
|
||||
xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) && xwayland::x11_libraries_found()
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let forced_to_x11 = false;
|
||||
let frame = start_frame(choice.frame().clone(), choice.overridden(), forced_to_x11, opted_into_app);
|
||||
custom_titlebar_from(&frame, opted_into_system)
|
||||
}
|
||||
|
||||
pub(crate) fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
|
||||
|
||||
@@ -13,6 +13,13 @@
|
||||
//! same undo step as the typing round it. The keypad digits themselves are taken out of the frame,
|
||||
//! so they don't run a shortcut bound to Alt and a digit.
|
||||
//!
|
||||
//! With NumLock off the keypad keys arrive as Insert, End, Down, Page Down, Left, Clear, Right,
|
||||
//! Home, Up and Page Up, and Windows still composes the code from them. They are told from the
|
||||
//! separate navigation keys by the extended-key flag, which only the separate keys set
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/inputdev/about-keyboard-input#extended-key-flag>),
|
||||
//! so with Alt held they count as digits and are taken out of the frame too, rather than moving
|
||||
//! the caret before the character arrives.
|
||||
//!
|
||||
//! egui reports a keypad digit as the same key as the digit above the letters, so the other
|
||||
//! platforms, whose systems have no such convention, can't tell them apart either.
|
||||
|
||||
@@ -28,10 +35,20 @@ const WM_CHAR: u32 = 0x0102;
|
||||
const WM_SYSKEYDOWN: u32 = 0x0104;
|
||||
const WM_SYSKEYUP: u32 = 0x0105;
|
||||
const WM_SYSCHAR: u32 = 0x0106;
|
||||
/// `VK_NUMPAD0` to `VK_NUMPAD9` (`winuser.h`): keypad digits with NumLock on. With it off the keys
|
||||
/// are Insert, End, … and type no code.
|
||||
/// `VK_NUMPAD0` to `VK_NUMPAD9` (`winuser.h`): keypad digits with NumLock on.
|
||||
const VK_NUMPAD0: usize = 0x60;
|
||||
const VK_NUMPAD9: usize = 0x69;
|
||||
/// The keypad's virtual keys with NumLock off, by digit (`winuser.h`): `VK_INSERT`, `VK_END`,
|
||||
/// `VK_DOWN`, `VK_NEXT`, `VK_LEFT`, `VK_CLEAR`, `VK_RIGHT`, `VK_HOME`, `VK_UP` and `VK_PRIOR`.
|
||||
const NUMLOCK_OFF_KEYS: [usize; 10] = [0x2D, 0x23, 0x28, 0x22, 0x25, 0x0C, 0x27, 0x24, 0x26, 0x21];
|
||||
/// The keys egui reports for the keypad with NumLock off, by digit (Clear has no egui key, so it
|
||||
/// comes as the top-row digit key, `Num5`).
|
||||
const NUMLOCK_OFF_EGUI_KEYS: [Key; 10] =
|
||||
[Key::Insert, Key::End, Key::ArrowDown, Key::PageDown, Key::ArrowLeft, Key::Num5, Key::ArrowRight, Key::Home, Key::ArrowUp, Key::PageUp];
|
||||
const DIGIT_KEYS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key::Num4, Key::Num5, Key::Num6, Key::Num7, Key::Num8, Key::Num9];
|
||||
/// Bit 24 of a key message's `lParam`: an extended key, such as the navigation keys beside the
|
||||
/// keypad (the keypad's own keys clear it).
|
||||
const EXTENDED_KEY: isize = 1 << 24;
|
||||
/// `VK_MENU`, `VK_LMENU` and `VK_RMENU`: Alt.
|
||||
const ALT_KEYS: [usize; 3] = [0x12, 0xA4, 0xA5];
|
||||
|
||||
@@ -51,23 +68,42 @@ struct AltCodes {
|
||||
high: Option<u16>,
|
||||
/// Characters the codes typed, for the next frame.
|
||||
typed: String,
|
||||
/// Keypad digit presses and releases with Alt held since the last frame, which egui reports
|
||||
/// as Alt and a digit: taken out of the frame.
|
||||
keypad_events: usize,
|
||||
/// The digits of the keypad presses and releases with Alt held since the last frame, which
|
||||
/// egui reports as Alt and a digit (or, with NumLock off, Alt and a navigation key): taken
|
||||
/// out of the frame.
|
||||
keypad_events: Vec<usize>,
|
||||
}
|
||||
|
||||
/// The digit a keypad key stands for in an Alt code: `wparam` is its virtual-key code and
|
||||
/// `lparam` the message's flags.
|
||||
fn keypad_digit(wparam: usize, lparam: isize) -> Option<usize> {
|
||||
if (VK_NUMPAD0..=VK_NUMPAD9).contains(&wparam) {
|
||||
return Some(wparam - VK_NUMPAD0);
|
||||
}
|
||||
if lparam & EXTENDED_KEY != 0 {
|
||||
return None;
|
||||
}
|
||||
NUMLOCK_OFF_KEYS.iter().position(|&k| k == wparam)
|
||||
}
|
||||
|
||||
impl AltCodes {
|
||||
/// Note a keyboard message `message` with `wparam` (the virtual-key code, or a UTF-16 unit).
|
||||
fn message(&mut self, message: u32, wparam: usize) {
|
||||
let keypad = (VK_NUMPAD0..=VK_NUMPAD9).contains(&wparam);
|
||||
match message {
|
||||
/// Note a keyboard message `message` with `wparam` (the virtual-key code, or a UTF-16 unit)
|
||||
/// and `lparam` (its flags).
|
||||
fn message(&mut self, message: u32, wparam: usize, lparam: isize) {
|
||||
let keypad = match message {
|
||||
WM_SYSKEYDOWN | WM_SYSKEYUP => keypad_digit(wparam, lparam),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(d) = keypad {
|
||||
// Windows sends a key pressed with Alt held as a system key.
|
||||
WM_SYSKEYDOWN if keypad => {
|
||||
if message == WM_SYSKEYDOWN {
|
||||
self.digits += 1;
|
||||
self.keypad_events += 1;
|
||||
self.armed = false;
|
||||
}
|
||||
WM_SYSKEYUP if keypad => self.keypad_events += 1,
|
||||
self.keypad_events.push(d);
|
||||
return;
|
||||
}
|
||||
match message {
|
||||
WM_KEYDOWN | WM_SYSKEYDOWN if ALT_KEYS.contains(&wparam) => {}
|
||||
// Any other key ends the sequence and keeps its own meaning.
|
||||
WM_KEYDOWN | WM_SYSKEYDOWN => self.reset(),
|
||||
@@ -99,14 +135,23 @@ impl AltCodes {
|
||||
/// out the keypad digits typed with Alt held.
|
||||
fn drain(&mut self, events: &mut Vec<Event>) {
|
||||
let mut keypad = std::mem::take(&mut self.keypad_events);
|
||||
if keypad > 0 {
|
||||
if !keypad.is_empty() {
|
||||
events.retain(|e| {
|
||||
let digit = matches!(e, Event::Key { key: Key::Num0 | Key::Num1 | Key::Num2 | Key::Num3 | Key::Num4 | Key::Num5 | Key::Num6 | Key::Num7 | Key::Num8 | Key::Num9, modifiers, .. } if modifiers.alt);
|
||||
if digit && keypad > 0 {
|
||||
keypad -= 1;
|
||||
return false;
|
||||
let Event::Key { key, modifiers, .. } = e else {
|
||||
return true;
|
||||
};
|
||||
if !modifiers.alt {
|
||||
return true;
|
||||
}
|
||||
// The first keypad key still to take out that egui reports as `key`.
|
||||
let stands_for = |d: &usize| DIGIT_KEYS.get(*d) == Some(key) || NUMLOCK_OFF_EGUI_KEYS.get(*d) == Some(key);
|
||||
match keypad.iter().position(stands_for) {
|
||||
Some(i) => {
|
||||
keypad.remove(i);
|
||||
false
|
||||
}
|
||||
None => true,
|
||||
}
|
||||
true
|
||||
});
|
||||
}
|
||||
if !self.typed.is_empty() {
|
||||
@@ -129,7 +174,7 @@ pub fn msg_hook(msg: *const std::ffi::c_void) {
|
||||
if (WM_KEYDOWN..=WM_SYSCHAR).contains(&msg.message) {
|
||||
CODES.with(|c| {
|
||||
if let Ok(mut c) = c.try_borrow_mut() {
|
||||
c.message(msg.message, msg.wParam.0);
|
||||
c.message(msg.message, msg.wParam.0, msg.lParam.0);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -152,14 +197,14 @@ mod tests {
|
||||
|
||||
/// Alt held, keypad digits `code`, Alt released, and the character Windows then posts.
|
||||
fn alt_code(c: &mut AltCodes, code: &str, posted: u16) {
|
||||
c.message(WM_SYSKEYDOWN, ALT);
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
for d in code.bytes() {
|
||||
let vk = VK_NUMPAD0 + usize::from(d - b'0');
|
||||
c.message(WM_SYSKEYDOWN, vk);
|
||||
c.message(WM_SYSKEYUP, vk);
|
||||
c.message(WM_SYSKEYDOWN, vk, 0);
|
||||
c.message(WM_SYSKEYUP, vk, 0);
|
||||
}
|
||||
c.message(WM_KEYUP, ALT);
|
||||
c.message(WM_CHAR, usize::from(posted));
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, usize::from(posted), 0);
|
||||
}
|
||||
|
||||
fn key(key: Key, alt: bool, pressed: bool) -> Event {
|
||||
@@ -186,11 +231,11 @@ mod tests {
|
||||
fn a_character_without_a_code_before_it_is_left_to_winit() {
|
||||
let mut c = AltCodes::default();
|
||||
// A plain key press's character (winit types it), and Alt pressed and released alone.
|
||||
c.message(WM_KEYDOWN, 0x41);
|
||||
c.message(WM_CHAR, usize::from(b'a'));
|
||||
c.message(WM_SYSKEYDOWN, ALT);
|
||||
c.message(WM_KEYUP, ALT);
|
||||
c.message(WM_CHAR, usize::from(b'b'));
|
||||
c.message(WM_KEYDOWN, 0x41, 0);
|
||||
c.message(WM_CHAR, usize::from(b'a'), 0);
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, usize::from(b'b'), 0);
|
||||
let mut events = vec![];
|
||||
c.drain(&mut events);
|
||||
assert!(events.is_empty(), "{events:?}");
|
||||
@@ -199,12 +244,12 @@ mod tests {
|
||||
#[test]
|
||||
fn another_key_while_alt_is_held_cancels_the_code() {
|
||||
let mut c = AltCodes::default();
|
||||
c.message(WM_SYSKEYDOWN, ALT);
|
||||
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1);
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0);
|
||||
// Alt+F: a shortcut, not a code.
|
||||
c.message(WM_SYSKEYDOWN, 0x46);
|
||||
c.message(WM_KEYUP, ALT);
|
||||
c.message(WM_CHAR, 0x41);
|
||||
c.message(WM_SYSKEYDOWN, 0x46, 0);
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, 0x41, 0);
|
||||
let mut events = vec![];
|
||||
c.drain(&mut events);
|
||||
assert!(!events.iter().any(|e| matches!(e, Event::Text(_))), "{events:?}");
|
||||
@@ -213,13 +258,81 @@ mod tests {
|
||||
#[test]
|
||||
fn a_code_above_the_basic_plane_arrives_as_two_halves() {
|
||||
let mut c = AltCodes::default();
|
||||
c.message(WM_SYSKEYDOWN, ALT);
|
||||
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1);
|
||||
c.message(WM_KEYUP, ALT);
|
||||
c.message(WM_CHAR, 0xD83D);
|
||||
c.message(WM_CHAR, 0xDE00);
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0);
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, 0xD83D, 0);
|
||||
c.message(WM_CHAR, 0xDE00, 0);
|
||||
let mut events = vec![];
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events, vec![Event::Text("😀".into())]);
|
||||
}
|
||||
|
||||
/// Alt held, keypad digits `code` with NumLock off (keypad Insert, End, …, flags without the
|
||||
/// extended-key bit), Alt released, and the character Windows then posts.
|
||||
fn alt_code_numlock_off(c: &mut AltCodes, code: &str, posted: u16) {
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
for d in code.bytes() {
|
||||
let vk = NUMLOCK_OFF_KEYS[usize::from(d - b'0')];
|
||||
c.message(WM_SYSKEYDOWN, vk, 0);
|
||||
c.message(WM_SYSKEYUP, vk, 0);
|
||||
}
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, usize::from(posted), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_numlock_off_the_keypad_keys_type_the_code_and_leave_the_caret_alone() {
|
||||
let mut c = AltCodes::default();
|
||||
alt_code_numlock_off(&mut c, "0176", 0xB0);
|
||||
// What egui reports for keypad 0, 1, 7 and 6 with NumLock off and Alt held, a press and a
|
||||
// release each, then a plain Home typed after Alt came up.
|
||||
let mut events = vec![];
|
||||
for k in [Key::Insert, Key::End, Key::Home, Key::ArrowRight] {
|
||||
events.push(key(k, true, true));
|
||||
events.push(key(k, true, false));
|
||||
}
|
||||
events.push(key(Key::Home, false, true));
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events, vec![key(Key::Home, false, true), Event::Text("°".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_numlock_off_keypad_five_counts_too() {
|
||||
let mut c = AltCodes::default();
|
||||
// Keypad 5 is Clear, which egui reports as the top-row 5. 0151 uses Insert, End and Clear;
|
||||
// 0234 uses Insert, Down, Page Down and Left.
|
||||
alt_code_numlock_off(&mut c, "0151", 0x2014);
|
||||
alt_code_numlock_off(&mut c, "0234", 0xEA);
|
||||
let mut events =
|
||||
vec![key(Key::Num5, true, true), key(Key::ArrowDown, true, true), key(Key::PageDown, true, true), key(Key::ArrowLeft, true, true)];
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events, vec![Event::Text("—ê".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_separate_navigation_keys_still_move_the_caret_and_cancel_the_code() {
|
||||
let mut c = AltCodes::default();
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[1], 0);
|
||||
c.message(WM_SYSKEYUP, NUMLOCK_OFF_KEYS[1], 0);
|
||||
// Alt+Home on the separate Home key (extended): a shortcut, not a digit.
|
||||
c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY);
|
||||
c.message(WM_SYSKEYUP, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY);
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, 0x41, 0);
|
||||
let mut events = vec![key(Key::End, true, true), key(Key::End, true, false), key(Key::Home, true, true), key(Key::Home, true, false)];
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events, vec![key(Key::Home, true, true), key(Key::Home, true, false)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numlock_off_keys_without_alt_are_left_alone() {
|
||||
let mut c = AltCodes::default();
|
||||
c.message(WM_KEYDOWN, NUMLOCK_OFF_KEYS[7], 0);
|
||||
c.message(WM_KEYUP, NUMLOCK_OFF_KEYS[7], 0);
|
||||
let mut events = vec![key(Key::Home, false, true), key(Key::Home, false, false)];
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events.len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ 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", "--version", "--help"] {
|
||||
for flag in ["--control", "--automation-read-root", "--automation-write-root", "--in-window-menus", "--safe-mode", "--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.
|
||||
@@ -74,3 +74,27 @@ fn help_prints_usage_and_exits_before_startup() {
|
||||
fn help_wins_over_a_bad_control_port_variable() {
|
||||
prints_usage(&["--help"], &[("VECTORCRAFT_CONTROL_PORT", "abc")]);
|
||||
}
|
||||
|
||||
/// 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]
|
||||
fn an_unknown_option_is_an_error_and_not_a_file() {
|
||||
for args in [&["--safe-mod"][..], &["drawing.svg", "--safe-mod"], &["-x"]] {
|
||||
let out = run(args, &[]);
|
||||
assert!(!out.status.success(), "{args:?}");
|
||||
assert!(out.stdout.is_empty(), "{args:?}");
|
||||
let stderr = String::from_utf8(out.stderr).unwrap();
|
||||
let unknown = args.iter().find(|a| a.starts_with('-')).unwrap();
|
||||
assert_eq!(
|
||||
stderr,
|
||||
format!("vectorcraft: unknown option {unknown}; see vectorcraft --help, or put -- before a file whose name starts with '-'\n"),
|
||||
"{args:?}"
|
||||
);
|
||||
}
|
||||
prints_usage(&["--safe-mod", "--help"], &[]);
|
||||
// After `--`, a name starting with '-' is a file: the run goes on to the control port, which
|
||||
// `run` makes fail.
|
||||
let out = run(&["--", "-x.svg"], &[]);
|
||||
let stderr = String::from_utf8(out.stderr).unwrap();
|
||||
assert!(stderr.contains("VECTORCRAFT_CONTROL_PORT") && !stderr.contains("unknown option"), "{stderr}");
|
||||
}
|
||||
@@ -29,6 +29,14 @@ const MAX_DOCUMENT_CELLS: usize = 1 << 18;
|
||||
/// Points of all strokes' pressure curves together (a stroke style may be shared by many layers).
|
||||
const MAX_DOCUMENT_PRESSURE_POINTS: usize = 1 << 20;
|
||||
|
||||
/// Child references inspected, page rectangles produced, and outline segments retained, in all
|
||||
/// (shared objects are visited once per link, so each visit is charged). Real documents stay
|
||||
/// within a few times [`MAX_NODES`]; this leaves ~30x headroom over that.
|
||||
const MAX_DOCUMENT_WORK: usize = 1 << 24;
|
||||
|
||||
/// Owned layer-name characters kept in all (each visit of a shared object keeps its own copy).
|
||||
const MAX_DOCUMENT_NAME_CHARS: usize = 16 << 20;
|
||||
|
||||
/// What a whole read may still use. Shared objects can be linked from many layers, and embedded
|
||||
/// documents are read with what their embedding document left, so linking or embedding the
|
||||
/// same content many times can't multiply the work.
|
||||
@@ -44,6 +52,10 @@ pub(crate) struct Budget {
|
||||
pub(crate) cells: usize,
|
||||
/// Points of pressure curves ([`MAX_DOCUMENT_PRESSURE_POINTS`] in all).
|
||||
pub(crate) pressure: usize,
|
||||
/// Child references, page rectangles and outline segments ([`MAX_DOCUMENT_WORK`] in all).
|
||||
pub(crate) work: usize,
|
||||
/// Layer-name characters ([`MAX_DOCUMENT_NAME_CHARS`] in all).
|
||||
pub(crate) name_chars: usize,
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
@@ -53,7 +65,15 @@ impl Budget {
|
||||
chars: MAX_DOCUMENT_CHARS,
|
||||
cells: MAX_DOCUMENT_CELLS,
|
||||
pressure: MAX_DOCUMENT_PRESSURE_POINTS,
|
||||
work: MAX_DOCUMENT_WORK,
|
||||
name_chars: MAX_DOCUMENT_NAME_CHARS,
|
||||
};
|
||||
|
||||
/// Take `n` units of work, or fail the read.
|
||||
pub(crate) fn spend(&mut self, n: usize) -> Result<(), Error> {
|
||||
self.work = self.work.checked_sub(n).ok_or(Error::Limit("too much shared geometry or page data"))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a document: archive, `doc.dat` and the model.
|
||||
@@ -192,6 +212,7 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
return Ok(None);
|
||||
}
|
||||
let pages = pages(s, spread);
|
||||
self.budget.spend(pages.len() + 1)?;
|
||||
let default_size = s.floats::<2>(doc, b"DfSz").filter(|[w, h]| *w > 0.0 && *h > 0.0).map(|[w, h]| Rect { x0: 0.0, y0: 0.0, x1: w, y1: h });
|
||||
let bounds = s.floats::<4>(spread, b"SprB").map(rect).or_else(|| pages.iter().copied().reduce(union)).or(default_size).unwrap_or(Rect {
|
||||
x0: 0.0,
|
||||
@@ -214,7 +235,10 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
let s = self.s;
|
||||
let mut out = Vec::new();
|
||||
let mut mask = None;
|
||||
for c in s.objs(parent, b"Chld") {
|
||||
let kids = s.objs(parent, b"Chld");
|
||||
// Invisible masks and skipped children cost no node, so the visit is charged here.
|
||||
self.budget.spend(kids.len())?;
|
||||
for c in kids {
|
||||
if s.is(c, b"MRst") {
|
||||
// A mask layer inside a group or layer masks that container.
|
||||
if s.bool(c, b"Visi") == Some(false) {
|
||||
@@ -254,7 +278,8 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
let world = local.then(parent);
|
||||
let class = s.class(id).unwrap_or(Tag(0));
|
||||
// A layer name is short; a long one is cut, as every visit of a shared object keeps a copy.
|
||||
let name: String = s.str(id, b"Desc").unwrap_or_default().chars().take(MAX_NAME_CHARS).collect();
|
||||
let name: String = s.str(id, b"Desc").unwrap_or_default().chars().take(MAX_NAME_CHARS.min(self.budget.name_chars)).collect();
|
||||
self.budget.name_chars -= name.chars().count();
|
||||
let visible = s.bool(id, b"Visi").unwrap_or(true);
|
||||
let locked = s.bool(id, b"Edtb").is_some_and(|e| !e);
|
||||
let opacity = s.f64(id, b"Opac").map_or(1.0, |o| o.clamp(0.0, 1.0));
|
||||
@@ -312,6 +337,7 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
self.warn(format!("a {} that could not be read", describe(class)));
|
||||
return Ok(Kind::Unsupported);
|
||||
};
|
||||
self.budget.spend(local.subpaths.iter().map(|sp| sp.segments.len() + 1).sum())?;
|
||||
let (fills, strokes) = paint::node_paint(self, id, world);
|
||||
Kind::Shape { path: local.transformed(world), fills, strokes, even_odd }
|
||||
}
|
||||
@@ -645,3 +671,15 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
Kind::Artboard { rect, path: path.transformed(world), even_odd, background, strokes }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod budget_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shared_work_is_bounded() {
|
||||
let mut b = Budget::FULL;
|
||||
assert!(b.spend(MAX_DOCUMENT_WORK).is_ok());
|
||||
assert_eq!(b.spend(1), Err(Error::Limit("too much shared geometry or page data")));
|
||||
}
|
||||
}
|
||||
@@ -238,12 +238,13 @@ pub(crate) fn descriptor(r: &mut Reader, id: ObjId, local: Affine) -> Option<Pai
|
||||
};
|
||||
let grad = s.obj(fill, b"Grad")?;
|
||||
let cols = s.objs(grad, b"Cols");
|
||||
let posn: Vec<Vec<f64>> = match s.field(grad, b"Posn") {
|
||||
Some(Value::Array(a)) => a.iter().filter_map(floats).collect(),
|
||||
_ => Vec::new(),
|
||||
// Convert only the positions that pair with a colour, as shared attributes repeat this per run.
|
||||
let posn: &[Value] = match s.field(grad, b"Posn") {
|
||||
Some(Value::Array(a)) => a,
|
||||
_ => &[],
|
||||
};
|
||||
let mut stops = Vec::new();
|
||||
for (c, p) in cols.iter().zip(&posn).take(MAX_STOPS) {
|
||||
for (c, p) in cols.iter().zip(posn.iter().filter_map(floats)).take(MAX_STOPS) {
|
||||
let color = color(r, *c)?;
|
||||
let offset = p.first().copied().filter(|v| v.is_finite()).unwrap_or(0.0).clamp(0.0, 1.0);
|
||||
let bias = p.get(1).copied().filter(|v| v.is_finite()).unwrap_or(0.5).clamp(0.0, 1.0);
|
||||
|
||||
@@ -195,6 +195,11 @@ fn decode_within(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), worl
|
||||
if let Some(name) = s.entry(bitmap, b"Bckg") {
|
||||
let width = s.int(bitmap, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
|
||||
let height = s.int(bitmap, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
|
||||
// The whole source is decoded for every layer that reads it, so charge it all, not only the crop.
|
||||
let Some(left) = r.budget.pixels.checked_sub(u64::from(width) * u64::from(height)) else {
|
||||
return Err(Error::Limit("embedded image pixels"));
|
||||
};
|
||||
r.budget.pixels = left;
|
||||
match original(r, name).and_then(|bytes| source_pixels(&bytes, width, height)) {
|
||||
Ok(pixels) => Some((width as usize, pixels)),
|
||||
Err(Error::Limit(e)) => return Err(Error::Limit(e)),
|
||||
@@ -318,8 +323,10 @@ fn grid(s: &stream::Stream, bitmap: ObjId, c: usize, bps: usize) -> (usize, usiz
|
||||
let height = s.int(bitmap, b"BmpH").and_then(|v| usize::try_from(v).ok()).unwrap_or(0);
|
||||
let tw = s.int(bitmap, &tag(b"TWi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| width.saturating_mul(bps).div_ceil(TILE));
|
||||
let th = s.int(bitmap, &tag(b"THi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| height.div_ceil(TILE));
|
||||
// A grid larger than the bitmap has tiles no crop can reach: don't convert or scan them on every reference.
|
||||
let tiles = width.saturating_mul(bps).div_ceil(TILE).saturating_mul(height.div_ceil(TILE));
|
||||
let states: Vec<u8> = match s.field(bitmap, &tag(b"Sta", c)) {
|
||||
Some(Value::Array(a)) => a.iter().map(|v| if let Value::UInt(u) = v { u8::try_from(*u).unwrap_or(255) } else { 255 }).collect(),
|
||||
Some(Value::Array(a)) => a.iter().take(tiles).map(|v| if let Value::UInt(u) = v { u8::try_from(*u).unwrap_or(255) } else { 255 }).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
(tw, th, states)
|
||||
|
||||
@@ -51,6 +51,9 @@ const MAX_TABLE_LINES: usize = 4096;
|
||||
/// Cells a table may have (rows × columns): each becomes a text object with its edge lines.
|
||||
const MAX_TABLE_CELLS: usize = 1 << 16;
|
||||
|
||||
/// Work charged for each copy of a run's formatting a table cell keeps.
|
||||
const TABLE_RUN_COST: usize = 16;
|
||||
|
||||
/// A table node (`TxtT`): the grid, the cells' text and the lines on the cell edges.
|
||||
pub(crate) fn table(r: &mut Reader, id: ObjId, world: Affine) -> Option<Table> {
|
||||
let s = r.s;
|
||||
@@ -108,9 +111,10 @@ pub(crate) fn table(r: &mut Reader, id: ObjId, world: Affine) -> Option<Table> {
|
||||
let mut parts = run.text.split(CELL_BREAK).peekable();
|
||||
while let Some(part) = parts.next() {
|
||||
if !part.is_empty() {
|
||||
// Each cell keeps its own copy of the run's formatting, so each copy is charged.
|
||||
match target.and_then(|i| cells.get_mut(i)) {
|
||||
Some(cell) => cell.runs.push(TextRun { text: part.to_string(), ..run.clone() }),
|
||||
None => extra = true,
|
||||
Some(cell) if r.budget.spend(TABLE_RUN_COST).is_ok() => cell.runs.push(TextRun { text: part.to_string(), ..run.clone() }),
|
||||
_ => extra = true,
|
||||
}
|
||||
}
|
||||
if parts.peek().is_some() {
|
||||
@@ -157,6 +161,13 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
|
||||
let mut placeholders = false;
|
||||
let mut attribute_budget = Some(MAX_ATTRIBUTE_BYTES);
|
||||
for block in s.objs(story, b"Blok") {
|
||||
// Shared blocks and run lists are visited once per link, so every visit is charged, empty or not.
|
||||
let paragraph_runs = s.obj(block, b"PAtt").map(|p| s.objs(p, b"Runs")).unwrap_or_default();
|
||||
let attribute_runs = s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default();
|
||||
if r.budget.spend(1 + paragraph_runs.len() + attribute_runs.len()).is_err() {
|
||||
r.warn("text beyond the work one document may hold (truncated)");
|
||||
break;
|
||||
}
|
||||
let Some(glyphs) = s.obj(block, b"Glyp") else {
|
||||
r.warn("a text block without readable characters (left out)");
|
||||
continue;
|
||||
@@ -209,7 +220,7 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
|
||||
// Paragraph formats by end index; a run without an index covers the rest of the block.
|
||||
let mut paragraphs: Vec<(usize, Paragraph)> = Vec::new();
|
||||
let mut open: Option<Paragraph> = None;
|
||||
for run in s.obj(block, b"PAtt").map(|p| s.objs(p, b"Runs")).unwrap_or_default() {
|
||||
for run in paragraph_runs {
|
||||
let Some(attrs) = s.obj(run, b"Item") else { continue };
|
||||
let a = paragraph(r, attrs);
|
||||
first_align.get_or_insert(a.align);
|
||||
@@ -238,7 +249,7 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
|
||||
}
|
||||
};
|
||||
let mut start = 0usize;
|
||||
for run in s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default() {
|
||||
for run in attribute_runs {
|
||||
let Some(index) = s.int(run, b"Indx").and_then(|v| usize::try_from(v).ok()) else {
|
||||
r.warn("invalid text attribute range (bounded; unassigned characters use defaults)");
|
||||
continue;
|
||||
|
||||
@@ -308,6 +308,78 @@ impl Default for DxfOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// A named set of DXF options (the `dxfPreset` param): the options it sets, and the ones a set of
|
||||
/// options matches.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum DxfPreset {
|
||||
/// The options as chosen (the export's defaults for those left out).
|
||||
#[default]
|
||||
Custom,
|
||||
/// For CNC and CAM cutting software: version 2000 (the oldest version that has both lightweight
|
||||
/// polylines and lineweights), 1 mm = 1 unit, 256 indexed colors (all version 2000 holds), Maximize
|
||||
/// Editability with Alter Paths off (every stroke a center line), Outline Text (type as paths),
|
||||
/// and placed images as PNG.
|
||||
Cnc,
|
||||
}
|
||||
|
||||
impl DxfPreset {
|
||||
pub const ALL: [Self; 2] = [Self::Custom, Self::Cnc];
|
||||
|
||||
/// The `dxfPreset` param value.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Custom => "custom",
|
||||
Self::Cnc => "cnc",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Custom => "Custom",
|
||||
Self::Cnc => "CNC / CAM",
|
||||
}
|
||||
}
|
||||
|
||||
/// A preset by id (`custom`, `cnc`), any case.
|
||||
pub fn from_id(s: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|p| s.trim().eq_ignore_ascii_case(p.id()))
|
||||
}
|
||||
|
||||
/// The options the preset sets (Custom: the defaults); the region and crop are the defaults.
|
||||
pub fn options(self) -> DxfOptions {
|
||||
match self {
|
||||
Self::Custom => DxfOptions::default(),
|
||||
Self::Cnc => DxfOptions {
|
||||
version: DxfVersion::R2000,
|
||||
unit: Unit::Millimeters,
|
||||
scale: 1.0,
|
||||
scale_lineweights: false,
|
||||
colors: ColorDepth::Aci256,
|
||||
raster: RasterFormat::Png,
|
||||
preserve: Preserve::Editability,
|
||||
alter_paths: false,
|
||||
outline_text: true,
|
||||
..DxfOptions::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The preset `o` matches: CNC / CAM when every option it sets is as it sets it, else Custom.
|
||||
pub fn of(o: &DxfOptions) -> Self {
|
||||
let c = Self::Cnc.options();
|
||||
let same = o.version == c.version
|
||||
&& o.unit == c.unit
|
||||
&& o.scale == c.scale
|
||||
&& o.scale_lineweights == c.scale_lineweights
|
||||
&& o.colors == c.colors
|
||||
&& o.raster == c.raster
|
||||
&& o.preserve == c.preserve
|
||||
&& o.alter_paths == c.alter_paths
|
||||
&& o.outline_text == c.outline_text;
|
||||
if same { Self::Cnc } else { Self::Custom }
|
||||
}
|
||||
}
|
||||
|
||||
/// An image file a drawing links to, to be written next to it under `name`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DxfImage {
|
||||
|
||||
@@ -1227,10 +1227,10 @@ impl<'a> Scene<'a> {
|
||||
let Some(&first) = run.first() else { continue };
|
||||
let lo = run.iter().map(|g| g.byte).min().unwrap_or(first.byte);
|
||||
let hi = run.iter().map(|g| g.byte + g.len).max().unwrap_or(lo);
|
||||
// A right-to-left paragraph's marker is drawn with its tab first and its number's
|
||||
// period at the number's left; the TEXT entity holds the characters in that order.
|
||||
// A right-to-left paragraph's marker is drawn with its number's period at the
|
||||
// number's left; the TEXT entity holds the characters in that order.
|
||||
let marker = chunk.first().and_then(|(_, _, m)| *m).map(|m| match m.text.strip_suffix('.') {
|
||||
Some(number) if m.tab == m.glyphs.start => format!(".{number}"),
|
||||
Some(number) if layout.glyphs.get(m.tab).is_some_and(|g| g.rtl) => format!(".{number}"),
|
||||
_ => m.text.clone(),
|
||||
});
|
||||
let Some(s) = marker.as_deref().or_else(|| plain.get(lo..hi).map(str::trim_end)).filter(|s| !s.trim().is_empty()) else { continue };
|
||||
|
||||
+45
-4
@@ -823,6 +823,30 @@ fn units_scale_coordinates_and_set_insunits() {
|
||||
assert!(export(&d, &DxfOptions { scale: f64::NAN, ..opts(&d) }).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_strokes_as_lines() {
|
||||
let mut d = text_doc("Cut", 20.0);
|
||||
let layer = d.layers[0].id;
|
||||
let frame = path(&mut d, shapes::rectangle(Rect::new(5.0, 5.0, 195.0, 95.0)), Paint::None, Paint::solid(Color::BLACK), 10.0);
|
||||
d.insert(Some(layer), usize::MAX, frame).unwrap();
|
||||
let o = DxfOptions { region: d.artboards[0].rect, ..DxfPreset::Cnc.options() };
|
||||
let out = export(&d, &o).unwrap();
|
||||
let p = pairs(&out.bytes);
|
||||
assert_eq!(header(&p, "$ACADVER").as_deref(), Some("AC1015"));
|
||||
assert_eq!(header(&p, "$INSUNITS").as_deref(), Some("4"));
|
||||
let k = kinds(&out);
|
||||
assert!(!k.iter().any(|k| matches!(k.as_str(), "TEXT" | "MTEXT" | "IMAGE")), "type is paths: {k:?}");
|
||||
assert!(k.len() > 2, "the glyphs' outlines: {k:?}");
|
||||
// The 10 pt stroke (wider than the widest lineweight) is one center line, not a filled outline.
|
||||
assert_eq!(k.last().map(String::as_str), Some("LWPOLYLINE"), "{k:?}");
|
||||
assert_ne!(k.get(k.len() - 2).map(String::as_str), Some("LWPOLYLINE"), "{k:?}");
|
||||
assert!(out.images.is_empty());
|
||||
assert_eq!(DxfPreset::of(&o), DxfPreset::Cnc);
|
||||
assert_eq!(DxfPreset::of(&DxfOptions { colors: ColorDepth::True, ..o.clone() }), DxfPreset::Custom);
|
||||
assert_eq!(DxfPreset::of(&DxfOptions::default()), DxfPreset::Custom);
|
||||
assert_eq!(DxfPreset::from_id(" CNC "), Some(DxfPreset::Cnc));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_become_dxf_layers() {
|
||||
let mut d = shapes_doc();
|
||||
@@ -1052,15 +1076,15 @@ fn a_bullet_is_text_of_its_own_before_its_paragraph() {
|
||||
|
||||
/// A numbered list paragraph's number and period are a TEXT entity of their own where they are
|
||||
/// drawn, in the order they are drawn: in a right-to-left paragraph the period comes first, at the
|
||||
/// number's left.
|
||||
/// number's left, with the marker aligned left or right.
|
||||
#[test]
|
||||
fn a_number_is_text_of_its_own_before_its_paragraph() {
|
||||
use vectorcraft_doc::text::{NumberStyle, ParaList};
|
||||
let numbered = |text: &str, count: u32| {
|
||||
use vectorcraft_doc::text::{ListAlign, NumberStyle, ParaList};
|
||||
let numbered_aligned = |text: &str, count: u32, align: ListAlign| {
|
||||
let mut d = text_doc(text, 20.0);
|
||||
let id = d.layers[0].children().unwrap()[0].id;
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) {
|
||||
t.para.list = Some(ParaList::numbered(NumberStyle::Arabic));
|
||||
t.para.list = Some(ParaList::numbered(NumberStyle::Arabic).aligned(align));
|
||||
t.para.left_indent = 30.0;
|
||||
t.para.first_line_indent = -30.0;
|
||||
t.list_count = count;
|
||||
@@ -1068,10 +1092,27 @@ fn a_number_is_text_of_its_own_before_its_paragraph() {
|
||||
let out = export(&d, &DxfOptions { version: DxfVersion::R2018, preserve: Preserve::Editability, ..opts(&d) }).unwrap();
|
||||
entities(&out).iter().map(|e| (get(e, 1).map(str::to_string), all(e, 10)[0])).collect::<Vec<_>>()
|
||||
};
|
||||
let numbered = |text: &str, count: u32| numbered_aligned(text, count, ListAlign::Left);
|
||||
assert_eq!(numbered("Item", 11), [(Some("12.".to_string()), 10.0), (Some("Item".to_string()), 40.0)]);
|
||||
let rtl = numbered("שלום", 11);
|
||||
assert_eq!(rtl.iter().map(|(s, _)| s.clone().unwrap_or_default()).collect::<Vec<_>>(), ["שלום", ".12"]);
|
||||
assert!(rtl[1].1 > rtl[0].1, "the number right of the text: {rtl:?}");
|
||||
// Aligned right, the number keeps its order and moves right, against the text.
|
||||
let right = numbered_aligned("Item", 11, ListAlign::Right);
|
||||
assert_eq!((right[0].0.as_deref(), right[1].clone()), (Some("12."), (Some("Item".to_string()), 40.0)));
|
||||
assert!(right[0].1 > 10.0 && right[0].1 < 40.0, "{right:?}");
|
||||
let rtl = numbered_aligned("שלום", 11, ListAlign::Right);
|
||||
assert_eq!(rtl.iter().map(|(s, _)| s.clone().unwrap_or_default()).collect::<Vec<_>>(), ["שלום", ".12"]);
|
||||
// A mixed paragraph: the period follows the paragraph's direction, not the script of the
|
||||
// words it holds, with either alignment.
|
||||
let marker = |text: &str, align: ListAlign| {
|
||||
let out = numbered_aligned(text, 11, align);
|
||||
out.into_iter().filter_map(|(s, _)| s).find(|s| s.contains("12")).unwrap_or_default()
|
||||
};
|
||||
for align in [ListAlign::Left, ListAlign::Right] {
|
||||
assert_eq!(marker("Item שלום", align), "12.", "{align:?}");
|
||||
assert_eq!(marker("שלום Item", align), ".12", "{align:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Area type that Shrink Text to Fit scales down is written at the height it draws at.
|
||||
|
||||
+176
-102
@@ -1,19 +1,26 @@
|
||||
//! "VectorCraft Generic CMYK (SWOP-like)": our own parametric press model.
|
||||
//!
|
||||
//! We can't redistribute Adobe's or ECI's characterisation profiles, so the built-in CMYK space is
|
||||
//! a small physical model instead of an ICC LUT. It is *ours* and only SWOP-*like*: the numbers
|
||||
//! are rounded, typical values for coated web offset, not a measured dataset.
|
||||
//! a small physical model instead of an ICC LUT. It is *ours* and only SWOP-*like*. Two of its
|
||||
//! figures are published values for SWOP printing: the tone value increase of each ink at 40% and
|
||||
//! 50% from CGATS TR 001 (<https://registry.color.org/cmyk-registry/cgats_tr_001>), and the 300%
|
||||
//! total ink limit (<https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications>).
|
||||
//! The paper, solid and overprint colors and the black-generation curve are VectorCraft's own values.
|
||||
//!
|
||||
//! * **Forward (CMYK → XYZ):** each ink's nominal dot area is widened by a parabolic dot-gain
|
||||
//! curve (`a + 4·g·a·(1−a)`, i.e. `g` gain at 50%); the effective areas mix the eight CMY
|
||||
//! Neugebauer primaries with Demichel weights; black is mixed in the same way against
|
||||
//! "primary + K" colours whose optical densities add but saturate towards a maximum density
|
||||
//! (normalised so K on paper is exact), so rich blacks don't multiply to an unrealistic depth.
|
||||
//! * **Forward (CMYK → XYZ):** each ink's nominal dot area `a` is widened by a tone curve
|
||||
//! `a + 4·g·a·(1−a)·(1 + s·(2a−1))` that passes through the TR 001 tone value increase at 50%
|
||||
//! (`g`) and 40% (which sets `s`). The effective areas mix the 16 Neugebauer primaries (paper and
|
||||
//! every solid and overprint of C, M, Y and K, media-relative) with Demichel weights, linearly in
|
||||
//! XYZ, so a single ink's colorimetric tone value increase (Murray–Davies) is the TR 001 value.
|
||||
//! * **Inverse (Lab → CMYK):** damped, bounded Gauss–Newton on the forward model solves CMY for a
|
||||
//! fixed K. Black generation is GCR: solve CMY with K = 0, take the grey component
|
||||
//! `min(C, M, Y)`, map it through the black-generation curve to K, re-solve CMY. Under-colour
|
||||
//! fixed K. Black generation is GCR: solve CMY with K = 0, take the gray component
|
||||
//! `min(C, M, Y)`, add [`BlackGeneration::shortfall`] for each L* point by which that solve stays
|
||||
//! lighter than the target, map the sum through the black curve to K, re-solve CMY. Under-color
|
||||
//! removal enforces the total area coverage (TAC) limit by adding K and re-solving, then scaling
|
||||
//! CMY as a last resort.
|
||||
//! CMY as a last resort. The black point, which source black separates to and which displays as
|
||||
//! black with black-point compensation, is [`BlackGeneration::black_point_k`] black with neutral
|
||||
//! CMY filling the TAC. With compensation, a build darker than it in every XYZ channel also
|
||||
//! displays as black (see [`GenericCmyk::display_xyz`]).
|
||||
//! * **Rendering intents:** colorimetric intents map the source white to paper (relative) or not
|
||||
//! (absolute) and clip; perceptual applies black-point compensation plus soft chroma compression
|
||||
//! against a gamut boundary descriptor (segment maxima of the forward model); saturation keeps
|
||||
@@ -24,50 +31,82 @@ use std::sync::OnceLock;
|
||||
use super::Intent;
|
||||
use super::lab::{D50, Lab, delta_e2000, lab_to_xyz, srgb_to_lab, xyz_to_lab, xyz_to_srgb};
|
||||
|
||||
/// Black generation strength.
|
||||
/// Black generation.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct BlackGeneration {
|
||||
/// Grey component below which no black is generated.
|
||||
pub start: f32,
|
||||
/// Maximum black.
|
||||
pub max_k: f32,
|
||||
/// Curve exponent (>1 = lighter black in the midtones).
|
||||
pub gamma: f32,
|
||||
/// The black curve as `(x, K)` knots with rising `x`, read by linear interpolation. `x` is the
|
||||
/// gray component of the solve without black plus [`Self::shortfall`] per L* point by which
|
||||
/// that solve stays lighter than the target.
|
||||
pub curve: [(f32, f32); 13],
|
||||
/// Added to the gray component for each L* point the black-free solve stays too light.
|
||||
pub shortfall: f32,
|
||||
/// Black of the black point, whose CMY is neutral and fills the TAC.
|
||||
pub black_point_k: f32,
|
||||
}
|
||||
|
||||
/// Parameters of the parametric press model.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GenericCmykParams {
|
||||
pub name: &'static str,
|
||||
/// Paper color (absolute Lab, D50).
|
||||
pub paper: Lab,
|
||||
/// Solid overprints, Demichel order: C, M, CM, Y, CY, MY, CMY.
|
||||
pub solids: [Lab; 7],
|
||||
pub black: Lab,
|
||||
/// Dot gain at 50% per ink (C, M, Y, K).
|
||||
pub dot_gain: [f32; 4],
|
||||
/// Media-relative Lab of the solids and overprints, Demichel order (index `c | m<<1 | y<<2 |
|
||||
/// k<<3`, paper left out): C, M, CM, Y, CY, MY, CMY, then K, CK, MK, CMK, YK, CYK, MYK, CMYK.
|
||||
pub primaries: [Lab; 15],
|
||||
/// Tone value increase at 50% per ink (C, M, Y, K).
|
||||
pub tvi50: [f32; 4],
|
||||
/// Tone value increase at 40% per ink (C, M, Y, K).
|
||||
pub tvi40: [f32; 4],
|
||||
/// Total area coverage limit (sum of inks, 1.0 = 100%).
|
||||
pub tac: f32,
|
||||
pub bg: BlackGeneration,
|
||||
}
|
||||
|
||||
/// Rounded, typical SWOP-like values (not measured data).
|
||||
/// The built-in SWOP-like press: TR 001 tone value increase, a 300% ink limit, and VectorCraft's
|
||||
/// own paper, primaries and black curve.
|
||||
pub fn swop_like() -> GenericCmykParams {
|
||||
GenericCmykParams {
|
||||
name: super::GENERIC_CMYK,
|
||||
paper: Lab::new(93.0, -0.5, 2.5),
|
||||
solids: [
|
||||
Lab::new(55.0, -37.0, -50.0), // C
|
||||
Lab::new(48.0, 74.0, -3.0), // M
|
||||
Lab::new(24.0, 22.0, -46.0), // CM (blue)
|
||||
Lab::new(89.0, -5.0, 93.0), // Y
|
||||
Lab::new(50.0, -65.0, 27.0), // CY (green)
|
||||
Lab::new(47.0, 68.0, 48.0), // MY (red)
|
||||
Lab::new(24.0, 1.0, 0.0), // CMY
|
||||
primaries: [
|
||||
Lab::new(65.7, -42.6, -47.2), // C
|
||||
Lab::new(55.5, 76.2, -9.4), // M
|
||||
Lab::new(31.1, 20.3, -49.7), // CM (blue)
|
||||
Lab::new(96.2, -7.0, 90.1), // Y
|
||||
Lab::new(61.0, -68.4, 30.1), // CY (green)
|
||||
Lab::new(55.0, 69.8, 45.0), // MY (red)
|
||||
Lab::new(28.3, 0.7, -0.5), // CMY
|
||||
Lab::new(21.5, 0.8, -0.9), // K
|
||||
Lab::new(15.9, -8.4, -10.0), // CK
|
||||
Lab::new(14.7, 15.4, -1.0), // MK
|
||||
Lab::new(11.2, 8.9, -6.6), // CMK
|
||||
Lab::new(20.2, -2.4, 12.0), // YK
|
||||
Lab::new(15.7, -14.6, 4.6), // CYK
|
||||
Lab::new(14.5, 11.2, 5.7), // MYK
|
||||
Lab::new(11.0, -0.7, 0.1), // CMYK
|
||||
],
|
||||
black: Lab::new(19.0, 0.5, 0.5),
|
||||
dot_gain: [0.20, 0.20, 0.20, 0.22],
|
||||
tvi50: [0.200, 0.176, 0.168, 0.216],
|
||||
tvi40: [0.200, 0.173, 0.167, 0.219],
|
||||
tac: 3.0,
|
||||
bg: BlackGeneration { start: 0.1, max_k: 0.95, gamma: 1.25 },
|
||||
bg: BlackGeneration {
|
||||
curve: [
|
||||
(0.0, 0.0),
|
||||
(0.25, 0.0),
|
||||
(0.35, 0.006),
|
||||
(0.45, 0.059),
|
||||
(0.55, 0.139),
|
||||
(0.65, 0.23),
|
||||
(0.75, 0.322),
|
||||
(0.85, 0.41),
|
||||
(0.95, 0.511),
|
||||
(1.05, 0.6),
|
||||
(1.2, 0.733),
|
||||
(1.35, 0.858),
|
||||
(1.5, 1.0),
|
||||
],
|
||||
shortfall: 0.03,
|
||||
black_point_k: 0.9,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,11 +122,12 @@ const GBD_H: usize = 72; // 5° bins
|
||||
|
||||
pub struct GenericCmyk {
|
||||
pub params: GenericCmykParams,
|
||||
/// XYZ of the 8 CMY primaries (index = c | m<<1 | y<<2), without and with K.
|
||||
prim: [[f32; 3]; 8],
|
||||
prim_k: [[f32; 3]; 8],
|
||||
/// Media-relative XYZ of the 16 primaries (index = c | m<<1 | y<<2 | k<<3; 0 is paper).
|
||||
prim: [[f32; 3]; 16],
|
||||
/// Shape `s` of each ink's tone curve, from its 40% and 50% tone value increase.
|
||||
skew: [f32; 4],
|
||||
paper_xyz: [f32; 3],
|
||||
/// Media-relative XYZ of the darkest printable black (for black-point compensation).
|
||||
/// Media-relative XYZ of the black point (for black-point compensation).
|
||||
black_rel: [f32; 3],
|
||||
gbd: OnceLock<Gbd>,
|
||||
}
|
||||
@@ -95,37 +135,17 @@ pub struct GenericCmyk {
|
||||
impl GenericCmyk {
|
||||
pub fn new(params: GenericCmykParams) -> Self {
|
||||
let paper_xyz = lab_to_xyz(params.paper);
|
||||
let mut prim = [[0.0f32; 3]; 8];
|
||||
prim[0] = paper_xyz;
|
||||
for (p, lab) in prim[1..].iter_mut().zip(params.solids.iter()) {
|
||||
*p = lab_to_xyz(*lab);
|
||||
let mut prim = [D50; 16];
|
||||
for (p, lab) in prim[1..].iter_mut().zip(params.primaries.iter()) {
|
||||
*p = lab_to_xyz(*lab).map(|v| v.max(1e-6));
|
||||
}
|
||||
let k_xyz = lab_to_xyz(params.black);
|
||||
// Black over other inks: optical densities add, but saturate towards a maximum density
|
||||
// (ink trapping / surface reflection), normalised so that K on paper is exact.
|
||||
const D_MAX: f32 = 2.0;
|
||||
let sat = |d: f32| D_MAX * (1.0 - (-d / D_MAX).exp());
|
||||
let mut prim_k = [[0.0f32; 3]; 8];
|
||||
for i in 0..8 {
|
||||
for ch in 0..3 {
|
||||
let di = -(prim[i][ch] / paper_xyz[ch]).max(1e-6).log10();
|
||||
let dk = -(k_xyz[ch] / paper_xyz[ch]).max(1e-6).log10();
|
||||
let d = sat(di + dk) * dk / sat(dk).max(1e-6);
|
||||
prim_k[i][ch] = paper_xyz[ch] * 10f32.powf(-d.max(di));
|
||||
}
|
||||
}
|
||||
let mut g = Self { params, prim, prim_k, paper_xyz, black_rel: [0.0; 3], gbd: OnceLock::new() };
|
||||
// Darkest black within TAC: search a few rich blacks.
|
||||
let mut best = [1.0f32; 3];
|
||||
for k in [0.8f32, 0.9, 1.0] {
|
||||
let rest = (g.params.tac - k).max(0.0) / 3.0;
|
||||
let cmy = rest.min(1.0);
|
||||
let x = g.to_xyz_rel([cmy, cmy, cmy, k]);
|
||||
if x[1] < best[1] {
|
||||
best = x;
|
||||
}
|
||||
}
|
||||
g.black_rel = best;
|
||||
// The curve's increase at 40% is 0.96·g·(1 − 0.2·s), so `s` follows from the 40% value.
|
||||
let skew = [0, 1, 2, 3].map(|i| {
|
||||
let g = params.tvi50[i];
|
||||
if g > 1e-6 { (1.0 - params.tvi40[i] / (0.96 * g)) / 0.2 } else { 0.0 }
|
||||
});
|
||||
let mut g = Self { params, prim, skew, paper_xyz, black_rel: [0.0; 3], gbd: OnceLock::new() };
|
||||
g.black_rel = g.to_xyz_rel(g.black_point_build());
|
||||
g
|
||||
}
|
||||
|
||||
@@ -133,35 +153,81 @@ impl GenericCmyk {
|
||||
self.params.name
|
||||
}
|
||||
|
||||
fn gain(a: f32, g: f32) -> f32 {
|
||||
let a = a.clamp(0.0, 1.0);
|
||||
(a + 4.0 * g * a * (1.0 - a)).clamp(0.0, 1.0)
|
||||
/// The black point: [`BlackGeneration::black_point_k`] black, with C, M and Y
|
||||
/// chosen so that they fill the TAC and the color is neutral (a* = b* = 0).
|
||||
pub fn black_point_build(&self) -> [f32; 4] {
|
||||
let k = self.params.bg.black_point_k.clamp(0.0, 1.0);
|
||||
let rest = (self.params.tac - k).clamp(0.0, 3.0);
|
||||
let build = |c: f32, m: f32| [c, m, (rest - c - m).clamp(0.0, 1.0), k];
|
||||
let ab = |c: f32, m: f32| {
|
||||
let l = self.to_lab_rel(build(c, m));
|
||||
[l.a, l.b]
|
||||
};
|
||||
let lo = (rest - 2.0).max(0.0);
|
||||
let hi = rest.min(1.0);
|
||||
let (mut c, mut m) = ((rest / 3.0).clamp(lo, hi), (rest / 3.0).clamp(lo, hi));
|
||||
for _ in 0..30 {
|
||||
let r = ab(c, m);
|
||||
if r[0].abs() + r[1].abs() < 1e-4 {
|
||||
break;
|
||||
}
|
||||
let h = 1e-3;
|
||||
let rc = ab(c - h, m);
|
||||
let rm = ab(c, m - h);
|
||||
let j = [[(r[0] - rc[0]) / h, (r[0] - rm[0]) / h], [(r[1] - rc[1]) / h, (r[1] - rm[1]) / h]];
|
||||
let det = j[0][0] * j[1][1] - j[0][1] * j[1][0];
|
||||
if det.abs() < 1e-9 {
|
||||
break;
|
||||
}
|
||||
let dc = (-r[0] * j[1][1] + r[1] * j[0][1]) / det;
|
||||
let dm = (-r[1] * j[0][0] + r[0] * j[1][0]) / det;
|
||||
c = (c + dc.clamp(-0.1, 0.1)).clamp(lo, hi);
|
||||
m = (m + dm.clamp(-0.1, 0.1)).clamp(lo, hi);
|
||||
// Yellow takes the rest, so keep it within 0..1 as well.
|
||||
let y = rest - c - m;
|
||||
if y > 1.0 {
|
||||
c += (y - 1.0) / 2.0;
|
||||
m += (y - 1.0) / 2.0;
|
||||
} else if y < 0.0 {
|
||||
c += y / 2.0;
|
||||
m += y / 2.0;
|
||||
}
|
||||
c = c.clamp(lo, hi);
|
||||
m = m.clamp(lo, hi);
|
||||
}
|
||||
build(c.clamp(lo, hi), m.clamp(lo, hi))
|
||||
}
|
||||
|
||||
/// Effective dot area of ink `i` at nominal area `a`: the TR 001-style tone curve.
|
||||
fn gain(&self, i: usize, a: f32) -> f32 {
|
||||
let a = if a.is_finite() { a.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let g = self.params.tvi50[i];
|
||||
(a + 4.0 * g * a * (1.0 - a) * (1.0 + self.skew[i] * (2.0 * a - 1.0))).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// CMYK (0..1) → absolute XYZ (D50).
|
||||
pub fn to_xyz(&self, cmyk: [f32; 4]) -> [f32; 3] {
|
||||
let dg = self.params.dot_gain;
|
||||
let c = Self::gain(cmyk[0], dg[0]);
|
||||
let m = Self::gain(cmyk[1], dg[1]);
|
||||
let y = Self::gain(cmyk[2], dg[2]);
|
||||
let k = Self::gain(cmyk[3], dg[3]);
|
||||
let mut out = [0.0f32; 3];
|
||||
for i in 0..8 {
|
||||
let w = (if i & 1 != 0 { c } else { 1.0 - c }) * (if i & 2 != 0 { m } else { 1.0 - m }) * (if i & 4 != 0 { y } else { 1.0 - y });
|
||||
if w == 0.0 {
|
||||
continue;
|
||||
}
|
||||
for (ch, o) in out.iter_mut().enumerate() {
|
||||
*o += w * ((1.0 - k) * self.prim[i][ch] + k * self.prim_k[i][ch]);
|
||||
}
|
||||
}
|
||||
out
|
||||
let x = self.to_xyz_rel(cmyk);
|
||||
[x[0] * self.paper_xyz[0] / D50[0], x[1] * self.paper_xyz[1] / D50[1], x[2] * self.paper_xyz[2] / D50[2]]
|
||||
}
|
||||
|
||||
/// Media-relative XYZ (paper = D50 white).
|
||||
pub fn to_xyz_rel(&self, cmyk: [f32; 4]) -> [f32; 3] {
|
||||
let x = self.to_xyz(cmyk);
|
||||
[x[0] * D50[0] / self.paper_xyz[0], x[1] * D50[1] / self.paper_xyz[1], x[2] * D50[2] / self.paper_xyz[2]]
|
||||
let e = [0, 1, 2, 3].map(|i| self.gain(i, cmyk[i]));
|
||||
let mut out = [0.0f32; 3];
|
||||
for (i, p) in self.prim.iter().enumerate() {
|
||||
let mut w = 1.0;
|
||||
for (bit, a) in e.iter().enumerate() {
|
||||
w *= if i & (1 << bit) != 0 { *a } else { 1.0 - a };
|
||||
}
|
||||
if w == 0.0 {
|
||||
continue;
|
||||
}
|
||||
for (o, v) in out.iter_mut().zip(p) {
|
||||
*o += w * v;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn to_lab_rel(&self, cmyk: [f32; 4]) -> Lab {
|
||||
@@ -174,7 +240,9 @@ impl GenericCmyk {
|
||||
/// Display XYZ: media-relative (paper shows as white) or absolute (simulate paper colour).
|
||||
/// With `bpc` (media-relative only) the press black displays as black, undoing the
|
||||
/// compensation [`Self::gamut_map`] applies on the way in, so sRGB black separated to the
|
||||
/// darkest rich black shows as black again.
|
||||
/// black point shows as black again. Each XYZ channel is clamped at 0 on its own, so a build
|
||||
/// darker than the black point in every channel shows as black, and one darker in only some
|
||||
/// channels shows as a colored near-black.
|
||||
pub fn display_xyz(&self, cmyk: [f32; 4], absolute: bool, bpc: bool) -> [f32; 3] {
|
||||
if absolute {
|
||||
return self.to_xyz(cmyk);
|
||||
@@ -192,7 +260,7 @@ impl GenericCmyk {
|
||||
xyz_to_srgb(self.display_xyz(cmyk, absolute, bpc))
|
||||
}
|
||||
|
||||
/// Lab of the darkest printable black (media-relative).
|
||||
/// Lab of the black point (media-relative), see [`Self::black_point_build`].
|
||||
pub fn black_point(&self) -> Lab {
|
||||
xyz_to_lab(self.black_rel)
|
||||
}
|
||||
@@ -283,12 +351,21 @@ impl GenericCmyk {
|
||||
rgb.map(|v| ((1.0 - v - k) / d).clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
fn black_for_grey(&self, grey: f32) -> f32 {
|
||||
let bg = self.params.bg;
|
||||
if grey <= bg.start {
|
||||
return 0.0;
|
||||
/// Black for `x` on the black curve (see [`BlackGeneration::curve`]).
|
||||
fn black_for(&self, x: f32) -> f32 {
|
||||
let curve = &self.params.bg.curve;
|
||||
let mut prev = curve[0];
|
||||
if x <= prev.0 {
|
||||
return prev.1.clamp(0.0, 1.0);
|
||||
}
|
||||
(((grey - bg.start) / (1.0 - bg.start)).clamp(0.0, 1.0).powf(bg.gamma) * bg.max_k).clamp(0.0, 1.0)
|
||||
for &(kx, kk) in &curve[1..] {
|
||||
if x <= kx {
|
||||
let t = if kx > prev.0 { (x - prev.0) / (kx - prev.0) } else { 1.0 };
|
||||
return (prev.1 + (kk - prev.1) * t).clamp(0.0, 1.0);
|
||||
}
|
||||
prev = (kx, kk);
|
||||
}
|
||||
prev.1.clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// Separate a media-relative Lab (already gamut-mapped) into CMYK with GCR/UCR and the TAC limit.
|
||||
@@ -297,13 +374,10 @@ impl GenericCmyk {
|
||||
return [0.0; 4];
|
||||
}
|
||||
let cmy0 = self.solve_cmy(target, 0.0, Self::initial_cmy(target, 0.0));
|
||||
let grey = cmy0[0].min(cmy0[1]).min(cmy0[2]);
|
||||
let mut k = self.black_for_grey(grey);
|
||||
// If CMY alone can't get dark enough, black must carry the rest.
|
||||
let gray = cmy0[0].min(cmy0[1]).min(cmy0[2]);
|
||||
// When CMY alone can't get dark enough, black carries the rest.
|
||||
let l0 = self.to_lab_rel([cmy0[0], cmy0[1], cmy0[2], 0.0]).l;
|
||||
if l0 > target.l + 1.0 {
|
||||
k = k.max(((l0 - target.l) / l0.max(1.0)).clamp(0.0, 1.0));
|
||||
}
|
||||
let mut k = self.black_for(gray + self.params.bg.shortfall * (l0 - target.l).max(0.0));
|
||||
let mut cmy = if k > 0.0 { self.solve_cmy(target, k, Self::initial_cmy(target, k)) } else { cmy0 };
|
||||
// UCR: trade CMY for K until within the TAC limit.
|
||||
for _ in 0..6 {
|
||||
|
||||
@@ -245,8 +245,8 @@ fn loads_system_cmyk_icc() {
|
||||
assert_eq!(c.cmyk_to_srgb([0.0; 4], false).map(|v| (v * 255.0).round() as u8), [255, 255, 255]);
|
||||
}
|
||||
|
||||
/// With black-point compensation, sRGB black separates to the press's darkest black and that black
|
||||
/// displays as black again (hex 000000 -> C67 M67 Y67 K100 -> 000000, not a dark grey).
|
||||
/// With black-point compensation, sRGB black separates to the press's black point and that black
|
||||
/// displays as black again (hex 000000 -> C75 M68 Y67 K90 -> 000000, not a dark gray).
|
||||
#[test]
|
||||
fn generic_cmyk_black_round_trips_with_bpc() {
|
||||
let c = cms();
|
||||
@@ -259,25 +259,104 @@ fn generic_cmyk_black_round_trips_with_bpc() {
|
||||
assert!(raw.iter().all(|v| *v > 0.05), "{raw:?}");
|
||||
}
|
||||
|
||||
/// A color whose solve holds cyan at 0 separates to the same inks when its values change by a few
|
||||
/// float steps: hex ed1e79 with its red stepped one `f32` at a time over 4,001 values (about 0.00024
|
||||
/// in all) stays within 0.001 on every ink.
|
||||
/// Each ink's 40% and 50% tints gain like CGATS TR 001 (SWOP): the colorimetric tone value increase
|
||||
/// (Murray–Davies on X for cyan, Y for magenta and black, Z for yellow) is C 20.0, M 17.6, Y 16.8 and
|
||||
/// K 21.6 points at 50%, and C 20.0, M 17.3, Y 16.7 and K 21.9 points at 40%.
|
||||
#[test]
|
||||
fn generic_cmyk_tints_gain_like_tr001() {
|
||||
let g = generic();
|
||||
let tvi = |ink: usize, a: f32| {
|
||||
let ch = [0, 1, 2, 1][ink];
|
||||
let mut cmyk = [0.0f32; 4];
|
||||
cmyk[ink] = a;
|
||||
let tint = g.to_xyz_rel(cmyk)[ch];
|
||||
cmyk[ink] = 1.0;
|
||||
let solid = g.to_xyz_rel(cmyk)[ch];
|
||||
let paper = g.to_xyz_rel([0.0; 4])[ch];
|
||||
(paper - tint) / (paper - solid) - a
|
||||
};
|
||||
for (ink, (at50, at40)) in [(0.200, 0.200), (0.176, 0.173), (0.168, 0.167), (0.216, 0.219)].into_iter().enumerate() {
|
||||
assert!((tvi(ink, 0.5) - at50).abs() < 0.002, "ink {ink} at 50%: {}", tvi(ink, 0.5));
|
||||
assert!((tvi(ink, 0.4) - at40).abs() < 0.002, "ink {ink} at 40%: {}", tvi(ink, 0.4));
|
||||
}
|
||||
}
|
||||
|
||||
/// More of any ink never makes a Generic CMYK color lighter, in any XYZ channel: on a 10% grid of
|
||||
/// builds within the 300% ink limit, adding 10% of one ink keeps X, Y and Z or lowers them.
|
||||
#[test]
|
||||
fn generic_cmyk_more_ink_is_never_lighter() {
|
||||
let g = generic();
|
||||
let steps = (0..=10).map(|i| i as f32 / 10.0);
|
||||
for c in steps.clone() {
|
||||
for m in steps.clone() {
|
||||
for y in steps.clone() {
|
||||
for k in steps.clone() {
|
||||
let base = [c, m, y, k];
|
||||
if base.iter().sum::<f32>() > 3.0 - 0.1 + 1e-4 {
|
||||
continue;
|
||||
}
|
||||
let x0 = g.to_xyz_rel(base);
|
||||
for ink in 0..4 {
|
||||
if base[ink] >= 1.0 {
|
||||
continue;
|
||||
}
|
||||
let mut more = base;
|
||||
more[ink] += 0.1;
|
||||
let x1 = g.to_xyz_rel(more);
|
||||
assert!((0..3).all(|ch| x1[ch] <= x0[ch] + 1e-5), "{base:?} plus ink {ink}: {x0:?} to {x1:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// sRGB black separates to 90% black under neutral CMY that fills the 300% ink limit, light grays
|
||||
/// carry no black, and black rises steadily from the light end of the gray ramp to the dark end.
|
||||
#[test]
|
||||
fn generic_cmyk_black_generation_follows_the_black_curve() {
|
||||
let c = cms();
|
||||
let black = c.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric);
|
||||
assert!((black[3] - 0.9).abs() < 0.005, "{black:?}");
|
||||
assert!((black.iter().sum::<f32>() - 3.0).abs() < 0.01, "{black:?}");
|
||||
let lab = c.cmyk_to_lab(black);
|
||||
assert!(lab.a.abs() < 0.05 && lab.b.abs() < 0.05, "neutral: {lab:?}");
|
||||
let light = c.srgb_to_cmyk([0.7; 3], Intent::RelativeColorimetric);
|
||||
assert_eq!(light[3], 0.0, "{light:?}");
|
||||
let mut prev = 0.0;
|
||||
for v in (0..=50).rev().map(|i| i as f32 / 50.0) {
|
||||
let k = c.srgb_to_cmyk([v; 3], Intent::RelativeColorimetric)[3];
|
||||
assert!(k >= prev - 1e-4, "gray {v}: K {k} after {prev}");
|
||||
prev = k;
|
||||
}
|
||||
}
|
||||
|
||||
/// A color whose solve holds an ink at a bound separates to the same inks when its values change by
|
||||
/// a few float steps: hex f01482 (cyan held at 0) and hex ed1e79 (magenta held at 100%), each with
|
||||
/// its red stepped one `f32` at a time over 4,001 values (about 0.00024 in all), stay within 0.001
|
||||
/// on every ink.
|
||||
#[test]
|
||||
fn generic_cmyk_separates_nearby_colors_at_the_gamut_edge_alike() {
|
||||
let c = cms();
|
||||
let pink = [237.0f32 / 255.0, 30.0 / 255.0, 121.0 / 255.0];
|
||||
let (mut lo, mut hi) = ([f32::MAX; 4], [f32::MIN; 4]);
|
||||
for step in -2000i32..=2000 {
|
||||
let mut rgb = pink;
|
||||
rgb[0] = f32::from_bits(pink[0].to_bits().wrapping_add_signed(step));
|
||||
let ink = c.srgb_to_cmyk(rgb, Intent::RelativeColorimetric);
|
||||
for i in 0..4 {
|
||||
lo[i] = lo[i].min(ink[i]);
|
||||
hi[i] = hi[i].max(ink[i]);
|
||||
let spread = |pink: [f32; 3]| {
|
||||
let (mut lo, mut hi) = ([f32::MAX; 4], [f32::MIN; 4]);
|
||||
for step in -2000i32..=2000 {
|
||||
let mut rgb = pink;
|
||||
rgb[0] = f32::from_bits(pink[0].to_bits().wrapping_add_signed(step));
|
||||
let ink = c.srgb_to_cmyk(rgb, Intent::RelativeColorimetric);
|
||||
for i in 0..4 {
|
||||
lo[i] = lo[i].min(ink[i]);
|
||||
hi[i] = hi[i].max(ink[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
(lo, hi)
|
||||
};
|
||||
let (lo, hi) = spread([240.0f32 / 255.0, 20.0 / 255.0, 130.0 / 255.0]);
|
||||
assert!((0..4).all(|i| hi[i] - lo[i] < 1e-3), "{lo:?} to {hi:?}");
|
||||
assert_eq!(lo[0], 0.0, "{lo:?}");
|
||||
let (lo, hi) = spread([237.0f32 / 255.0, 30.0 / 255.0, 121.0 / 255.0]);
|
||||
assert!((0..4).all(|i| hi[i] - lo[i] < 1e-3), "{lo:?} to {hi:?}");
|
||||
assert_eq!(hi[1], 1.0, "{hi:?}");
|
||||
}
|
||||
|
||||
/// A color whose solve holds cyan and magenta at 1 separates to the same inks when its values change
|
||||
|
||||
@@ -395,6 +395,15 @@ impl Source {
|
||||
}
|
||||
}
|
||||
|
||||
/// The centers of a `cols` × `rows` grid of cells over `b`, row by row.
|
||||
fn cell_centers(b: Rect, cols: u16, rows: u16) -> impl Iterator<Item = Point> {
|
||||
let (cw, ch) = (b.width() / cols as f64, b.height() / rows as f64);
|
||||
(0..rows as usize * cols as usize).map(move |k| {
|
||||
let (i, j) = (k % cols as usize, k / cols as usize);
|
||||
Point::new(b.x0 + (i as f64 + 0.5) * cw, b.y0 + (j as f64 + 0.5) * ch)
|
||||
})
|
||||
}
|
||||
|
||||
/// A freeform gradient ready to sample ([`Freeform::field`]).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Field {
|
||||
@@ -429,11 +438,7 @@ impl Field {
|
||||
/// Samples at the centres of a `cols` × `rows` grid of cells over `b`, row by row: RGB and
|
||||
/// opacity (as [`Self::sample`]).
|
||||
pub fn grid(&self, b: Rect, cols: u16, rows: u16) -> impl Iterator<Item = ([f32; 3], f32)> + '_ {
|
||||
let (cw, ch) = (b.width() / cols as f64, b.height() / rows as f64);
|
||||
(0..rows as usize * cols as usize).map(move |k| {
|
||||
let (i, j) = (k % cols as usize, k / cols as usize);
|
||||
self.sample(Point::new(b.x0 + (i as f64 + 0.5) * cw, b.y0 + (j as f64 + 0.5) * ch))
|
||||
})
|
||||
cell_centers(b, cols, rows).map(move |p| self.sample(p))
|
||||
}
|
||||
|
||||
/// Display RGB and opacity at `p`.
|
||||
@@ -503,6 +508,27 @@ impl ModelField {
|
||||
};
|
||||
(c, a)
|
||||
}
|
||||
|
||||
/// [`Self::sample`] at the centers of a `cols` × `rows` grid of cells over `b`, row by row.
|
||||
pub fn grid(&self, b: Rect, cols: u16, rows: u16) -> impl Iterator<Item = (Color, f32)> + '_ {
|
||||
cell_centers(b, cols, rows).map(move |p| self.sample(p))
|
||||
}
|
||||
|
||||
/// Display RGB and opacity at `p`: the display color of [`Self::sample`], or the display RGB
|
||||
/// the points mix in when their models differ.
|
||||
pub fn display_sample(&self, p: Point) -> ([f32; 3], f32) {
|
||||
if self.model.is_none() {
|
||||
return self.first.sample(p);
|
||||
}
|
||||
let (c, a) = self.sample(p);
|
||||
(c.to_rgb(), a)
|
||||
}
|
||||
|
||||
/// [`Self::display_sample`] at the centers of a `cols` × `rows` grid of cells over `b`, row by
|
||||
/// row.
|
||||
pub fn display_grid(&self, b: Rect, cols: u16, rows: u16) -> impl Iterator<Item = ([f32; 3], f32)> + '_ {
|
||||
cell_centers(b, cols, rows).map(move |p| self.display_sample(p))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -530,6 +556,22 @@ mod tests {
|
||||
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_model_field_grid_and_display_samples_match_its_sample() {
|
||||
let mut f = two(0.0);
|
||||
(f.points[0].color, f.points[1].color) = (Color::cmyk(1.0, 0.0, 0.0, 0.0), Color::cmyk(0.0, 0.0, 0.0, 1.0));
|
||||
let field = f.model_field(50.0);
|
||||
let b = Rect::new(0.0, 0.0, 100.0, 20.0);
|
||||
let (cells, shown): (Vec<_>, Vec<_>) = (field.grid(b, 5, 1).collect(), field.display_grid(b, 5, 1).collect());
|
||||
let (mid, a) = field.sample(Point::new(50.0, 10.0));
|
||||
assert_eq!(cells[2], (mid, a));
|
||||
assert_eq!(shown[2], (mid.to_rgb(), a));
|
||||
// Points in different models give their display mix.
|
||||
(f.points[0].color, f.points[1].color) = (red(), Color::gray(0.5));
|
||||
let (rgb, _) = f.model_field(50.0).display_sample(Point::new(50.0, 0.0));
|
||||
assert!(close(rgb, [0.75, 0.25, 0.25]), "{rgb:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sample_at_a_point_is_its_colour() {
|
||||
let f = two(0.0);
|
||||
|
||||
+42
-30
@@ -143,38 +143,11 @@ impl Color {
|
||||
}
|
||||
/// HSB with hue in degrees 0..360, saturation and brightness 0..1.
|
||||
pub fn to_hsb(&self) -> [f32; 3] {
|
||||
let [r, g, b] = self.to_rgb();
|
||||
let max = r.max(g).max(b);
|
||||
let min = r.min(g).min(b);
|
||||
let d = max - min;
|
||||
let h = if d <= 0.0 {
|
||||
0.0
|
||||
} else if max == r {
|
||||
60.0 * (((g - b) / d).rem_euclid(6.0))
|
||||
} else if max == g {
|
||||
60.0 * ((b - r) / d + 2.0)
|
||||
} else {
|
||||
60.0 * ((r - g) / d + 4.0)
|
||||
};
|
||||
// f32 rounding in rem_euclid can yield exactly 360; wrap back to 0.
|
||||
let h = if h >= 360.0 { 0.0 } else { h };
|
||||
let s = if max <= 0.0 { 0.0 } else { d / max };
|
||||
[h, s, max]
|
||||
rgb_to_hsb(self.to_rgb())
|
||||
}
|
||||
pub fn from_hsb(h: f32, s: f32, v: f32) -> Self {
|
||||
let h = h.rem_euclid(360.0) / 60.0;
|
||||
let c = v * s;
|
||||
let x = c * (1.0 - (h % 2.0 - 1.0).abs());
|
||||
let (r, g, b) = match h as u32 {
|
||||
0 => (c, x, 0.0),
|
||||
1 => (x, c, 0.0),
|
||||
2 => (0.0, c, x),
|
||||
3 => (0.0, x, c),
|
||||
4 => (x, 0.0, c),
|
||||
_ => (c, 0.0, x),
|
||||
};
|
||||
let m = v - c;
|
||||
Color::Rgb { r: r + m, g: g + m, b: b + m }
|
||||
let [r, g, b] = hsb_to_rgb([h, s, v]);
|
||||
Color::Rgb { r, g, b }
|
||||
}
|
||||
/// `#rrggbb` (display RGB).
|
||||
pub fn to_hex(&self) -> String {
|
||||
@@ -327,6 +300,45 @@ impl Color {
|
||||
}
|
||||
}
|
||||
|
||||
/// HSB (hue in degrees 0..360, saturation and brightness 0..1) of RGB numbers 0..1, with no color
|
||||
/// conversion ([`Color::to_hsb`] reads the display color first).
|
||||
pub fn rgb_to_hsb([r, g, b]: [f32; 3]) -> [f32; 3] {
|
||||
let max = r.max(g).max(b);
|
||||
let min = r.min(g).min(b);
|
||||
let d = max - min;
|
||||
let h = if d <= 0.0 {
|
||||
0.0
|
||||
} else if max == r {
|
||||
60.0 * (((g - b) / d).rem_euclid(6.0))
|
||||
} else if max == g {
|
||||
60.0 * ((b - r) / d + 2.0)
|
||||
} else {
|
||||
60.0 * ((r - g) / d + 4.0)
|
||||
};
|
||||
// f32 rounding in rem_euclid can yield exactly 360; wrap back to 0.
|
||||
let h = if h >= 360.0 { 0.0 } else { h };
|
||||
let s = if max <= 0.0 { 0.0 } else { d / max };
|
||||
[h, s, max]
|
||||
}
|
||||
|
||||
/// RGB numbers 0..1 of HSB `[h, s, v]` (hue in degrees, saturation and brightness 0..1): the inverse
|
||||
/// of [`rgb_to_hsb`].
|
||||
pub fn hsb_to_rgb([h, s, v]: [f32; 3]) -> [f32; 3] {
|
||||
let h = h.rem_euclid(360.0) / 60.0;
|
||||
let c = v * s;
|
||||
let x = c * (1.0 - (h % 2.0 - 1.0).abs());
|
||||
let (r, g, b) = match h as u32 {
|
||||
0 => (c, x, 0.0),
|
||||
1 => (x, c, 0.0),
|
||||
2 => (0.0, c, x),
|
||||
3 => (0.0, x, c),
|
||||
4 => (x, 0.0, c),
|
||||
_ => (c, 0.0, x),
|
||||
};
|
||||
let m = v - c;
|
||||
[r + m, g + m, b + m]
|
||||
}
|
||||
|
||||
/// `new` expressed in the colour model of `orig` ([`Color::in_model`]): results of colour operations
|
||||
/// (harmonies, blends, inversions, recolouring) keep the model of the colour they came from.
|
||||
pub fn keep_model(orig: Color, new: Color) -> Color {
|
||||
|
||||
@@ -296,6 +296,28 @@ impl Appearance {
|
||||
scale(e, s);
|
||||
}
|
||||
}
|
||||
/// The id of Effect › SVG Filters' effect, whose `origin` parameter is a point of the document.
|
||||
pub const SVG_FILTER: &str = "svg.filter";
|
||||
|
||||
/// Does any effect (the object's or a fill's or stroke's) hold an SVG filter?
|
||||
pub fn has_svg_filter(&self) -> bool {
|
||||
self.effects.iter().chain(self.items.iter().flat_map(|i| i.effects().iter())).any(|e| e.id == Self::SVG_FILTER)
|
||||
}
|
||||
|
||||
/// Move the `origin` of every SVG filter effect (where its user space starts in the document)
|
||||
/// by `a`, as the object it is on moves.
|
||||
pub fn transform_svg_filters(&mut self, a: kurbo::Affine) {
|
||||
let items = self.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut());
|
||||
for e in self.effects.iter_mut().chain(items).filter(|e| e.id == Self::SVG_FILTER) {
|
||||
let at =
|
||||
|i: usize| e.params.get("origin").and_then(|o| o.get(i)).and_then(serde_json::Value::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0);
|
||||
let p = a * kurbo::Point::new(at(0), at(1));
|
||||
if p.x.is_finite() && p.y.is_finite() && e.params.is_object() {
|
||||
e.params["origin"] = serde_json::json!([p.x, p.y]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gradient paints of the fills and strokes.
|
||||
fn gradients_mut(&mut self) -> impl Iterator<Item = &mut vectorcraft_color::GradientPaint> {
|
||||
self.items.iter_mut().filter_map(|i| match i {
|
||||
@@ -354,6 +376,11 @@ impl Appearance {
|
||||
pub fn has_placed_gradient(&self) -> bool {
|
||||
self.has_gradient(true)
|
||||
}
|
||||
/// Does a fill or stroke carry a gradient that is drawn at a place in document space: a placed
|
||||
/// one, or a freeform gradient with points of its own whose vector is fitted to the bounds?
|
||||
pub fn has_positioned_gradient(&self) -> bool {
|
||||
self.gradients().any(|g| g.is_placed() || g.has_freeform_points())
|
||||
}
|
||||
/// Fix unplaced gradients to their fit on `bounds` (the object's geometric bounds; strokes fit
|
||||
/// the stroke-inflated box), so they can follow transforms that refitting wouldn't reproduce.
|
||||
pub fn pin_gradients(&mut self, bounds: vectorcraft_geom::Rect) {
|
||||
|
||||
@@ -106,6 +106,60 @@ impl super::Document {
|
||||
d.layers.insert(0, Arc::new(layer));
|
||||
Some(d)
|
||||
}
|
||||
|
||||
/// Where an artboard the size of artboard `i` goes on `side` of it, [`ARTBOARD_GAP`] away,
|
||||
/// when there is room for it there: every side within [`crate::MAX_COORD`] of the origin and
|
||||
/// no other artboard overlapping it (touching edges don't overlap). `None` when there is no
|
||||
/// such artboard or no room.
|
||||
pub fn room_beside_artboard(&self, i: usize, side: ArtboardSide) -> Option<Rect> {
|
||||
let src = self.artboards.get(i)?.rect;
|
||||
let r = src + side.offset(src);
|
||||
let in_canvas = [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= crate::MAX_COORD);
|
||||
let clear = self.artboards.iter().all(|a| !(r.x0 < a.rect.x1 && a.rect.x0 < r.x1 && r.y0 < a.rect.y1 && a.rect.y0 < r.y1));
|
||||
(in_canvas && clear).then_some(r)
|
||||
}
|
||||
}
|
||||
|
||||
/// The space between an artboard and one added or duplicated beside it (VectorCraft's own value,
|
||||
/// the space New Artboard and Duplicate Artboards leave right of the last artboard).
|
||||
pub const ARTBOARD_GAP: f64 = 20.0;
|
||||
|
||||
/// A side of an artboard, where an artboard added or duplicated beside it goes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ArtboardSide {
|
||||
Left,
|
||||
Right,
|
||||
Top,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
impl ArtboardSide {
|
||||
pub const ALL: [Self; 4] = [Self::Top, Self::Right, Self::Bottom, Self::Left];
|
||||
|
||||
/// The side a command's `side` param names: "left", "right", "top" or "bottom".
|
||||
pub fn parse(name: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|s| s.name() == name)
|
||||
}
|
||||
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Left => "left",
|
||||
Self::Right => "right",
|
||||
Self::Top => "top",
|
||||
Self::Bottom => "bottom",
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a copy of `r` moves to sit on this side of it, [`ARTBOARD_GAP`] away (y down).
|
||||
pub fn offset(self, r: Rect) -> vectorcraft_geom::Vec2 {
|
||||
let (w, h) = (r.width() + ARTBOARD_GAP, r.height() + ARTBOARD_GAP);
|
||||
match self {
|
||||
Self::Left => vectorcraft_geom::Vec2::new(-w, 0.0),
|
||||
Self::Right => vectorcraft_geom::Vec2::new(w, 0.0),
|
||||
Self::Top => vectorcraft_geom::Vec2::new(0.0, -h),
|
||||
Self::Bottom => vectorcraft_geom::Vec2::new(0.0, h),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A document's locked artboards ([`Document::locked_artboards`]).
|
||||
|
||||
@@ -11,12 +11,16 @@ use serde::{Deserialize, Serialize};
|
||||
use crate::{Document, NodeId};
|
||||
|
||||
/// One asset: what it is called (its files' names) and the objects it exports, cropped to their
|
||||
/// visual bounds.
|
||||
/// visual bounds, or for a 3D asset its object's solids as a mesh file.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ExportAsset {
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
pub nodes: Vec<NodeId>,
|
||||
/// A 3D asset's mesh format (`usda`, `usdz`, `gltf` or `obj`): its object exports as a 3D
|
||||
/// file. `None` for art exported as pictures.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub format_3d: Option<String>,
|
||||
}
|
||||
|
||||
/// What the assets are named when they aren't named after their object: `Asset 1`, `Asset 2`…
|
||||
@@ -30,7 +34,16 @@ impl Document {
|
||||
|
||||
/// The name of the next unnamed asset: one more than the highest `Asset N` so far.
|
||||
pub fn next_asset_name(&self) -> String {
|
||||
let n = self.assets.iter().filter_map(|a| a.name.strip_prefix(ASSET)?.parse::<u64>().ok()).max().unwrap_or(0);
|
||||
let n = self
|
||||
.assets
|
||||
.iter()
|
||||
.filter_map(|a| {
|
||||
let digits = a.name.strip_prefix(ASSET)?;
|
||||
// `parse` alone would accept a leading `+`.
|
||||
digits.bytes().all(|b| b.is_ascii_digit()).then(|| digits.parse::<u64>().ok()).flatten()
|
||||
})
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
format!("{ASSET}{}", n.saturating_add(1))
|
||||
}
|
||||
|
||||
@@ -57,3 +70,23 @@ impl Document {
|
||||
v.into_iter().map(|(_, id)| id).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn name_after(names: &[&str]) -> String {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
for (i, n) in names.iter().enumerate() {
|
||||
doc.assets.push(ExportAsset { id: i as u64 + 1, name: (*n).to_string(), nodes: vec![], format_3d: None });
|
||||
}
|
||||
doc.next_asset_name()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_asset_name_ignores_non_digit_suffixes() {
|
||||
assert_eq!(name_after(&["Asset +5"]), "Asset 1");
|
||||
assert_eq!(name_after(&["Asset ", "Asset 5x"]), "Asset 1");
|
||||
assert_eq!(name_after(&["Asset 5"]), "Asset 6");
|
||||
}
|
||||
}
|
||||
+69
-14
@@ -19,7 +19,7 @@ use std::f64::consts::PI;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_geom::kurbo::ParamCurveArclen;
|
||||
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv};
|
||||
use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
|
||||
|
||||
use crate::appearance::{Appearance, AppearanceItem, Dash, StrokeLayer, WidthProfile};
|
||||
@@ -904,9 +904,12 @@ pub struct Spine {
|
||||
cum: Vec<f64>,
|
||||
anchors: Vec<f64>,
|
||||
closed: bool,
|
||||
path: PathData,
|
||||
}
|
||||
|
||||
impl Spine {
|
||||
/// Build a spine from the first subpath of `path`: flatten it to a polyline, record cumulative
|
||||
/// arc lengths, and the arc length at each anchor.
|
||||
pub fn new(path: &PathData) -> Option<Self> {
|
||||
let sp = path.subpaths.first()?;
|
||||
let mut pts: Vec<Point> = Vec::new();
|
||||
@@ -943,8 +946,9 @@ impl Spine {
|
||||
if pts.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
Some(Self { pts, cum, anchors, closed: sp.closed })
|
||||
Some(Self { pts, cum, anchors, closed: sp.closed, path: path.clone() })
|
||||
}
|
||||
/// The spine's flattened length in arc length.
|
||||
pub fn length(&self) -> f64 {
|
||||
*self.cum.last().unwrap_or(&0.0)
|
||||
}
|
||||
@@ -1002,20 +1006,32 @@ impl Spine {
|
||||
pub fn at(&self, f: f64) -> (Point, f64) {
|
||||
self.at_length(f.clamp(0.0, 1.0) * self.length())
|
||||
}
|
||||
/// Point and tangent angle (radians) at arc length `s` (clamped to the spine).
|
||||
/// Point and tangent angle (radians) at arc length `s` (clamped to the spine). The point and
|
||||
/// tangent come from the original curve at that arc length, not from the flattened polyline: a
|
||||
/// flattened chord's direction is piecewise constant, so steps oriented to a curved spine with
|
||||
/// `Align to Path` jump between chords instead of following the curve smoothly.
|
||||
pub fn at_length(&self, s: f64) -> (Point, f64) {
|
||||
let last = self.pts.len().saturating_sub(2);
|
||||
let s = if s.is_finite() { s.clamp(0.0, self.length()) } else { 0.0 };
|
||||
let i = match self.cum.binary_search_by(|c| c.total_cmp(&s)) {
|
||||
Ok(i) => i.min(last),
|
||||
Err(i) => i.saturating_sub(1).min(last),
|
||||
};
|
||||
let (Some(p0), Some(p1), Some(c0), Some(c1)) = (self.pts.get(i), self.pts.get(i + 1), self.cum.get(i), self.cum.get(i + 1)) else {
|
||||
return (self.pts.first().copied().unwrap_or_default(), 0.0);
|
||||
};
|
||||
let u = ((s - c0) / (c1 - c0).max(1e-12)).clamp(0.0, 1.0);
|
||||
let d = *p1 - *p0;
|
||||
(p0.lerp(*p1, u), d.y.atan2(d.x))
|
||||
let Some(sp) = self.path.subpaths.first() else { return (self.pts.first().copied().unwrap_or_default(), 0.0) };
|
||||
let n = sp.segment_count();
|
||||
let mut start = 0.0;
|
||||
for i in 0..n {
|
||||
let c = sp.segment(i);
|
||||
let end = self.anchor_length(i + 1).unwrap_or(self.length());
|
||||
if s <= end || i + 1 == n {
|
||||
let local_s = (s - start).max(0.0) / (end - start).max(1e-12) * c.arclen(1e-9);
|
||||
let t = c.inv_arclen(local_s, 1e-9).clamp(0.0, 1.0);
|
||||
let e = c.eval(t);
|
||||
let tv = c.deriv().eval(t).to_vec2();
|
||||
// Where a handle sits on its anchor the derivative vanishes there: take the
|
||||
// direction between points a little before and after instead.
|
||||
let tv = if tv.hypot2() < 1e-24 { c.eval((t + 1e-3).min(1.0)) - c.eval((t - 1e-3).max(0.0)) } else { tv };
|
||||
return (Point::new(e.x, e.y), tv.y.atan2(tv.x));
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
// Only a spine without segments gets here: the loop returns at the last one.
|
||||
(self.pts.first().copied().unwrap_or_default(), 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1446,6 +1462,45 @@ mod tests {
|
||||
assert_eq!(out[0].geometric_bounds().unwrap().center(), Point::new(5.0, 5.0), "keys stay put");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn orientations_follow_a_curved_spine_smoothly() {
|
||||
// A curved spine: from (0, 0) with handles (+50, +50) / (-50, -50) to (100, 0) with handles
|
||||
// (+50, -50) / (-50, +50) — the classic up-bow arc.
|
||||
let spine = PathData::single(SubPath::new(
|
||||
vec![Anchor::smooth(Point::new(0.0, 0.0), Point::new(50.0, 50.0)), Anchor::smooth(Point::new(100.0, 0.0), Point::new(50.0, -50.0))],
|
||||
false,
|
||||
));
|
||||
let sp = Spine::new(&spine).unwrap();
|
||||
// Many steps along the bow: each step's tangent comes from the curve at its arc length,
|
||||
// not from a flattened chord — so the orientations must sweep the true angle, smoothly.
|
||||
let len = sp.length();
|
||||
let mut prev: Option<f64> = None;
|
||||
for i in 1..=200 {
|
||||
let (pt, ang) = sp.at_length(len * i as f64 / 201.0);
|
||||
if let Some(p) = prev {
|
||||
let step = (ang - p).abs().min(2.0 * std::f64::consts::PI - (ang - p).abs());
|
||||
assert!(step < 0.1, "tangent step {} is too big at {} ({}, {})", step, i, pt.x, pt.y);
|
||||
}
|
||||
prev = Some(ang);
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the spine starts at an anchor whose handle sits on it, the first step still faces along
|
||||
/// the curve (towards the next handle), not along a direction of zero length.
|
||||
#[test]
|
||||
fn a_handle_on_its_anchor_still_gives_the_curve_direction() {
|
||||
let spine = PathData::single(SubPath::new(
|
||||
vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor::smooth(Point::new(100.0, 0.0), Point::new(150.0, -50.0))],
|
||||
false,
|
||||
));
|
||||
let sp = Spine::new(&spine).unwrap();
|
||||
let (p, angle) = sp.at_length(0.0);
|
||||
assert!(p.x.abs() < 1e-6 && p.y.abs() < 1e-6, "{p:?}");
|
||||
assert!((angle - std::f64::consts::FRAC_PI_4).abs() < 0.05, "faces the in handle at (50, 50): {angle}");
|
||||
let (_, end) = sp.at_length(sp.length());
|
||||
assert!(end.is_finite(), "{end}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn easing_keeps_the_ends_and_stays_monotone() {
|
||||
use crate::live::{BlendEase, BlendEaseType as K};
|
||||
|
||||
@@ -313,8 +313,8 @@ mod tests {
|
||||
d.guides = vec![Guide { layer: Some(NodeId(40)), ..Guide::new(false, 5.0) }, Guide { layer: Some(d.layers[0].id), ..Guide::new(true, 5.0) }];
|
||||
d.saved_selections = vec![crate::records::SavedSelection { name: "s".into(), objects: vec![NodeId(10), NodeId(11)] }].into();
|
||||
d.assets = vec![
|
||||
crate::assets::ExportAsset { id: 1, name: "far".into(), nodes: vec![NodeId(11)] },
|
||||
crate::assets::ExportAsset { id: 2, name: "both".into(), nodes: vec![NodeId(10), NodeId(11)] },
|
||||
crate::assets::ExportAsset { id: 1, name: "far".into(), nodes: vec![NodeId(11)], format_3d: None },
|
||||
crate::assets::ExportAsset { id: 2, name: "both".into(), nodes: vec![NodeId(10), NodeId(11)], format_3d: None },
|
||||
];
|
||||
d.variables.bindings.insert(NodeId(11), ["v".to_string()].into());
|
||||
d.variables.bindings.insert(NodeId(10), ["w".to_string()].into());
|
||||
|
||||
@@ -34,6 +34,7 @@ impl Document {
|
||||
graphic_styles,
|
||||
char_styles,
|
||||
para_styles,
|
||||
composite_fonts,
|
||||
text_threads,
|
||||
symbols,
|
||||
graph_designs,
|
||||
@@ -68,6 +69,7 @@ impl Document {
|
||||
print_setup,
|
||||
assets,
|
||||
svg_scripts,
|
||||
svg_filters,
|
||||
puppet,
|
||||
new_art,
|
||||
dimensions,
|
||||
@@ -89,6 +91,7 @@ impl Document {
|
||||
&& *graphic_styles == other.graphic_styles
|
||||
&& *char_styles == other.char_styles
|
||||
&& *para_styles == other.para_styles
|
||||
&& *composite_fonts == other.composite_fonts
|
||||
&& *text_threads == other.text_threads
|
||||
&& symbols.len() == other.symbols.len()
|
||||
&& symbols.iter().zip(&other.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
|
||||
@@ -135,6 +138,7 @@ impl Document {
|
||||
&& *print_setup == other.print_setup
|
||||
&& *assets == other.assets
|
||||
&& *svg_scripts == other.svg_scripts
|
||||
&& *svg_filters == other.svg_filters
|
||||
&& match (puppet, &other.puppet) {
|
||||
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
|
||||
(a, b) => a.is_none() && b.is_none(),
|
||||
@@ -211,6 +215,7 @@ impl Document {
|
||||
graphic_styles: default_graphic_styles().into(),
|
||||
char_styles: Default::default(),
|
||||
para_styles: Default::default(),
|
||||
composite_fonts: Default::default(),
|
||||
text_threads: vec![],
|
||||
symbols: vec![],
|
||||
graph_designs: vec![],
|
||||
@@ -245,6 +250,7 @@ impl Document {
|
||||
print_setup: None,
|
||||
assets: vec![],
|
||||
svg_scripts: vec![],
|
||||
svg_filters: vec![],
|
||||
puppet: None,
|
||||
new_art: Default::default(),
|
||||
dimensions: false,
|
||||
|
||||
@@ -123,6 +123,39 @@ impl Document {
|
||||
std::borrow::Cow::Owned(d)
|
||||
}
|
||||
|
||||
/// Does `wants` hold for a node anywhere in the document's art: the layers, symbol definitions,
|
||||
/// graph designs, pattern swatches (the one being edited included) and their opacity masks?
|
||||
pub fn any_node(&self, wants: impl Fn(&Node) -> bool) -> bool {
|
||||
let roots = self
|
||||
.layers
|
||||
.iter()
|
||||
.chain(self.symbols.iter().map(|s| &s.art))
|
||||
.chain(self.graph_designs.iter().map(|g| &g.art))
|
||||
.chain(self.patterns.iter().flat_map(|p| p.art.iter()))
|
||||
.chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter()));
|
||||
let mut any = false;
|
||||
for root in roots {
|
||||
crate::swatches::walk_with_masks(root, &mut |n| any |= wants(n));
|
||||
}
|
||||
any
|
||||
}
|
||||
|
||||
/// Change with `f` every node for which `wants` holds, anywhere in the document's art (as
|
||||
/// [`Self::any_node`] looks). Only the trees that hold such a node are copied out of the art
|
||||
/// they share.
|
||||
pub fn edit_nodes_where(&mut self, wants: impl Fn(&Node) -> bool, mut f: impl FnMut(&mut Node)) {
|
||||
let roots = self
|
||||
.layers
|
||||
.iter_mut()
|
||||
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
|
||||
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
|
||||
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
|
||||
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
|
||||
for root in roots {
|
||||
edit_branches_where(root, &wants, &mut f);
|
||||
}
|
||||
}
|
||||
|
||||
/// Round every path's anchors and handles to `decimals` decimal places: path objects (with
|
||||
/// Live Corners' uncut outlines), blend spines, envelopes' top-object outlines and Intertwine
|
||||
/// areas, in the layers, symbol definitions, graph designs, pattern swatches (the one being
|
||||
@@ -164,7 +197,7 @@ impl Document {
|
||||
}
|
||||
}
|
||||
NodeKind::Envelope { kind, .. } => {
|
||||
if let EnvelopeKind::TopObject { path } = kind.as_mut() {
|
||||
if let EnvelopeKind::TopObject { path, .. } = kind.as_mut() {
|
||||
round_path(path);
|
||||
}
|
||||
}
|
||||
@@ -194,6 +227,26 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// Change with `f` the nodes of `n`'s tree (opacity-mask art included) for which `wants` holds,
|
||||
/// copying out of the shared art only the branches that hold one.
|
||||
fn edit_branches_where(n: &mut Arc<Node>, wants: &impl Fn(&Node) -> bool, f: &mut impl FnMut(&mut Node)) {
|
||||
let mut any = false;
|
||||
crate::swatches::walk_with_masks(n, &mut |c| any |= wants(c));
|
||||
if !any {
|
||||
return;
|
||||
}
|
||||
let node = Arc::make_mut(n);
|
||||
if wants(node) {
|
||||
f(node);
|
||||
}
|
||||
if let Some(m) = node.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
edit_branches_where(&mut m.art, wants, f);
|
||||
}
|
||||
for c in node.children_mut().into_iter().flatten() {
|
||||
edit_branches_where(c, wants, f);
|
||||
}
|
||||
}
|
||||
|
||||
/// Round with `round` the anchors of the paths in `v`, nodes in their file form kept as JSON: every
|
||||
/// `{"subpaths": [{"anchors": [{"p", "in", "out"}]}]}` outside type (`{"type": "text"}`), as
|
||||
/// [`Document::round_geometry`] rounds the nodes it holds.
|
||||
|
||||
@@ -321,6 +321,20 @@ pub struct SeriesPaint {
|
||||
/// Opacity (0..1) of the topmost stroke of each path directly in the series group, as [`Self::fill_opacity`].
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub stroke_opacity: Option<f32>,
|
||||
/// Blend mode of the topmost fill of each path directly in the series group, as [`Self::fill_opacity`]. Absent: Normal.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub fill_blend: Option<vectorcraft_color::BlendMode>,
|
||||
/// Blend mode of the topmost stroke of each path directly in the series group, as [`Self::fill_opacity`]. Absent:
|
||||
/// Normal.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub stroke_blend: Option<vectorcraft_color::BlendMode>,
|
||||
/// Object opacity (0..1) of each path directly in the series group, taken from the object opacity set on one of them.
|
||||
/// Absent: fully opaque.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub opacity: Option<f32>,
|
||||
/// Object blend mode of each path directly in the series group, as [`Self::opacity`]. Absent: Normal.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub blend: Option<vectorcraft_color::BlendMode>,
|
||||
}
|
||||
|
||||
/// Graph data and options. `rows` are categories (one per row of the Graph Data window), each
|
||||
|
||||
+297
-19
@@ -84,8 +84,9 @@ impl Default for HitOptions {
|
||||
|
||||
/// The shapes that an image's own fills and strokes paint, each with its fill rule and the fill or
|
||||
/// stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated
|
||||
/// above this crate, so the engine registers one with [`set_image_paint`].
|
||||
pub type ImagePaint = fn(&Node) -> Vec<(BezPath, FillRule, AppearanceItem)>;
|
||||
/// above this crate, so the engine registers one with [`set_image_paint`]. It looks up swatches and
|
||||
/// patterns in the document it is given.
|
||||
pub type ImagePaint = fn(Option<&Document>, &Node) -> Vec<(BezPath, FillRule, AppearanceItem)>;
|
||||
|
||||
static IMAGE_PAINT: OnceLock<ImagePaint> = OnceLock::new();
|
||||
|
||||
@@ -98,8 +99,8 @@ pub fn set_image_paint(f: ImagePaint) {
|
||||
|
||||
/// The shapes that the image `n`'s own fills and strokes paint ([`set_image_paint`]), none while
|
||||
/// nothing is registered.
|
||||
pub(crate) fn image_paint(n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
|
||||
IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(n))
|
||||
pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
|
||||
IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(doc, n))
|
||||
}
|
||||
|
||||
/// One level of evaluation of a live object in a document, as the canvas draws it: type in an
|
||||
@@ -127,11 +128,14 @@ fn live_inputs() -> u64 {
|
||||
}
|
||||
|
||||
/// A live object evaluated by [`live_art`] on this thread: the object, its document's symbols (by
|
||||
/// name and art) and patterns and the [`LiveInputs`] as they were, the art and its [`art_size`].
|
||||
/// name and art), patterns, swatches and color groups and the [`LiveInputs`] as they were, the art
|
||||
/// and its [`art_size`].
|
||||
struct EvaluatedLive {
|
||||
node: Node,
|
||||
symbols: Vec<(String, Arc<Node>)>,
|
||||
patterns: Vec<crate::PatternDef>,
|
||||
swatches: crate::Shared<Vec<vectorcraft_color::Swatch>>,
|
||||
swatch_groups: crate::Shared<Vec<vectorcraft_color::SwatchGroup>>,
|
||||
inputs: u64,
|
||||
art: Rc<Vec<Node>>,
|
||||
size: usize,
|
||||
@@ -145,6 +149,8 @@ impl EvaluatedLive {
|
||||
&& self.symbols.iter().zip(&doc.symbols).all(|((name, art), s)| *name == s.name && Arc::ptr_eq(art, &s.art))
|
||||
&& self.node == *n
|
||||
&& self.patterns == doc.patterns
|
||||
&& self.swatches == doc.swatches
|
||||
&& self.swatch_groups == doc.swatch_groups
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,8 +189,8 @@ thread_local! {
|
||||
|
||||
/// The art live object `n` of `doc` draws ([`set_live_art`]); [`crate::live::expand_live`] while
|
||||
/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc`, a pattern of
|
||||
/// `doc` or the [`LiveInputs`] have changed since, and on every click while it or the document's
|
||||
/// symbols or patterns hold a placed document ([`holds_placed`]).
|
||||
/// `doc`, its swatches or color groups, or the [`LiveInputs`] have changed since, and on every
|
||||
/// click while it or the document's symbols or patterns hold a placed document ([`holds_placed`]).
|
||||
fn live_art(doc: &Document, n: &Node) -> Rc<Vec<Node>> {
|
||||
let inputs = live_inputs();
|
||||
let kept = EVALUATED.with_borrow_mut(|kept| {
|
||||
@@ -205,7 +211,16 @@ fn live_art(doc: &Document, n: &Node) -> Rc<Vec<Node>> {
|
||||
return art;
|
||||
}
|
||||
let symbols = doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect();
|
||||
let e = EvaluatedLive { node: n.clone(), symbols, patterns: doc.patterns.clone(), inputs, art: art.clone(), size };
|
||||
let e = EvaluatedLive {
|
||||
node: n.clone(),
|
||||
symbols,
|
||||
patterns: doc.patterns.clone(),
|
||||
swatches: doc.swatches.clone(),
|
||||
swatch_groups: doc.swatch_groups.clone(),
|
||||
inputs,
|
||||
art: art.clone(),
|
||||
size,
|
||||
};
|
||||
EVALUATED.with_borrow_mut(|kept| {
|
||||
kept.insert(0, e);
|
||||
kept.truncate(LIVE_KEPT);
|
||||
@@ -437,7 +452,7 @@ pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<NodeI
|
||||
/// whole, and an unlocked layer, group, blend or envelope in Edit Contents is searched inside.
|
||||
fn locked_children(parent: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, out: &mut Vec<NodeId>) {
|
||||
let Some(children) = parent.children() else { return };
|
||||
if parent.clips() && children.first().is_some_and(|clip| !clip_contains(clip, p)) {
|
||||
if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p)) {
|
||||
return;
|
||||
}
|
||||
for i in hit_order(parent, children, p) {
|
||||
@@ -653,6 +668,15 @@ fn clip_outline_hit(parent: &Node, clip: &Node, p: Point, opt: HitOptions, symbo
|
||||
clip_outline(clip, p, opt)
|
||||
}
|
||||
|
||||
/// Does isolation mode (`scope`) edit what `parent` holds: is `parent` the isolated container, or
|
||||
/// the parent of the single object isolated? Then the selection tools hit the art that the
|
||||
/// clipping mask of `parent` hides, and the Unlock submenu lists it (#3748). The reference
|
||||
/// app's help says that the parts outside a clipping mask can still be edited
|
||||
/// (<https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-clipping-masks.html>).
|
||||
fn edits_inside(parent: &Node, scope: Option<NodeId>) -> bool {
|
||||
scope.is_some_and(|s| s == parent.id || parent.children().is_some_and(|c| c.iter().any(|c| c.id == s)))
|
||||
}
|
||||
|
||||
fn hit_children(
|
||||
parent: &Node,
|
||||
p: Point,
|
||||
@@ -670,8 +694,10 @@ fn hit_children(
|
||||
chain.push(clip.id);
|
||||
return Some(Hit { leaf: clip.id, ancestry: chain.clone(), kind, contents_of: None, layers: 1 });
|
||||
}
|
||||
// Elsewhere a clip group (or a layer with a clipping mask) only hits inside it.
|
||||
if !clip_contains(clip, p) {
|
||||
// Elsewhere a clip group (or a layer with a clipping mask) only hits inside it, except for
|
||||
// the selection tools in isolation mode within it.
|
||||
let edited = opt.clip_outlines && editable_only && edits_inside(parent, opt.scope);
|
||||
if !edited && !clip_contains(clip, p) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
@@ -860,7 +886,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
if opt.outline {
|
||||
return None;
|
||||
}
|
||||
image_paint(n).iter().rev().find_map(|(bp, rule, item)| match item {
|
||||
image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item {
|
||||
AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke),
|
||||
AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill),
|
||||
})
|
||||
@@ -936,6 +962,257 @@ fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option
|
||||
}
|
||||
}
|
||||
|
||||
/// The art of a symbol instance with its own appearance changes, in the symbol's coordinates, and
|
||||
/// how the canvas places each object of it: through the symbol's 9-slice guides when the instance
|
||||
/// is scaled by them ([`Document::place_symbol_art`]), otherwise by the instance's transform.
|
||||
struct InstanceArt {
|
||||
art: Node,
|
||||
map: Option<crate::NineSliceMap>,
|
||||
xf: vectorcraft_geom::Affine,
|
||||
}
|
||||
|
||||
impl InstanceArt {
|
||||
/// The art of symbol instance `inst`. `None` for anything else, a missing symbol, or art that
|
||||
/// placing through the guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of,
|
||||
/// which [`Document::place_symbol_art`] does not place and the canvas does not draw.
|
||||
fn of(doc: &Document, inst: &Node) -> Option<Self> {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None };
|
||||
let sym = doc.symbols.iter().find(|s| s.name == *symbol)?;
|
||||
let art = crate::symbol_overrides::dynamic_art(&sym.art, inst);
|
||||
let map = doc.symbol_slice_map(symbol, *xf);
|
||||
if map.as_ref().is_some_and(|m| m.most_placed(&art, doc) > crate::MAX_SYMBOL_NODES) {
|
||||
return None;
|
||||
}
|
||||
Some(Self { art, map, xf: *xf })
|
||||
}
|
||||
|
||||
/// The map that the objects inside group or layer `n` are moved by as one piece: `whole`, the
|
||||
/// map of an object around `n` that is moved as one piece, or else the map of the 9-slice cell
|
||||
/// `n` lies in ([`crate::NineSliceMap::one_cell`]). `None` when `n` is placed through the guides
|
||||
/// object by object.
|
||||
fn whole(&self, n: &Node, doc: &Document, whole: Option<vectorcraft_geom::Affine>) -> Option<vectorcraft_geom::Affine> {
|
||||
whole.or_else(|| self.map.as_ref()?.one_cell(n, doc))
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// [`Document::place_symbol_art`] refuses it.
|
||||
fn place(&self, n: &Node, doc: &Document, whole: Option<vectorcraft_geom::Affine>) -> Option<Node> {
|
||||
match (&self.map, whole) {
|
||||
(_, Some(a)) => Some(moved(n, a)),
|
||||
(Some(m), None) => (m.most_placed(n, doc) <= crate::MAX_SYMBOL_NODES).then(|| m.place(n, doc)),
|
||||
(None, None) => Some(moved(n, self.xf)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Object `n` of the art placed on the canvas without clip groups
|
||||
/// ([`crate::NineSliceMap::place_unclipped`]), as [`Self::place`] places it and within the
|
||||
/// same limit ([`Document::place_symbol_art_unclipped`]).
|
||||
fn place_unclipped(&self, n: &Node, doc: &Document, whole: Option<vectorcraft_geom::Affine>) -> Option<Node> {
|
||||
match (&self.map, whole) {
|
||||
(_, Some(a)) => Some(moved(n, a)),
|
||||
(Some(m), None) => (m.most_placed_unclipped(n, doc) <= crate::MAX_SYMBOL_NODES).then(|| m.place_unclipped(n, doc)),
|
||||
(None, None) => Some(moved(n, self.xf)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` transformed by `xf`, its strokes at their own weight.
|
||||
fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
|
||||
let mut out = n.clone();
|
||||
out.transform(xf, false);
|
||||
out
|
||||
}
|
||||
|
||||
/// The object of symbol instance `inst`'s art under `p`, for Direct Selection on a dynamic symbol's
|
||||
/// instance: its path of child indices from the art's root ([`crate::symbol_overrides::part`]), the
|
||||
/// topmost object hit inside the art's groups. With [`HitOptions::clip_outlines`], a press on the
|
||||
/// outline of the clipping path of a clip group or a clipping layer picks that path before the art
|
||||
/// it clips, as [`hit_test`] does outside symbols. Hidden, locked and template objects are passed
|
||||
/// over, as [`hit_test`] passes over them when it looks for editable objects, and so are a Shaper
|
||||
/// group's original shapes, which the canvas does not draw, and guide paths with
|
||||
/// [`HitOptions::skip_guides`]. Nothing is picked in art that placing through the symbol's 9-slice
|
||||
/// guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, which the canvas does not
|
||||
/// draw. `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> {
|
||||
doc: &'a Document,
|
||||
art: &'a InstanceArt,
|
||||
p: Point,
|
||||
opt: HitOptions,
|
||||
symbols: &'a SymbolBoxes<'a>,
|
||||
}
|
||||
impl Find<'_> {
|
||||
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>) -> bool {
|
||||
self.art.place(n, self.doc, whole).is_some_and(|n| hit_any(&n, self.p, self.opt, self.symbols).is_some())
|
||||
}
|
||||
fn skips_guide(&self, n: &Node) -> bool {
|
||||
self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>) -> bool {
|
||||
if !n.visible || n.locked || n.is_template() || self.skips_guide(n) {
|
||||
return false;
|
||||
}
|
||||
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole) };
|
||||
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
|
||||
return self.hit(n, whole);
|
||||
}
|
||||
let whole = self.art.whole(n, self.doc, whole);
|
||||
if n.clips()
|
||||
&& let Some(first) = children.first()
|
||||
{
|
||||
let Some(clip) = self.art.place_unclipped(first, self.doc, whole) else { return false };
|
||||
if self.opt.clip_outlines
|
||||
&& first.visible
|
||||
&& !first.locked
|
||||
&& !self.skips_guide(first)
|
||||
&& clip_outline(&clip, self.p, self.opt).is_some()
|
||||
{
|
||||
path.push(0);
|
||||
return true;
|
||||
}
|
||||
if !clip_contains(&clip, self.p) {
|
||||
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) {
|
||||
return true;
|
||||
}
|
||||
path.pop();
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
let art = InstanceArt::of(doc, inst)?;
|
||||
let symbols = doc.symbol_boxes();
|
||||
let mut path = vec![];
|
||||
Find { doc, art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None).then_some(path)
|
||||
}
|
||||
|
||||
/// The outlines of the object at `path` in symbol instance `inst`'s art (see [`symbol_part_at`]),
|
||||
/// placed on the canvas as it is drawn: its paths' outlines, and the bounds of objects without a
|
||||
/// path. Inside a clip group (an object drawn once in each 9-slice cell it reaches is one clip
|
||||
/// group per cell) they are cut to the bounds of the group's clip path, which is not outlined. An
|
||||
/// object inside a clip group or a clipping layer of the art, other than its clipping path, is cut
|
||||
/// to the bounds of that clipping path as well, which contain the region where [`symbol_part_at`]
|
||||
/// picks it.
|
||||
/// `None` for art past the 9-slice object limit that [`symbol_part_at`] applies.
|
||||
pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option<BezPath> {
|
||||
let art = InstanceArt::of(doc, inst)?;
|
||||
let part = crate::symbol_overrides::part(&art.art, path)?;
|
||||
let mut out = BezPath::new();
|
||||
let mut limit = None;
|
||||
let mut whole = None;
|
||||
let mut n = &art.art;
|
||||
for &i in path {
|
||||
let children = n.children()?;
|
||||
whole = art.whole(n, doc, whole);
|
||||
if i != 0
|
||||
&& n.clips()
|
||||
&& let Some(first) = children.first()
|
||||
&& let Some(clip) = art.place_unclipped(first, doc, whole)?.geometric_bounds()
|
||||
{
|
||||
match meet(Some(clip), limit) {
|
||||
Some(r) => limit = Some(r),
|
||||
None => return Some(out),
|
||||
}
|
||||
}
|
||||
n = children.get(usize::try_from(i).ok()?)?;
|
||||
}
|
||||
outline_within(&art.place(part, doc, whole)?, limit, &mut out);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// [`symbol_part_outline`] for placed object `n`, cut to `limit` when there is one.
|
||||
fn outline_within(n: &Node, limit: Option<Rect>, out: &mut BezPath) {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
if let Some(pd) = n.path_data() {
|
||||
match limit {
|
||||
Some(r) => push_cut(out, &pd.to_bezpath(), r),
|
||||
None => out.extend(pd.to_bezpath()),
|
||||
}
|
||||
} else if n.children().is_none()
|
||||
&& let Some(b) = n.geometric_bounds()
|
||||
&& let Some(b) = meet(Some(b), limit)
|
||||
{
|
||||
out.extend(b.to_path(0.1));
|
||||
}
|
||||
let Some(children) = n.children() else { return };
|
||||
if n.clips()
|
||||
&& let Some((first, rest)) = children.split_first()
|
||||
{
|
||||
let inner = match first.geometric_bounds() {
|
||||
Some(c) => match meet(Some(c), limit) {
|
||||
Some(r) => Some(r),
|
||||
None => return,
|
||||
},
|
||||
None => limit,
|
||||
};
|
||||
rest.iter().for_each(|c| outline_within(c, inner, out));
|
||||
return;
|
||||
}
|
||||
children.iter().for_each(|c| outline_within(c, limit, out));
|
||||
}
|
||||
|
||||
/// The overlap of `a` and `b` (`a` alone without `b`), `None` when they do not overlap.
|
||||
fn meet(a: Option<Rect>, b: Option<Rect>) -> Option<Rect> {
|
||||
let a = a?;
|
||||
let Some(b) = b else { return Some(a) };
|
||||
let r = Rect::new(a.x0.max(b.x0), a.y0.max(b.y0), a.x1.min(b.x1), a.y1.min(b.y1));
|
||||
(r.x0 <= r.x1 && r.y0 <= r.y1).then_some(r)
|
||||
}
|
||||
|
||||
/// The parts of path `p`, flattened to lines, that lie inside `r`, appended to `out`.
|
||||
fn push_cut(out: &mut BezPath, p: &BezPath, r: Rect) {
|
||||
use vectorcraft_geom::kurbo::PathEl;
|
||||
let (mut at, mut start, mut last) = (Point::ZERO, Point::ZERO, None::<Point>);
|
||||
vectorcraft_geom::kurbo::flatten(p.iter(), 0.1, |el| {
|
||||
let to = match el {
|
||||
PathEl::MoveTo(q) => {
|
||||
(at, start, last) = (q, q, None);
|
||||
return;
|
||||
}
|
||||
PathEl::LineTo(q) => q,
|
||||
PathEl::ClosePath => start,
|
||||
_ => return,
|
||||
};
|
||||
if let Some((a, b)) = cut_segment(at, to, r) {
|
||||
if last != Some(a) {
|
||||
out.move_to(a);
|
||||
}
|
||||
out.line_to(b);
|
||||
last = Some(b);
|
||||
}
|
||||
at = to;
|
||||
});
|
||||
}
|
||||
|
||||
/// The part of segment `a` to `b` inside `r`, `None` when none of it is.
|
||||
fn cut_segment(a: Point, b: Point, r: Rect) -> Option<(Point, Point)> {
|
||||
let d = b - a;
|
||||
let (mut t0, mut t1) = (0.0_f64, 1.0_f64);
|
||||
for (p, q) in [(-d.x, a.x - r.x0), (d.x, r.x1 - a.x), (-d.y, a.y - r.y0), (d.y, r.y1 - a.y)] {
|
||||
if p.abs() < 1e-12 {
|
||||
if q < 0.0 {
|
||||
return None;
|
||||
}
|
||||
} else if p < 0.0 {
|
||||
t0 = t0.max(q / p);
|
||||
} else {
|
||||
t1 = t1.min(q / p);
|
||||
}
|
||||
}
|
||||
(t0 <= t1).then(|| (a + d * t0, a + d * t1))
|
||||
}
|
||||
|
||||
/// The path of compound path `n` under `p`, for the Group Selection tool: the one whose outline is
|
||||
/// within `tol`, else the innermost one whose area holds `p` (a hole inside an outer shape, an
|
||||
/// island inside a hole). `None` when `n` isn't a compound path or no part is under `p`.
|
||||
@@ -954,7 +1231,9 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
|
||||
/// 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
|
||||
/// clipping mask counts only when the marquee meets the region its clipping path clips to, and then
|
||||
/// only within that region's bounds.
|
||||
/// 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
|
||||
/// the selection tools' clicks.
|
||||
pub fn marquee(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, leaves, false)
|
||||
}
|
||||
@@ -972,16 +1251,15 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
// Isolated art whose layer, or a group around it, was locked or hidden afterwards: the
|
||||
// marquee touches none of it, as clicks don't (#5309).
|
||||
Some(s) if !doc.is_editable(s.id) => vec![],
|
||||
Some(s) => match (s.children(), marquee_in(s, r)) {
|
||||
(Some(c), Some(r)) => c.iter().enumerate().filter(|(i, _)| !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
|
||||
(Some(_), None) => vec![],
|
||||
Some(s) => match s.children() {
|
||||
Some(c) => c.iter().enumerate().filter(|(i, _)| !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
|
||||
// A single object isolated: only it.
|
||||
(None, _) => doc
|
||||
None => doc
|
||||
.parent_of(s.id)
|
||||
.and_then(|p| doc.node(p))
|
||||
.and_then(|p| Some((p.children()?, marquee_in(p, r)?)))
|
||||
.and_then(|p| p.children())
|
||||
.into_iter()
|
||||
.flat_map(|(c, r)| c.iter().filter(|c| c.id == s.id).map(move |c| (c, r)))
|
||||
.flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, r)))
|
||||
.collect(),
|
||||
},
|
||||
// The objects of the layers, looking through sublayers (hidden, locked and template ones
|
||||
|
||||
+238
-4
@@ -255,7 +255,9 @@ fn a_selected_objects_hidden_art_on_a_preview_off_layer_counts_on_its_outline()
|
||||
/// #2345: a marquee touches a clip group only where its art shows. Over the clipped-away
|
||||
/// half alone it selects nothing, and around a rectangle drawn beside the group's mask it
|
||||
/// takes that rectangle alone; reaching into the mask takes the group. The same holds for
|
||||
/// Group Selection's leaves and in isolation mode.
|
||||
/// Group Selection's leaves. In isolation mode (#3748) the isolated group's own mask does not
|
||||
/// limit the marquee, as it does not limit clicks: with the group or the art isolated, the
|
||||
/// marquee takes the hidden art.
|
||||
#[test]
|
||||
fn a_marquee_leaves_a_clip_group_by_its_clipped_away_art() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
@@ -270,8 +272,9 @@ fn a_marquee_leaves_a_clip_group_by_its_clipped_away_art() {
|
||||
let hidden = Rect::new(150.0, -10.0, 210.0, 50.0);
|
||||
assert!(marquee(&d, hidden, None, false).is_empty());
|
||||
assert!(marquee(&d, hidden, None, true).is_empty());
|
||||
assert!(marquee(&d, hidden, Some(g), false).is_empty());
|
||||
assert!(marquee(&d, hidden, Some(art_id), false).is_empty());
|
||||
assert_eq!(marquee(&d, hidden, Some(g), false), vec![art_id]);
|
||||
assert_eq!(marquee(&d, hidden, Some(g), true), vec![art_id]);
|
||||
assert_eq!(marquee(&d, hidden, Some(art_id), false), vec![art_id]);
|
||||
// This marquee surrounds the rectangle beside and crosses the hidden art's bottom edge.
|
||||
assert_eq!(marquee(&d, Rect::new(140.0, 70.0, 195.0, 140.0), None, false), vec![beside]);
|
||||
// This marquee crosses the shown half's top edge and goes on into the hidden half.
|
||||
@@ -602,11 +605,41 @@ fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() {
|
||||
fn a_kept_evaluation_is_stale_after_the_live_inputs_change() {
|
||||
let d = Document::new(100.0, 100.0);
|
||||
let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
let e = EvaluatedLive { node: n.clone(), symbols: vec![], patterns: vec![], inputs: 7, art: std::rc::Rc::new(vec![]), size: 0 };
|
||||
let e = kept_evaluation(&d, &n);
|
||||
assert!(e.is_of(&d, &n, 7));
|
||||
assert!(!e.is_of(&d, &n, 8));
|
||||
}
|
||||
|
||||
/// An evaluation of `n` in `d`, with inputs 7, holding no symbols, patterns or art.
|
||||
fn kept_evaluation(d: &Document, n: &Node) -> EvaluatedLive {
|
||||
EvaluatedLive {
|
||||
node: n.clone(),
|
||||
symbols: vec![],
|
||||
patterns: vec![],
|
||||
swatches: d.swatches.clone(),
|
||||
swatch_groups: d.swatch_groups.clone(),
|
||||
inputs: 7,
|
||||
art: std::rc::Rc::new(vec![]),
|
||||
size: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A kept evaluation is stale once a swatch changes, in a color group too: a painted live effect's
|
||||
/// pieces name swatches.
|
||||
#[test]
|
||||
fn a_kept_evaluation_is_stale_after_a_swatch_changes() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
let e = kept_evaluation(&d, &n);
|
||||
assert!(e.is_of(&d, &n, 7));
|
||||
d.swatches.first_mut().unwrap().name = "Renamed".into();
|
||||
assert!(!e.is_of(&d, &n, 7));
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let e = kept_evaluation(&d, &n);
|
||||
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Added".into(), swatches: vec![] });
|
||||
assert!(!e.is_of(&d, &n, 7));
|
||||
}
|
||||
|
||||
/// A rectangle (40, 40)–(140, 140) clipping a filled 200 × 200 square drawn over its edges, in a
|
||||
/// clip group (or, `layer`, as the first layer's clipping mask): the group (or the layer), the
|
||||
/// clipping path and the art.
|
||||
@@ -682,6 +715,82 @@ fn select_behind_takes_a_layer_masks_outline_first() {
|
||||
assert_eq!(objects_at(&d, Point::new(138.5, 90.0), HitOptions::default(), None), vec![art, clip]);
|
||||
}
|
||||
|
||||
/// #3748: in isolation mode the selection tools hit the art that the isolated clip group (or
|
||||
/// the isolated layer with a clipping mask) hides outside its mask, and the art when it is the
|
||||
/// single object isolated; the mask's outline is still hit first. Outside isolation mode, and
|
||||
/// for the tools that act on what is drawn, the hidden art is not hit. The Unlock submenu
|
||||
/// lists the hidden art when it is locked.
|
||||
#[test]
|
||||
fn isolation_reaches_the_art_a_clipping_mask_hides() {
|
||||
let hidden = Point::new(170.0, 90.0);
|
||||
for layer in [false, true] {
|
||||
let (mut d, g, clip, art) = masked_square(layer);
|
||||
let isolated = HitOptions { scope: Some(g), ..SELECTING };
|
||||
assert!(hit_test(&d, hidden, SELECTING).is_none(), "layer {layer}: not isolated");
|
||||
let h = hit_test(&d, hidden, isolated);
|
||||
assert_eq!(h.map(|h| (h.leaf, h.top_object(Some(g)))), Some((art, art)), "layer {layer}");
|
||||
assert_eq!(objects_at(&d, hidden, SELECTING, Some(g)), vec![art], "layer {layer}");
|
||||
assert_eq!(hit_test(&d, Point::new(140.0, 90.0), isolated).map(|h| h.leaf), Some(clip), "layer {layer}: the outline first");
|
||||
let one = HitOptions { scope: Some(art), ..SELECTING };
|
||||
assert_eq!(hit_test(&d, hidden, one).map(|h| h.leaf), Some(art), "layer {layer}: the art isolated");
|
||||
assert!(hit_test(&d, hidden, HitOptions { scope: Some(g), ..HitOptions::default() }).is_none(), "layer {layer}: drawn art only");
|
||||
assert!(hit_test_visible(&d, hidden, isolated).is_none(), "layer {layer}: sampling");
|
||||
d.node_mut(art).unwrap().locked = true;
|
||||
assert_eq!(locked_objects_at(&d, hidden, HitOptions { scope: Some(g), ..HitOptions::default() }), vec![art], "layer {layer}");
|
||||
assert!(locked_objects_at(&d, hidden, HitOptions::default()).is_empty(), "layer {layer}: not isolated");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3748, nested clip groups: with the outer clip group isolated, a click or a marquee takes
|
||||
/// the art its own mask hides, while the mask of a clip group inside it still limits that
|
||||
/// group's art. With the inner clip group isolated, or its art, the inner mask does not.
|
||||
#[test]
|
||||
fn isolation_reaches_hidden_art_only_for_the_isolated_clip_group() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (outer, outer_clip, outer_art, inner, inner_clip, inner_art) =
|
||||
(d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let mask = |id, r| {
|
||||
let mut path = Node::path(id, shapes::rectangle(r), Appearance::basic(Paint::None, Paint::None, 0.0));
|
||||
if let NodeKind::Path { clipping, .. } = &mut path.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
Arc::new(path)
|
||||
};
|
||||
let art = |id, r| Arc::new(Node::path(id, shapes::rectangle(r), Appearance::default_art()));
|
||||
let inner_group = Node::new(
|
||||
inner,
|
||||
NodeKind::Group {
|
||||
children: vec![mask(inner_clip, Rect::new(60.0, 60.0, 120.0, 120.0)), art(inner_art, Rect::new(40.0, 40.0, 160.0, 160.0))],
|
||||
clip: true,
|
||||
},
|
||||
);
|
||||
let children =
|
||||
vec![mask(outer_clip, Rect::new(20.0, 20.0, 180.0, 180.0)), art(outer_art, Rect::new(190.0, 20.0, 260.0, 180.0)), Arc::new(inner_group)];
|
||||
d.insert(Some(l), 0, Node::new(outer, NodeKind::Group { children, clip: true })).unwrap();
|
||||
// `outer_hidden` is outside the outer mask, on the outer group's own art; `inner_hidden` is
|
||||
// inside the outer mask and outside the inner one, on the inner group's art.
|
||||
let (outer_hidden, inner_hidden, shown) = (Point::new(220.0, 100.0), Point::new(150.0, 100.0), Point::new(90.0, 90.0));
|
||||
let leaf = |p, scope| hit_test(&d, p, HitOptions { scope, ..SELECTING }).map(|h| h.leaf);
|
||||
assert_eq!((leaf(outer_hidden, None), leaf(inner_hidden, None)), (None, None), "not isolated");
|
||||
assert_eq!(leaf(outer_hidden, Some(outer)), Some(outer_art), "outer isolated: its own hidden art");
|
||||
assert_eq!(leaf(inner_hidden, Some(outer)), None, "outer isolated: the inner mask still clips");
|
||||
let h = hit_test(&d, shown, HitOptions { scope: Some(outer), ..SELECTING });
|
||||
assert_eq!(h.map(|h| (h.leaf, h.top_object(Some(outer)))), Some((inner_art, inner)), "outer isolated: shown art");
|
||||
assert_eq!(leaf(inner_hidden, Some(inner)), Some(inner_art), "inner isolated");
|
||||
assert_eq!(leaf(outer_hidden, Some(inner)), None, "inner isolated: the outer group's art");
|
||||
assert_eq!(leaf(inner_hidden, Some(inner_art)), Some(inner_art), "the inner art isolated");
|
||||
// These marquees cross the right edge of the outer art (outside the outer mask) and of the
|
||||
// inner art (inside the outer mask, outside the inner one).
|
||||
let (outer_edge, inner_edge) = (Rect::new(255.0, 95.0, 265.0, 105.0), Rect::new(155.0, 95.0, 165.0, 105.0));
|
||||
assert_eq!(marquee(&d, outer_edge, Some(outer), false), vec![outer_art]);
|
||||
assert!(marquee(&d, inner_edge, Some(outer), false).is_empty());
|
||||
assert!(marquee(&d, inner_edge, Some(outer), true).is_empty());
|
||||
assert_eq!(marquee(&d, inner_edge, Some(inner), false), vec![inner_art]);
|
||||
assert!(marquee(&d, inner_edge, None, false).is_empty());
|
||||
assert!(marquee(&d, outer_edge, None, false).is_empty());
|
||||
}
|
||||
|
||||
/// Art in a sublayer is an object of its own: a click or a marquee takes it, not the
|
||||
/// sublayer; hidden, locked and template sublayers block both.
|
||||
#[test]
|
||||
@@ -1373,3 +1482,128 @@ fn cull_box_holds_the_reach_of_paths_and_compound_paths() {
|
||||
assert!(holds(cull, reach), "{cull:?} does not hold {reach:?}");
|
||||
assert_eq!(checked, 201);
|
||||
}
|
||||
|
||||
/// In a dynamic symbol's art, a layer with a clipping mask clips its objects as a clip group does:
|
||||
/// Direct Selection picks an object only where the mask shows it, and outlines it there.
|
||||
#[test]
|
||||
fn an_object_a_clipping_layer_in_symbol_art_hides_is_not_picked_there() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mask, art) = half_clipped(&mut d);
|
||||
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.set_clips(true);
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(layer)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Clipped".into(), art: Arc::new(root) });
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Clipped".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
let n = d.node(inst).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), Some(vec![0, 1]), "where the mask shows the art");
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 50.0), opt), None, "where the mask hides it");
|
||||
let b = vectorcraft_geom::kurbo::Shape::bounding_box(&symbol_part_outline(&d, n, &[0, 1]).unwrap());
|
||||
assert!((b.x1 - 100.0).abs() < 1e-6, "the outline is cut to the mask: {b:?}");
|
||||
// Its outline inside the group around the layer is cut too.
|
||||
let b = vectorcraft_geom::kurbo::Shape::bounding_box(&symbol_part_outline(&d, n, &[0]).unwrap());
|
||||
assert!((b.x1 - 100.0).abs() < 1e-6, "the layer's outline is cut to the mask: {b:?}");
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[test]
|
||||
fn symbol_art_past_the_object_limit_picks_nothing() {
|
||||
use vectorcraft_color::{Gradient, GradientPaint};
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let leaf = Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()));
|
||||
let inner = Arc::new(Node::group(d.alloc_id(), vec![leaf; 1_800]));
|
||||
let mut mask = crate::OpacityMask::new(Node::group(d.alloc_id(), vec![inner; 1_800]), true);
|
||||
mask.linked = false;
|
||||
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
|
||||
// Drawn in six cells, each with its own copy of the mask's 3,240,000 squares.
|
||||
let mut big = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), Appearance::basic(gradient, Paint::None, 0.0));
|
||||
big.extras_mut().mask = Some(Box::new(mask));
|
||||
let plain = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 50.0, 100.0, 100.0)), Appearance::default_art());
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(plain), Arc::new(big)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Big".into(), art: Arc::new(root) });
|
||||
d.set_symbol_nine_slice("Big", Some(crate::SymbolNineSlice::default()));
|
||||
let scaled = d.alloc_id();
|
||||
let natural = d.alloc_id();
|
||||
let xf = vectorcraft_geom::Affine::scale_non_uniform(2.0, 1.5);
|
||||
d.insert(Some(l), 0, Node::new(scaled, NodeKind::SymbolInstance { symbol: "Big".into(), xf })).unwrap();
|
||||
d.insert(Some(l), 0, Node::new(natural, NodeKind::SymbolInstance { symbol: "Big".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
assert!(d.place_symbol_art("Big", &d.symbols[0].art, xf).is_none(), "the art is past the limit");
|
||||
let opt = HitOptions::default();
|
||||
let n = d.node(scaled).unwrap();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(100.0, 110.0), opt), None, "the plain square");
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(100.0, 40.0), opt), None, "the masked path");
|
||||
assert!(symbol_part_outline(&d, n, &[0]).is_none());
|
||||
assert!(symbol_part_outline(&d, n, &[1]).is_none());
|
||||
let n = d.node(natural).unwrap();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 75.0), opt), Some(vec![0]));
|
||||
assert!(symbol_part_outline(&d, n, &[0]).is_some());
|
||||
}
|
||||
|
||||
/// A clip group that lies in one 9-slice cell is moved by that cell as one piece, everything in it
|
||||
/// included, so an object in it is picked and outlined there even when placing that object through
|
||||
/// the guides on its own would pass [`crate::MAX_SYMBOL_NODES`] objects.
|
||||
#[test]
|
||||
fn objects_of_a_clip_group_in_one_cell_are_placed_with_it() {
|
||||
use vectorcraft_color::{Gradient, GradientPaint};
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let leaf = Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()));
|
||||
let inner = Arc::new(Node::group(d.alloc_id(), vec![leaf; 1_800]));
|
||||
let mut mask = crate::OpacityMask::new(Node::group(d.alloc_id(), vec![inner; 1_800]), true);
|
||||
mask.linked = false;
|
||||
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
|
||||
let mut big = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(gradient, Paint::None, 0.0));
|
||||
big.extras_mut().mask = Some(Box::new(mask));
|
||||
let clip = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art());
|
||||
let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(big.clone())]);
|
||||
group.set_clips(true);
|
||||
let frame = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art());
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(frame), Arc::new(group)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Corner".into(), art: Arc::new(root) });
|
||||
d.set_symbol_nine_slice("Corner", Some(crate::SymbolNineSlice::default()));
|
||||
let inst = d.alloc_id();
|
||||
let xf = vectorcraft_geom::Affine::scale_non_uniform(2.0, 1.5);
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Corner".into(), xf })).unwrap();
|
||||
let m = d.symbol_slice_map("Corner", xf).unwrap();
|
||||
assert!(m.most_placed(&big, &d) > crate::MAX_SYMBOL_NODES, "the object alone is past the limit");
|
||||
assert!(d.place_symbol_art("Corner", &d.symbols[0].art, xf).is_some(), "the art is drawn");
|
||||
let n = d.node(inst).unwrap();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(10.0, 10.0), HitOptions::default()), Some(vec![1, 1]));
|
||||
let b = vectorcraft_geom::kurbo::Shape::bounding_box(&symbol_part_outline(&d, n, &[1, 1]).unwrap());
|
||||
assert!((b.x1 - 20.0).abs() < 1e-6 && (b.y1 - 20.0).abs() < 1e-6, "cut to the clip in its corner: {b:?}");
|
||||
}
|
||||
|
||||
/// In a dynamic symbol's art, Direct Selection does not pick a Shaper group's original shapes,
|
||||
/// which the canvas does not draw: a click over an original shape whose face the group erased
|
||||
/// picks nothing, and a click over the face it shows picks the face.
|
||||
#[test]
|
||||
fn a_shaper_groups_original_shapes_in_symbol_art_are_not_picked() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 100.0, 100.0));
|
||||
let a = Node::path(d.alloc_id(), square(0.0), Appearance::default_art());
|
||||
let b = Node::path(d.alloc_id(), square(50.0), Appearance::default_art());
|
||||
let mut sources = Node::group(d.alloc_id(), vec![Arc::new(a), Arc::new(b)]);
|
||||
sources.name = Some(crate::shaper::SOURCES.into());
|
||||
sources.opacity = 0.0;
|
||||
let mut face = Node::path(d.alloc_id(), square(0.0), Appearance::default_art());
|
||||
face.name = Some(format!("{}0", crate::shaper::FILL_PREFIX));
|
||||
let mut group = Node::group(d.alloc_id(), vec![Arc::new(sources), Arc::new(face)]);
|
||||
group.extras_mut().shaper = Some(Box::default());
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(group)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Shaped".into(), art: Arc::new(root) });
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Shaped".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
let n = d.node(inst).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(130.0, 50.0), opt), None, "over the erased original shape");
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), Some(vec![0, 1]), "over the shown face");
|
||||
}
|
||||
+14
-6
@@ -109,7 +109,7 @@ pub use placed_document::{PageBox, PlacedDocument};
|
||||
pub use profiles::ColorProfiles;
|
||||
pub use puppet::{PuppetPin, PuppetPins};
|
||||
pub use rastersettings::{RasterColorModel, RasterEffectsSettings};
|
||||
pub use selection::{AnchorRef, SegmentRef, Selection};
|
||||
pub use selection::{AnchorRef, SegmentRef, Selection, SymbolPart};
|
||||
pub use setup::{Background, DocSetup, ExportText, GridSize, Quotes};
|
||||
pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOptions, SliceSource};
|
||||
pub use style_libs::StyleLibrary;
|
||||
@@ -117,10 +117,11 @@ pub use text::FontHeightReference;
|
||||
pub use text::GlyphChoice;
|
||||
pub use text::{
|
||||
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
|
||||
JustificationOptions, Justify, Kinsoku, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign, RubyPosition,
|
||||
RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign,
|
||||
WrapShape,
|
||||
JustificationOptions, Justify, Kinsoku, KinsokuShoriType, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign,
|
||||
RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap,
|
||||
VerticalAlign, WrapShape,
|
||||
};
|
||||
pub use text::{CharClass, CompositeFont, CompositePart, CompositeParts};
|
||||
pub use trace::TraceView;
|
||||
pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables};
|
||||
pub use vectorcraft_color as color;
|
||||
@@ -141,7 +142,7 @@ mod limits;
|
||||
mod records;
|
||||
mod units;
|
||||
|
||||
pub use artboard::{Artboard, LockedArtboards, RetiredArtboardId, VIDEO_PIXEL_ASPECT_RANGE, VIDEO_SAFE_INSETS};
|
||||
pub use artboard::{ARTBOARD_GAP, Artboard, ArtboardSide, LockedArtboards, RetiredArtboardId, VIDEO_PIXEL_ASPECT_RANGE, VIDEO_SAFE_INSETS};
|
||||
pub use canvas_range::BeyondCanvas;
|
||||
#[cfg(test)]
|
||||
use document_ext::free_id;
|
||||
@@ -150,7 +151,7 @@ pub use guides::{GridPrefs, Guide, RulerMode};
|
||||
#[cfg(test)]
|
||||
use limits::MAX_NEXT_ID;
|
||||
pub use limits::{DocError, FORMAT_VERSION, MAX_COORD};
|
||||
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, Symbol, SymbolEdit};
|
||||
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit};
|
||||
pub use units::{ColorMode, Unit, parse_number};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -195,6 +196,9 @@ pub struct Document {
|
||||
/// Paragraph styles (besides the built-in [Normal Paragraph Style]).
|
||||
#[serde(default, skip_serializing_if = "skip::is_empty_vec")]
|
||||
pub para_styles: Shared<Vec<TextStyleDef>>,
|
||||
/// Type › Composite Fonts…: the composite fonts defined in the document, by name.
|
||||
#[serde(default, skip_serializing_if = "skip::is_empty_vec")]
|
||||
pub composite_fonts: Shared<Vec<CompositeFont>>,
|
||||
/// Threaded text: area-type frames one story flows through, in order.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub text_threads: Vec<Vec<NodeId>>,
|
||||
@@ -310,6 +314,10 @@ pub struct Document {
|
||||
/// given) SVG export links with `<script>` elements, in order.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub svg_scripts: Vec<String>,
|
||||
/// Effect › SVG Filters: the SVG filters the document holds (at most [`SvgFilter::MAX`]), in
|
||||
/// the order the submenu lists them.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub svg_filters: Vec<SvgFilter>,
|
||||
/// Puppet Warp pins on the selected artwork while the tool edits it ([`PuppetPins`]): editing
|
||||
/// state, never saved.
|
||||
#[serde(skip)]
|
||||
|
||||
@@ -174,6 +174,303 @@ mod tests {
|
||||
assert!((c.x - 105.0).abs() < 1e-6 && (c.y + 10.0).abs() < 1e-6, "{c:?}");
|
||||
}
|
||||
|
||||
/// A 100 × 50 outline whose top side runs (0,0) → (30,0) → (100,0) as two straight segments.
|
||||
fn top_split_at_30() -> PathData {
|
||||
let a = |x: f64, y: f64| Anchor::corner(Point::new(x, y));
|
||||
PathData::single(SubPath::new(vec![a(0.0, 0.0), a(30.0, 0.0), a(100.0, 0.0), a(100.0, 50.0), a(0.0, 50.0)], true))
|
||||
}
|
||||
|
||||
/// The length of `c`'s control polygon.
|
||||
fn polygon(c: CubicBez) -> f64 {
|
||||
c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3)
|
||||
}
|
||||
|
||||
/// An anchor and its incoming and outgoing handles.
|
||||
type Knot = ((f64, f64), (f64, f64), (f64, f64));
|
||||
|
||||
/// A closed path through `pts`.
|
||||
fn outline(pts: &[Knot]) -> PathData {
|
||||
let a = |&(p, i, o): &Knot| Anchor { p: p.into(), h_in: i.into(), h_out: o.into(), ..Anchor::corner(p.into()) };
|
||||
PathData::single(SubPath::new(pts.iter().map(a).collect(), true))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_side_of_straight_segments_spreads_by_length() {
|
||||
// The top side runs (0,0) → (30,0) → (100,0): each straight piece takes its length's share.
|
||||
let kind = EnvelopeKind::TopObject { path: top_split_at_30(), corners: None };
|
||||
let map = envelope_mapper(&kind, Rect::new(0.0, 0.0, 100.0, 50.0));
|
||||
for (q, want) in [((50.0, 0.0), (50.0, 0.0)), ((15.0, 0.0), (15.0, 0.0)), ((80.0, 0.0), (80.0, 0.0)), ((50.0, 25.0), (50.0, 25.0))] {
|
||||
let p = map(Point::new(q.0, q.1));
|
||||
assert!(p.distance(Point::new(want.0, want.1)) < 1e-6, "{q:?} → {p:?}, want {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_shares_a_side_by_control_polygon_length() {
|
||||
// Two curves of unequal polygons make the top side; the anchor between them lands at the
|
||||
// first one's share, and inside each curve the content follows its parameter.
|
||||
let first = CubicBez::new((0.0, 0.0), (10.0, -20.0), (30.0, -20.0), (40.0, 0.0));
|
||||
let second = CubicBez::new((40.0, 0.0), (60.0, 10.0), (90.0, 10.0), (100.0, 0.0));
|
||||
let path = outline(&[
|
||||
((0.0, 0.0), (0.0, 0.0), (10.0, -20.0)),
|
||||
((40.0, 0.0), (30.0, -20.0), (60.0, 10.0)),
|
||||
((100.0, 0.0), (90.0, 10.0), (100.0, 0.0)),
|
||||
((100.0, 80.0), (100.0, 80.0), (100.0, 80.0)),
|
||||
((0.0, 80.0), (0.0, 80.0), (0.0, 80.0)),
|
||||
]);
|
||||
let c = Coons::from_top_object(&path, None).unwrap();
|
||||
let share = polygon(first) / (polygon(first) + polygon(second));
|
||||
assert!(c.eval(share, 0.0).distance(Point::new(40.0, 0.0)) < 1e-9, "{:?}", c.eval(share, 0.0));
|
||||
for f in [0.25, 0.5, 0.75] {
|
||||
let p = c.eval(share * f, 0.0);
|
||||
assert!(p.distance(first.eval(f)) < 1e-9, "first curve at {f}: {p:?}");
|
||||
let p = c.eval(share + (1.0 - share) * f, 0.0);
|
||||
assert!(p.distance(second.eval(f)) < 1e-9, "second curve at {f}: {p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rounded_rectangle_top_object_stays_close_to_the_identity() {
|
||||
// The corners fall at the middle of each corner arc. Each half arc takes the share of its
|
||||
// control polygon, so the straight edges stay close to where the content was.
|
||||
let r = Rect::new(0.0, 0.0, 200.0, 100.0);
|
||||
let path = shapes::rounded_rectangle(r, 10.0);
|
||||
let c = Coons::from_top_object(&path, None).unwrap();
|
||||
let [tl, tr, br, bl] = c.corners();
|
||||
let k = 10.0 * (1.0 - std::f64::consts::FRAC_1_SQRT_2);
|
||||
for (p, want) in [(tl, (k, k)), (tr, (200.0 - k, k)), (br, (200.0 - k, 100.0 - k)), (bl, (k, 100.0 - k))] {
|
||||
assert!(p.distance(Point::from(want)) < 0.01, "corner {p:?}, want {want:?}");
|
||||
}
|
||||
for (u, v) in [(0.25, 0.0), (0.5, 0.0), (0.8, 1.0), (0.0, 0.5), (0.5, 0.5), (1.0, 0.3)] {
|
||||
let p = c.eval(u, v);
|
||||
assert!(p.distance(Point::new(200.0 * u, 100.0 * v)) < 3.0, "({u}, {v}) → {p:?}");
|
||||
}
|
||||
// The top edge starts after the first half arc's share.
|
||||
let sp = &path.subpaths[0];
|
||||
let edge = Point::new(10.0, 0.0);
|
||||
let arc = (0..sp.segment_count())
|
||||
.filter(|i| !sp.segment_is_line(*i))
|
||||
.map(|i| sp.segment(i))
|
||||
.find(|s| s.p0.distance(edge) < 1e-9 || s.p3.distance(edge) < 1e-9)
|
||||
.unwrap();
|
||||
let half = polygon(if arc.p3.distance(edge) < 1e-9 { arc.subsegment(0.5..1.0) } else { arc.subsegment(0.0..0.5) });
|
||||
let p = c.eval(half / (2.0 * half + 180.0), 0.0);
|
||||
assert!(p.distance(Point::new(10.0, 0.0)) < 1e-6, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_corner_inside_a_bulging_curve_is_the_nearest_outline_point() {
|
||||
// The top left anchor's handle bulges out past the corner, so the anchor turns inward
|
||||
// there and the corner falls inside the curve.
|
||||
// The outline's bounding box starts at (-7.957, -22.222); the top curve's point nearest
|
||||
// that corner, found by sampling the curve 2,000,000 times, is (-5.072093, -18.127254).
|
||||
let path = outline(&[
|
||||
((0.0, 0.0), (0.0, 0.0), (-50.0, -50.0)),
|
||||
((200.0, 0.0), (150.0, 0.0), (200.0, 0.0)),
|
||||
((200.0, 100.0), (200.0, 100.0), (200.0, 100.0)),
|
||||
((0.0, 100.0), (0.0, 100.0), (0.0, 100.0)),
|
||||
]);
|
||||
let want = Point::new(-5.072093, -18.127254);
|
||||
let tl = Coons::from_top_object(&path, None).unwrap().corners()[0];
|
||||
assert!(tl.distance(want) < 1e-5, "{tl:?}, want {want:?}");
|
||||
assert!(tl.distance(Point::ZERO) > 1.0, "{tl:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_corner_takes_an_anchor_only_near_its_box_corner() {
|
||||
// A chamfered top left corner of a 200 × 100 outline. With both chamfer anchors within
|
||||
// 47.5% of the box from its corner, the nearer anchor is the corner.
|
||||
let chamfer = |a: (f64, f64), b: (f64, f64)| {
|
||||
let c = |p: (f64, f64)| (p, p, p);
|
||||
outline(&[c(a), c(b), c((200.0, 0.0)), c((200.0, 100.0)), c((0.0, 100.0))])
|
||||
};
|
||||
let tl = Coons::from_top_object(&chamfer((0.0, 46.0), (94.0, 0.0)), None).unwrap().corners()[0];
|
||||
assert!(tl.distance(Point::new(0.0, 46.0)) < 1e-9, "{tl:?}");
|
||||
// Farther out, neither anchor counts: the corner is the chamfer's point nearest the box corner.
|
||||
let tl = Coons::from_top_object(&chamfer((0.0, 50.0), (100.0, 0.0)), None).unwrap().corners()[0];
|
||||
assert!(tl.distance(Point::new(20.0, 40.0)) < 1e-6, "{tl:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_corner_skips_smooth_and_inward_anchors() {
|
||||
// A top left anchor whose outgoing handle turns from its incoming one by `deg` degrees
|
||||
// (positive turns out of the outline). The top side bulges up past it.
|
||||
let shape = |deg: f64| {
|
||||
let a = deg.to_radians();
|
||||
let (hx, hy) = (50.0 * a.cos() + 40.0 * a.sin(), 40.0 * a.cos() - 50.0 * a.sin());
|
||||
outline(&[
|
||||
((50.0, -300.0), (25.0, -280.0), (50.0 + hx, -300.0 - hy)),
|
||||
((250.0, -300.0), (200.0, -340.0), (250.0, -300.0)),
|
||||
((250.0, -200.0), (250.0, -200.0), (250.0, -200.0)),
|
||||
((50.0, -200.0), (50.0, -200.0), (50.0, -230.0)),
|
||||
])
|
||||
};
|
||||
let corner = |deg: f64| Coons::from_top_object(&shape(deg), None).unwrap().corners()[0];
|
||||
let anchor = Point::new(50.0, -300.0);
|
||||
for deg in [0.0, 0.4, 0.6, -1.5] {
|
||||
assert!(corner(deg).distance(anchor) > 1.0, "{deg}°: {:?}", corner(deg));
|
||||
}
|
||||
for deg in [0.9, 1.5, 10.0] {
|
||||
assert!(corner(deg).distance(anchor) < 1e-9, "{deg}°: {:?}", corner(deg));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_corner_skips_an_inward_anchor_between_straight_segments() {
|
||||
// A 200 × 100 outline of straight segments with a notch at its top left: (40,40) is the
|
||||
// anchor nearest the box corner, but it turns into the outline, so (60,0) is the corner.
|
||||
let c = |p: (f64, f64)| (p, p, p);
|
||||
let path = outline(&[c((60.0, 0.0)), c((200.0, 0.0)), c((200.0, 100.0)), c((0.0, 100.0)), c((0.0, 60.0)), c((40.0, 40.0))]);
|
||||
let tl = Coons::from_top_object(&path, None).unwrap().corners()[0];
|
||||
assert!(tl.distance(Point::new(60.0, 0.0)) < 1e-9, "{tl:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_corner_tie_goes_to_the_first_anchor() {
|
||||
// Both chamfer anchors lie 30 from the box corner: the first one along the outline, in
|
||||
// the order it was drawn, wins.
|
||||
let c = |p: (f64, f64)| (p, p, p);
|
||||
let tl = |pts: &[Knot]| Coons::from_top_object(&outline(pts), None).unwrap().corners()[0];
|
||||
let from_left = tl(&[c((0.0, 30.0)), c((30.0, 0.0)), c((100.0, 0.0)), c((100.0, 100.0)), c((0.0, 100.0))]);
|
||||
assert!(from_left.distance(Point::new(0.0, 30.0)) < 1e-9, "{from_left:?}");
|
||||
let from_top = tl(&[c((30.0, 0.0)), c((100.0, 0.0)), c((100.0, 100.0)), c((0.0, 100.0)), c((0.0, 30.0))]);
|
||||
assert!(from_top.distance(Point::new(30.0, 0.0)) < 1e-9, "{from_top:?}");
|
||||
// Drawn counter-clockwise, the anchor met first in that order wins.
|
||||
let back = tl(&[c((0.0, 100.0)), c((100.0, 100.0)), c((100.0, 0.0)), c((30.0, 0.0)), c((0.0, 30.0))]);
|
||||
assert!(back.distance(Point::new(30.0, 0.0)) < 1e-9, "{back:?}");
|
||||
let back = tl(&[c((0.0, 30.0)), c((0.0, 100.0)), c((100.0, 100.0)), c((100.0, 0.0)), c((30.0, 0.0))]);
|
||||
assert!(back.distance(Point::new(0.0, 30.0)) < 1e-9, "{back:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reflected_top_object_keeps_the_corners_a_file_gives() {
|
||||
// Reflecting the outline across x = 0 keeps its anchors in the same order, now running
|
||||
// counter-clockwise: the corners stay on the same anchors, so the content is reflected too.
|
||||
let mut path = top_split_at_30();
|
||||
path.transform(Affine::FLIP_X);
|
||||
let c = Coons::from_top_object(&path, Some([1, 2, 3, 4])).unwrap();
|
||||
let want = [(-30.0, 0.0), (-100.0, 0.0), (-100.0, 50.0), (0.0, 50.0)].map(Point::from);
|
||||
assert!(c.corners().iter().zip(want).all(|(p, q)| p.distance(q) < 1e-9), "{:?}", c.corners());
|
||||
let p = c.eval(0.5, 0.5);
|
||||
assert!(p.distance(Point::new(-50.0, 17.5)) < 1e-9, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_keeps_the_corners_a_file_gives() {
|
||||
let same = |a: [Point; 4], b: [Point; 4]| a.iter().zip(b).all(|(p, q)| p.distance(q) < 1e-9);
|
||||
let want = [(30.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)].map(Point::from);
|
||||
let c = Coons::from_top_object(&top_split_at_30(), Some([1, 2, 3, 4])).unwrap();
|
||||
assert!(same(c.corners(), want), "{:?}", c.corners());
|
||||
// Drawn the other way round, with the corners counted along that order.
|
||||
let mut back = top_split_at_30();
|
||||
back.subpaths[0].reverse();
|
||||
let c = Coons::from_top_object(&back, Some([3, 2, 1, 0])).unwrap();
|
||||
assert!(same(c.corners(), want), "{:?}", c.corners());
|
||||
// Corners that repeat, run out of order or go past the outline are found from it instead.
|
||||
let found = [(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)].map(Point::from);
|
||||
for bad in [[0, 0, 3, 4], [2, 1, 3, 4], [1, 2, 3, 9]] {
|
||||
let c = Coons::from_top_object(&top_split_at_30(), Some(bad)).unwrap();
|
||||
assert!(same(c.corners(), found), "{bad:?}: {:?}", c.corners());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_curve_moves_the_top_object_share_to_its_new_anchor() {
|
||||
// Splitting the top curve at t = 0.3 keeps its shape but changes the polygon shares: the
|
||||
// new anchor lands at the first piece's share, not at u = 0.3.
|
||||
let top = CubicBez::new((0.0, 0.0), (40.0, -40.0), (160.0, -40.0), (200.0, 0.0));
|
||||
let (a, b) = (top.subsegment(0.0..0.3), top.subsegment(0.3..1.0));
|
||||
let path = outline(&[
|
||||
((0.0, 0.0), (0.0, 0.0), a.p1.into()),
|
||||
(a.p3.into(), a.p2.into(), b.p1.into()),
|
||||
((200.0, 0.0), b.p2.into(), (200.0, 0.0)),
|
||||
((200.0, 100.0), (200.0, 100.0), (200.0, 100.0)),
|
||||
((0.0, 100.0), (0.0, 100.0), (0.0, 100.0)),
|
||||
]);
|
||||
let c = Coons::from_top_object(&path, None).unwrap();
|
||||
let share = polygon(a) / (polygon(a) + polygon(b));
|
||||
assert!(c.eval(share, 0.0).distance(a.p3) < 1e-9, "{:?}", c.eval(share, 0.0));
|
||||
assert!((share - 0.3).abs() > 0.01, "{share}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rectangle_top_object_is_the_identity() {
|
||||
let r = Rect::new(10.0, 20.0, 110.0, 70.0);
|
||||
let c = Coons::from_top_object(&shapes::rectangle(r), None).unwrap();
|
||||
for (u, v) in [(0.125, 0.3), (0.9, 0.05), (0.37, 0.81)] {
|
||||
let p = c.eval(u, v);
|
||||
assert!(p.distance(Point::new(10.0 + 100.0 * u, 20.0 + 50.0 * v)) < 1e-9, "({u}, {v}) → {p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_straight_line_top_object_maps_onto_its_bounding_box() {
|
||||
let line = PathData::single(SubPath::new(vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor::corner(Point::new(100.0, 40.0))], false));
|
||||
let p = Coons::from_top_object(&line, None).unwrap().eval(0.25, 0.75);
|
||||
assert!(p.distance(Point::new(25.0, 30.0)) < 1e-9, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_spreads_a_segment_by_its_parameter() {
|
||||
// The top side is one straight segment whose handles sit at 60 and 80: its parameter
|
||||
// reaches the middle at x = 63.75, not at 45.
|
||||
let mut top = vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor::corner(Point::new(90.0, 0.0))];
|
||||
top[0].h_out = Point::new(60.0, 0.0);
|
||||
top[1].h_in = Point::new(80.0, 0.0);
|
||||
top.extend([Anchor::corner(Point::new(90.0, 40.0)), Anchor::corner(Point::new(0.0, 40.0))]);
|
||||
let kind = EnvelopeKind::TopObject { path: PathData::single(SubPath::new(top, true)), corners: None };
|
||||
let map = envelope_mapper(&kind, Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let p = map(Point::new(5.0, 0.0));
|
||||
assert!(p.distance(Point::new(63.75, 0.0)) < 1e-6, "{p:?}");
|
||||
let p = map(Point::new(5.0, 10.0));
|
||||
assert!(p.distance(Point::new(45.0, 40.0)) < 1e-6, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_follows_a_curved_side_by_its_parameter() {
|
||||
// The top side bends down from (0,0) to (100,0) through handles at (20,30) and (90,30):
|
||||
// halfway along its parameter it passes (53.75, 22.5).
|
||||
let mut top = vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor::corner(Point::new(100.0, 0.0))];
|
||||
top[0].h_out = Point::new(20.0, 30.0);
|
||||
top[1].h_in = Point::new(90.0, 30.0);
|
||||
top.extend([Anchor::corner(Point::new(100.0, 80.0)), Anchor::corner(Point::new(0.0, 80.0))]);
|
||||
let path = PathData::single(SubPath::new(top, true));
|
||||
let c = Coons::from_top_object(&path, None).unwrap();
|
||||
for (u, t) in [(0.5, 0.5), (0.25, 0.25), (0.8125, 0.8125)] {
|
||||
let want = CubicBez::new((0.0, 0.0), (20.0, 30.0), (90.0, 30.0), (100.0, 0.0)).eval(t);
|
||||
let p = c.eval(u, 0.0);
|
||||
assert!(p.distance(want) < 1e-6, "u {u}: {p:?} vs {want:?}");
|
||||
}
|
||||
// Drawn the other way round, the outline gives the same patch.
|
||||
let mut back = path.clone();
|
||||
back.subpaths[0].reverse();
|
||||
let p = Coons::from_top_object(&back, None).unwrap().eval(0.5, 0.0);
|
||||
assert!(p.distance(Point::new(53.75, 22.5)) < 1e-6, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_side_of_many_segments_keeps_each_corner() {
|
||||
// The top side zigzags through `n` straight segments, between y = 0 and y = 2.
|
||||
for n in [3, 100] {
|
||||
let w = f64::from(n);
|
||||
let zig = |i: i32| Point::new(f64::from(i) * 100.0 / w, if i % 2 == 1 { 2.0 } else { 0.0 });
|
||||
let mut pts: Vec<Anchor> = (0..=n).map(|i| Anchor::corner(zig(i))).collect();
|
||||
pts.extend([Anchor::corner(Point::new(100.0, 50.0)), Anchor::corner(Point::new(0.0, 50.0))]);
|
||||
let c = Coons::from_top_object(&PathData::single(SubPath::new(pts, true)), None).unwrap();
|
||||
for i in (1..n).filter(|i| n < 10 || [1, 37, 38, 99].contains(i)) {
|
||||
let p = c.eval(f64::from(i) / w, 0.0);
|
||||
assert!(p.distance(zig(i)) < 1e-9, "{n} segments, anchor {i}: {p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_mesh_outline_keeps_its_sides_measured_by_length() {
|
||||
let c = Coons::from_path(&top_split_at_30()).unwrap();
|
||||
let p = c.eval(0.5, 0.0);
|
||||
assert!(p.distance(Point::new(50.0, 0.0)) < 1e-6, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_identity() {
|
||||
let r = Rect::new(0.0, 0.0, 100.0, 100.0);
|
||||
|
||||
@@ -32,7 +32,14 @@ pub enum EnvelopeKind {
|
||||
handles: Vec<[Vec2; 4]>,
|
||||
},
|
||||
/// The content's bounding box maps onto the outline of this path.
|
||||
TopObject { path: PathData },
|
||||
TopObject {
|
||||
path: PathData,
|
||||
/// The anchors (indices into the outline, the path's largest subpath, in its own order)
|
||||
/// at the top left, top right, bottom right and bottom left corners, as a saved file gives
|
||||
/// them. `None`: the corners are found from the outline.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
corners: Option<[u32; 4]>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Envelope Options → Preserve Shape Using: how a distorted raster keeps the envelope's shape.
|
||||
@@ -518,7 +525,7 @@ pub fn envelope_overlay(n: &Node) -> Option<(PathData, Option<GradientMesh>)> {
|
||||
Some((grid.lines(), Some(grid)))
|
||||
}
|
||||
EnvelopeKind::Warp { .. } => Some((EnvelopeMap::of(n)?.surface_mesh(4, 4, Color::BLACK).lines(), None)),
|
||||
EnvelopeKind::TopObject { path } => Some((path.clone(), None)),
|
||||
EnvelopeKind::TopObject { path, .. } => Some((path.clone(), None)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -642,7 +649,7 @@ pub fn envelope_bounds(content: &[Arc<Node>], kind: &EnvelopeKind, frame: Affine
|
||||
let first = *points.first()?;
|
||||
Some(points.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p)))
|
||||
}
|
||||
EnvelopeKind::TopObject { path } => path.bounds(),
|
||||
EnvelopeKind::TopObject { path, .. } => path.bounds(),
|
||||
EnvelopeKind::Warp { .. } => EnvelopeMap::new(content, kind, frame, options)?.bounds(),
|
||||
}
|
||||
}
|
||||
|
||||
+262
-7
@@ -73,13 +73,16 @@ const SIDE: usize = 65;
|
||||
|
||||
/// Four boundary curves (top TL→TR, right TR→BR, bottom BL→BR, left TL→BL), each resampled to
|
||||
/// [`SIDE`] points, from the outline of a closed path split at the points nearest its bounding
|
||||
/// box corners.
|
||||
/// box corners. [`Coons::from_top_object`] samples its sides at the places `knots` gives instead.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Coons {
|
||||
top: Vec<Point>,
|
||||
right: Vec<Point>,
|
||||
bottom: Vec<Point>,
|
||||
left: Vec<Point>,
|
||||
/// Where along its side (0 to 1, rising) each point of the top, right, bottom and left side
|
||||
/// lies; `None` when the points are evenly spaced.
|
||||
knots: Option<Box<[Vec<f64>; 4]>>,
|
||||
}
|
||||
|
||||
impl Coons {
|
||||
@@ -87,9 +90,11 @@ impl Coons {
|
||||
pub fn rect(r: Rect) -> Self {
|
||||
let line = |a: Point, b: Point| (0..SIDE).map(|i| a.lerp(b, i as f64 / (SIDE - 1) as f64)).collect::<Vec<_>>();
|
||||
let (tl, tr, br, bl) = (Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1));
|
||||
Self { top: line(tl, tr), right: line(tr, br), bottom: line(bl, br), left: line(tl, bl) }
|
||||
Self { top: line(tl, tr), right: line(tr, br), bottom: line(bl, br), left: line(tl, bl), knots: None }
|
||||
}
|
||||
|
||||
/// The patch of `path`'s outline, each side measured by its length: equal steps in `u` or `v`
|
||||
/// cover equal lengths of the side.
|
||||
pub fn from_path(path: &PathData) -> Option<Self> {
|
||||
// The largest subpath is the outline.
|
||||
let sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?;
|
||||
@@ -136,7 +141,145 @@ impl Coons {
|
||||
bottom.reverse();
|
||||
let mut left = resample(&arc(bl, tl), SIDE);
|
||||
left.reverse();
|
||||
Some(Self { top, right, bottom, left })
|
||||
Some(Self { top, right, bottom, left, knots: None })
|
||||
}
|
||||
|
||||
/// The patch of a top object's outline (the largest subpath of `path`), split into four sides
|
||||
/// at its corners. Each piece of a side between two anchors or corners takes a share of `u` or
|
||||
/// `v` in proportion to the length of its control polygon, spread along the piece by its own
|
||||
/// curve parameter. A segment without handles counts as a cubic with its handles a third of
|
||||
/// the way along, so the content spreads evenly along it. `corners` are the anchors (indices
|
||||
/// into the outline, in its own order) at the top left, top right, bottom right and bottom
|
||||
/// left, as a saved file gives them. They stay on those anchors when they run the way the
|
||||
/// outline does or the opposite way, so a reflected outline keeps them; without them, or when
|
||||
/// they don't fit the outline, each corner is found from the outline ([`top_object_corner`]).
|
||||
/// A straight segment closes an open subpath, and segments of no length are left out. A top
|
||||
/// object's envelope maps onto this patch.
|
||||
pub fn from_top_object(path: &PathData, corners: Option<[u32; 4]>) -> Option<Self> {
|
||||
let sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?;
|
||||
let mut sp = sp.clone();
|
||||
let count = sp.anchors.len();
|
||||
// Stored corners count only when they are distinct anchors met in order around the outline.
|
||||
let fits = |c: &[usize; 4]| {
|
||||
if !c.iter().all(|i| *i < count) {
|
||||
return false;
|
||||
}
|
||||
let gaps: Vec<usize> = (0..4).map(|k| (c[(k + 1) % 4] + count - c[k]) % count).collect();
|
||||
gaps.iter().all(|g| *g > 0) && gaps.iter().sum::<usize>() == count
|
||||
};
|
||||
let given = corners.map(|c| c.map(|i| i as usize));
|
||||
// Stored corners met in the outline's own order keep it as drawn, even counter-clockwise
|
||||
// (a reflected outline). Otherwise orient it clockwise in y-down (TL → TR → BR → BL).
|
||||
let mut corners = given.filter(fits);
|
||||
let reversed = corners.is_none() && sp.signed_area() < 0.0;
|
||||
if reversed {
|
||||
sp.reverse();
|
||||
corners = given.map(|c| c.map(|i| count.saturating_sub(1).saturating_sub(i))).filter(fits);
|
||||
}
|
||||
// Each segment, and whether it is straight: a straight one's parameter runs evenly along it.
|
||||
let line = |a: Point, b: Point| (CubicBez::new(a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b), true);
|
||||
let mut segs: Vec<(usize, (CubicBez, bool))> = (0..sp.segment_count())
|
||||
.map(|i| {
|
||||
let c = sp.segment(i);
|
||||
(i, if sp.segment_is_line(i) { line(c.p0, c.p3) } else { (c, false) })
|
||||
})
|
||||
.collect();
|
||||
if !sp.closed
|
||||
&& let (Some(a), Some(b)) = (sp.anchors.last(), sp.anchors.first())
|
||||
{
|
||||
segs.push((count.saturating_sub(1), line(a.p, b.p)));
|
||||
}
|
||||
segs.retain(|(_, (c, _))| [c.p1, c.p2, c.p3].iter().any(|p| p.distance(c.p0) > 1e-9));
|
||||
// The kept segment that anchor `k` starts (a segment of no length starts where the next begins).
|
||||
let starts: Vec<usize> = segs.iter().map(|(i, _)| *i).collect();
|
||||
// Where each kept segment and the anchor it starts at come in the outline as drawn: a tie
|
||||
// between corners goes to the one met first there.
|
||||
let order: Vec<(usize, usize)> = starts
|
||||
.iter()
|
||||
.map(|&i| if reversed { (count.saturating_sub(1).saturating_sub(i), (2 * count).saturating_sub(2 + i) % count.max(1)) } else { (i, i) })
|
||||
.collect();
|
||||
let segs: Vec<(CubicBez, bool)> = segs.into_iter().map(|(_, s)| s).collect();
|
||||
let r = segs.iter().map(|(c, _)| c.bounding_box()).reduce(|a, b| a.union(b)).or_else(|| path.bounds())?;
|
||||
// An outline of fewer than three points (a straight line there and back) maps onto its
|
||||
// bounding box, as in `from_path`.
|
||||
if segs.len() < 2 || (segs.len() == 2 && segs.iter().all(|(_, straight)| *straight)) {
|
||||
return Some(Self::rect(r));
|
||||
}
|
||||
let n = segs.len() as f64;
|
||||
let at = |s: f64| {
|
||||
let s = s.rem_euclid(n);
|
||||
let i = (s.floor() as usize).min(segs.len() - 1);
|
||||
segs.get(i).map_or(Point::ZERO, |(c, _)| c.eval((s - i as f64).clamp(0.0, 1.0)))
|
||||
};
|
||||
// The side from `a` to `b`: its points, and where along it (0 to 1) each lies. It runs
|
||||
// through pieces of segments, split at `a` and `b`. Each piece takes its share of the side
|
||||
// by the length of its control polygon and holds points at even steps of its parameter
|
||||
// (at least 16, and at least `SIDE` points on the side), its ends included. A side of
|
||||
// many pieces takes fewer points in each, so it holds at most `MAX_SIDE_POINTS` points,
|
||||
// or one for each piece when it has more pieces than that.
|
||||
let side = |a: f64, b: f64| {
|
||||
let span = (b - a).rem_euclid(n);
|
||||
if !(span.is_finite() && span > 0.0) {
|
||||
return (vec![at(a), at(a)], vec![0.0, 1.0]);
|
||||
}
|
||||
let mut pieces: Vec<CubicBez> = vec![];
|
||||
let (mut s, end) = (a, a + span);
|
||||
while s < end - 1e-12 && pieces.len() <= segs.len() {
|
||||
let i = s.floor();
|
||||
let next = (i + 1.0).min(end);
|
||||
if let Some((c, _)) = segs.get((i as usize) % segs.len()) {
|
||||
pieces.push(c.subsegment((s - i).clamp(0.0, 1.0)..(next - i).clamp(0.0, 1.0)));
|
||||
}
|
||||
s = next;
|
||||
}
|
||||
let polygon = |c: &CubicBez| c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3);
|
||||
let mut weights: Vec<f64> = pieces.iter().map(polygon).collect();
|
||||
let mut total: f64 = weights.iter().sum();
|
||||
if !(total.is_finite() && total > 0.0) {
|
||||
weights.iter_mut().for_each(|w| *w = 1.0);
|
||||
total = weights.len().max(1) as f64;
|
||||
}
|
||||
let count = pieces.len().max(1);
|
||||
let per = 16usize.max((SIDE - 1).div_ceil(count));
|
||||
let per = if count * per < MAX_SIDE_POINTS { per } else { (MAX_SIDE_POINTS / count).max(1) };
|
||||
let mut pts = vec![pieces.first().map_or_else(|| at(a), |c| c.p0)];
|
||||
let mut knots = vec![0.0];
|
||||
let mut before = 0.0;
|
||||
for (c, w) in pieces.iter().zip(&weights) {
|
||||
for k in 1..=per {
|
||||
let f = k as f64 / per as f64;
|
||||
pts.push(c.eval(f));
|
||||
knots.push((before + w * f) / total);
|
||||
}
|
||||
before += w;
|
||||
}
|
||||
if let Some(last) = knots.last_mut() {
|
||||
*last = 1.0;
|
||||
}
|
||||
(pts, knots)
|
||||
};
|
||||
let (tl, tr, br, bl) = match corners {
|
||||
// Anchor `k` sits at the start of the first kept segment from it on.
|
||||
Some(c) => {
|
||||
let place = |k: usize| starts.iter().position(|i| *i >= k).unwrap_or(0) as f64;
|
||||
(place(c[0]), place(c[1]), place(c[2]), place(c[3]))
|
||||
}
|
||||
None => {
|
||||
let corner = |q: Point| top_object_corner(&segs, &order, r, q);
|
||||
(corner(Point::new(r.x0, r.y0)), corner(Point::new(r.x1, r.y0)), corner(Point::new(r.x1, r.y1)), corner(Point::new(r.x0, r.y1)))
|
||||
}
|
||||
};
|
||||
let flip = |(mut p, mut u): (Vec<Point>, Vec<f64>)| {
|
||||
p.reverse();
|
||||
u.reverse();
|
||||
u.iter_mut().for_each(|x| *x = 1.0 - *x);
|
||||
(p, u)
|
||||
};
|
||||
let (top, top_u) = side(tl, tr);
|
||||
let (right, right_u) = side(tr, br);
|
||||
let (bottom, bottom_u) = flip(side(br, bl));
|
||||
let (left, left_u) = flip(side(bl, tl));
|
||||
Some(Self { top, right, bottom, left, knots: Some(Box::new([top_u, right_u, bottom_u, left_u])) })
|
||||
}
|
||||
|
||||
/// The point at `u` along a side; past its ends the end segments go on straight (art an
|
||||
@@ -147,10 +290,36 @@ impl Coons {
|
||||
side[i].lerp(side[i + 1], s - i as f64)
|
||||
}
|
||||
|
||||
/// The point at `u` along a side whose points lie at `knots` (rising, 0 to 1); past its ends
|
||||
/// the end segments go on straight, as in [`Self::sample`].
|
||||
fn sample_at(side: &[Point], knots: &[f64], u: f64) -> Point {
|
||||
if side.len() < 2 || side.len() != knots.len() {
|
||||
return side.first().copied().unwrap_or_default();
|
||||
}
|
||||
let i = knots.partition_point(|k| *k <= u).clamp(1, side.len() - 1) - 1;
|
||||
let (k0, k1) = (knots[i], knots[i + 1]);
|
||||
let f = if k1 > k0 { (u - k0) / (k1 - k0) } else { 0.0 };
|
||||
side[i].lerp(side[i + 1], f)
|
||||
}
|
||||
|
||||
/// The point at `u` along side `which` (0 top, 1 right, 2 bottom, 3 left).
|
||||
fn side_at(&self, which: usize, u: f64) -> Point {
|
||||
let side = match which {
|
||||
0 => &self.top,
|
||||
1 => &self.right,
|
||||
2 => &self.bottom,
|
||||
_ => &self.left,
|
||||
};
|
||||
match self.knots.as_deref().and_then(|k| k.get(which)) {
|
||||
Some(knots) => Self::sample_at(side, knots, u),
|
||||
None => Self::sample(side, u),
|
||||
}
|
||||
}
|
||||
|
||||
/// The surface point at (u, v) ∈ [0,1]².
|
||||
pub fn eval(&self, u: f64, v: f64) -> Point {
|
||||
let (t, b, l, r) = (Self::sample(&self.top, u), Self::sample(&self.bottom, u), Self::sample(&self.left, v), Self::sample(&self.right, v));
|
||||
let (p00, p10, p01, p11) = (self.top[0], self.top[SIDE - 1], self.bottom[0], self.bottom[SIDE - 1]);
|
||||
let (t, b, l, r) = (self.side_at(0, u), self.side_at(2, u), self.side_at(3, v), self.side_at(1, v));
|
||||
let [p00, p10, p11, p01] = self.corners();
|
||||
let c = (1.0 - v) * t.to_vec2() + v * b.to_vec2() + (1.0 - u) * l.to_vec2() + u * r.to_vec2()
|
||||
- ((1.0 - u) * (1.0 - v) * p00.to_vec2() + u * (1.0 - v) * p10.to_vec2() + (1.0 - u) * v * p01.to_vec2() + u * v * p11.to_vec2());
|
||||
c.to_point()
|
||||
@@ -158,7 +327,93 @@ impl Coons {
|
||||
|
||||
/// The four corners TL, TR, BR, BL.
|
||||
pub fn corners(&self) -> [Point; 4] {
|
||||
[self.top[0], self.top[SIDE - 1], self.bottom[SIDE - 1], self.bottom[0]]
|
||||
let end = |side: &[Point]| side.last().copied().unwrap_or_default();
|
||||
[self.top[0], end(&self.top), end(&self.bottom), self.bottom[0]]
|
||||
}
|
||||
}
|
||||
|
||||
/// The most points one side of [`Coons::from_top_object`] holds while it adds points between its
|
||||
/// anchors.
|
||||
const MAX_SIDE_POINTS: usize = 1 << 16;
|
||||
|
||||
/// How far into the outline's bounding box, as a share of its width and of its height, a corner
|
||||
/// of a top object looks for an anchor.
|
||||
const CORNER_REACH: f64 = 0.475;
|
||||
|
||||
/// A handle this long (in points) or shorter makes its anchor a corner of a top object.
|
||||
const SHORT_HANDLE: f64 = 0.01;
|
||||
|
||||
/// An anchor whose tangent directions, as unit vectors, differ by less than this in x and in y is
|
||||
/// smooth, and is not a corner of a top object.
|
||||
const SMOOTH_TURN: f64 = 0.01;
|
||||
|
||||
/// A top object's corner this close (in curve parameter) to either end of its segment moves onto
|
||||
/// the anchor there.
|
||||
const CORNER_END_SNAP: f64 = 0.005;
|
||||
|
||||
/// Is the anchor at `a`, reached by handle `h_in` and left by handle `h_out` on an outline that
|
||||
/// runs clockwise on screen, a corner of a top object? A handle of [`SHORT_HANDLE`] or shorter
|
||||
/// makes it one. Otherwise its tangent directions must differ by [`SMOOTH_TURN`] or more and turn
|
||||
/// clockwise, so it points out of the outline. A straight segment's handles here are the ones
|
||||
/// [`Coons::from_top_object`] gives it, a third of the way along, so an anchor between two
|
||||
/// straight segments longer than three times [`SHORT_HANDLE`] is a corner only when it turns out
|
||||
/// of the outline.
|
||||
fn top_object_corner_anchor(h_in: Point, a: Point, h_out: Point) -> bool {
|
||||
let (vin, vout) = (a - h_in, h_out - a);
|
||||
let (len_in, len_out) = (vin.hypot(), vout.hypot());
|
||||
if len_in <= SHORT_HANDLE || len_out <= SHORT_HANDLE {
|
||||
return true;
|
||||
}
|
||||
let (ui, uo) = (vin / len_in, vout / len_out);
|
||||
if (ui.x - uo.x).abs() < SMOOTH_TURN && (ui.y - uo.y).abs() < SMOOTH_TURN {
|
||||
return false;
|
||||
}
|
||||
ui.cross(uo) >= 0.0
|
||||
}
|
||||
|
||||
/// Where along `segs` (segment index + parameter, in [0, n)) the corner of a top object nearest
|
||||
/// corner `q` of its bounding box `r` lies, for an outline that runs clockwise on screen. It is
|
||||
/// the nearest anchor to `q` that is a corner ([`top_object_corner_anchor`]) and lies within
|
||||
/// [`CORNER_REACH`] of the box's width and height from `q`. Without one, it is the nearest point
|
||||
/// of the outline to `q`, moved onto its segment's anchor when within [`CORNER_END_SNAP`] of
|
||||
/// either end. `order` gives where each segment's first anchor and the segment itself come in the
|
||||
/// outline as drawn, which may run the other way; on a tie the one met first there wins.
|
||||
fn top_object_corner(segs: &[(CubicBez, bool)], order: &[(usize, usize)], r: Rect, q: Point) -> f64 {
|
||||
use vectorcraft_geom::kurbo::ParamCurveNearest;
|
||||
let n = segs.len();
|
||||
if n == 0 {
|
||||
return 0.0;
|
||||
}
|
||||
let rank = |i: usize| order.get(i).copied().unwrap_or((i, i));
|
||||
let (reach_x, reach_y) = (r.width() * CORNER_REACH, r.height() * CORNER_REACH);
|
||||
let mut best: Option<(f64, usize, usize)> = None;
|
||||
for i in 0..n {
|
||||
let (Some((prev, _)), Some((cur, _))) = (segs.get((i + n - 1) % n), segs.get(i)) else { continue };
|
||||
let a = cur.p0;
|
||||
if (a.x - q.x).abs() > reach_x || (a.y - q.y).abs() > reach_y || !top_object_corner_anchor(prev.p2, a, cur.p1) {
|
||||
continue;
|
||||
}
|
||||
let (d, k) = (a.distance_squared(q), rank(i).0);
|
||||
if best.is_none_or(|(b, bk, _)| d < b || (d == b && k < bk)) {
|
||||
best = Some((d, k, i));
|
||||
}
|
||||
}
|
||||
if let Some((_, _, i)) = best {
|
||||
return i as f64;
|
||||
}
|
||||
let tol = (r.width() + r.height()).max(1e-6) * 1e-9;
|
||||
let nearest = segs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (c, _))| (c.nearest(q, tol), i))
|
||||
.min_by(|a, b| a.0.distance_sq.total_cmp(&b.0.distance_sq).then(rank(a.1).1.cmp(&rank(b.1).1)));
|
||||
let Some((near, i)) = nearest else { return 0.0 };
|
||||
if near.t > CORNER_END_SNAP && near.t < 1.0 - CORNER_END_SNAP {
|
||||
i as f64 + near.t
|
||||
} else if near.t < 0.5 {
|
||||
i as f64
|
||||
} else {
|
||||
((i + 1) % n) as f64
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1033,7 +1288,7 @@ pub(super) fn surface_of<'a>(kind: &'a EnvelopeKind, src: Rect, frame: Affine) -
|
||||
let (rows, cols) = (*rows as usize, *cols as usize);
|
||||
Box::new(move |u: f64, v: f64| grid_eval(rows, cols, points, u, v))
|
||||
}
|
||||
EnvelopeKind::TopObject { path } => match Coons::from_path(path) {
|
||||
EnvelopeKind::TopObject { path, corners } => match Coons::from_top_object(path, *corners) {
|
||||
Some(co) => Box::new(move |u: f64, v: f64| co.eval(u, v)),
|
||||
None => Box::new(flat),
|
||||
},
|
||||
|
||||
@@ -103,6 +103,11 @@ impl Document {
|
||||
let styles = |s: &Vec<TextStyleDef>| vec_bytes(s) + s.iter().map(|s| s.name.capacity() + map_bytes(&s.attrs)).sum::<usize>();
|
||||
n += shared(&self.char_styles, &newer.char_styles, styles);
|
||||
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();
|
||||
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>()
|
||||
});
|
||||
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>()
|
||||
});
|
||||
|
||||
@@ -31,6 +31,7 @@ pub use ids::{LAYER_COLORS, LayerColor, NodeId};
|
||||
pub use kind::{ImageObject, MAX_BUFFERED_VALUES, NodeKind, with_buffered_value_budget};
|
||||
pub use live_shape::{LiveShape, Scaling};
|
||||
pub use opacity::{Knockout, OpacityMask, whiten};
|
||||
pub use ops::{flattens, keeps_gradient_fit};
|
||||
use wire::NodeWire;
|
||||
pub use wire::{MAX_READ_NODES, with_node_budget};
|
||||
|
||||
|
||||
@@ -69,6 +69,9 @@ pub struct NodeExtras {
|
||||
/// As an envelope with margins in Edit Contents, the margins its strokes gave when Edit Contents
|
||||
/// began ([`crate::live::EnvelopeOptions::bounds_margin`]).
|
||||
pub envelope_edit_margin: Option<[f32; 4]>,
|
||||
/// Transform panel › Align to Pixel Grid: the path's or compound path's horizontal and vertical
|
||||
/// segments stay on the pixel grid when it is transformed.
|
||||
pub pixel_aligned: bool,
|
||||
}
|
||||
|
||||
/// No extras: what [`Node::extras`] gives for a node without any.
|
||||
@@ -95,6 +98,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
|
||||
shape_mode: crate::ShapeMode::Add,
|
||||
symbol_overrides: Vec::new(),
|
||||
envelope_edit_margin: None,
|
||||
pixel_aligned: false,
|
||||
};
|
||||
|
||||
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
|
||||
|
||||
@@ -329,6 +329,10 @@ pub struct Scaling {
|
||||
/// Pattern fills and strokes move with the art (Transform Patterns; General › Transform
|
||||
/// Pattern Tiles is its default): their tiles transform too, instead of staying put.
|
||||
pub patterns: bool,
|
||||
/// Gradients fitted to the object stay fitted under a transform that flattens it to a line or
|
||||
/// a point (no area left), as a Transform effect leaves them, instead of being fixed to their
|
||||
/// fit and flattened to one color with the object.
|
||||
pub keep_fit_when_flat: bool,
|
||||
}
|
||||
|
||||
impl Scaling {
|
||||
|
||||
@@ -239,10 +239,12 @@ impl Node {
|
||||
NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))),
|
||||
// The frame and each shape the image's own fills and strokes paint, a stroke's grown by
|
||||
// the farthest it can reach from its shape.
|
||||
NodeKind::Image(_) => crate::hit::image_paint(self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| {
|
||||
let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
|
||||
vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
|
||||
}),
|
||||
NodeKind::Image(_) => {
|
||||
crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| {
|
||||
let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
|
||||
vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
|
||||
})
|
||||
}
|
||||
// Keys and steps placed on a spine, turned to it with Align to Path, can reach past the
|
||||
// keys and the spine.
|
||||
NodeKind::Blend { children, spec } => {
|
||||
@@ -431,7 +433,7 @@ impl Node {
|
||||
// Type and symbols in perspective keep looking the same, moved by `a`.
|
||||
self.transform_projection(a);
|
||||
// Refitting an unplaced gradient only reproduces moves and uniform scales.
|
||||
if !keeps_gradient_fit(a) {
|
||||
if !keeps_gradient_fit(a) && !(sc.keep_fit_when_flat && flattens(a)) {
|
||||
self.pin_gradients();
|
||||
}
|
||||
let k = Scaling::factor(a);
|
||||
@@ -448,6 +450,9 @@ impl Node {
|
||||
if self.appearance.gradients().next().is_some() {
|
||||
self.appearance.transform_gradients(a);
|
||||
}
|
||||
if self.appearance.has_svg_filter() {
|
||||
self.appearance.transform_svg_filters(a);
|
||||
}
|
||||
if sc.patterns {
|
||||
crate::pattern::transform_pattern_paints(self, a);
|
||||
}
|
||||
@@ -508,7 +513,7 @@ impl Node {
|
||||
*h = (lin * h.to_point()).to_vec2();
|
||||
}
|
||||
}
|
||||
EnvelopeKind::TopObject { path } => path.transform(a),
|
||||
EnvelopeKind::TopObject { path, .. } => path.transform(a),
|
||||
EnvelopeKind::Warp { .. } => {}
|
||||
}
|
||||
}
|
||||
@@ -767,13 +772,24 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `a` a move plus a positive uniform scale (after which a refit gradient still matches)?
|
||||
fn keeps_gradient_fit(a: Affine) -> bool {
|
||||
/// Is `a` a move plus a positive uniform scale (after which a refit gradient still matches)? The
|
||||
/// terms are compared within 1e-12 of the scale (at least of 1). A scale of 0 or less, a turn, a
|
||||
/// reflection and an uneven scale give false, and so does a map that flattens the object
|
||||
/// ([`flattens`]), which callers that keep a fitted gradient there check apart.
|
||||
pub fn keeps_gradient_fit(a: Affine) -> bool {
|
||||
let [m0, m1, m2, m3, _, _] = a.as_coeffs();
|
||||
let eps = 1e-12 * m0.abs().max(1.0);
|
||||
m0 > 0.0 && m1.abs() <= eps && m2.abs() <= eps && (m0 - m3).abs() <= eps
|
||||
}
|
||||
|
||||
/// Does `a` flatten what it maps to a line or a point (its determinant 0, within 1e-12 of the
|
||||
/// squares of its terms), or is it not finite?
|
||||
pub fn flattens(a: Affine) -> bool {
|
||||
let [m0, m1, m2, m3, _, _] = a.as_coeffs();
|
||||
let norm = m0 * m0 + m1 * m1 + m2 * m2 + m3 * m3;
|
||||
!a.is_finite() || a.determinant().abs() <= 1e-12 * norm
|
||||
}
|
||||
|
||||
impl Node {
|
||||
/// Whether a document point lies in this object's filled regions ([`Node::clip_shapes`]; true
|
||||
/// everywhere for objects without them, such as type, whose boxes stand in).
|
||||
|
||||
@@ -22,6 +22,7 @@ fn extras_are_written_flat_in_order() {
|
||||
e.compound_shape = true;
|
||||
e.shape_mode = crate::ShapeMode::Exclude;
|
||||
e.envelope_edit_margin = Some([0.5, 0.5, 0.25, 0.25]);
|
||||
e.pixel_aligned = true;
|
||||
}
|
||||
/// The top-level keys of a JSON object, in the order written.
|
||||
struct Keys(Vec<String>);
|
||||
@@ -67,9 +68,11 @@ fn extras_are_written_flat_in_order() {
|
||||
"compound_shape",
|
||||
"shape_mode",
|
||||
"envelope_edit_margin",
|
||||
"pixel_aligned",
|
||||
];
|
||||
assert_eq!(keys, order);
|
||||
assert_eq!(v["shape_mode"], "exclude");
|
||||
assert_eq!(v["pixel_aligned"], true);
|
||||
assert_eq!(serde_json::from_value::<Node>(v).unwrap(), n);
|
||||
let plain = Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), Appearance::default_art());
|
||||
let back: Node = serde_json::from_value(serde_json::to_value(&plain).unwrap()).unwrap();
|
||||
@@ -218,7 +221,8 @@ fn assert_round_corners(n: &Node, back: Affine, r: f64) {
|
||||
}
|
||||
}
|
||||
|
||||
const KEEP_CORNERS: Scaling = Scaling { strokes: false, effects: None, keep_type_strokes: false, keep_corners: true, patterns: false };
|
||||
const KEEP_CORNERS: Scaling =
|
||||
Scaling { strokes: false, effects: None, keep_type_strokes: false, keep_corners: true, patterns: false, keep_fit_when_flat: false };
|
||||
|
||||
#[test]
|
||||
fn uneven_scales_keep_live_corners_circular() {
|
||||
|
||||
@@ -54,6 +54,7 @@ impl Serialize for Node {
|
||||
is_default(&e.shape_mode),
|
||||
e.symbol_overrides.is_empty(),
|
||||
e.envelope_edit_margin.is_none(),
|
||||
is_default(&e.pixel_aligned),
|
||||
];
|
||||
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
|
||||
let mut skip = skips.into_iter();
|
||||
@@ -96,6 +97,7 @@ impl Serialize for Node {
|
||||
field!("shape_mode", &e.shape_mode);
|
||||
field!("symbol_overrides", &e.symbol_overrides);
|
||||
field!("envelope_edit_margin", &e.envelope_edit_margin);
|
||||
field!("pixel_aligned", &e.pixel_aligned);
|
||||
st.end()
|
||||
}
|
||||
}
|
||||
@@ -236,6 +238,8 @@ pub(super) struct NodeWire {
|
||||
symbol_overrides: Vec<crate::SymbolOverride>,
|
||||
#[serde(default)]
|
||||
envelope_edit_margin: Option<[f32; 4]>,
|
||||
#[serde(default)]
|
||||
pixel_aligned: bool,
|
||||
}
|
||||
|
||||
impl From<NodeWire> for Node {
|
||||
@@ -263,6 +267,7 @@ impl From<NodeWire> for Node {
|
||||
shape_mode: w.shape_mode,
|
||||
symbol_overrides: w.symbol_overrides,
|
||||
envelope_edit_margin: w.envelope_edit_margin,
|
||||
pixel_aligned: w.pixel_aligned,
|
||||
};
|
||||
Node {
|
||||
id: w.id,
|
||||
|
||||
@@ -572,7 +572,8 @@ mod tests {
|
||||
place(&mut g, &symbols);
|
||||
g.transform(Affine::new([2.0, 0.0, 0.0, 1.0, 0.0, 0.0]), false);
|
||||
let rec = g.extras().objects_on_path.as_deref().cloned().unwrap();
|
||||
assert_eq!((rec.spacing, rec.start), (Some(40.0), 20.0));
|
||||
// The spine measures arc length along the curve, so within rounding of the exact values.
|
||||
assert!(rec.spacing.is_some_and(|d| (d - 40.0).abs() < 1e-9) && (rec.start - 20.0).abs() < 1e-9, "{rec:?}");
|
||||
place(&mut g, &symbols);
|
||||
let x = |id| g.children().and_then(|c| c.iter().find(|c| c.id == id).cloned()).unwrap().geometric_bounds().unwrap().center().x;
|
||||
assert!((x(NodeId(2)) - 20.0).abs() < 1e-9 && (x(NodeId(3)) - 60.0).abs() < 1e-9, "{} {}", x(NodeId(2)), x(NodeId(3)));
|
||||
|
||||
@@ -126,6 +126,23 @@ impl SavedSelection {
|
||||
}
|
||||
}
|
||||
|
||||
/// An SVG filter the document holds (Effect › SVG Filters): a `<filter>` element named by its
|
||||
/// `id`, listed in the SVG Filters submenu and in Apply SVG Filter.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SvgFilter {
|
||||
/// The filter element's `id`.
|
||||
pub name: String,
|
||||
/// The `<filter>` element's XML, as it was written.
|
||||
pub xml: String,
|
||||
}
|
||||
|
||||
impl SvgFilter {
|
||||
/// Most SVG filters a document holds.
|
||||
pub const MAX: usize = 64;
|
||||
/// Longest filter element, in bytes.
|
||||
pub const MAX_XML: usize = 64 * 1024;
|
||||
}
|
||||
|
||||
/// A symbol definition.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Symbol {
|
||||
|
||||
@@ -54,6 +54,20 @@ pub struct Selection {
|
||||
/// the engine then sets the document's from it. Editing state, never saved.
|
||||
#[serde(skip)]
|
||||
pub new_art: Arc<HashSet<NodeId>>,
|
||||
/// An object of a dynamic symbol instance's art, selected with Direct Selection: the instance
|
||||
/// is the one selected object, and solid fill and stroke changes go to its own appearance for
|
||||
/// that object ([`crate::symbol_overrides`]). Any other selection change clears it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub symbol_part: Option<SymbolPart>,
|
||||
}
|
||||
|
||||
/// See [`Selection::symbol_part`].
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SymbolPart {
|
||||
/// The symbol instance.
|
||||
pub instance: NodeId,
|
||||
/// The object in the symbol's art, as [`crate::symbol_overrides::part`] names it.
|
||||
pub path: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Selection {
|
||||
@@ -79,6 +93,13 @@ impl Selection {
|
||||
self.slices.clear();
|
||||
self.guides.clear();
|
||||
self.key_guide = None;
|
||||
self.symbol_part = None;
|
||||
}
|
||||
/// Select only instance `instance`, with the object at `path` of its symbol's art (see
|
||||
/// [`Selection::symbol_part`]).
|
||||
pub fn set_symbol_part(&mut self, instance: NodeId, path: Vec<u32>) {
|
||||
self.set([instance]);
|
||||
self.symbol_part = Some(SymbolPart { instance, path });
|
||||
}
|
||||
/// Is there a key for Align: an object or a guide?
|
||||
pub fn has_key(&self) -> bool {
|
||||
@@ -93,6 +114,7 @@ impl Selection {
|
||||
pub fn add(&mut self, id: NodeId) {
|
||||
self.target = None;
|
||||
self.slices.clear();
|
||||
self.symbol_part = None;
|
||||
if !self.objects.contains(&id) {
|
||||
self.objects.push(id);
|
||||
}
|
||||
@@ -100,6 +122,7 @@ impl Selection {
|
||||
pub fn remove(&mut self, id: NodeId) {
|
||||
self.target = None;
|
||||
self.slices.clear();
|
||||
self.symbol_part = None;
|
||||
self.objects.retain(|x| *x != id);
|
||||
self.anchors.remove(&id);
|
||||
self.segments.remove(&id);
|
||||
@@ -128,6 +151,7 @@ impl Selection {
|
||||
/// Add ruler guide `i` to the selection, or take it out, keeping the selected objects (a
|
||||
/// Shift-click on a guide).
|
||||
pub fn toggle_guide(&mut self, i: usize) {
|
||||
self.symbol_part = None;
|
||||
if let Some(k) = self.guides.iter().position(|g| *g == i) {
|
||||
self.guides.remove(k);
|
||||
if self.key_guide == Some(i) {
|
||||
@@ -207,6 +231,27 @@ 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 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.
|
||||
let editable_part = |art: &crate::Node, path: &[u32]| {
|
||||
crate::symbol_overrides::part(art, path).is_some_and(crate::symbol_overrides::takes_part_paint)
|
||||
&& (0..=path.len())
|
||||
.all(|k| crate::symbol_overrides::part(art, &path[..k]).is_some_and(|n| n.visible && !n.locked && !n.is_template()))
|
||||
};
|
||||
let part_kept = self.symbol_part.as_ref().is_some_and(|sp| {
|
||||
self.objects == [sp.instance]
|
||||
&& self.guides.is_empty()
|
||||
&& found.get(&sp.instance).and_then(|p| doc.node_at(p)).is_some_and(|n| match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => {
|
||||
doc.symbols.iter().find(|s| s.name == *symbol).is_some_and(|s| s.dynamic && editable_part(&s.art, &sp.path))
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
});
|
||||
if !part_kept {
|
||||
self.symbol_part = None;
|
||||
}
|
||||
}
|
||||
/// Deselect the objects that are hidden or locked, themselves or through a group or layer
|
||||
/// around them (and so the key object when it is one): hidden or locked art can't stay
|
||||
@@ -238,6 +283,9 @@ impl Selection {
|
||||
}
|
||||
self.target = None;
|
||||
self.slices.clear();
|
||||
if self.symbol_part.as_ref().is_some_and(|sp| gone.contains(&sp.instance)) {
|
||||
self.symbol_part = None;
|
||||
}
|
||||
self.objects.retain(|o| !gone.contains(o));
|
||||
self.anchors.retain(|id, _| !gone.contains(id));
|
||||
self.segments.retain(|id, _| !gone.contains(id));
|
||||
|
||||
@@ -41,6 +41,82 @@ fn guides_are_selected_on_their_own() {
|
||||
assert_eq!(s.guides, vec![0]);
|
||||
}
|
||||
|
||||
/// A picked object of a dynamic symbol's instance stays picked while it and the groups and layers
|
||||
/// around it in the symbol's art are visible, unlocked and not a template. An art edit that hides
|
||||
/// or locks it, or one around it, or makes a layer around it a template, drops the pick.
|
||||
#[test]
|
||||
fn a_picked_symbol_part_is_dropped_once_it_cannot_be_edited() {
|
||||
let rect = || vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let l = d.layers[0].id;
|
||||
let leaf = Node::path(d.alloc_id(), rect(), crate::Appearance::default_art());
|
||||
let group = Node::group(d.alloc_id(), vec![Arc::new(leaf)]);
|
||||
let layer = Node::layer(d.alloc_id(), "Inner", crate::LayerColor::Preset(2));
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(group), Arc::new(layer)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Parts".into(), art: Arc::new(root.clone()) });
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Parts".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
// The layer in the art holds a path too.
|
||||
let in_layer = Node::path(d.alloc_id(), rect(), crate::Appearance::default_art());
|
||||
let mut art = root;
|
||||
if let Some(NodeKind::Layer { children, .. }) = art.children_mut().and_then(|c| c.get_mut(1)).map(|c| &mut Arc::make_mut(c).kind) {
|
||||
children.push(Arc::new(in_layer));
|
||||
}
|
||||
d.symbols[0].art = Arc::new(art.clone());
|
||||
let picked = |d: &Document, path: &[u32]| {
|
||||
let mut s = Selection::default();
|
||||
s.set_symbol_part(inst, path.to_vec());
|
||||
s.prune(d);
|
||||
s.symbol_part.is_some()
|
||||
};
|
||||
assert!(picked(&d, &[0, 0]) && picked(&d, &[1, 0]), "editable parts stay picked");
|
||||
assert!(!picked(&d, &[0]) && !picked(&d, &[1]) && !picked(&d, &[]), "a group or layer does not stay picked");
|
||||
let edited = |change: &dyn Fn(&mut Node)| {
|
||||
let mut d = d.clone();
|
||||
let mut art = art.clone();
|
||||
change(&mut art);
|
||||
d.symbols[0].art = Arc::new(art);
|
||||
d
|
||||
};
|
||||
let child = |art: &mut Node, path: &[usize]| -> Node {
|
||||
let mut n = &*art;
|
||||
for &i in path {
|
||||
n = &n.children().unwrap()[i];
|
||||
}
|
||||
n.clone()
|
||||
};
|
||||
let set = |art: &mut Node, path: &[usize], n: Node| {
|
||||
let mut at = art;
|
||||
for &i in path {
|
||||
at = Arc::make_mut(&mut at.children_mut().unwrap()[i]);
|
||||
}
|
||||
*at = n;
|
||||
};
|
||||
let hidden = edited(&|art| {
|
||||
let mut n = child(art, &[0, 0]);
|
||||
n.visible = false;
|
||||
set(art, &[0, 0], n);
|
||||
});
|
||||
assert!(!picked(&hidden, &[0, 0]), "the part is hidden");
|
||||
let locked_group = edited(&|art| {
|
||||
let mut n = child(art, &[0]);
|
||||
n.locked = true;
|
||||
set(art, &[0], n);
|
||||
});
|
||||
assert!(!picked(&locked_group, &[0, 0]), "the group around it is locked");
|
||||
assert!(picked(&locked_group, &[1, 0]), "a part outside the locked group stays");
|
||||
let template = edited(&|art| {
|
||||
let mut n = child(art, &[1]);
|
||||
if let NodeKind::Layer { template, .. } = &mut n.kind {
|
||||
*template = true;
|
||||
}
|
||||
set(art, &[1], n);
|
||||
});
|
||||
assert!(!picked(&template, &[1, 0]), "the layer around it is a template");
|
||||
let hidden_root = edited(&|art| art.visible = false);
|
||||
assert!(!picked(&hidden_root, &[0, 0]), "the art is hidden");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guides_show_and_lock_with_their_layer() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
|
||||
@@ -120,6 +120,21 @@ impl Quotes {
|
||||
prev.is_none_or(|p| p.is_whitespace() || matches!(p, '(' | '[' | '{' | '—' | '–') || quote_opened.unwrap_or_else(|| self.is_open(p)))
|
||||
}
|
||||
|
||||
/// The straight quote a typed curly quote stands for: `"` for `”` (U+201D) and nothing else.
|
||||
/// The macOS Serbian Cyrillic layout has no straight `"` and types `”` on Shift+2, so with
|
||||
/// Typographer's Quotes on, a `”` typed alone where a quote opens takes the document's opening
|
||||
/// quote ([`Quotes::opens_after`]); where a quote closes it stays `”`. `“ „` and the single
|
||||
/// quotes `‘ ’ ‚` stay as typed: that layout's apostrophe key already types `’`, as Serbian
|
||||
/// wants, and `’90s` keeps its apostrophe.
|
||||
pub fn typed_as_straight(c: char) -> Option<char> {
|
||||
(c == '”').then_some('"')
|
||||
}
|
||||
|
||||
/// Does a quote typed after `prev` (the character before it, `None` at the start) open?
|
||||
pub fn opens_after(&self, prev: Option<char>) -> bool {
|
||||
self.opens(prev, None)
|
||||
}
|
||||
|
||||
/// `text` with straight quotes (`"` and `'`) replaced by these quotes: opening or closing by
|
||||
/// context (an apostrophe is a closing single quote). `prev` is the character before `text`,
|
||||
/// and is updated to its last character, so text can be converted in pieces.
|
||||
@@ -420,6 +435,12 @@ mod tests {
|
||||
}
|
||||
let mut prev = None;
|
||||
assert_eq!(language_quotes("croatian").unwrap().apply("\"a 'b' c\"", &mut prev), "„a ‚b‘ c“");
|
||||
// Only a typed `”` stands for a straight quote; the other curly quotes stay as typed.
|
||||
assert_eq!(Quotes::typed_as_straight('”'), Some('"'));
|
||||
assert!(['“', '„', '‘', '’', '‚', '"', '\'', '«', '»', '「', 'a'].iter().all(|&c| Quotes::typed_as_straight(c).is_none()));
|
||||
// A quote opens at the start and after a space, and closes after a letter.
|
||||
assert!(Quotes::ENGLISH.opens_after(None) && Quotes::ENGLISH.opens_after(Some(' ')));
|
||||
assert!(!Quotes::ENGLISH.opens_after(Some('a')));
|
||||
// Bulgarian: „…“ at either level, as CLDR has it.
|
||||
let mut prev = None;
|
||||
assert_eq!(language_quotes("bulgarian").unwrap().apply("\"a 'b' c\"", &mut prev), "„a „b“ c“");
|
||||
|
||||
@@ -176,7 +176,7 @@ impl Document {
|
||||
pub fn visit_paints(&self, f: &mut dyn FnMut(&Paint)) {
|
||||
let mut tree = |n: &Node| {
|
||||
walk_with_masks(n, &mut |m| {
|
||||
node_paints(m).for_each(&mut *f);
|
||||
node_paints(m).chain(override_paints(m)).for_each(&mut *f);
|
||||
if let NodeKind::Mesh(mesh) = &m.kind {
|
||||
mesh.points.iter().for_each(|p| f(&Paint::solid(p.color)));
|
||||
}
|
||||
@@ -275,10 +275,11 @@ fn map_style_paint(attrs: &mut serde_json::Map<String, serde_json::Value>, key:
|
||||
}
|
||||
|
||||
/// Every colour in the subtree of `n` with the swatch it links to: solid fills, strokes, text runs
|
||||
/// and gradient stops (with their link), then mesh points (unlinked), in paint order.
|
||||
/// and gradient stops (with their link), a dynamic symbol instance's own paints
|
||||
/// ([`override_paints`]), then mesh points (unlinked), in paint order.
|
||||
pub fn node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) {
|
||||
n.walk(&mut |m| {
|
||||
for p in node_paints(m) {
|
||||
for p in node_paints(m).chain(override_paints(m)) {
|
||||
match p {
|
||||
Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()),
|
||||
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())),
|
||||
@@ -315,6 +316,12 @@ pub fn node_paints(n: &Node) -> impl Iterator<Item = &Paint> {
|
||||
n.appearance.items.iter().map(item_paint).chain(runs.iter().flat_map(|r| [&r.style.fill, &r.style.stroke])).chain(n.extras().colorize.as_deref())
|
||||
}
|
||||
|
||||
/// The paints a dynamic symbol instance keeps for objects of its art
|
||||
/// ([`crate::symbol_overrides`]), which [`node_paints`] leaves out.
|
||||
pub fn override_paints(n: &Node) -> impl Iterator<Item = &Paint> {
|
||||
n.extras().symbol_overrides.iter().flat_map(|o| [o.fill.as_ref(), o.stroke.as_ref()]).flatten()
|
||||
}
|
||||
|
||||
/// Mutable [`node_paints`], in the same order.
|
||||
pub fn node_paints_mut(n: &mut Node) -> impl Iterator<Item = &mut Paint> {
|
||||
let runs = match &mut n.kind {
|
||||
@@ -353,6 +360,20 @@ fn map_node(n: &Node, f: &mut LinkFn) -> Option<(Node, usize)> {
|
||||
}
|
||||
out = Some(m);
|
||||
}
|
||||
// A dynamic symbol instance's own paints for objects of its art (`symbol_overrides`).
|
||||
if !n.extras().symbol_overrides.is_empty() {
|
||||
let mut overrides = n.extras().symbol_overrides.clone();
|
||||
let mut k = 0;
|
||||
for p in overrides.iter_mut().flat_map(|o| [&mut o.fill, &mut o.stroke]).flatten() {
|
||||
if matches!(p, Paint::Solid { .. } | Paint::Gradient(_)) && p.map_links(f) {
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
if k > 0 {
|
||||
out.get_or_insert_with(|| n.clone()).extras_mut().symbol_overrides = overrides;
|
||||
count += k;
|
||||
}
|
||||
}
|
||||
if let Some(ch) = n.children() {
|
||||
for (i, c) in ch.iter().enumerate() {
|
||||
if let Some((new, k)) = map_node(c, f) {
|
||||
|
||||
@@ -451,6 +451,18 @@ impl NineSliceMap {
|
||||
self.most_at(art, &boxes, 0)
|
||||
}
|
||||
|
||||
/// The affine map that [`Self::place`] and [`Self::place_unclipped`] move object `n` by as one
|
||||
/// piece, with everything in it: the map of the cell its box lies in, or of the cell at the
|
||||
/// origin when it has no box. `None` when its box crosses a guide.
|
||||
pub fn one_cell(&self, n: &Node, doc: &Document) -> Option<Affine> {
|
||||
let boxes = doc.symbol_boxes().quick();
|
||||
let Some(b) = n.geometric(Some(&boxes)).map(|b| self.natural.transform_rect_bbox(b)).filter(|b| finite(*b)) else {
|
||||
return Some(self.cell_at(Point::ZERO));
|
||||
};
|
||||
let (cols, rows) = (self.x.cells(b.x0, b.x1), self.y.cells(b.y0, b.y1));
|
||||
(cols[0] == cols[1] && rows[0] == rows[1]).then(|| self.cell_xf(cols[0], rows[0]))
|
||||
}
|
||||
|
||||
/// [`Self::most_placed`] for [`Self::place_unclipped`]: the most objects it makes of `art`.
|
||||
pub fn most_placed_unclipped(&self, art: &Node, doc: &Document) -> u64 {
|
||||
Self { clips: false, ..*self }.most_placed(art, doc)
|
||||
|
||||
@@ -49,6 +49,10 @@ impl SymbolOverride {
|
||||
r.style.fill = p.clone();
|
||||
}
|
||||
if let Some(p) = &self.stroke {
|
||||
// A painted stroke on characters without a weight gets 1 pt, as a path's does.
|
||||
if !p.is_none() && r.style.stroke_width == 0.0 {
|
||||
r.style.stroke_width = 1.0;
|
||||
}
|
||||
r.style.stroke = p.clone();
|
||||
}
|
||||
}
|
||||
@@ -57,6 +61,14 @@ impl SymbolOverride {
|
||||
n.appearance.set_fill(p.clone());
|
||||
}
|
||||
if let Some(p) = &self.stroke {
|
||||
// A stroke without paint has no weight; painting it gives it 1 pt.
|
||||
if !p.is_none()
|
||||
&& let Some(s) = n.appearance.stroke_mut()
|
||||
&& s.paint.is_none()
|
||||
&& s.width == 0.0
|
||||
{
|
||||
s.width = 1.0;
|
||||
}
|
||||
n.appearance.set_stroke(p.clone());
|
||||
}
|
||||
}
|
||||
@@ -69,6 +81,13 @@ impl SymbolOverride {
|
||||
}
|
||||
}
|
||||
|
||||
/// Can Direct Selection select `n`, an object of a dynamic symbol's art, and change its fill and
|
||||
/// stroke for one instance? Paths, compound paths and type can; groups, images and every other
|
||||
/// object cannot.
|
||||
pub fn takes_part_paint(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_))
|
||||
}
|
||||
|
||||
/// An override's path read from a file: at most [`MAX_PATH_DEPTH`] indices, so a compressed file
|
||||
/// of one endless path stays small once read.
|
||||
fn short_path<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<u32>, D::Error> {
|
||||
@@ -180,6 +199,27 @@ mod tests {
|
||||
assert_eq!(kept.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stroke_on_type_without_a_weight_gets_one_point() {
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let style = crate::CharStyle { stroke: Paint::None, stroke_width: 0.0, ..crate::CharStyle::default() };
|
||||
let text = Node::new(NodeId(2), NodeKind::Text(Box::new(crate::TextObject::point(vectorcraft_geom::Point::ZERO, "Hi", style))));
|
||||
let mut a = Node::group(NodeId(1), vec![Arc::new(text)]);
|
||||
apply(&mut a, &[SymbolOverride { path: vec![0], stroke: Some(red.clone()), ..Default::default() }]);
|
||||
let Some(NodeKind::Text(t)) = part(&a, &[0]).map(|n| &n.kind) else { panic!("type") };
|
||||
assert!(t.runs.iter().all(|r| r.style.stroke == red && r.style.stroke_width == 1.0), "the stroke draws at 1 pt");
|
||||
|
||||
// A path whose stroke has neither paint nor weight gets 1 pt too.
|
||||
let mut ap = Appearance::default_art();
|
||||
if let Some(s) = ap.stroke_mut() {
|
||||
(s.paint, s.width) = (Paint::None, 0.0);
|
||||
}
|
||||
let path = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), ap);
|
||||
let mut a = Node::group(NodeId(1), vec![Arc::new(path)]);
|
||||
apply(&mut a, &[SymbolOverride { path: vec![0], stroke: Some(red.clone()), ..Default::default() }]);
|
||||
assert_eq!(part(&a, &[0]).unwrap().appearance.stroke_width(), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_deeper_than_the_cap_does_not_read() {
|
||||
let deep = format!("{{\"path\":{:?}}}", vec![0; MAX_PATH_DEPTH + 1]);
|
||||
|
||||
+22
-4
@@ -8,6 +8,7 @@ use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, Li
|
||||
|
||||
mod area;
|
||||
mod char_style;
|
||||
mod composite;
|
||||
mod object;
|
||||
mod para_style;
|
||||
mod runs;
|
||||
@@ -17,12 +18,19 @@ 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, ScriptMetrics};
|
||||
pub use composite::{
|
||||
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart,
|
||||
CompositeParts,
|
||||
};
|
||||
pub use para_style::{
|
||||
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, LeadingModel, Mojikumi, ParaDirection,
|
||||
ParaStyle, SingleWordJustify,
|
||||
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, KinsokuShoriType, LeadingModel,
|
||||
Mojikumi, ParaDirection, ParaStyle, SingleWordJustify,
|
||||
};
|
||||
pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef, TypeAntiAlias};
|
||||
pub use tabs_lists::{
|
||||
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign,
|
||||
TabStop,
|
||||
};
|
||||
pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef};
|
||||
pub use tabs_lists::{Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, NumberStyle, ParaList, TabAlign, TabStop};
|
||||
pub use wrap::{resolve_wrap, wrap_work};
|
||||
|
||||
/// A text object. `runs` split into paragraphs at `\n`.
|
||||
@@ -78,6 +86,11 @@ pub struct TextObject {
|
||||
/// Off for new type and for documents from before it, and saved only when on.
|
||||
#[serde(default, rename = "opticalMarginAlignment", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub optical_margin: bool,
|
||||
/// Character panel › Anti-aliasing Method: how the type's edges are drawn as pixels. Each
|
||||
/// frame of a thread keeps its own method. Sharp for new type and for documents from before it,
|
||||
/// and saved only when it is another method.
|
||||
#[serde(default, rename = "antiAlias", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub anti_alias: TypeAntiAlias,
|
||||
/// Character panel menu › System Layout, copied from the document: when on, each character
|
||||
/// that takes space advances by a whole number of points. Off by default, and saved only when
|
||||
/// on. The document setting is [`crate::DocSetup::system_layout`].
|
||||
@@ -96,6 +109,11 @@ pub struct TextObject {
|
||||
/// file saves the count only when it is not 0.
|
||||
#[serde(default, rename = "listCount", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub list_count: u32,
|
||||
/// Threaded text: as [`Self::list_count`], the counts the earlier frames carry into this frame
|
||||
/// at list levels 2 on, level 2 first ([`ListCounts::from_parts`]). Empty when they are all 0,
|
||||
/// and the file saves them only when not empty. A file's longer list opens with the first 8.
|
||||
#[serde(default, rename = "listLevelCounts", skip_serializing_if = "Vec::is_empty", deserialize_with = "tabs_lists::read_level_counts")]
|
||||
pub list_level_counts: Vec<u32>,
|
||||
/// Cached layout bounds in text space, filled in by the layout engine (not serialized).
|
||||
#[serde(skip)]
|
||||
pub cached_bounds: Option<Rect>,
|
||||
|
||||
@@ -101,15 +101,24 @@ impl PathEffect {
|
||||
}
|
||||
}
|
||||
|
||||
/// Type on a Path Options › Align to Path: which height of the type runs along the path.
|
||||
/// Type on a Path Options › Align to Path: which height of the type runs along the path. Each
|
||||
/// character is measured by its own font, size and vertical scale, and in vertical type by its own
|
||||
/// size and horizontal scale. An inline graphic moves as a character of its run would, by its
|
||||
/// run's vertical scale in vertical type too. These distances are VectorCraft's own values.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PathAlign {
|
||||
/// The font's top edge: the type hangs below the path.
|
||||
/// The top of the font's em box: the type hangs below the path. The em box is the font's
|
||||
/// ideographic em box (from its `BASE` table, its typographic or `hhea` box, or its
|
||||
/// ideographs), else an em box centered on the cap height, else a box whose top is 0.88 em
|
||||
/// above the baseline. In vertical type the characters move half an em.
|
||||
Ascender,
|
||||
/// The font's bottom edge: the type stands above the path.
|
||||
/// The bottom of the font's bounding box, else the font's descent: the type stands above the
|
||||
/// path. In vertical type the characters move half an em the other way.
|
||||
Descender,
|
||||
/// Halfway between the ascender and the descender.
|
||||
/// A line at half the height of the top of the font's H above the baseline, else at half its
|
||||
/// cap height, else at the middle of its em box. In vertical type the characters stay on the
|
||||
/// path.
|
||||
Center,
|
||||
/// The baseline (the default).
|
||||
#[default]
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
//! 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.
|
||||
//!
|
||||
//! 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.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// A class of characters a composite font gives a font of its own.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum CharClass {
|
||||
/// The base font: ideographs, full-width letters and digits, and every character no other
|
||||
/// class takes.
|
||||
Kanji,
|
||||
/// Hiragana and katakana, full-width and half-width.
|
||||
Kana,
|
||||
/// East Asian and full-width punctuation, and typographic quotes and dashes.
|
||||
Punctuation,
|
||||
/// Arrows, math, shapes, enclosed and other symbols.
|
||||
Symbols,
|
||||
/// Half-width Roman letters, their punctuation and spaces.
|
||||
Roman,
|
||||
/// The half-width digits 0 to 9.
|
||||
Numerals,
|
||||
}
|
||||
|
||||
impl CharClass {
|
||||
/// Every class, in the order the Composite Fonts dialog lists them.
|
||||
pub const ALL: [CharClass; 6] = [Self::Kanji, Self::Kana, Self::Punctuation, Self::Symbols, Self::Roman, Self::Numerals];
|
||||
|
||||
/// The name commands and files use (`kanji`, `kana`, …).
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
Self::Kanji => "kanji",
|
||||
Self::Kana => "kana",
|
||||
Self::Punctuation => "punctuation",
|
||||
Self::Symbols => "symbols",
|
||||
Self::Roman => "roman",
|
||||
Self::Numerals => "numerals",
|
||||
}
|
||||
}
|
||||
|
||||
/// The class named `key` ([`Self::key`], any case).
|
||||
pub fn named(key: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|c| c.key().eq_ignore_ascii_case(key))
|
||||
}
|
||||
|
||||
/// Whether the class's characters can be scaled across and up (Kana, Roman and Numerals).
|
||||
pub fn scales(self) -> bool {
|
||||
matches!(self, Self::Kana | Self::Roman | Self::Numerals)
|
||||
}
|
||||
|
||||
/// The class of character `c`.
|
||||
pub fn of(c: char) -> Self {
|
||||
let u = c as u32;
|
||||
match u {
|
||||
0x30..=0x39 => Self::Numerals,
|
||||
// Basic Latin, Latin-1, Latin Extended, IPA, spacing and combining marks, and Latin
|
||||
// Extended Additional.
|
||||
0x00..=0x036F | 0x1E00..=0x1EFF => Self::Roman,
|
||||
// The other Latin blocks: combining marks extended, phonetic extensions and their
|
||||
// supplement, combining marks supplement, Latin Extended-C, -D, -E, -F and -G, and the
|
||||
// Latin ligatures of the alphabetic presentation forms.
|
||||
0x1AB0..=0x1AFF
|
||||
| 0x1D00..=0x1DFF
|
||||
| 0x2C60..=0x2C7F
|
||||
| 0xA720..=0xA7FF
|
||||
| 0xAB30..=0xAB6F
|
||||
| 0xFB00..=0xFB06
|
||||
| 0x10780..=0x107BF
|
||||
| 0x1DF00..=0x1DFFF => Self::Roman,
|
||||
// ・ and ゠ sit in the katakana block but are punctuation.
|
||||
0x30A0 | 0x30FB => Self::Punctuation,
|
||||
// Hiragana, katakana, katakana phonetic extensions, half-width katakana (with its
|
||||
// prolonged sound and voicing marks) and the kana supplements.
|
||||
0x3041..=0x309F | 0x30A1..=0x30FF | 0x31F0..=0x31FF | 0xFF66..=0xFF9F | 0x1B000..=0x1B16F => Self::Kana,
|
||||
// CJK symbols: 〄 〒 〓 〠 〶; ideographic space, 々 〆 〇 and the like stay with the base.
|
||||
0x3004 | 0x3012 | 0x3013 | 0x3020 | 0x3036 => Self::Symbols,
|
||||
0x3000 | 0x3005..=0x3007 | 0x3021..=0x302F | 0x3031..=0x3035 | 0x3038..=0x303C => Self::Kanji,
|
||||
0x3001..=0x303F => Self::Punctuation,
|
||||
// ※ is a symbol; the rest of General Punctuation (dashes, quotes, leaders) punctuation.
|
||||
0x203B => Self::Symbols,
|
||||
0x2010..=0x205E => Self::Punctuation,
|
||||
// Letterlike symbols, number forms, arrows, math, technical, enclosed alphanumerics, box
|
||||
// drawing, shapes, miscellaneous symbols and dingbats; enclosed CJK and CJK
|
||||
// compatibility; full-width signs.
|
||||
0x2100..=0x2BFF | 0x3200..=0x33FF | 0xFFE0..=0xFFEE => Self::Symbols,
|
||||
// Full-width forms of the ASCII signs.
|
||||
0xFF03..=0xFF06 | 0xFF0A | 0xFF0B | 0xFF1C..=0xFF1E | 0xFF20 | 0xFF3C | 0xFF3E | 0xFF5C | 0xFF5E => Self::Symbols,
|
||||
// Full-width forms of the other ASCII punctuation, and the half-width CJK punctuation.
|
||||
0xFF01..=0xFF0F | 0xFF1A..=0xFF1F | 0xFF3B..=0xFF40 | 0xFF5B..=0xFF65 => Self::Punctuation,
|
||||
_ => Self::Kanji,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The font a composite font sets one class of characters in, and how.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CompositePart {
|
||||
/// The font family and style.
|
||||
pub font: String,
|
||||
#[serde(default = "regular")]
|
||||
pub style: String,
|
||||
/// The size, in percent of the type's size.
|
||||
#[serde(default = "hundred")]
|
||||
pub size: f64,
|
||||
/// How far the characters are raised from the baseline, in percent of the type's size
|
||||
/// (negative lowers them).
|
||||
#[serde(default)]
|
||||
pub baseline: f64,
|
||||
/// Horizontal and vertical scale, in percent (Kana, Roman and Numerals only).
|
||||
#[serde(default = "hundred")]
|
||||
pub h_scale: f64,
|
||||
#[serde(default = "hundred")]
|
||||
pub v_scale: f64,
|
||||
/// Kana only: the characters are scaled from the center of the em box rather than from the
|
||||
/// baseline.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub scale_at_center: bool,
|
||||
}
|
||||
|
||||
fn hundred() -> f64 {
|
||||
100.0
|
||||
}
|
||||
|
||||
fn regular() -> String {
|
||||
"Regular".into()
|
||||
}
|
||||
|
||||
impl CompositePart {
|
||||
/// The part a new composite font gives every class: `font` in `style` at full size, on the
|
||||
/// baseline, unscaled.
|
||||
pub fn new(font: impl Into<String>, style: impl Into<String>) -> Self {
|
||||
Self { font: font.into(), style: style.into(), size: 100.0, baseline: 0.0, h_scale: 100.0, v_scale: 100.0, scale_at_center: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// The six parts of a composite font, one per [`CharClass`].
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CompositeParts {
|
||||
pub kanji: CompositePart,
|
||||
pub kana: CompositePart,
|
||||
pub punctuation: CompositePart,
|
||||
pub symbols: CompositePart,
|
||||
pub roman: CompositePart,
|
||||
pub numerals: CompositePart,
|
||||
}
|
||||
|
||||
impl CompositeParts {
|
||||
/// Every class set in `part`.
|
||||
pub fn all(part: CompositePart) -> Self {
|
||||
Self { kanji: part.clone(), kana: part.clone(), punctuation: part.clone(), symbols: part.clone(), roman: part.clone(), numerals: part }
|
||||
}
|
||||
|
||||
pub fn get(&self, class: CharClass) -> &CompositePart {
|
||||
match class {
|
||||
CharClass::Kanji => &self.kanji,
|
||||
CharClass::Kana => &self.kana,
|
||||
CharClass::Punctuation => &self.punctuation,
|
||||
CharClass::Symbols => &self.symbols,
|
||||
CharClass::Roman => &self.roman,
|
||||
CharClass::Numerals => &self.numerals,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_mut(&mut self, class: CharClass) -> &mut CompositePart {
|
||||
match class {
|
||||
CharClass::Kanji => &mut self.kanji,
|
||||
CharClass::Kana => &mut self.kana,
|
||||
CharClass::Punctuation => &mut self.punctuation,
|
||||
CharClass::Symbols => &mut self.symbols,
|
||||
CharClass::Roman => &mut self.roman,
|
||||
CharClass::Numerals => &mut self.numerals,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
|
||||
/// The size a part can take, in percent of the type's size.
|
||||
pub const COMPOSITE_SIZE: std::ops::RangeInclusive<f64> = 10.0..=400.0;
|
||||
/// How far a part can raise or lower its characters, in percent of the type's size.
|
||||
pub const COMPOSITE_BASELINE: std::ops::RangeInclusive<f64> = -100.0..=100.0;
|
||||
/// The horizontal and vertical scale a part can take, in percent.
|
||||
pub const COMPOSITE_SCALE: std::ops::RangeInclusive<f64> = 10.0..=400.0;
|
||||
/// The longest composite font name, in characters.
|
||||
pub const COMPOSITE_NAME_MAX: usize = 255;
|
||||
/// The most composite fonts a document or a file keeps.
|
||||
pub const COMPOSITE_FONTS_MAX: usize = 256;
|
||||
|
||||
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)) }
|
||||
}
|
||||
|
||||
/// Do `a` and `b` name the same composite font: equal in any case?
|
||||
pub fn same_name(a: &str, b: &str) -> bool {
|
||||
a == b || a.to_lowercase() == b.to_lowercase()
|
||||
}
|
||||
|
||||
/// The font of `fonts` (a document's composite fonts) named `name`, in any case.
|
||||
pub fn named<'a>(fonts: &'a [CompositeFont], name: &str) -> Option<&'a CompositeFont> {
|
||||
fonts.iter().find(|f| Self::same_name(&f.name, name))
|
||||
}
|
||||
|
||||
/// `name` trimmed, when it can name a composite font: not empty, at most
|
||||
/// [`COMPOSITE_NAME_MAX`] characters and without control characters.
|
||||
pub fn clean_name(name: &str) -> Option<String> {
|
||||
let name = name.trim();
|
||||
let ok = !name.is_empty() && name.chars().count() <= COMPOSITE_NAME_MAX && !name.chars().any(char::is_control);
|
||||
ok.then(|| name.to_string())
|
||||
}
|
||||
|
||||
/// 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.
|
||||
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"));
|
||||
}
|
||||
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 && !class.scales() {
|
||||
return Err(format!("{k}: only kana, roman and numerals can be scaled"));
|
||||
}
|
||||
}
|
||||
if p.scale_at_center && class != CharClass::Kana {
|
||||
return Err(format!("{k}: only kana can be scaled at the center"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `fonts` without the ones that can't be used: those [`Self::check`] refuses, a later font
|
||||
/// sharing an earlier one's name (in any case), a part set in one of the fonts, and those past
|
||||
/// [`COMPOSITE_FONTS_MAX`]. `None` when every font can be used.
|
||||
pub fn usable(fonts: &[CompositeFont]) -> Option<Vec<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.len() != fonts.len()).then_some(kept)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Each class takes its characters: digits and Latin letters are half-width numerals and
|
||||
/// Roman, kana both widths, and the punctuation, symbols and full-width forms their own.
|
||||
#[test]
|
||||
fn characters_fall_in_their_classes() {
|
||||
for (s, class) in [
|
||||
("漢字国一龍〇々", CharClass::Kanji),
|
||||
("AZa09 ", CharClass::Kanji),
|
||||
("あをアンーアンー", CharClass::Kana),
|
||||
("、。「」『』【】〜・!?():", CharClass::Punctuation),
|
||||
("“”‘’—…", CharClass::Punctuation),
|
||||
("※→★○〒+=$%①㈱", CharClass::Symbols),
|
||||
("AZaz é!? ()", CharClass::Roman),
|
||||
// Latin Extended-C, -D and -E, phonetic extensions and a ligature.
|
||||
("\u{2C60}\u{A7A0}\u{AB30}\u{1D00}\u{FB01}", CharClass::Roman),
|
||||
("0123456789", CharClass::Numerals),
|
||||
] {
|
||||
for c in s.chars() {
|
||||
assert_eq!(CharClass::of(c), class, "{c:?} (U+{:04X})", c as u32);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A composite font is read and written by its fields' names, and a part's omitted values
|
||||
/// take the defaults.
|
||||
#[test]
|
||||
fn composite_fonts_read_back_with_defaults() {
|
||||
let mut f = CompositeFont::new("Mixed", "Source Sans 3", "Regular");
|
||||
f.parts.kana.v_scale = 90.0;
|
||||
f.parts.kana.scale_at_center = true;
|
||||
f.parts.roman.baseline = -5.0;
|
||||
let json = serde_json::to_value(&f).unwrap();
|
||||
assert_eq!(json["parts"]["kana"]["vScale"], 90.0);
|
||||
assert_eq!(json["parts"]["kana"]["scaleAtCenter"], true);
|
||||
assert!(json["parts"]["roman"].get("scaleAtCenter").is_none());
|
||||
assert_eq!(serde_json::from_value::<CompositeFont>(json).unwrap(), f);
|
||||
let part: CompositePart = serde_json::from_value(serde_json::json!({"font": "Inter"})).unwrap();
|
||||
assert_eq!(part, CompositePart::new("Inter", "Regular"));
|
||||
}
|
||||
|
||||
/// Names are trimmed; values out of their ranges, and scales on classes that don't scale, are
|
||||
/// refused.
|
||||
#[test]
|
||||
fn composite_fonts_check_their_values() {
|
||||
assert_eq!(CompositeFont::clean_name(" Mixed ").as_deref(), Some("Mixed"));
|
||||
for bad in ["", " ", "a\tb", &"x".repeat(COMPOSITE_NAME_MAX + 1)] {
|
||||
assert_eq!(CompositeFont::clean_name(bad), None, "{bad:?}");
|
||||
}
|
||||
let ok = CompositeFont::new("Mixed", "Inter", "Regular");
|
||||
assert_eq!(ok.check(), Ok(()));
|
||||
let with = |f: fn(&mut CompositeParts)| {
|
||||
let mut c = ok.clone();
|
||||
f(&mut c.parts);
|
||||
c.check()
|
||||
};
|
||||
assert!(with(|p| p.roman.size = 9.0).is_err());
|
||||
assert!(with(|p| p.roman.size = f64::NAN).is_err());
|
||||
assert!(with(|p| p.kana.baseline = 101.0).is_err());
|
||||
assert!(with(|p| p.kana.h_scale = 401.0).is_err());
|
||||
assert!(with(|p| p.kanji.v_scale = 90.0).is_err());
|
||||
assert!(with(|p| p.symbols.h_scale = 90.0).is_err());
|
||||
assert!(with(|p| p.roman.scale_at_center = true).is_err());
|
||||
assert!(with(|p| p.numerals.font = " ".into()).is_err());
|
||||
assert_eq!(with(|p| p.kana.scale_at_center = true), Ok(()));
|
||||
assert_eq!(with(|p| p.numerals.h_scale = 50.0), Ok(()));
|
||||
let mut spaced = ok.clone();
|
||||
spaced.name = " Mixed".into();
|
||||
assert!(spaced.check().is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::area::{AreaOptions, PathAlign, PathEffect};
|
||||
use super::char_style::CharStyle;
|
||||
use super::para_style::ParaStyle;
|
||||
use super::runs::{RubySpan, TextKind, TextRun, move_anchors, reverse_from_end};
|
||||
use super::tabs_lists::ParaList;
|
||||
use super::runs::{RubySpan, TextKind, TextRun, TypeAntiAlias, move_anchors, reverse_from_end};
|
||||
use super::tabs_lists::{ListCounts, ParaList};
|
||||
use super::{Affine, PathData, Point, Rect, TextObject, TextStyleScale, Vec2};
|
||||
|
||||
impl TextObject {
|
||||
@@ -90,13 +90,24 @@ impl TextObject {
|
||||
path_spacing: 0.0,
|
||||
wrap: Vec::new(),
|
||||
optical_margin: false,
|
||||
anti_alias: TypeAntiAlias::Sharp,
|
||||
system_layout: false,
|
||||
fractional_widths: true,
|
||||
list_count: 0,
|
||||
list_level_counts: Vec::new(),
|
||||
cached_bounds: None,
|
||||
cached_baselines: Vec::new(),
|
||||
}
|
||||
}
|
||||
/// The list counts the story's earlier frames carry into this frame at each level
|
||||
/// ([`Self::list_count`] and [`Self::list_level_counts`]).
|
||||
pub fn list_counts(&self) -> ListCounts {
|
||||
ListCounts::from_parts(self.list_count, &self.list_level_counts)
|
||||
}
|
||||
/// Set the list counts the story's earlier frames carry into this frame ([`Self::list_counts`]).
|
||||
pub fn set_list_counts(&mut self, counts: ListCounts) {
|
||||
(self.list_count, self.list_level_counts) = counts.parts();
|
||||
}
|
||||
pub fn plain_text(&self) -> String {
|
||||
self.runs.iter().map(|r| r.text.as_str()).collect()
|
||||
}
|
||||
|
||||
@@ -234,6 +234,9 @@ pub struct ParaStyle {
|
||||
/// Kinsoku (Paragraph panel › Kinsoku Set): which Japanese characters may not start or end a
|
||||
/// line.
|
||||
pub kinsoku: Kinsoku,
|
||||
/// Kinsoku Shori Type (Paragraph panel menu): how a line keeps those characters off its start
|
||||
/// and end, by pushing them in onto the line or out to the next one. No effect without kinsoku.
|
||||
pub kinsoku_type: KinsokuShoriType,
|
||||
/// Roman Hanging Punctuation (Paragraph panel menu): quotation marks, hyphens, full stops and
|
||||
/// commas starting or ending a line hang outside the margin, and asterisks, tildes, ellipses,
|
||||
/// dashes, colons and semicolons hang by half. East Asian punctuation hangs by burasagari.
|
||||
@@ -258,6 +261,12 @@ impl ParaStyle {
|
||||
}
|
||||
}
|
||||
|
||||
/// The left indent the layout sets the paragraph at: its left indent, and for a paragraph in a
|
||||
/// list at a level past the first, [`ParaList::level_indent`] more.
|
||||
pub fn laid_out_left_indent(&self) -> f64 {
|
||||
self.left_indent + self.list.map_or(0.0, |l| l.level_indent())
|
||||
}
|
||||
|
||||
/// The leading of characters styled `st` in this paragraph, as the layout sets it: their own
|
||||
/// leading, or for Auto leading the paragraph's Justification › Auto Leading share of their
|
||||
/// size (exactly [`CharStyle::effective_leading`] at the default 120%, or when the share is
|
||||
@@ -316,6 +325,8 @@ struct ParaStyleFile {
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
kinsoku: Kinsoku,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
kinsoku_type: KinsokuShoriType,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
roman_hanging: bool,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
kashida: Kashida,
|
||||
@@ -347,6 +358,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
..
|
||||
@@ -371,6 +383,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
}
|
||||
@@ -399,6 +412,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
..
|
||||
@@ -422,6 +436,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
}
|
||||
@@ -486,6 +501,25 @@ pub enum Kinsoku {
|
||||
Soft,
|
||||
}
|
||||
|
||||
/// How a line keeps the characters [`Kinsoku`] rules out of its start and end (Kinsoku Shori
|
||||
/// Type). Pushing in sets the characters that would start the next line (or that an opening
|
||||
/// bracket ending this line would pull with it) on this line, with the line's gaps next to CJK
|
||||
/// characters closed to make room, each by the same share of the em of the character before it
|
||||
/// and by at most a tenth of that em; pushing out moves the character before them to the next
|
||||
/// line.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum KinsokuShoriType {
|
||||
/// Push in when the line can close up enough, else push out.
|
||||
PushInFirst,
|
||||
/// Push out, unless that would leave the line more than an em short (of the character before
|
||||
/// the break): then push in when the line can close up enough.
|
||||
PushOutFirst,
|
||||
/// Always push out; never push in.
|
||||
#[default]
|
||||
PushOutOnly,
|
||||
}
|
||||
|
||||
/// Hanging punctuation (burasagari): an East Asian comma or full stop ending a line (、。,.、。)
|
||||
/// stands outside the line's measure, in the space its punctuation spacing gives it (half width
|
||||
/// with Line-end Punctuation Half Width). Closing brackets and Latin punctuation don't hang. Shown
|
||||
|
||||
@@ -144,6 +144,44 @@ pub(super) fn reverse_from_end(path: &mut PathData) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The anti-aliasing method of a type object (Character panel › Anti-aliasing Method): how the
|
||||
/// edges of its characters are drawn when the type is drawn as pixels (the canvas, raster exports,
|
||||
/// rasterizing). SVG, PDF and EPS export ignore it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TypeAntiAlias {
|
||||
/// Hard edges: a pixel takes the type's color where the type covers at least half of it, and
|
||||
/// nothing elsewhere.
|
||||
None,
|
||||
/// Each edge pixel shows the share of it the type covers.
|
||||
#[default]
|
||||
Sharp,
|
||||
/// An edge pixel covered by a share `c` shows `2c - 0.5`, between 0 and 1: edges about half as
|
||||
/// wide as Sharp's.
|
||||
Crisp,
|
||||
/// An edge pixel covered by a share `c` shows `2c`, at most 1: heavier type.
|
||||
Strong,
|
||||
}
|
||||
|
||||
impl TypeAntiAlias {
|
||||
pub const ALL: [Self; 4] = [Self::None, Self::Sharp, Self::Crisp, Self::Strong];
|
||||
|
||||
/// The id used in command params and files (`none`, `sharp`, `crisp`, `strong`).
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::None => "none",
|
||||
Self::Sharp => "sharp",
|
||||
Self::Crisp => "crisp",
|
||||
Self::Strong => "strong",
|
||||
}
|
||||
}
|
||||
|
||||
/// The method an id names.
|
||||
pub fn from_id(id: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|a| a.id() == id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where ruby (furigana) text sits: above its base text in horizontal type, right of it in
|
||||
/// vertical type (the Japanese convention), or below (left in vertical type).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
||||
@@ -155,14 +155,29 @@ fn roman(mut n: u32) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
/// Where a list's marker stands before the first line's text ([`ParaList::align`]): the Bullets
|
||||
/// and Numbering dialog's Alignment.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ListAlign {
|
||||
/// The marker starts where the first line starts: at the left indent plus the first-line
|
||||
/// indent.
|
||||
#[default]
|
||||
Left,
|
||||
/// The marker ends where the first line's text starts, against the text.
|
||||
Right,
|
||||
}
|
||||
|
||||
/// The list a paragraph is in (Paragraph panel › Bullets and Numbered List). The layout draws the
|
||||
/// list's marker before the paragraph's first line, in the font, size and color of the paragraph's
|
||||
/// first character without its baseline shift, rotation, superscript or subscript, tracking, manual
|
||||
/// kerning, tate-chu-yoko, underline and strikethrough ([`Self::marker_style`]), and the text after
|
||||
/// it starts at the next tab stop, the left indent counting as a stop. The marker is not a
|
||||
/// character of the text, and an empty paragraph has none. A saved list reads the fields it leaves
|
||||
/// out as their defaults, and a build ignores the fields it doesn't know.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
/// it starts at the next tab stop, the left indent counting as a stop. The marker stands at the
|
||||
/// first line's start, or against the text with [`ListAlign::Right`]. A paragraph at a level past
|
||||
/// the first ([`Self::level`]) is set [`LIST_LEVEL_INDENT`] further in for each level. The marker
|
||||
/// is not a character of the text, and an empty paragraph has none. A saved list reads the fields
|
||||
/// it leaves out as their defaults, and a build ignores the fields it doesn't know.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct ParaList {
|
||||
/// The bullet each paragraph of a bulleted list starts with. A numbered list keeps it for
|
||||
@@ -172,17 +187,127 @@ pub struct ParaList {
|
||||
/// numbered list.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub number: Option<NumberStyle>,
|
||||
/// Where the marker stands before the first line's text. The file saves it only when it is
|
||||
/// [`ListAlign::Right`].
|
||||
#[serde(skip_serializing_if = "crate::skip::is_default")]
|
||||
pub align: ListAlign,
|
||||
/// The paragraph's level in the list, 1 to [`LIST_LEVELS`] (Tab and Shift+Tab at the start of
|
||||
/// the paragraph, Bullets and Numbering…'s Level): each level counts its own numbers
|
||||
/// ([`Self::next_marker`]). A value outside that range is read as the nearest level
|
||||
/// ([`Self::depth`]). The file saves it only when it is not 1.
|
||||
#[serde(skip_serializing_if = "is_first_level", deserialize_with = "read_level")]
|
||||
pub level: u8,
|
||||
}
|
||||
|
||||
impl Default for ParaList {
|
||||
/// A bulleted list with a dot, its marker aligned left, at level 1.
|
||||
fn default() -> Self {
|
||||
Self { bullet: Bullet::default(), number: None, align: ListAlign::default(), level: 1 }
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `level` the first list level, which the file does not save?
|
||||
fn is_first_level(level: &u8) -> bool {
|
||||
*level == 1
|
||||
}
|
||||
|
||||
/// Reads a saved list level, a whole number, as the nearest of 1 to [`LIST_LEVELS`], so a level
|
||||
/// such as -1 or 300 opens the file at level 1 or 9. Anything else is an error.
|
||||
fn read_level<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u8, D::Error> {
|
||||
let level = match serde_json::Value::deserialize(d)? {
|
||||
serde_json::Value::Number(n) if n.is_i64() || n.is_u64() => n.as_i64().map_or(LIST_LEVELS as i64, |n| n.clamp(1, LIST_LEVELS as i64)),
|
||||
_ => return Err(serde::de::Error::custom("a list level must be a whole number")),
|
||||
};
|
||||
Ok(level as u8)
|
||||
}
|
||||
|
||||
/// Reads a type object's saved counts at list levels 2 on ([`ListCounts::from_parts`]), keeping
|
||||
/// the first `LIST_LEVELS - 1` and skipping the rest of a longer list without storing it.
|
||||
pub(super) fn read_level_counts<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<u32>, D::Error> {
|
||||
struct Counts;
|
||||
impl<'de> serde::de::Visitor<'de> for Counts {
|
||||
type Value = Vec<u32>;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("a list of list counts")
|
||||
}
|
||||
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<u32>, A::Error> {
|
||||
let mut out = Vec::new();
|
||||
while out.len() < LIST_LEVELS - 1 {
|
||||
match seq.next_element::<u32>()? {
|
||||
Some(c) => out.push(c),
|
||||
None => return Ok(out),
|
||||
}
|
||||
}
|
||||
while seq.next_element::<serde::de::IgnoredAny>()?.is_some() {}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
d.deserialize_seq(Counts)
|
||||
}
|
||||
|
||||
/// How many levels a list has (Bullets and Numbering…'s Level: 1 to 9).
|
||||
pub const LIST_LEVELS: usize = 9;
|
||||
|
||||
/// How much further in (pt) the layout sets a list paragraph for each level past the first: its
|
||||
/// left indent counts that much more, and the marker and the text move with it.
|
||||
pub const LIST_LEVEL_INDENT: f64 = 18.0;
|
||||
|
||||
/// The numbered paragraphs a story's list has counted at each level, level 1 first
|
||||
/// ([`ParaList::next_marker`]).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ListCounts(pub [u32; LIST_LEVELS]);
|
||||
|
||||
impl ListCounts {
|
||||
/// The counts with `first` at level 1 and `deeper` at levels 2 on, a missing level at 0, as a
|
||||
/// type object saves them ([`TextObject::list_count`], [`TextObject::list_level_counts`]).
|
||||
pub fn from_parts(first: u32, deeper: &[u32]) -> Self {
|
||||
let mut counts = [0; LIST_LEVELS];
|
||||
counts[0] = first;
|
||||
for (c, &d) in counts[1..].iter_mut().zip(deeper) {
|
||||
*c = d;
|
||||
}
|
||||
Self(counts)
|
||||
}
|
||||
|
||||
/// The count at level 1, and the counts at levels 2 on without the zeros that end them.
|
||||
pub fn parts(&self) -> (u32, Vec<u32>) {
|
||||
let deeper = &self.0[1..];
|
||||
let used = deeper.iter().rposition(|&c| c != 0).map_or(0, |i| i + 1);
|
||||
(self.0[0], deeper[..used].to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
impl ParaList {
|
||||
/// A bulleted list with `bullet`.
|
||||
pub fn bulleted(bullet: Bullet) -> Self {
|
||||
Self { bullet, number: None }
|
||||
Self { bullet, ..Self::default() }
|
||||
}
|
||||
|
||||
/// A numbered list with `style`.
|
||||
pub fn numbered(style: NumberStyle) -> Self {
|
||||
Self { bullet: Bullet::default(), number: Some(style) }
|
||||
Self { number: Some(style), ..Self::default() }
|
||||
}
|
||||
|
||||
/// This list with its marker at `align`.
|
||||
pub fn aligned(self, align: ListAlign) -> Self {
|
||||
Self { align, ..self }
|
||||
}
|
||||
|
||||
/// This list at level `level` (1 to [`LIST_LEVELS`]).
|
||||
pub fn at_level(self, level: u8) -> Self {
|
||||
Self { level, ..self }
|
||||
}
|
||||
|
||||
/// The list's level, 1 to [`LIST_LEVELS`]: [`Self::level`], a value outside the range taken
|
||||
/// as the nearest level.
|
||||
pub fn depth(&self) -> usize {
|
||||
usize::from(self.level).clamp(1, LIST_LEVELS)
|
||||
}
|
||||
|
||||
/// How much further in (pt) than its left indent the layout sets a paragraph of this list:
|
||||
/// [`LIST_LEVEL_INDENT`] for each level past the first.
|
||||
pub fn level_indent(&self) -> f64 {
|
||||
(self.depth() - 1) as f64 * LIST_LEVEL_INDENT
|
||||
}
|
||||
|
||||
/// The characters of the marker the layout draws before the paragraph: the bullet, or for a
|
||||
@@ -195,18 +320,26 @@ impl ParaList {
|
||||
}
|
||||
|
||||
/// The marker of the next paragraph of a story, whose list is `list` (None: in no list) and
|
||||
/// which holds no text when `empty`, with `count` the numbered paragraphs counted before it.
|
||||
/// A paragraph in no list sets the count back to 0 and has no marker; an empty paragraph has
|
||||
/// none and leaves the count as it is; a bulleted paragraph has its bullet and leaves the
|
||||
/// count as it is; a numbered paragraph adds one to the count and is numbered with it.
|
||||
pub fn next_marker(list: Option<ParaList>, empty: bool, count: &mut u32) -> Option<String> {
|
||||
/// which holds no text when `empty`, with `counts` the numbered paragraphs counted before it at
|
||||
/// each level. A paragraph in no list sets every count back to 0 and has no marker; an empty
|
||||
/// paragraph has none and leaves the counts as they are. A paragraph with text sets the counts
|
||||
/// of the levels deeper than its own back to 0, so a deeper paragraph after it counts from 1
|
||||
/// again; a bulleted one has its bullet and leaves the count of its level as it is, and a
|
||||
/// numbered one adds one to the count of its level and is numbered with it. A paragraph back
|
||||
/// at a shallower level then goes on with that level's count.
|
||||
pub fn next_marker(list: Option<ParaList>, empty: bool, counts: &mut ListCounts) -> Option<String> {
|
||||
let Some(list) = list else {
|
||||
*count = 0;
|
||||
*counts = ListCounts::default();
|
||||
return None;
|
||||
};
|
||||
if empty {
|
||||
return None;
|
||||
}
|
||||
let level = list.depth() - 1;
|
||||
for deeper in &mut counts.0[level + 1..] {
|
||||
*deeper = 0;
|
||||
}
|
||||
let count = &mut counts.0[level];
|
||||
if list.number.is_some() {
|
||||
*count = count.saturating_add(1);
|
||||
}
|
||||
@@ -233,13 +366,16 @@ impl ParaList {
|
||||
|
||||
/// The list that the Type tool starts when `typed` and a space are typed at the start of a
|
||||
/// paragraph: "1." or "1)" starts a numbered list in 1, 2, 3, "A." or "A)" starts one in A, B,
|
||||
/// C, and "*", "#", ">" or "+" starts a bulleted list with the filled dot. Any other text starts
|
||||
/// none.
|
||||
/// C, and "*" starts a bulleted list with the filled dot, "+" one with the hollow circle, "#"
|
||||
/// one with the filled square and ">" one with the dash. Any other text starts none.
|
||||
pub fn typed(typed: &str) -> Option<ParaList> {
|
||||
match typed {
|
||||
"1." | "1)" => Some(Self::numbered(NumberStyle::Arabic)),
|
||||
"A." | "A)" => Some(Self::numbered(NumberStyle::UpperLetters)),
|
||||
"*" | "#" | ">" | "+" => Some(Self::bulleted(Bullet::Dot)),
|
||||
"*" => Some(Self::bulleted(Bullet::Dot)),
|
||||
"+" => Some(Self::bulleted(Bullet::Circle)),
|
||||
"#" => Some(Self::bulleted(Bullet::Square)),
|
||||
">" => Some(Self::bulleted(Bullet::Dash)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,13 +194,13 @@ fn number_styles_write_their_numbers_and_roll_over() {
|
||||
assert_eq!(ParaList::numbered(NumberStyle::UpperRoman).marker(4), "IV.");
|
||||
assert_eq!(ParaList::bulleted(Bullet::Square).marker(4), "\u{25AA}");
|
||||
let (num, dot) = (Some(ParaList::numbered(NumberStyle::Arabic)), Some(ParaList::bulleted(Bullet::Dot)));
|
||||
let mut count = 0;
|
||||
let mut count = ListCounts::default();
|
||||
let markers: Vec<Option<String>> = [(num, false), (num, true), (dot, false), (num, false), (None, false), (num, false)]
|
||||
.iter()
|
||||
.map(|&(l, empty)| ParaList::next_marker(l, empty, &mut count))
|
||||
.collect();
|
||||
assert_eq!(markers, [Some("1.".into()), None, Some("\u{2022}".into()), Some("2.".into()), None, Some("1.".into())]);
|
||||
assert_eq!(count, 1);
|
||||
assert_eq!(count.parts(), (1, vec![]));
|
||||
let read = |v: serde_json::Value| serde_json::from_value::<ParaList>(v).unwrap();
|
||||
assert_eq!(read(serde_json::json!({"bullet": "dash"})), ParaList::bulleted(Bullet::Dash));
|
||||
assert_eq!(read(serde_json::json!({"number": "threeDigits"})), ParaList::numbered(NumberStyle::ThreeDigits));
|
||||
@@ -211,23 +211,38 @@ fn number_styles_write_their_numbers_and_roll_over() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A list's marker alignment: Left by default and not saved, Right saved as `"align": "right"`;
|
||||
/// a list saved without it reads as Left.
|
||||
#[test]
|
||||
fn a_list_saves_its_marker_alignment_only_when_it_is_right() {
|
||||
let right = ParaList::numbered(NumberStyle::Arabic).aligned(ListAlign::Right);
|
||||
assert_eq!(ParaList::bulleted(Bullet::Dot).align, ListAlign::Left);
|
||||
assert_eq!(serde_json::to_value(right).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic", "align": "right"}));
|
||||
assert_eq!(serde_json::to_value(ParaList::bulleted(Bullet::Dash)).unwrap(), serde_json::json!({"bullet": "dash"}));
|
||||
let read = |v: serde_json::Value| serde_json::from_value::<ParaList>(v).unwrap();
|
||||
assert_eq!(read(serde_json::json!({"bullet": "dot", "number": "arabic", "align": "right"})), right);
|
||||
assert_eq!(read(serde_json::json!({"bullet": "square"})).align, ListAlign::Left);
|
||||
assert!(serde_json::from_value::<ParaList>(serde_json::json!({"align": "center"})).is_err());
|
||||
}
|
||||
|
||||
/// Typed list detection: "1.", "1)", "A." and "A)" and a space at the start of a paragraph
|
||||
/// start a numbered list, and "*", "#", ">" and "+" and a space start a bulleted list with the
|
||||
/// filled dot. Other text, the same characters later in a paragraph or without the space, and
|
||||
/// a paragraph already in a list start nothing.
|
||||
/// start a numbered list, and "*", "+", "#" and ">" and a space start a bulleted list with the
|
||||
/// filled dot, the hollow circle, the filled square and the dash. Other text, the same characters
|
||||
/// later in a paragraph or without the space, and a paragraph already in a list start nothing.
|
||||
#[test]
|
||||
fn typed_list_starts_are_found_at_a_paragraphs_start() {
|
||||
let (arabic, letters, dot) =
|
||||
(ParaList::numbered(NumberStyle::Arabic), ParaList::numbered(NumberStyle::UpperLetters), ParaList::bulleted(Bullet::Dot));
|
||||
let typed = ["1.", "1)", "A.", "A)", "*", "#", ">", "+"].map(ParaList::typed);
|
||||
assert_eq!(typed, [arabic, arabic, letters, letters, dot, dot, dot, dot].map(Some));
|
||||
let (circle, square, dash) = (ParaList::bulleted(Bullet::Circle), ParaList::bulleted(Bullet::Square), ParaList::bulleted(Bullet::Dash));
|
||||
let typed = ["1.", "1)", "A.", "A)", "*", "+", "#", ">"].map(ParaList::typed);
|
||||
assert_eq!(typed, [arabic, arabic, letters, letters, dot, circle, square, dash].map(Some));
|
||||
for other in ["", "2.", "a.", "a)", "I.", "1", "A", "1:", "-", "•", "1.)", " 1.", "*1", "1."] {
|
||||
assert_eq!(ParaList::typed(other), None, "{other:?}");
|
||||
}
|
||||
let mut t = TextObject::point(Point::ZERO, "Fruit\n1. Apples\nA) x * y\n+ ", CharStyle::default());
|
||||
assert_eq!(t.typed_list_at(9), Some((6, arabic)));
|
||||
assert_eq!(t.typed_list_at(19), Some((16, letters)));
|
||||
assert_eq!(t.typed_list_at(27), Some((25, dot)));
|
||||
assert_eq!(t.typed_list_at(27), Some((25, circle)));
|
||||
// Not at the paragraph's start, not right after the space, or past the end.
|
||||
for at in [0, 5, 8, 10, 15, 23, 25, 26, 99] {
|
||||
assert_eq!(t.typed_list_at(at), None, "{at}");
|
||||
@@ -239,13 +254,77 @@ fn typed_list_starts_are_found_at_a_paragraphs_start() {
|
||||
assert_eq!(t.typed_list_at(19), Some((16, letters)));
|
||||
}
|
||||
|
||||
/// List levels: each level counts its own numbers, a deeper paragraph starts its count at 1,
|
||||
/// a paragraph back at a shallower level goes on with that level's count, and a paragraph in
|
||||
/// no list starts every level again. A level past the first sets the paragraph 18 pt further
|
||||
/// in; the file saves the level only when it is not 1, and a level outside 1 to 9 reads as the
|
||||
/// nearest one. A type object's counts save level 1 and the deeper levels apart.
|
||||
#[test]
|
||||
fn list_levels_count_their_own_numbers_and_save_only_past_the_first() {
|
||||
let num = |level| Some(ParaList::numbered(NumberStyle::Arabic).at_level(level));
|
||||
let dot = |level| Some(ParaList::bulleted(Bullet::Dot).at_level(level));
|
||||
let mut counts = ListCounts::default();
|
||||
let markers: Vec<Option<String>> = [
|
||||
(num(1), false),
|
||||
(num(2), false),
|
||||
(num(2), false),
|
||||
(num(3), false),
|
||||
(num(2), true),
|
||||
(num(2), false),
|
||||
(num(1), false),
|
||||
(num(2), false),
|
||||
(dot(1), false),
|
||||
(num(2), false),
|
||||
(num(1), false),
|
||||
(None, false),
|
||||
(num(2), false),
|
||||
]
|
||||
.iter()
|
||||
.map(|&(l, empty)| ParaList::next_marker(l, empty, &mut counts))
|
||||
.collect();
|
||||
let want = ["1.", "1.", "2.", "1.", "", "3.", "2.", "1.", "\u{2022}", "1.", "3.", "", "1."];
|
||||
assert_eq!(markers.iter().map(|m| m.as_deref().unwrap_or("")).collect::<Vec<_>>(), want);
|
||||
assert_eq!(counts, ListCounts([0, 1, 0, 0, 0, 0, 0, 0, 0]));
|
||||
assert_eq!((ParaList::default().level, ParaList::bulleted(Bullet::Dot).depth()), (1, 1));
|
||||
assert_eq!([0, 1, 4, 9, 12].map(|l| ParaList::bulleted(Bullet::Dot).at_level(l).depth()), [1, 1, 4, 9, 9]);
|
||||
assert_eq!([1, 2, 9].map(|l| ParaList::bulleted(Bullet::Dot).at_level(l).level_indent()), [0.0, 18.0, 144.0]);
|
||||
let para = ParaStyle { left_indent: 18.0, list: dot(3), ..Default::default() };
|
||||
assert_eq!((para.laid_out_left_indent(), ParaStyle { list: None, ..para.clone() }.laid_out_left_indent()), (54.0, 18.0));
|
||||
assert_eq!(serde_json::to_value(dot(1)).unwrap(), serde_json::json!({"bullet": "dot"}));
|
||||
assert_eq!(serde_json::to_value(num(4)).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic", "level": 4}));
|
||||
let read = |v: serde_json::Value| serde_json::from_value::<ParaList>(v).unwrap();
|
||||
assert_eq!((read(serde_json::json!({"bullet": "dash"})).level, read(serde_json::json!({"level": 4}))), (1, dot(4).unwrap()));
|
||||
assert!(serde_json::from_value::<ParaList>(serde_json::json!({"level": "two"})).is_err());
|
||||
assert!(serde_json::from_value::<ParaList>(serde_json::json!({"level": 2.5})).is_err());
|
||||
let levels = [serde_json::json!(0), serde_json::json!(-1), serde_json::json!(12), serde_json::json!(300), serde_json::json!(u64::MAX)];
|
||||
assert_eq!(
|
||||
levels.map(|l| read(serde_json::json!({ "level": l })).level),
|
||||
[1, 1, 9, 9, 9],
|
||||
"a saved level outside 1 to 9 reads as the nearest one"
|
||||
);
|
||||
let deep = ListCounts([5, 0, 2, 0, 0, 0, 0, 0, 0]);
|
||||
assert_eq!(deep.parts(), (5, vec![0, 2]));
|
||||
assert_eq!((ListCounts::from_parts(5, &[0, 2]), ListCounts::default().parts()), (deep, (0, vec![])));
|
||||
let mut t = TextObject::point(Point::ZERO, "Text", CharStyle::default());
|
||||
t.set_list_counts(deep);
|
||||
assert_eq!((t.list_count, t.list_level_counts.as_slice(), t.list_counts()), (5, &[0, 2][..], deep));
|
||||
let saved = serde_json::to_value(&t).unwrap();
|
||||
assert_eq!((&saved["listCount"], &saved["listLevelCounts"]), (&serde_json::json!(5), &serde_json::json!([0, 2])));
|
||||
t.set_list_counts(ListCounts::default());
|
||||
assert!(serde_json::to_value(&t).unwrap().get("listLevelCounts").is_none(), "no counts past level 1 are saved without them");
|
||||
let mut saved = serde_json::to_value(&t).unwrap();
|
||||
saved["listLevelCounts"] = serde_json::json!((1..=20).collect::<Vec<u32>>());
|
||||
let opened = serde_json::from_value::<TextObject>(saved).unwrap();
|
||||
assert_eq!(opened.list_level_counts, (1..=8).collect::<Vec<u32>>(), "a file keeps only the counts of levels 2 to 9");
|
||||
}
|
||||
|
||||
/// In a threaded frame whose first paragraph continues from the frame before, the text at the
|
||||
/// frame's start is not the start of a paragraph, so typing a list's start there starts nothing.
|
||||
/// The paragraphs after it still start lists.
|
||||
#[test]
|
||||
fn typed_list_starts_skip_a_continued_paragraph() {
|
||||
let dot = ParaList::bulleted(Bullet::Dot);
|
||||
let mut t = TextObject::point(Point::ZERO, "* Pears\n# ", CharStyle::default());
|
||||
let mut t = TextObject::point(Point::ZERO, "* Pears\n* ", CharStyle::default());
|
||||
assert_eq!(t.typed_list_at(2), Some((0, dot)));
|
||||
t.first_para_continues = true;
|
||||
assert_eq!(t.typed_list_at(2), None, "a continued paragraph starts no list");
|
||||
|
||||
+31
-29
@@ -95,8 +95,9 @@ pub struct DataSet {
|
||||
|
||||
impl DataSet {
|
||||
/// Whether the art, as [`Document::captured_values`] read it, still holds what this row
|
||||
/// says. A value the art can't report (its object is locked or gone) isn't drift: the row
|
||||
/// keeps it, and applying it again would skip it too.
|
||||
/// says. A value the art can't report (its object is gone, or is locked or in a locked layer
|
||||
/// or group and the variable isn't a visibility variable) isn't drift: the row keeps it, and
|
||||
/// applying it again would skip it too.
|
||||
pub fn matches(&self, current: &BTreeMap<String, DataValue>) -> bool {
|
||||
self.values.iter().all(|(k, v)| current.get(k).is_none_or(|c| c == v))
|
||||
}
|
||||
@@ -105,12 +106,11 @@ impl DataSet {
|
||||
/// The variable state of a document: definitions, datasets, bindings
|
||||
/// (object id → the variables bound to it) and which dataset is active.
|
||||
///
|
||||
/// An object may be driven by several variables — the reference app binds the selected object
|
||||
/// to the selected variable, one click at a time, and never says a second binding replaces the
|
||||
/// first — so a binding is a set. `dataset.select` applies the text values in the order the
|
||||
/// variables are defined, which is what makes two text variables on one object deterministic:
|
||||
/// the last one wins, and `applied` counts both. Of two visibility variables on one object, the
|
||||
/// last one defined wins too.
|
||||
/// An object may be driven by several variables, so a binding is a set. `variable.bind` and Make
|
||||
/// Text Dynamic refuse a second text variable on one type object, but a document saved before
|
||||
/// they did may hold two: `dataset.select` applies the text values in the order the variables
|
||||
/// are defined, so the last one wins, and `applied` counts both. Of two visibility variables on
|
||||
/// one object, the last one defined wins too.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Variables {
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
@@ -194,33 +194,35 @@ impl Document {
|
||||
self.variables.bindings = bindings;
|
||||
}
|
||||
|
||||
/// Whether a variable may be bound to the object `id`: it is in the document, neither it nor
|
||||
/// anything above it is locked, nothing above it is hidden, and it is not on a locked artboard
|
||||
/// ([`Document::on_locked_artboard`]). Its own visibility doesn't count, as that is what a
|
||||
/// visibility variable drives.
|
||||
pub fn variable_target(&self, id: NodeId) -> bool {
|
||||
self.variable_target_with(&self.locked_artboards(), id)
|
||||
/// Whether a variable of `kind` may be bound to the object `id`: it is in the document,
|
||||
/// nothing above it is hidden, it is not on a locked artboard ([`Document::on_locked_artboard`]),
|
||||
/// and, unless `kind` is visibility, neither it nor anything above it is locked. Its own
|
||||
/// visibility doesn't count, as that is what a visibility variable drives.
|
||||
pub fn variable_target(&self, id: NodeId, kind: VariableKind) -> bool {
|
||||
self.variable_target_with(&self.locked_artboards(), id, kind)
|
||||
}
|
||||
|
||||
/// [`Document::variable_target`] with the locked artboards `locks` of this document, measured
|
||||
/// once for many ids.
|
||||
pub fn variable_target_with(&self, locks: &LockedArtboards, id: NodeId) -> bool {
|
||||
self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| !n.locked && (n.visible || *i == id))))
|
||||
pub fn variable_target_with(&self, locks: &LockedArtboards, id: NodeId, kind: VariableKind) -> bool {
|
||||
let locking = kind != VariableKind::Visibility;
|
||||
self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| !(locking && n.locked) && (n.visible || *i == id))))
|
||||
&& !locks.holds_id(id)
|
||||
}
|
||||
|
||||
/// Whether a data set reads and rewrites the bound object `id`: it is in the document, neither
|
||||
/// it nor anything above it is locked, and it is not on a locked artboard
|
||||
/// ([`Document::on_locked_artboard`]). Hidden objects count, and so do objects in a hidden
|
||||
/// layer or group.
|
||||
pub fn dataset_target(&self, id: NodeId) -> bool {
|
||||
self.dataset_target_with(&self.locked_artboards(), id)
|
||||
/// Whether a data set reads and rewrites the bound object `id` for a variable of `kind`: it
|
||||
/// is in the document, it is not on a locked artboard ([`Document::on_locked_artboard`]) and,
|
||||
/// unless `kind` is visibility, neither it nor anything above it is locked. Hidden objects
|
||||
/// count, and so do objects in a hidden layer or group.
|
||||
pub fn dataset_target(&self, id: NodeId, kind: VariableKind) -> bool {
|
||||
self.dataset_target_with(&self.locked_artboards(), id, kind)
|
||||
}
|
||||
|
||||
/// [`Document::dataset_target`] with the locked artboards `locks` of this document, measured
|
||||
/// once for many ids.
|
||||
pub fn dataset_target_with(&self, locks: &LockedArtboards, id: NodeId) -> bool {
|
||||
self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| !n.locked))) && !locks.holds_id(id)
|
||||
pub fn dataset_target_with(&self, locks: &LockedArtboards, id: NodeId, kind: VariableKind) -> bool {
|
||||
let locking = kind != VariableKind::Visibility;
|
||||
self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| !(locking && n.locked)))) && !locks.holds_id(id)
|
||||
}
|
||||
|
||||
/// The type objects of the story that the type object `id` belongs to, in thread order: the
|
||||
@@ -254,21 +256,21 @@ impl Document {
|
||||
/// [`Document::story_target`] with the locked artboards `locks` of this document, measured
|
||||
/// once for many ids.
|
||||
pub fn story_target_with(&self, locks: &LockedArtboards, id: NodeId) -> bool {
|
||||
self.story_of(id).into_iter().all(|f| self.dataset_target_with(locks, f))
|
||||
self.story_of(id).into_iter().all(|f| self.dataset_target_with(locks, f, VariableKind::Text))
|
||||
}
|
||||
|
||||
/// What the object `id` holds for the variable of `kind`: its characters (the whole story
|
||||
/// for a frame of threaded text), whether it shows, or a linked image's path. `None` when the
|
||||
/// object is gone, is not of that kind, has no link path yet (an embedded image), or is locked,
|
||||
/// in a locked layer or group, or on a locked artboard, or for text when a frame of its story
|
||||
/// is (the document's value is whatever it was left at).
|
||||
/// object is gone, is not of that kind, has no link path yet (an embedded image), or, unless
|
||||
/// `kind` is visibility, is locked or in a locked layer or group, or is on a locked artboard,
|
||||
/// or for text when a frame of its story is (the document's value is whatever it was left at).
|
||||
pub fn variable_value(&self, id: NodeId, kind: VariableKind) -> Option<DataValue> {
|
||||
self.variable_value_with(&self.locked_artboards(), id, kind)
|
||||
}
|
||||
|
||||
/// [`Document::variable_value`] with the locked artboards `locks` of this document.
|
||||
fn variable_value_with(&self, locks: &LockedArtboards, id: NodeId, kind: VariableKind) -> Option<DataValue> {
|
||||
if !self.dataset_target_with(locks, id) {
|
||||
if !self.dataset_target_with(locks, id, kind) {
|
||||
return None;
|
||||
}
|
||||
let node = self.node(id)?;
|
||||
|
||||
@@ -17,6 +17,11 @@ vectorcraft-text = { workspace = true }
|
||||
vectorcraft-plugins = { workspace = true }
|
||||
image = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
# Effect › SVG Filters draws its filters with resvg (MIT OR Apache-2.0), at the usvg version the
|
||||
# workspace reads SVG with; raster-images decodes the object's pixels it hands the filter as a PNG.
|
||||
resvg = { version = "0.48", default-features = false, features = ["raster-images"] }
|
||||
# The number lists of filter attributes, read as usvg reads them (MIT OR Apache-2.0; already used by usvg).
|
||||
svgtypes = "0.16"
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
+46
-29
@@ -28,7 +28,7 @@ use crate::distort::{transform_move, transform_offsets};
|
||||
use crate::group::{has_own_paint, paints};
|
||||
use crate::reshape::{as_art, geometry_effects, glyph_outlines, outline_nested_text, reshape_leaves};
|
||||
use crate::{
|
||||
GeomContext, adjust_in_document, apply_geometry_with, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry,
|
||||
GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry,
|
||||
has_item_geometry, has_pathfinder, is_geometry, is_pathfinder, merged_params, needs_outline, outline_text, reshape,
|
||||
};
|
||||
|
||||
@@ -71,12 +71,27 @@ fn geometry(n: &Node) -> Option<(PathData, FillRule)> {
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(effects: &[vectorcraft_doc::Effect], path: &PathData, ctx: &GeomContext) -> PathData {
|
||||
/// `path` with the geometry effects of `effects` applied, and how gradients follow them
|
||||
/// ([`crate::Carry`]).
|
||||
fn apply(effects: &[vectorcraft_doc::Effect], path: &PathData, ctx: &GeomContext) -> (PathData, crate::Carry) {
|
||||
if !has_geometry(effects) || path.is_empty() {
|
||||
return path.clone();
|
||||
return (path.clone(), crate::Carry::default());
|
||||
}
|
||||
let b = vectorcraft_geom::Shape::bounding_box(&path.to_bezpath());
|
||||
apply_geometry_with(effects, path, b, ctx)
|
||||
apply_geometry_carrying(effects, path, b, ctx)
|
||||
}
|
||||
|
||||
/// The geometry `g` with the own effects of `item` (one of the fills and strokes `ctx` is the
|
||||
/// context of) applied, and `carried` (`item` as the object's effects left it) with its gradient
|
||||
/// moved along with them.
|
||||
fn apply_item(item: &AppearanceItem, carried: &AppearanceItem, g: &PathData, ctx: &GeomContext) -> (PathData, AppearanceItem) {
|
||||
let (ig, carry) = apply(item_effects(item), g, &ctx.item(item));
|
||||
let mut ap = Appearance { items: vec![carried.clone()], ..Default::default() };
|
||||
if !carry.moves(&ap) {
|
||||
return (ig, carried.clone());
|
||||
}
|
||||
carry.apply(&mut ap);
|
||||
(ig, ap.items.pop().unwrap_or_else(|| carried.clone()))
|
||||
}
|
||||
|
||||
/// A path node of `kind`'s flavour (compound when the result has several subpaths).
|
||||
@@ -333,16 +348,16 @@ fn moved_type_group(n: &Node) -> Option<Node> {
|
||||
/// outlined as [`evaluate_container`] outlines it, and the other members become what it makes of
|
||||
/// them. `None` when no type stays type.
|
||||
fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
|
||||
fn keep(n: &mut Node, moves: &[serde_json::Value], clipping: bool, kept: &mut bool) {
|
||||
fn keep(d: &Document, n: &mut Node, moves: &[serde_json::Value], clipping: bool, kept: &mut bool) {
|
||||
let clips = n.clips();
|
||||
let Some(ch) = n.children_mut() else { return };
|
||||
for (i, c) in ch.iter_mut().enumerate() {
|
||||
let clipping = clipping || (clips && i == 0);
|
||||
if !matches!(c.kind, NodeKind::Text(_)) {
|
||||
if has_pathfinder(c) || has_own_paint(c) || !geometry_effects(c).is_empty() {
|
||||
outline_nested_text(Arc::make_mut(c), clipping);
|
||||
outline_nested_text(Some(d), Arc::make_mut(c), clipping);
|
||||
} else if c.children().is_some() {
|
||||
keep(Arc::make_mut(c), moves, clipping, kept);
|
||||
keep(d, Arc::make_mut(c), moves, clipping, kept);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -357,7 +372,7 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
|
||||
}
|
||||
}
|
||||
None if clipping => outline_text(c).map(|o| Node { visible: c.visible, ..o }),
|
||||
None => as_art(None, c, None),
|
||||
None => as_art(Some(d), c, None),
|
||||
};
|
||||
if let Some(o) = art {
|
||||
*c = Arc::new(o);
|
||||
@@ -376,11 +391,11 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
|
||||
}
|
||||
let mut m = crate::reshape::evaluated(Some(d), n);
|
||||
let mut kept = false;
|
||||
keep(&mut m, &moves, false, &mut kept);
|
||||
keep(d, &mut m, &moves, false, &mut kept);
|
||||
if !kept {
|
||||
return None;
|
||||
}
|
||||
reshape_leaves(&mut m, &fx);
|
||||
reshape_leaves(&mut m, &fx, Some(d));
|
||||
m.appearance.effects.retain(|e| !is_pathfinder(&e.id) && !is_geometry(&e.id));
|
||||
m.appearance.items.clear();
|
||||
m.appearance.contents_index = None;
|
||||
@@ -414,12 +429,15 @@ fn piece(d: &mut Document, n: &Node, path: PathData, rule: FillRule, item: Appea
|
||||
}
|
||||
|
||||
/// `n`'s geometry with its object-level geometry effects applied, its fill rule, the context of
|
||||
/// its effects, and `n` without those effects.
|
||||
/// its effects, and `n` without those effects, its gradients moved along with them.
|
||||
fn leaf_base(n: &Node) -> Option<(PathData, FillRule, GeomContext<'_>, Node)> {
|
||||
let (base, rule) = geometry(n)?;
|
||||
let ctx = GeomContext::of(n);
|
||||
let g = apply(&n.appearance.effects, &base, &ctx);
|
||||
let mut m = n.clone();
|
||||
let (g, carry) = apply(&n.appearance.effects, &base, &ctx);
|
||||
if carry.moves(&m.appearance) {
|
||||
carry.apply(&mut m.appearance);
|
||||
}
|
||||
m.appearance.effects.retain(|e| !is_geometry(&e.id));
|
||||
Some((g, rule, ctx, m))
|
||||
}
|
||||
@@ -436,9 +454,9 @@ fn bake_leaf(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
.appearance
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| {
|
||||
let ig = apply(item_effects(item), &g, &ctx.item(item));
|
||||
let mut it = item.clone();
|
||||
.zip(&m.appearance.items)
|
||||
.map(|(item, carried)| {
|
||||
let (ig, mut it) = apply_item(item, carried, &g, &ctx);
|
||||
clear_item_effects(&mut it);
|
||||
Arc::new(piece(d, n, ig, rule, it))
|
||||
})
|
||||
@@ -470,9 +488,8 @@ pub fn expand_leaf(d: &mut Document, n: &Node, stroke_art: StrokeArt) -> Option<
|
||||
let (g, rule, ctx, mut m) = leaf_base(n)?;
|
||||
m.appearance.effects.retain(|e| e.visible);
|
||||
let mut pieces = vec![];
|
||||
for item in n.appearance.items.iter().filter(|i| paints(i)) {
|
||||
let ig = apply(item.effects(), &g, &ctx.item(item));
|
||||
let mut it = item.clone();
|
||||
for (item, carried) in n.appearance.items.iter().zip(&m.appearance.items).filter(|(i, _)| paints(i)) {
|
||||
let (ig, mut it) = apply_item(item, carried, &g, &ctx);
|
||||
clear_item_effects(&mut it);
|
||||
it.effects_mut().retain(|e| e.visible);
|
||||
let p = match &it {
|
||||
@@ -530,9 +547,10 @@ pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) {
|
||||
/// its gradient meshes clipped to the outline; a brushed stroke stays a stroke), in paint order, as
|
||||
/// the members of a group keeping `n`'s id, transparency, opacity mask and raster effects. A path
|
||||
/// with [`has_transform_art`](crate::has_transform_art) is first made into the art [`reshape`]
|
||||
/// makes of it, and each copy is baked this way. `None` when it has neither a stroke to outline nor
|
||||
/// a geometry effect, so bending first changes nothing.
|
||||
pub fn bake_appearance(n: &Node) -> Option<Node> {
|
||||
/// makes of it, and each copy is baked this way; the swatches and patterns that live-effect plug-ins
|
||||
/// painting their pieces name are looked up in `doc`. `None` when it has neither a stroke to
|
||||
/// outline nor a geometry effect, so bending first changes nothing.
|
||||
pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
if let Some(m) = crate::revolve_art(n).or_else(|| crate::solid_art(n)) {
|
||||
return Some(m);
|
||||
}
|
||||
@@ -543,9 +561,9 @@ pub fn bake_appearance(n: &Node) -> Option<Node> {
|
||||
// patterns: the art Expand Appearance makes of it (each copy an object with its own strokes,
|
||||
// patterns and gradients), each piece baked in turn.
|
||||
if crate::has_transform_art(n)
|
||||
&& let Some(mut m) = reshape(None, n, None)
|
||||
&& let Some(mut m) = reshape(doc, n, None)
|
||||
{
|
||||
bake_appearance_pieces(&mut m);
|
||||
bake_appearance_pieces(doc, &mut m);
|
||||
return Some(m);
|
||||
}
|
||||
let outlined = |i: &AppearanceItem| paints(i) && matches!(i, AppearanceItem::Stroke(s) if s.brush.is_none());
|
||||
@@ -562,9 +580,8 @@ pub fn bake_appearance(n: &Node) -> Option<Node> {
|
||||
Arc::new(p)
|
||||
};
|
||||
let mut pieces = vec![];
|
||||
for item in n.appearance.items.iter().filter(|i| paints(i)) {
|
||||
let ig = apply(item_effects(item), &g, &ctx.item(item));
|
||||
let mut it = item.clone();
|
||||
for (item, carried) in n.appearance.items.iter().zip(&m.appearance.items).filter(|(i, _)| paints(i)) {
|
||||
let (ig, mut it) = apply_item(item, carried, &g, &ctx);
|
||||
clear_item_effects(&mut it);
|
||||
pieces.push(match &it {
|
||||
AppearanceItem::Stroke(st) if st.brush.is_none() => {
|
||||
@@ -601,15 +618,15 @@ pub fn bake_appearance(n: &Node) -> Option<Node> {
|
||||
}
|
||||
|
||||
/// [`bake_appearance`] every path and compound path in `n` that it changes, in place.
|
||||
fn bake_appearance_pieces(n: &mut Node) {
|
||||
fn bake_appearance_pieces(doc: Option<&Document>, n: &mut Node) {
|
||||
if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) {
|
||||
if let Some(m) = bake_appearance(n) {
|
||||
if let Some(m) = bake_appearance(doc, n) {
|
||||
*n = m;
|
||||
}
|
||||
return;
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
bake_appearance_pieces(Arc::make_mut(c));
|
||||
bake_appearance_pieces(doc, Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,20 @@ fn fx(id: &str, params: serde_json::Value) -> Effect {
|
||||
Effect { id: id.into(), params, visible: true }
|
||||
}
|
||||
|
||||
/// Asserts that placed gradient `got` has `want`'s start, end, aspect and focal point, within 1e-6.
|
||||
fn assert_geom_near(got: vectorcraft_color::GradientGeom, want: vectorcraft_color::GradientGeom, what: &str) {
|
||||
let near = |a: Point, b: Point| a.distance(b) < 1e-6;
|
||||
let focal = match (got.focal, want.focal) {
|
||||
(None, None) => true,
|
||||
(Some(a), Some(b)) => near(a, b),
|
||||
_ => false,
|
||||
};
|
||||
assert!(
|
||||
near(got.start, want.start) && near(got.end, want.end) && (got.aspect - want.aspect).abs() < 1e-6 && focal,
|
||||
"{what}: got {got:?}, want {want:?}"
|
||||
);
|
||||
}
|
||||
|
||||
fn doc_with(n: Node) -> Document {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
@@ -45,6 +59,461 @@ fn object_effects_become_geometry_and_raster_effects_stay() {
|
||||
assert_eq!(m.appearance.effects[0].id, "stylize.dropShadow");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_baked_transform_moves_a_placed_gradient_with_the_path() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
|
||||
let geom = GradientGeom { start: Point::new(0.0, 50.0), end: Point::new(100.0, 50.0), aspect: 1.0, focal: None };
|
||||
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }));
|
||||
let placed_geom = |n: &Node| match n.appearance.fill_paint() {
|
||||
Paint::Gradient(g) => g.geom.unwrap(),
|
||||
p => panic!("a gradient: {p:?}"),
|
||||
};
|
||||
// A move 30 pt right, and a turn of 90° with the width halved about the center (50, 50): the
|
||||
// square becomes 100 pt wide and 50 pt tall, and the gradient runs from the bottom up.
|
||||
let moves = [
|
||||
(json!({"moveH": 30.0}), Point::new(30.0, 0.0), GradientGeom { start: Point::new(30.0, 50.0), end: Point::new(130.0, 50.0), ..geom }),
|
||||
(
|
||||
json!({"rotate": 90.0, "scaleH": 50.0}),
|
||||
Point::new(0.0, 25.0),
|
||||
GradientGeom { start: Point::new(50.0, 75.0), end: Point::new(50.0, 25.0), ..geom },
|
||||
),
|
||||
];
|
||||
// Alone, with a stroke whose own effect makes one path for each fill and stroke, and as the
|
||||
// fill's own effect.
|
||||
for (params, corner, want) in moves {
|
||||
for (split, own) in [(false, false), (true, false), (true, true)] {
|
||||
let mut ap = Appearance::basic(placed.clone(), Paint::solid(Color::BLACK), if split { 1.0 } else { 0.0 });
|
||||
if split && let AppearanceItem::Stroke(s) = &mut ap.items[1] {
|
||||
s.effects.push(fx("path.offsetPath", json!({"offset": 5.0})));
|
||||
}
|
||||
let transform = fx("distort.transform", params.clone());
|
||||
if own {
|
||||
ap.items[0].effects_mut().push(transform.clone());
|
||||
}
|
||||
let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), ap);
|
||||
if !own {
|
||||
n.appearance.effects.push(transform);
|
||||
}
|
||||
let d = bake_document(&doc_with(n)).unwrap();
|
||||
let m = d.node(NodeId(50)).unwrap();
|
||||
let fill: &Node = if split { &m.children().unwrap()[0] } else { m };
|
||||
let b = fill.geometric_bounds().unwrap();
|
||||
assert!(b.origin().distance(corner) < 1e-6, "{params}, split {split}, own {own}: {b:?}");
|
||||
assert_geom_near(placed_geom(fill), want, &format!("{params}, split {split}, own {own}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke's own Transform effect or Free Distort moves the gradient placed on that stroke.
|
||||
#[test]
|
||||
fn a_strokes_own_transform_and_free_distort_move_its_placed_gradient() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
|
||||
let geom = GradientGeom { start: Point::new(0.0, 50.0), end: Point::new(100.0, 50.0), aspect: 1.0, focal: None };
|
||||
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }));
|
||||
// Moved 30 pt right by Transform, and one width (100 pt) right by Free Distort.
|
||||
let moves = [
|
||||
(fx("distort.transform", json!({"moveH": 30.0})), 30.0),
|
||||
(fx("distort.freeDistort", json!({"corners": [[1.0, 0.0], [2.0, 0.0], [2.0, 1.0], [1.0, 1.0]]})), 100.0),
|
||||
];
|
||||
for (e, moved) in moves {
|
||||
let mut ap = Appearance::basic(Paint::None, placed.clone(), 4.0);
|
||||
let Some(stroke) = ap.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) else { panic!("a stroke") };
|
||||
stroke.effects_mut().push(e.clone());
|
||||
let n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), ap);
|
||||
let d = bake_document(&doc_with(n)).unwrap();
|
||||
let mut geoms = vec![];
|
||||
d.node(NodeId(50)).unwrap().walk(&mut |c: &Node| {
|
||||
for item in &c.appearance.items {
|
||||
if let AppearanceItem::Stroke(s) = item
|
||||
&& let Paint::Gradient(g) = &s.paint
|
||||
{
|
||||
geoms.push(g.geom.unwrap());
|
||||
}
|
||||
}
|
||||
});
|
||||
assert!(!geoms.is_empty(), "{}: the stroke keeps its gradient", e.id);
|
||||
let want = GradientGeom { start: Point::new(moved, 50.0), end: Point::new(100.0 + moved, 50.0), ..geom };
|
||||
for g in geoms {
|
||||
assert_geom_near(g, want, &e.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fills_gradient_follows_the_effects_around_its_transform_with_options() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
|
||||
let geom = GradientGeom { start: Point::new(0.0, 50.0), end: Point::new(100.0, 50.0), aspect: 1.0, focal: None };
|
||||
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }));
|
||||
let moved = fx("distort.transform", json!({"moveH": 30.0}));
|
||||
let scales_strokes = fx("distort.transform", json!({"strokes": true}));
|
||||
// A move before and a move after the fill's Transform effect with Scale Strokes & Effects on.
|
||||
for fill_fx in [vec![moved.clone(), scales_strokes.clone()], vec![scales_strokes, moved]] {
|
||||
let mut ap = Appearance::basic(placed.clone(), Paint::None, 0.0);
|
||||
*ap.items[0].effects_mut() = fill_fx.clone();
|
||||
let n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), ap);
|
||||
let d = bake_document(&doc_with(n)).unwrap();
|
||||
let mut found = vec![];
|
||||
d.node(NodeId(50)).unwrap().walk(&mut |c: &Node| {
|
||||
if let Paint::Gradient(g) = c.appearance.fill_paint() {
|
||||
found.push((c.geometric_bounds().unwrap(), g.geom.unwrap()));
|
||||
}
|
||||
});
|
||||
assert!(!found.is_empty(), "{fill_fx:?}: the fill keeps its gradient");
|
||||
let want = GradientGeom { start: Point::new(30.0, 50.0), end: Point::new(130.0, 50.0), ..geom };
|
||||
for (b, g) in found {
|
||||
assert!(b.origin().distance(Point::new(30.0, 0.0)) < 1e-6, "{fill_fx:?}: {b:?}");
|
||||
assert_geom_near(g, want, &format!("{fill_fx:?}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn baked_free_distort_moves_placed_gradients_from_the_bounds_to_the_distorted_bounds() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let ramp = |kind| GradientPaint::new(Gradient::new(kind, stops.clone()));
|
||||
let linear = GradientGeom { start: Point::new(20.0, 50.0), end: Point::new(80.0, 50.0), aspect: 1.0, focal: None };
|
||||
let radial = GradientGeom { start: Point::new(40.0, 30.0), end: Point::new(60.0, 30.0), aspect: 0.5, focal: Some(Point::new(45.0, 32.0)) };
|
||||
let placed_linear = Paint::Gradient(Box::new(GradientPaint { geom: Some(linear), ..ramp(GradientKind::Linear) }));
|
||||
let placed_radial = Paint::Gradient(Box::new(GradientPaint { geom: Some(radial), ..ramp(GradientKind::Radial) }));
|
||||
let fitted = Paint::Gradient(Box::new(ramp(GradientKind::Linear)));
|
||||
let baked = |fill: &Paint, e: Effect| {
|
||||
let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(fill.clone(), Paint::None, 0.0));
|
||||
n.appearance.effects.push(e);
|
||||
let d = bake_document(&doc_with(n)).unwrap();
|
||||
let m = d.node(NodeId(50)).unwrap();
|
||||
match m.appearance.fill_paint() {
|
||||
Paint::Gradient(g) => (m.geometric_bounds().unwrap(), (*g).clone()),
|
||||
p => panic!("a gradient: {p:?}"),
|
||||
}
|
||||
};
|
||||
let near = |a: Point, b: Point| a.distance(b) < 1e-6;
|
||||
// The bottom right corner moves 50 pt right, so the bounds grow from 0..100 to 0..150 across.
|
||||
let corners = json!({"corners": [[0.0, 0.0], [1.0, 0.0], [1.5, 1.0], [0.0, 1.0]]});
|
||||
let distort = || fx("distort.freeDistort", corners.clone());
|
||||
let (b, g) = baked(&placed_linear, distort());
|
||||
assert!((b.x1 - 150.0).abs() < 1e-6, "{b:?}");
|
||||
let geom = g.geom.unwrap();
|
||||
assert!(near(geom.start, Point::new(30.0, 50.0)) && near(geom.end, Point::new(120.0, 50.0)), "{geom:?}");
|
||||
// A radial gradient's center, focal point and ellipse take the same stretch: the radius along
|
||||
// the vector grows from 20 to 30 pt and the 10 pt radius across it stays.
|
||||
let (_, g) = baked(&placed_radial, distort());
|
||||
let want = GradientGeom { start: Point::new(60.0, 30.0), end: Point::new(90.0, 30.0), aspect: 1.0 / 3.0, focal: Some(Point::new(67.5, 32.0)) };
|
||||
assert_geom_near(g.geom.unwrap(), want, "radial");
|
||||
// A fitted gradient stays fitted, and fits the distorted outline.
|
||||
assert_eq!(baked(&fitted, distort()).1.geom, None);
|
||||
}
|
||||
|
||||
/// A gradient fitted to the object turns, reflects and stretches with a Transform effect that a
|
||||
/// refit would not reproduce: it is fixed to its fit on the geometry the effect takes, then mapped.
|
||||
/// Moves and even scales leave it fitted.
|
||||
#[test]
|
||||
fn a_fitted_gradient_turns_reflects_and_stretches_with_a_transform_effect() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let fitted = |kind| Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(kind, stops.clone()))));
|
||||
let geom = |start: (f64, f64), end: (f64, f64)| GradientGeom { start: start.into(), end: end.into(), aspect: 1.0, focal: None };
|
||||
// The geometry of the baked fill (`own`: the Transform effect is the fill's own effect).
|
||||
let baked = |kind, effects: &[Effect], own: bool| {
|
||||
let mut ap = Appearance::basic(fitted(kind), Paint::None, 0.0);
|
||||
if own {
|
||||
*ap.items[0].effects_mut() = effects.to_vec();
|
||||
}
|
||||
let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), ap);
|
||||
if !own {
|
||||
n.appearance.effects = effects.to_vec();
|
||||
}
|
||||
let d = bake_document(&doc_with(n)).unwrap();
|
||||
let mut found = vec![];
|
||||
d.node(NodeId(50)).unwrap().walk(&mut |c: &Node| {
|
||||
if let Paint::Gradient(g) = c.appearance.fill_paint() {
|
||||
found.push(g.geom);
|
||||
}
|
||||
});
|
||||
assert_eq!(found.len(), 1, "{effects:?}, own {own}");
|
||||
found[0]
|
||||
};
|
||||
let t = |params| fx("distort.transform", params);
|
||||
let offset = fx("path.offsetPath", json!({"offset": 10.0, "joins": "miter"}));
|
||||
let corners = json!({"corners": [[1.0, 0.0], [2.0, 0.0], [2.0, 1.0], [1.0, 1.0]]});
|
||||
let linear = GradientKind::Linear;
|
||||
let cases = [
|
||||
// A quarter turn about the center: the left to right ramp runs from the bottom up.
|
||||
(linear, vec![t(json!({"rotate": 90.0}))], geom((50.0, 100.0), (50.0, 0.0))),
|
||||
// Reflected left to right: the ramp runs from right to left.
|
||||
(linear, vec![t(json!({"reflectX": true}))], geom((100.0, 50.0), (0.0, 50.0))),
|
||||
// With Scale Strokes & Effects on, the same.
|
||||
(linear, vec![t(json!({"rotate": 90.0, "strokes": true}))], geom((50.0, 100.0), (50.0, 0.0))),
|
||||
// Offset Path grows the square to -10..110 first: the turn takes the fit across 120 pt.
|
||||
(linear, vec![offset.clone(), t(json!({"rotate": 90.0}))], geom((50.0, 110.0), (50.0, -10.0))),
|
||||
// Stretched to twice the width: the circle of radius 50 about the center becomes an
|
||||
// ellipse 100 pt across and 50 pt tall.
|
||||
(GradientKind::Radial, vec![t(json!({"scaleH": 200.0}))], GradientGeom { aspect: 0.5, ..geom((50.0, 50.0), (150.0, 50.0)) }),
|
||||
// Turned, then moved one width right by Free Distort: the fixed gradient moves with it.
|
||||
(linear, vec![t(json!({"rotate": 90.0})), fx("distort.freeDistort", corners)], geom((150.0, 100.0), (150.0, 0.0))),
|
||||
];
|
||||
for (kind, effects, want) in cases {
|
||||
for own in [false, true] {
|
||||
let what = format!("{kind:?} {effects:?}, own {own}");
|
||||
let got = baked(kind, &effects, own).unwrap_or_else(|| panic!("{what}: fixed to its fit"));
|
||||
assert_geom_near(got, want, &what);
|
||||
}
|
||||
}
|
||||
// A move and an even scale are what a refit gives: the gradient stays fitted.
|
||||
for effects in [vec![t(json!({"moveH": 30.0}))], vec![t(json!({"scaleH": 150.0, "scaleV": 150.0})), offset]] {
|
||||
for own in [false, true] {
|
||||
assert_eq!(baked(linear, &effects, own), None, "{effects:?}, own {own}");
|
||||
}
|
||||
}
|
||||
// A stroke's gradient is fixed to its fit on the box grown by half its weight (4 pt), -2..102,
|
||||
// with Scale Strokes & Effects off or on.
|
||||
let stroked = |effects: &[Effect], own: bool| {
|
||||
let mut ap = Appearance::basic(Paint::None, fitted(linear), 4.0);
|
||||
let Some(stroke) = ap.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) else { panic!("a stroke") };
|
||||
if own {
|
||||
*stroke.effects_mut() = effects.to_vec();
|
||||
}
|
||||
let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), ap);
|
||||
if !own {
|
||||
n.appearance.effects = effects.to_vec();
|
||||
}
|
||||
let d = bake_document(&doc_with(n)).unwrap();
|
||||
let mut found = vec![];
|
||||
d.node(NodeId(50)).unwrap().walk(&mut |c: &Node| {
|
||||
for item in &c.appearance.items {
|
||||
if let AppearanceItem::Stroke(s) = item
|
||||
&& let Paint::Gradient(g) = &s.paint
|
||||
{
|
||||
found.push(g.geom);
|
||||
}
|
||||
}
|
||||
});
|
||||
assert_eq!(found.len(), 1, "{effects:?}, own {own}");
|
||||
found[0]
|
||||
};
|
||||
for strokes in [false, true] {
|
||||
for own in [false, true] {
|
||||
let what = format!("stroke, strokes {strokes}, own {own}");
|
||||
let got = stroked(&[t(json!({"rotate": 90.0, "strokes": strokes}))], own).unwrap_or_else(|| panic!("{what}: fixed to its fit"));
|
||||
assert_geom_near(got, geom((50.0, 102.0), (50.0, -2.0)), &what);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Transform effect that scales the geometry to nothing across leaves a fitted gradient fitted:
|
||||
/// mapping it with the effect would flatten it to one color.
|
||||
#[test]
|
||||
fn a_transform_effect_that_scales_to_nothing_leaves_a_fitted_gradient_fitted() {
|
||||
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let fitted = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
// With Scale Strokes & Effects or Transform Patterns on, and for each copy, as without them.
|
||||
for (options, strokes) in [
|
||||
(json!({}), 1),
|
||||
(json!({"strokes": true}), 1),
|
||||
(json!({"patterns": true}), 1),
|
||||
(json!({"copies": 2}), 3),
|
||||
(json!({"strokes": true, "copies": 2}), 3),
|
||||
(json!({"patterns": true, "copies": 2}), 3),
|
||||
] {
|
||||
let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::None, fitted.clone(), 4.0));
|
||||
let mut p = json!({"scaleH": 0.0, "rotate": 30.0});
|
||||
if let (Some(p), Some(o)) = (p.as_object_mut(), options.as_object()) {
|
||||
p.extend(o.clone());
|
||||
}
|
||||
n.appearance.effects = vec![fx("distort.transform", p)];
|
||||
let d = bake_document(&doc_with(n)).unwrap();
|
||||
let mut found = vec![];
|
||||
d.node(NodeId(50)).unwrap().walk(&mut |c: &Node| {
|
||||
for item in &c.appearance.items {
|
||||
if let AppearanceItem::Stroke(s) = item
|
||||
&& let Paint::Gradient(g) = &s.paint
|
||||
{
|
||||
found.push(g.geom);
|
||||
}
|
||||
}
|
||||
});
|
||||
assert_eq!(found, vec![None; strokes], "{options}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn baked_warps_move_placed_gradients_from_the_bounds_to_the_warped_bounds() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let ramp = |kind| GradientPaint::new(Gradient::new(kind, stops.clone()));
|
||||
// A ramp across the square and one down it, so both axes of the box map show.
|
||||
let across = GradientGeom { start: Point::new(20.0, 30.0), end: Point::new(80.0, 30.0), aspect: 1.0, focal: None };
|
||||
let down = GradientGeom { start: Point::new(60.0, 10.0), end: Point::new(60.0, 75.0), aspect: 1.0, focal: None };
|
||||
let placed = |geom| Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp(GradientKind::Linear) }));
|
||||
let fitted = Paint::Gradient(Box::new(ramp(GradientKind::Linear)));
|
||||
let square = Rect::new(0.0, 0.0, 100.0, 100.0);
|
||||
let baked = |fill: &Paint, e: Effect| {
|
||||
let mut n = Node::path(NodeId(50), shapes::rectangle(square), Appearance::basic(fill.clone(), Paint::None, 0.0));
|
||||
n.appearance.effects.push(e);
|
||||
let d = bake_document(&doc_with(n)).unwrap();
|
||||
let m = d.node(NodeId(50)).unwrap();
|
||||
match m.appearance.fill_paint() {
|
||||
Paint::Gradient(g) => (m.geometric_bounds().unwrap(), (*g).clone()),
|
||||
p => panic!("a gradient: {p:?}"),
|
||||
}
|
||||
};
|
||||
// Where the box map from the square to `to` takes `p`.
|
||||
let follow = |p: Point, to: Rect| Point::new(to.x0 + p.x / 100.0 * to.width(), to.y0 + p.y / 100.0 * to.height());
|
||||
let styles = [
|
||||
"arc",
|
||||
"arcLower",
|
||||
"arcUpper",
|
||||
"arch",
|
||||
"bulge",
|
||||
"shellLower",
|
||||
"shellUpper",
|
||||
"flag",
|
||||
"wave",
|
||||
"fish",
|
||||
"rise",
|
||||
"fisheye",
|
||||
"inflate",
|
||||
"squeeze",
|
||||
"twist",
|
||||
];
|
||||
// The square's warped bounds, from `warp_point` on 401 points along each side: the square's
|
||||
// corners are (-1, -1) and (1, 1) in the warp's box coordinates, and a vertical warp swaps
|
||||
// the axes.
|
||||
let warped_bounds = |style: &str, p: &serde_json::Value| {
|
||||
let Some(style) = crate::WarpStyle::from_id(style) else { panic!("warp.{style}: a style") };
|
||||
let share = |key: &str, default: f64| p.get(key).and_then(serde_json::Value::as_f64).unwrap_or(default) / 100.0;
|
||||
let vertical = p.get("orientation").and_then(serde_json::Value::as_str) == Some("vertical");
|
||||
let (bend, dh, dv) = (share("bend", 50.0), share("horizontal", 0.0), share("vertical", 0.0));
|
||||
let mut r: Option<Rect> = None;
|
||||
for k in 0..=400 {
|
||||
let s = f64::from(k) / 200.0 - 1.0;
|
||||
for (x, y) in [(s, -1.0), (s, 1.0), (-1.0, s), (1.0, s)] {
|
||||
let (x2, y2) = if vertical {
|
||||
let (a, b) = crate::warp_point(style, bend, dh, dv, 1.0, y, x);
|
||||
(b, a)
|
||||
} else {
|
||||
crate::warp_point(style, bend, dh, dv, 1.0, x, y)
|
||||
};
|
||||
let q = Point::new(50.0 + x2 * 50.0, 50.0 + y2 * 50.0);
|
||||
r = Some(r.map_or(Rect::from_points(q, q), |r| r.union_pt(q)));
|
||||
}
|
||||
}
|
||||
r.unwrap_or(square)
|
||||
};
|
||||
let near =
|
||||
|a: Rect, b: Rect, tol: f64| (a.x0 - b.x0).abs() < tol && (a.y0 - b.y0).abs() < tol && (a.x1 - b.x1).abs() < tol && (a.y1 - b.y1).abs() < tol;
|
||||
let mut moved = 0;
|
||||
for style in styles {
|
||||
for params in
|
||||
[json!({"bend": 30.0}), json!({"bend": -40.0, "orientation": "vertical"}), json!({"bend": 20.0, "horizontal": 30.0, "vertical": -20.0})]
|
||||
{
|
||||
// A warp that bends the square's sides inward keeps its bounds (within 0.5 pt), and the
|
||||
// gradient stays with them.
|
||||
let expected = warped_bounds(style, ¶ms);
|
||||
let moves = !near(expected, square, 0.5);
|
||||
moved += usize::from(moves);
|
||||
for linear in [across, down] {
|
||||
let what = format!("warp.{style} {params} {linear:?}");
|
||||
let (b, g) = baked(&placed(linear), fx(&format!("warp.{style}"), params.clone()));
|
||||
assert!(near(b, expected, 0.1), "{what}: bounds {b:?}, want {expected:?}");
|
||||
let geom = g.geom.unwrap();
|
||||
let shifted = geom.start.distance(linear.start).max(geom.end.distance(linear.end));
|
||||
assert_eq!(shifted > 0.1, moves, "{what}: the gradient moves {shifted} with bounds {b:?}");
|
||||
let want = GradientGeom { start: follow(linear.start, b), end: follow(linear.end, b), ..linear };
|
||||
assert_geom_near(geom, want, &what);
|
||||
}
|
||||
let what = format!("warp.{style} {params}");
|
||||
// A fitted gradient stays fitted, and fits the warped outline.
|
||||
assert_eq!(baked(&fitted, fx(&format!("warp.{style}"), params)).1.geom, None, "{what}");
|
||||
}
|
||||
}
|
||||
assert_eq!(moved, 39, "the warps that move the bounds, of 45");
|
||||
// With no bend and no distortion the gradient stays where it is.
|
||||
let (_, g) = baked(&placed(across), fx("warp.arc", json!({"bend": 0.0})));
|
||||
assert_geom_near(g.geom.unwrap(), across, "no bend");
|
||||
}
|
||||
|
||||
/// A warp with no distortion and no bend (or a bend Arc takes as none) leaves a placed gradient
|
||||
/// exactly where it was, even where warping the outline moves its bounds by a rounding error.
|
||||
#[test]
|
||||
fn a_warp_with_no_bend_leaves_a_placed_gradient_exactly_in_place() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let geom = GradientGeom { start: Point::new(13.7, 31.3), end: Point::new(91.1, 47.9), aspect: 1.0, focal: None };
|
||||
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..GradientPaint::new(Gradient::new(GradientKind::Linear, stops)) }));
|
||||
let mut drift = 0;
|
||||
let cases = crate::WARP_STYLES.map(|(s, _)| (s, 0.0));
|
||||
for (k, (style, bend)) in cases.into_iter().chain([("arc", 1e-5), ("arc", -1e-5)]).enumerate() {
|
||||
let k = k as f64;
|
||||
let oval = Rect::new(10.1 + k * 0.37, 20.3 - k * 1.13, 97.7 + k * 3.31, 71.9 + k * 0.71);
|
||||
let mut n = Node::path(NodeId(50), shapes::ellipse(oval), Appearance::basic(placed.clone(), Paint::None, 0.0));
|
||||
n.appearance.effects.push(fx(&format!("warp.{style}"), json!({ "bend": bend })));
|
||||
let d = bake_document(&doc_with(n)).unwrap();
|
||||
let m = d.node(NodeId(50)).unwrap();
|
||||
drift += usize::from(m.geometric_bounds() != shapes::ellipse(oval).bounds());
|
||||
let Paint::Gradient(g) = m.appearance.fill_paint() else { panic!("warp.{style} {bend}: a gradient") };
|
||||
assert_eq!(g.geom, Some(geom), "warp.{style} {bend}");
|
||||
}
|
||||
assert!(drift > 0, "the warped outlines' bounds move by a rounding error");
|
||||
// Another style with as small a bend still moves the outline, and the gradient follows it.
|
||||
let mut n = Node::path(NodeId(50), shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(placed, Paint::None, 0.0));
|
||||
n.appearance.effects.push(fx("warp.rise", json!({"bend": 1e-5})));
|
||||
let d = bake_document(&doc_with(n)).unwrap();
|
||||
let Paint::Gradient(g) = d.node(NodeId(50)).unwrap().appearance.fill_paint() else { panic!("warp.rise: a gradient") };
|
||||
assert_ne!(g.geom, Some(geom), "warp.rise 1e-5");
|
||||
}
|
||||
|
||||
/// A Warp effect on a fill or a stroke itself moves and scales its placed gradient from the
|
||||
/// path's bounds before the warp to its bounds after it (a stroke: its stroke-inflated bounds).
|
||||
#[test]
|
||||
fn a_fills_and_a_strokes_own_warp_move_its_placed_gradient_with_the_bounds() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
|
||||
let geom = GradientGeom { start: Point::new(20.0, 60.0), end: Point::new(80.0, 60.0), aspect: 1.0, focal: None };
|
||||
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }));
|
||||
let square = Rect::new(0.0, 0.0, 100.0, 100.0);
|
||||
let width = 4.0;
|
||||
// Where the box map from `from` to `to` takes `p`.
|
||||
let follow = |p: Point, from: Rect, to: Rect| {
|
||||
Point::new(to.x0 + (p.x - from.x0) / from.width() * to.width(), to.y0 + (p.y - from.y0) / from.height() * to.height())
|
||||
};
|
||||
let pad = |r: Rect| r.inflate(width / 2.0, width / 2.0);
|
||||
for style in ["arc", "rise", "inflate"] {
|
||||
for stroke in [false, true] {
|
||||
let what = format!("warp.{style} on the {}", if stroke { "stroke" } else { "fill" });
|
||||
let mut ap =
|
||||
if stroke { Appearance::basic(Paint::None, placed.clone(), width) } else { Appearance::basic(placed.clone(), Paint::None, 0.0) };
|
||||
let Some(item) = ap.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_)) == stroke) else { panic!("{what}: the item") };
|
||||
item.effects_mut().push(fx(&format!("warp.{style}"), json!({"bend": 40.0})));
|
||||
let n = Node::path(NodeId(50), shapes::rectangle(square), ap);
|
||||
let d = bake_document(&doc_with(n)).unwrap();
|
||||
let mut found = vec![];
|
||||
d.node(NodeId(50)).unwrap().walk(&mut |c: &Node| {
|
||||
for item in &c.appearance.items {
|
||||
if let Paint::Gradient(g) = item.paint() {
|
||||
found.push((c.geometric_bounds().unwrap(), g.geom.unwrap()));
|
||||
}
|
||||
}
|
||||
});
|
||||
assert!(!found.is_empty(), "{what}: the gradient is kept");
|
||||
for (b, g) in found {
|
||||
assert_ne!(b, square, "{what}: the warp changes the bounds");
|
||||
let (from, to) = if stroke { (pad(square), pad(b)) } else { (square, b) };
|
||||
let want = GradientGeom { start: follow(geom.start, from, to), end: follow(geom.end, from, to), ..geom };
|
||||
assert_geom_near(g, want, &what);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn item_effects_split_into_one_path_per_item() {
|
||||
let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art());
|
||||
@@ -67,7 +536,7 @@ fn a_baked_stroke_keeps_its_raster_effects() {
|
||||
s.effects.push(fx("path.offsetPath", json!({"offset": 5.0})));
|
||||
s.effects.push(fx("stylize.dropShadow", json!({})));
|
||||
}
|
||||
let m = bake_appearance(&n).unwrap();
|
||||
let m = bake_appearance(None, &n).unwrap();
|
||||
let ch = m.children().unwrap();
|
||||
let Some(AppearanceItem::Fill(f)) = ch[1].appearance.items.first() else { panic!("the outline is filled") };
|
||||
assert_eq!(f.effects.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), ["stylize.dropShadow"]);
|
||||
@@ -82,7 +551,7 @@ fn a_baked_stroke_leaves_dither_behind() {
|
||||
g.gradient.dither = true;
|
||||
s.paint = Paint::Gradient(Box::new(g));
|
||||
}
|
||||
let m = bake_appearance(&n).unwrap();
|
||||
let m = bake_appearance(None, &n).unwrap();
|
||||
let ch = m.children().unwrap();
|
||||
let Some(AppearanceItem::Fill(f)) = ch[1].appearance.items.first() else { panic!("the outline is filled") };
|
||||
let Paint::Gradient(g) = &f.paint else { panic!("a gradient fill") };
|
||||
@@ -98,7 +567,7 @@ fn a_baked_stroke_with_a_gradient_along_it_becomes_meshes_clipped_to_its_outline
|
||||
s.gradient_mode = vectorcraft_doc::StrokeGradientMode::Along;
|
||||
s.opacity = 0.5;
|
||||
}
|
||||
let m = bake_appearance(&n).unwrap();
|
||||
let m = bake_appearance(None, &n).unwrap();
|
||||
let ch = m.children().unwrap();
|
||||
let NodeKind::Group { children, clip: true } = &ch[1].kind else { panic!("a clip group: {:?}", ch[1].kind) };
|
||||
assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. }));
|
||||
@@ -131,7 +600,7 @@ fn a_baked_transform_copy_keeps_its_scaled_stroke() {
|
||||
// Distort Appearance: the 200% copy's stroke is 4 pt, as outside the envelope, so its outline
|
||||
// is 204 pt wide.
|
||||
let n = transformed(Paint::None, Paint::solid(Color::BLACK), 2.0, json!({"scaleH": 200, "scaleV": 200, "copies": 1, "strokes": true}));
|
||||
let m = bake_appearance(&n).unwrap();
|
||||
let m = bake_appearance(None, &n).unwrap();
|
||||
let w = widths(&m);
|
||||
assert_eq!(w.len(), 2, "{w:?}");
|
||||
assert!((w[0] - 102.0).abs() < 0.5 && (w[1] - 204.0).abs() < 0.5, "{w:?}");
|
||||
@@ -142,7 +611,7 @@ fn a_baked_transform_copy_keeps_its_scaled_stroke() {
|
||||
fn a_baked_transform_copy_keeps_its_moved_pattern() {
|
||||
let paint = Paint::Pattern { pattern: "p".into(), xf: vectorcraft_geom::Affine::IDENTITY };
|
||||
let n = transformed(paint, Paint::None, 0.0, json!({"moveH": 30, "copies": 1, "patterns": true}));
|
||||
let m = bake_appearance(&n).unwrap();
|
||||
let m = bake_appearance(None, &n).unwrap();
|
||||
let xs: Vec<f64> = baked_paths(&m)
|
||||
.iter()
|
||||
.map(|p| match p.appearance.fill_paint() {
|
||||
@@ -157,7 +626,7 @@ fn a_baked_transform_copy_keeps_its_moved_pattern() {
|
||||
fn a_baked_transform_without_its_options_outlines_the_copies_together() {
|
||||
// Without Scale Strokes & Effects the copy keeps the 2 pt stroke: one outline of both squares.
|
||||
let n = transformed(Paint::None, Paint::solid(Color::BLACK), 2.0, json!({"scaleH": 200, "scaleV": 200, "copies": 1}));
|
||||
let m = bake_appearance(&n).unwrap();
|
||||
let m = bake_appearance(None, &n).unwrap();
|
||||
let w = widths(&m);
|
||||
assert_eq!(w.len(), 1, "{w:?}");
|
||||
assert!((w[0] - 202.0).abs() < 0.5, "{w:?}");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{CROP_MARKS, EXTRUDE, INFLATE, PATHFINDER_EFFECTS, RASTERIZE, REVOLVE, ROTATE, TRAP, Value, json, trap};
|
||||
use super::{CLASSIC_EXTRUDE, CROP_MARKS, EXTRUDE, INFLATE, PATHFINDER_EFFECTS, RASTERIZE, REVOLVE, ROTATE, TRAP, Value, json, trap};
|
||||
|
||||
/// Catalogue entry for one effect.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -80,6 +80,7 @@ fn lengths_of(id: &str) -> Lengths {
|
||||
"path.offsetPath" => always(&["offset"]),
|
||||
"threeD.revolve" => always(&["offset"]),
|
||||
"threeD.extrude" => always(&["depth", "bevelWidth", "bevelHeight"]),
|
||||
"threeD.classicExtrude" => always(&["depth", "bevelHeight"]),
|
||||
"threeD.inflate" => always(&["depth"]),
|
||||
"path.outlineStroke" => always(&["width"]),
|
||||
"stylize.roundCorners" | "stylize.feather" | "blur.gaussian" | "blur.smart" | "sharpen.unsharpMask" => always(&["radius"]),
|
||||
@@ -105,12 +106,13 @@ fn lengths_of(id: &str) -> Lengths {
|
||||
"sketch.waterPaper" => always(&["fiberLength"]),
|
||||
TRAP => always(&["thickness", "precision"]),
|
||||
RASTERIZE => always(&["addAround"]),
|
||||
// The points one unit of the filter measures.
|
||||
crate::SVG_FILTER => always(&["scale"]),
|
||||
_ => Lengths::default(),
|
||||
}
|
||||
}
|
||||
|
||||
const WARP_DOC: &str =
|
||||
"{bend: % (-100..100, 50), horizontal: % distortion (0), vertical: % distortion (0), orientation: \"horizontal\"|\"vertical\"}";
|
||||
const WARP_DOC: &str = "{bend: % (-100..100, 50; with a bend or a distortion, placed gradients move and scale from the object's bounds to its warped bounds), horizontal: % distortion (0), vertical: % distortion (0), orientation: \"horizontal\"|\"vertical\"}";
|
||||
|
||||
const DT: &[&str] = &["Effect", "Distort & Transform"];
|
||||
|
||||
@@ -198,6 +200,13 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"{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), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), 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, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
|
||||
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0}),
|
||||
),
|
||||
g(
|
||||
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}),
|
||||
),
|
||||
g(
|
||||
"convertToShape.rectangle",
|
||||
"Rectangle…",
|
||||
@@ -223,7 +232,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"distort.freeDistort",
|
||||
"Free Distort…",
|
||||
DT,
|
||||
"{corners: [[x,y]×4] (new positions of the bounding-box corners TL, TR, BR, BL in unit box coordinates; identity [[0,0],[1,0],[1,1],[0,1]])}",
|
||||
"{corners: [[x,y]×4] (new positions of the bounding-box corners TL, TR, BR, BL in unit box coordinates; identity [[0,0],[1,0],[1,1],[0,1]]; placed gradients move and scale from the object's bounds to its distorted bounds)}",
|
||||
json!({"corners": [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]}),
|
||||
),
|
||||
g("distort.puckerBloat", "Pucker & Bloat…", DT, "{amount: % (-200 pucker … 200 bloat, default 0)}", json!({"amount": 0.0})),
|
||||
@@ -238,7 +247,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), copies: 0..1000 (0; each copy transforms the last again), 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), 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)}",
|
||||
"{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; 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), 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)}",
|
||||
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(
|
||||
@@ -826,6 +835,13 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"{colorModel: \"document\" (the document's mode, RGB or CMYK)|\"grayscale\"|\"bitmap\" (\"document\"), useDocumentResolution: bool (true: Document Raster Effects Settings › Resolution), resolution: ppi 1..2400 (72; with useDocumentResolution false), background: \"white\"|\"transparent\" (\"transparent\"), antiAlias: \"none\"|\"art\"|\"type\" (\"art\"; none: hard edges), clippingMask: bool (false; the image clipped to the art's outline), addAround: pt 0..1000 (0; room around the art)} draws the object as an image of square pixels over its bounds and the room around them, leaving its paths, type and other art as they are; when it is the object's only raster effect, Expand Appearance makes the image Object › Rasterize makes",
|
||||
json!({"colorModel": "document", "useDocumentResolution": true, "resolution": 72.0, "background": "transparent", "antiAlias": "art", "clippingMask": false, "addAround": 0.0}),
|
||||
));
|
||||
v.push(r(
|
||||
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)",
|
||||
json!({"scale": 1.0, "origin": [0.0, 0.0]}),
|
||||
));
|
||||
v
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,21 @@ fn diag(b: Rect) -> f64 {
|
||||
/// Free Distort: bilinear map of the bounding box onto four new corners (unit box coordinates),
|
||||
/// making at most `max` anchors ([`map_nonlinear_within`]).
|
||||
pub fn free_distort(path: &PathData, b: Rect, p: &Value, max: usize) -> PathData {
|
||||
let c = free_distort_corners(b, p);
|
||||
let (w, h) = (b.width().max(1e-9), b.height().max(1e-9));
|
||||
let f = |q: Point| {
|
||||
let u = (q.x - b.x0) / w;
|
||||
let v = (q.y - b.y0) / h;
|
||||
let top = c[0].lerp(c[1], u);
|
||||
let bot = c[3].lerp(c[2], u);
|
||||
top.lerp(bot, v)
|
||||
};
|
||||
map_nonlinear_within(path, diag(b) / 16.0, max, f)
|
||||
}
|
||||
|
||||
/// The four corners (top left, top right, bottom right, bottom left) Free Distort with params `p`
|
||||
/// moves bounding box `b`'s corners to, in the document.
|
||||
pub(crate) fn free_distort_corners(b: Rect, p: &Value) -> [Point; 4] {
|
||||
let mut c = [Point::new(0.0, 0.0), Point::new(1.0, 0.0), Point::new(1.0, 1.0), Point::new(0.0, 1.0)];
|
||||
if let Some(arr) = p.get("corners").and_then(Value::as_array) {
|
||||
for (i, v) in arr.iter().take(4).enumerate() {
|
||||
@@ -26,16 +41,7 @@ pub fn free_distort(path: &PathData, b: Rect, p: &Value, max: usize) -> PathData
|
||||
}
|
||||
}
|
||||
let (w, h) = (b.width().max(1e-9), b.height().max(1e-9));
|
||||
let to_doc = |q: Point| Point::new(b.x0 + q.x * w, b.y0 + q.y * h);
|
||||
let c = c.map(to_doc);
|
||||
let f = |q: Point| {
|
||||
let u = (q.x - b.x0) / w;
|
||||
let v = (q.y - b.y0) / h;
|
||||
let top = c[0].lerp(c[1], u);
|
||||
let bot = c[3].lerp(c[2], u);
|
||||
top.lerp(bot, v)
|
||||
};
|
||||
map_nonlinear_within(path, diag(b) / 16.0, max, f)
|
||||
c.map(|q| Point::new(b.x0 + q.x * w, b.y0 + q.y * h))
|
||||
}
|
||||
|
||||
/// Pucker & Bloat: anchors move toward (bloat) or away from (pucker) the centre, handles the
|
||||
|
||||
@@ -3,6 +3,7 @@ use super::{
|
||||
Appearance, AppearanceItem, BezPath, Effect, FillRule, Node, NodeKind, PathData, Rect, StrokeLayer, Value, WarpStyle, distort, stroke, stylize,
|
||||
util, warp,
|
||||
};
|
||||
use vectorcraft_doc::Document;
|
||||
|
||||
/// Context the geometry effects may need from the object's appearance.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
@@ -22,6 +23,9 @@ pub struct GeomContext<'a> {
|
||||
/// The index in `appearance.items` of the fill or stroke whose own effects these are; `None`:
|
||||
/// the object's effects.
|
||||
pub item: Option<usize>,
|
||||
/// The document that the swatches and patterns named by a live-effect plug-in that paints its
|
||||
/// pieces are looked up in. Without one, a result that names any is refused.
|
||||
pub doc: Option<&'a Document>,
|
||||
}
|
||||
|
||||
impl<'a> GeomContext<'a> {
|
||||
@@ -32,7 +36,7 @@ impl<'a> GeomContext<'a> {
|
||||
_ => FillRule::NonZero,
|
||||
};
|
||||
let stroke = n.appearance.stroke().filter(|s| !s.paint.is_none() && s.width > 0.0);
|
||||
Self { stroke, rule, seed: n.id.0, appearance: Some(&n.appearance), item: None }
|
||||
Self { stroke, rule, seed: n.id.0, appearance: Some(&n.appearance), item: None, doc: None }
|
||||
}
|
||||
|
||||
/// The context of the effects on `item`, one of the same object's appearance items: a
|
||||
@@ -157,6 +161,153 @@ pub(crate) fn optimize_geometry_effects<'a>(effects: &[&'a Effect], style_safe:
|
||||
/// [`apply_geometry_with`] whose effects keep to `budget`, raised to what `path` costs where that
|
||||
/// is more.
|
||||
pub(crate) fn apply_geometry_within(effects: &[Effect], path: &PathData, bounds: Rect, ctx: &GeomContext, budget: Budget) -> PathData {
|
||||
apply_geometry_carrying_within(effects, path, bounds, ctx, budget, None)
|
||||
}
|
||||
|
||||
/// [`apply_geometry_with`], and the [`Carry`] that moves the object's gradients along with the
|
||||
/// effects that move the object as a whole.
|
||||
pub fn apply_geometry_carrying(effects: &[Effect], path: &PathData, bounds: Rect, ctx: &GeomContext) -> (PathData, Carry) {
|
||||
let mut carry = Carry::default();
|
||||
let out = apply_geometry_carrying_within(effects, path, bounds, ctx, Budget::EFFECTS, Some(&mut carry));
|
||||
(out, carry)
|
||||
}
|
||||
|
||||
/// [`apply_geometry_carrying`] on kurbo paths.
|
||||
pub fn apply_geometry_bez_carrying(effects: &[Effect], path: &BezPath, bounds: Rect, ctx: &GeomContext) -> (BezPath, Carry) {
|
||||
let (out, carry) = apply_geometry_carrying(effects, &PathData::from_bezpath(path), bounds, ctx);
|
||||
(out.to_bezpath(), carry)
|
||||
}
|
||||
|
||||
/// How gradients follow geometry effects. The Transform effect without copies maps placed
|
||||
/// gradients as it maps the object (with copies, `crate::reshape` gives each copy its own). Free
|
||||
/// Distort and the Warp effects move and scale them from the object's bounds before the effect to
|
||||
/// its bounds after it. For the other geometry effects it is empty. A gradient fitted to the
|
||||
/// object fits the geometry each effect makes, until a Transform effect turns, reflects or scales
|
||||
/// it unevenly (a map after which a refit would not match the mapped gradient): it is fixed to its
|
||||
/// fit on the geometry that effect takes, and then follows that effect and the ones after it as a
|
||||
/// placed gradient does.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Carry(Vec<CarryStep>);
|
||||
|
||||
/// Does `m` fix a gradient fitted to the object to its fit before mapping it? It does when a refit
|
||||
/// would not reproduce the map (a turn, a reflection or an uneven scale) and `m` keeps area: a map
|
||||
/// that flattens the geometry to a line (a scale of 0) leaves the gradient fitted, since mapping it
|
||||
/// would flatten it to one color ([`vectorcraft_doc::node::flattens`]).
|
||||
pub(crate) fn fixes_fit(m: vectorcraft_geom::Affine) -> bool {
|
||||
!vectorcraft_doc::node::flattens(m) && !vectorcraft_doc::node::keeps_gradient_fit(m)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum CarryStep {
|
||||
/// Map `m`; `from` is the geometric bounds of the geometry it takes, which a fitted gradient
|
||||
/// fits before `m` moves it (none: fitted gradients stay fitted).
|
||||
Affine { m: vectorcraft_geom::Affine, from: Option<Rect> },
|
||||
/// From box `from` to box `to` (strokes: their stroke-inflated boxes).
|
||||
Boxes { from: Rect, to: Rect },
|
||||
}
|
||||
|
||||
impl Carry {
|
||||
/// Does effect `id` with merged params `p` on geometry with reference box `b` (`seed` for
|
||||
/// Random) move placed gradients? Free Distort does unless it leaves every corner in place, a
|
||||
/// Warp effect unless it has no bend and no distortion, and the Transform effect does without
|
||||
/// copies (with copies the original stays where it is, and `crate::reshape` gives each copy
|
||||
/// its own gradients).
|
||||
pub(crate) fn follows(id: &str, p: &Value, b: Rect, seed: u64) -> bool {
|
||||
match id {
|
||||
"distort.transform" => {
|
||||
let (m, copies) = distort::transform_map(b, p, seed);
|
||||
copies == 0 && m != vectorcraft_geom::Affine::IDENTITY && m.is_finite()
|
||||
}
|
||||
"distort.freeDistort" => {
|
||||
let corners = distort::free_distort_corners(b, p);
|
||||
let tol = 1e-9 * b.width().hypot(b.height()).max(1.0);
|
||||
let still =
|
||||
[(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].iter().zip(&corners).all(|(a, c)| c.distance((*a).into()) <= tol);
|
||||
!still && corners.iter().all(|c| c.x.is_finite() && c.y.is_finite())
|
||||
}
|
||||
_ if id.starts_with("warp.") => crate::warp::bends(id, p),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Does effect `id` move placed gradients from each path's bounds before it to its bounds
|
||||
/// after it, rather than by one map for the whole object?
|
||||
pub(crate) fn by_bounds(id: &str) -> bool {
|
||||
id == "distort.freeDistort" || id.starts_with("warp.")
|
||||
}
|
||||
|
||||
/// How placed gradients follow effect `id` (as [`Self::follows`]) on an object whose geometric
|
||||
/// bounds are `from` before the effect and `to` after it; empty when they stay in place.
|
||||
pub(crate) fn of(id: &str, p: &Value, b: Rect, from: Option<Rect>, to: Option<Rect>, seed: u64) -> Carry {
|
||||
if !Self::follows(id, p, b, seed) {
|
||||
return Carry::default();
|
||||
}
|
||||
let step = match id {
|
||||
"distort.transform" => Some(CarryStep::Affine { m: distort::transform_map(b, p, seed).0, from }),
|
||||
_ => match (from, to) {
|
||||
(Some(from), Some(to)) if from != to && [to.x0, to.y0, to.x1, to.y1].iter().all(|v| v.is_finite()) => {
|
||||
Some(CarryStep::Boxes { from, to })
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
};
|
||||
Carry(step.into_iter().collect())
|
||||
}
|
||||
|
||||
/// Does it leave gradients where they are?
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
|
||||
/// Does it move any of the gradients of `ap` (those drawn at a place in document space, a
|
||||
/// freeform gradient's own points included)? Callers check first, so an appearance shared with
|
||||
/// other objects is not copied for nothing.
|
||||
pub fn moves(&self, ap: &Appearance) -> bool {
|
||||
!self.0.is_empty() && (ap.has_positioned_gradient() || (self.pin().is_some() && ap.has_unplaced_gradient()))
|
||||
}
|
||||
|
||||
/// The first step that fixes gradients fitted to the object: a map a refit would not
|
||||
/// reproduce, on geometry whose bounds are known.
|
||||
fn pin(&self) -> Option<usize> {
|
||||
self.0.iter().position(|s| matches!(s, CarryStep::Affine { m, from: Some(_) } if fixes_fit(*m)))
|
||||
}
|
||||
|
||||
/// Move the gradients of `ap` along. Placed gradients take every step in turn; fitted ones
|
||||
/// are fixed to their fit at the first step [`Self::pin`] finds and take it and the steps
|
||||
/// after it.
|
||||
pub fn apply(&self, ap: &mut Appearance) {
|
||||
if !self.moves(ap) {
|
||||
return;
|
||||
}
|
||||
// The steps move placed gradients only; fitted ones become placed at the pin.
|
||||
let pin = self.pin();
|
||||
for (k, s) in self.0.iter().enumerate() {
|
||||
if Some(k) == pin
|
||||
&& let CarryStep::Affine { from: Some(b), .. } = *s
|
||||
{
|
||||
ap.pin_gradients(b);
|
||||
}
|
||||
match *s {
|
||||
CarryStep::Affine { m, .. } => ap.transform_gradients(m),
|
||||
CarryStep::Boxes { from, to } => crate::reshape::follow_boxes(ap, from, to),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn push(&mut self, more: Carry) {
|
||||
self.0.extend(more.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`apply_geometry_within`], adding to `carry` how gradients follow each effect.
|
||||
pub(crate) fn apply_geometry_carrying_within(
|
||||
effects: &[Effect],
|
||||
path: &PathData,
|
||||
bounds: Rect,
|
||||
ctx: &GeomContext,
|
||||
budget: Budget,
|
||||
mut carry: Option<&mut Carry>,
|
||||
) -> PathData {
|
||||
// `budget` raised to what `path` costs, measured once, and only for a path that has geometry
|
||||
// effects.
|
||||
let has_stroke = match (ctx.item, ctx.appearance) {
|
||||
@@ -185,6 +336,9 @@ pub(crate) fn apply_geometry_within(effects: &[Effect], path: &PathData, bounds:
|
||||
let p = merged_params(&e.id, &e.params);
|
||||
let limit = *limit.get_or_insert_with(|| budget.at_least(Budget::of(path)));
|
||||
if let Some(next) = apply_one(&e.id, &p, &cur, b, ctx, limit) {
|
||||
if let Some(c) = carry.as_deref_mut() {
|
||||
c.push(Carry::of(&e.id, &p, b, cur.bounds(), next.bounds(), ctx.seed));
|
||||
}
|
||||
cur = next;
|
||||
}
|
||||
}
|
||||
@@ -224,7 +378,7 @@ fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomCont
|
||||
use util::{join, num};
|
||||
if let Some(plugin) = vectorcraft_plugins::effect::plugin_id(id) {
|
||||
let paints = vectorcraft_plugins::effect::Paints { appearance: ctx.appearance, item: ctx.item };
|
||||
return vectorcraft_plugins::effect::apply(plugin, p, path, b, ctx.rule, paints).unwrap_or_else(|| path.clone());
|
||||
return vectorcraft_plugins::effect::apply(plugin, p, path, b, ctx.rule, paints, ctx.doc).unwrap_or_else(|| path.clone());
|
||||
}
|
||||
match id {
|
||||
"distort.freeDistort" => distort::free_distort(path, b, p, max),
|
||||
|
||||
+79
-47
@@ -67,25 +67,28 @@ pub type OutlineHook<'a> = &'a dyn Fn(&Node) -> Option<Node>;
|
||||
/// back to front: a compound shape as its area, a blend, an envelope or an object with a warp as
|
||||
/// the art it draws, and type and symbol instances as their art through `hook`. Past
|
||||
/// [`SYMBOL_ART_MAX_NODES`](crate::SYMBOL_ART_MAX_NODES) objects of symbol art, further
|
||||
/// instances add nothing.
|
||||
pub fn member_leaves(n: &Node, hook: Option<OutlineHook>) -> Vec<Node> {
|
||||
/// instances add nothing. The swatches and patterns that live-effect plug-ins painting their
|
||||
/// pieces name are looked up in `doc` ([`shape_art`]).
|
||||
pub fn member_leaves(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>) -> Vec<Node> {
|
||||
let mut out = vec![];
|
||||
leaves(n, hook, &SymbolNodes::default(), &mut out);
|
||||
leaves(doc, n, hook, &SymbolNodes::default(), &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// [`member_leaves`], with the symbol art given so far counted in `nodes`.
|
||||
fn leaves(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes, out: &mut Vec<Node>) {
|
||||
fn leaves(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes, out: &mut Vec<Node>) {
|
||||
if !n.visible {
|
||||
return;
|
||||
}
|
||||
// A blend, an envelope or an object with a warp takes part as the art it draws.
|
||||
if let Some(art) = shape_art_in(n, hook, nodes) {
|
||||
if let Some(art) = shape_art_in(doc, n, hook, nodes) {
|
||||
let first = out.len();
|
||||
leaves(&art, hook, nodes, out);
|
||||
// Every path of a live object's, type's or symbol instance's art is drawn inside the
|
||||
// object's opacity and blend mode.
|
||||
if crate::needs_outline(n) {
|
||||
leaves(doc, &art, hook, nodes, out);
|
||||
// Every path of a live object's, type's or symbol instance's art, and every piece of a path
|
||||
// whose live-effect plug-in paints its pieces, is drawn inside the object's opacity and
|
||||
// blend mode.
|
||||
let pieces = matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && matches!(art.kind, NodeKind::Group { .. });
|
||||
if crate::needs_outline(n) || pieces {
|
||||
for l in out.iter_mut().skip(first) {
|
||||
within(l, n);
|
||||
}
|
||||
@@ -95,11 +98,11 @@ fn leaves(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes, out: &mut Ve
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => out.push(n.clone()),
|
||||
// A compound shape takes part as its area, styled like it.
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => match compound_shape_art_in(n, hook, nodes) {
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => match compound_shape_art_in(doc, n, hook, nodes) {
|
||||
Some(art) => out.push(art),
|
||||
None => {
|
||||
for c in children {
|
||||
leaves(c, hook, nodes, out);
|
||||
leaves(doc, c, hook, nodes, out);
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -114,7 +117,7 @@ fn leaves(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes, out: &mut Ve
|
||||
let art = match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } if nodes.charge(&art) => {
|
||||
let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
|
||||
crate::reshape::outline_nested_text(&mut art, false);
|
||||
crate::reshape::outline_nested_text(doc, &mut art, false);
|
||||
transparency_into_members(&mut art);
|
||||
art
|
||||
}
|
||||
@@ -122,7 +125,7 @@ fn leaves(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes, out: &mut Ve
|
||||
_ => art,
|
||||
};
|
||||
let first = out.len();
|
||||
leaves(&art, None, nodes, out);
|
||||
leaves(doc, &art, None, nodes, out);
|
||||
for l in out.iter_mut().skip(first) {
|
||||
within(l, n);
|
||||
}
|
||||
@@ -176,29 +179,41 @@ fn transparency_into_members(n: &mut Node) {
|
||||
/// [`outline_object`](crate::outline_object) gives a symbol instance its symbol's art. The art
|
||||
/// keeps the effects of `n` other than its geometry effects, and the groups inside it pass their
|
||||
/// opacity and blend mode to the objects they hold. `None` when `n` is none of these, for images,
|
||||
/// for symbol instances without geometry effects, and for one without art from `hook`.
|
||||
pub fn shape_art(n: &Node, hook: Option<OutlineHook>) -> Option<Node> {
|
||||
shape_art_in(n, hook, &SymbolNodes::default())
|
||||
/// for symbol instances without geometry effects, and for one without art from `hook`. A
|
||||
/// live-effect plug-in that paints its pieces makes a path, and each path of a group's or symbol's
|
||||
/// art, a group of its pieces, whose swatches and patterns must be in `doc` (without one, pieces
|
||||
/// that name one are refused and the path stays as it is).
|
||||
pub fn shape_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>) -> Option<Node> {
|
||||
shape_art_in(doc, n, hook, &SymbolNodes::default())
|
||||
}
|
||||
|
||||
/// [`shape_art`], with the symbol art given so far counted in `nodes`.
|
||||
fn shape_art_in(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<Node> {
|
||||
let mut art = reshaped_art(n, hook, nodes)?;
|
||||
fn shape_art_in(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<Node> {
|
||||
let mut art = reshaped_art(doc, n, hook, nodes)?;
|
||||
transparency_into_members(&mut art);
|
||||
Some(art)
|
||||
}
|
||||
|
||||
/// [`shape_art_in`] before the groups inside the art pass on their transparency.
|
||||
fn reshaped_art(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<Node> {
|
||||
fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<Node> {
|
||||
let fx = crate::reshape::geometry_effects(n);
|
||||
let outline = hook.unwrap_or(&crate::outline_text);
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } if !fx.is_empty() => Some(reshaped(n, n)),
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } if !fx.is_empty() => match compound_shape_art_in(n, hook, nodes) {
|
||||
Some(area) => Some(reshaped(&area, n)),
|
||||
// A path with a live-effect plug-in that paints its pieces: the group of its pieces, each
|
||||
// with its own paints, as the renderer draws it.
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } if !fx.is_empty() => {
|
||||
let painted = crate::reshape::has_painted_effects(n).then(|| crate::reshape::reshape(doc, n, None)).flatten();
|
||||
Some(painted.unwrap_or_else(|| reshaped(n, n, doc)))
|
||||
}
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } if !fx.is_empty() => match compound_shape_art_in(doc, n, hook, nodes) {
|
||||
Some(area) => Some(reshaped(&area, n, doc)),
|
||||
None => {
|
||||
let mut m = crate::reshape::outlined_members_with(None, n, outline, nodes);
|
||||
crate::reshape::reshape_leaves(&mut m, &fx);
|
||||
let mut m = crate::reshape::outlined_members_with(None, doc, n, outline, nodes);
|
||||
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, doc);
|
||||
// The group's own fills and strokes follow the effects as its members do.
|
||||
if carry.moves(&m.appearance) {
|
||||
carry.apply(&mut m.appearance);
|
||||
}
|
||||
without_geometry_effects(&mut m);
|
||||
Some(m)
|
||||
}
|
||||
@@ -209,8 +224,12 @@ fn reshaped_art(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Opt
|
||||
let h = hook?;
|
||||
let art = h(n).filter(|art| nodes.charge(art))?;
|
||||
let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
|
||||
crate::reshape::outline_nested_text(&mut art, false);
|
||||
crate::reshape::reshape_leaves(&mut art, &fx);
|
||||
crate::reshape::outline_nested_text(doc, &mut art, false);
|
||||
let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, doc);
|
||||
// The art's own fills and strokes follow the effects as its members do.
|
||||
if carry.moves(&art.appearance) {
|
||||
carry.apply(&mut art.appearance);
|
||||
}
|
||||
(art.opacity, art.blend, art.isolate) = (n.opacity, n.blend, n.isolate);
|
||||
art.appearance.effects = n.appearance.effects.clone();
|
||||
without_geometry_effects(&mut art);
|
||||
@@ -218,20 +237,26 @@ fn reshaped_art(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Opt
|
||||
}
|
||||
NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => None,
|
||||
_ if crate::needs_outline(n) && (vectorcraft_doc::live::is_live(n) || !fx.is_empty()) => {
|
||||
crate::reshape::as_art_with(None, n, None, outline, nodes)
|
||||
crate::reshape::as_art_with(None, doc, n, None, outline, nodes)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `src`, a path, compound path or compound shape's area, as one path reshaped by the visible
|
||||
/// geometry effects of `n`, without those effects.
|
||||
fn reshaped(src: &Node, n: &Node) -> Node {
|
||||
/// geometry effects of `n`, without those effects. The swatches and patterns a live-effect plug-in
|
||||
/// that paints its pieces names are looked up in `doc`.
|
||||
fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node {
|
||||
let mut m = src.clone();
|
||||
if let Some((path, rule)) = geometry(src) {
|
||||
let bounds = vectorcraft_geom::Shape::bounding_box(&path.to_bezpath());
|
||||
let g = crate::apply_geometry_with(&n.appearance.effects, &path, bounds, &crate::GeomContext::of(n));
|
||||
let (g, carry) =
|
||||
crate::apply_geometry_carrying(&n.appearance.effects, &path, bounds, &crate::GeomContext { doc, ..crate::GeomContext::of(n) });
|
||||
m.kind = NodeKind::Path { path: g, rule, live: None, clipping: false, guide: false };
|
||||
// Its gradients move with the outline, as the canvas paints them.
|
||||
if carry.moves(&m.appearance) {
|
||||
carry.apply(&mut m.appearance);
|
||||
}
|
||||
}
|
||||
without_geometry_effects(&mut m);
|
||||
m
|
||||
@@ -270,12 +295,12 @@ fn shape_op(mode: ShapeMode) -> po::BoolOp {
|
||||
/// it by the member's shape mode; the backmost member starts the area. `None` when `n` is not a
|
||||
/// compound shape, or its members are past a live Pathfinder's budget ([`PATHFINDER_MAX_SEGMENTS`],
|
||||
/// [`PATHFINDER_MAX_OVERLAPS`], [`SYMBOL_ART_MAX_NODES`](crate::SYMBOL_ART_MAX_NODES)).
|
||||
pub fn compound_shape_area(n: &Node, hook: Option<OutlineHook>) -> Option<PathData> {
|
||||
compound_shape_area_in(n, hook, &SymbolNodes::default())
|
||||
pub fn compound_shape_area(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>) -> Option<PathData> {
|
||||
compound_shape_area_in(doc, n, hook, &SymbolNodes::default())
|
||||
}
|
||||
|
||||
/// [`compound_shape_area`], with the symbol art given so far counted in `nodes`.
|
||||
fn compound_shape_area_in(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<PathData> {
|
||||
fn compound_shape_area_in(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<PathData> {
|
||||
if !n.is_compound_shape() {
|
||||
return None;
|
||||
}
|
||||
@@ -284,7 +309,7 @@ fn compound_shape_area_in(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNod
|
||||
let mut members: Vec<(po::BoolOp, usize)> = vec![];
|
||||
for c in n.children()? {
|
||||
let before = all.len();
|
||||
leaves(c, hook, nodes, &mut all);
|
||||
leaves(doc, c, hook, nodes, &mut all);
|
||||
if all.len() > before {
|
||||
members.push((shape_op(c.extras().shape_mode), all.len() - before));
|
||||
}
|
||||
@@ -300,7 +325,8 @@ fn compound_shape_area_in(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNod
|
||||
Some(po::boolean_n(&refs, |inside| {
|
||||
let (mut start, mut area) = (0, false);
|
||||
for (k, (op, count)) in members.iter().enumerate() {
|
||||
let here = inside.get(start..start + count).is_some_and(|flags| flags.contains(&true));
|
||||
// `inside` is ascending: the first leaf at or after `start` tells whether one of this member's is in it.
|
||||
let here = inside.get(inside.partition_point(|&i| i < start)).is_some_and(|&i| i < start + count);
|
||||
start += count;
|
||||
area = if k == 0 { here } else { op.apply(area, here) };
|
||||
}
|
||||
@@ -310,13 +336,13 @@ fn compound_shape_area_in(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNod
|
||||
|
||||
/// Compound shape `n` as one path of its area ([`compound_shape_area`]) with its appearance,
|
||||
/// opacity and blend mode: how it takes part in a Pathfinder operation.
|
||||
pub fn compound_shape_art(n: &Node, hook: Option<OutlineHook>) -> Option<Node> {
|
||||
compound_shape_art_in(n, hook, &SymbolNodes::default())
|
||||
pub fn compound_shape_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>) -> Option<Node> {
|
||||
compound_shape_art_in(doc, n, hook, &SymbolNodes::default())
|
||||
}
|
||||
|
||||
/// [`compound_shape_art`], with the symbol art given so far counted in `nodes`.
|
||||
fn compound_shape_art_in(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<Node> {
|
||||
let area = compound_shape_area_in(n, hook, nodes)?;
|
||||
fn compound_shape_art_in(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<Node> {
|
||||
let area = compound_shape_area_in(doc, n, hook, nodes)?;
|
||||
let mut art = Node::path(n.id, area, Appearance { items: n.appearance.items.clone(), ..Default::default() });
|
||||
(art.opacity, art.blend) = (n.opacity, n.blend);
|
||||
Some(art)
|
||||
@@ -422,15 +448,16 @@ fn within_budget<'a>(leaves: impl IntoIterator<Item = &'a Node>) -> bool {
|
||||
/// Evaluate the visible Pathfinder effects of `group` in order: the resulting child objects.
|
||||
/// `None` when the group has no Pathfinder effect. Past the budget ([`PATHFINDER_MAX_SEGMENTS`],
|
||||
/// [`PATHFINDER_MAX_OVERLAPS`], [`SYMBOL_ART_MAX_NODES`](crate::SYMBOL_ART_MAX_NODES) for
|
||||
/// each effect) it returns the children as they are.
|
||||
pub fn pathfinder_children(group: &Node, hook: Option<OutlineHook>) -> Option<Vec<Arc<Node>>> {
|
||||
/// each effect) it returns the children as they are. The swatches and patterns that live-effect
|
||||
/// plug-ins painting their pieces name are looked up in `doc` ([`shape_art`]).
|
||||
pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<OutlineHook>) -> Option<Vec<Arc<Node>>> {
|
||||
if !has_pathfinder(group) {
|
||||
return None;
|
||||
}
|
||||
let source: &[Arc<Node>] = group.children()?;
|
||||
let mut stack: Vec<Arc<Node>> = if group.is_compound_shape() {
|
||||
// The group's own appearance paints the area ([`evaluate_container`]), so the art has none.
|
||||
match compound_shape_area(group, hook) {
|
||||
match compound_shape_area(doc, group, hook) {
|
||||
Some(area) if area.is_empty() => vec![],
|
||||
Some(area) => vec![Arc::new(Node::path(group.id, area, Appearance::default()))],
|
||||
None => return Some(source.to_vec()),
|
||||
@@ -442,7 +469,7 @@ pub fn pathfinder_children(group: &Node, hook: Option<OutlineHook>) -> Option<Ve
|
||||
if e.id == crate::trap::TRAP {
|
||||
let (mut lv, nodes) = (vec![], SymbolNodes::default());
|
||||
for c in &stack {
|
||||
leaves(c, hook, &nodes, &mut lv);
|
||||
leaves(doc, c, hook, &nodes, &mut lv);
|
||||
}
|
||||
if nodes.spent() || !within_budget(&lv) {
|
||||
return Some(source.to_vec());
|
||||
@@ -466,7 +493,7 @@ pub fn pathfinder_children(group: &Node, hook: Option<OutlineHook>) -> Option<Ve
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let mut lv = vec![];
|
||||
leaves(c, hook, &nodes, &mut lv);
|
||||
leaves(doc, c, hook, &nodes, &mut lv);
|
||||
lv
|
||||
})
|
||||
.collect();
|
||||
@@ -620,7 +647,7 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => out.extend(crate::reshape::leaf_geometry(n)),
|
||||
NodeKind::Group { .. } if n.is_compound_shape() => {
|
||||
let hook = |c: &Node| crate::outline_object(doc, c);
|
||||
match compound_shape_area(n, Some(&hook)) {
|
||||
match compound_shape_area(doc, n, Some(&hook)) {
|
||||
Some(area) => out.push((area, FillRule::NonZero)),
|
||||
None => members(doc, n, out),
|
||||
}
|
||||
@@ -702,7 +729,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
let mut m = n.clone();
|
||||
if pathfinder {
|
||||
let hook = |c: &Node| crate::outline_object(doc, c);
|
||||
let result = pathfinder_children(n, Some(&hook)).unwrap_or_default();
|
||||
let result = pathfinder_children(doc, n, Some(&hook)).unwrap_or_default();
|
||||
if let Some(ch) = m.children_mut() {
|
||||
*ch = result;
|
||||
}
|
||||
@@ -711,7 +738,12 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
}
|
||||
if !fx.is_empty() {
|
||||
m = crate::reshape::outlined_members(doc, &m);
|
||||
crate::reshape::reshape_leaves(&mut m, &fx);
|
||||
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, doc);
|
||||
// The group's own fills and strokes paint the members as a whole: their gradients follow
|
||||
// the effects as the members' do.
|
||||
if paint && carry.moves(&m.appearance) {
|
||||
carry.apply(&mut m.appearance);
|
||||
}
|
||||
}
|
||||
m.appearance.effects.retain(|e| !is_pathfinder(&e.id) && !crate::is_geometry(&e.id));
|
||||
if paint {
|
||||
|
||||
@@ -27,7 +27,7 @@ fn area(n: &Node) -> f64 {
|
||||
}
|
||||
|
||||
fn overlap_cmyk(g: &Node) -> [f32; 4] {
|
||||
let faces = pathfinder_children(g, None).unwrap();
|
||||
let faces = pathfinder_children(None, g, None).unwrap();
|
||||
assert_eq!(faces.len(), 3);
|
||||
let overlap = faces
|
||||
.iter()
|
||||
@@ -61,7 +61,7 @@ fn trap_effect_adds_an_overprinting_strip_above_the_members() {
|
||||
let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, yellow), sq(2, 10.0, blue)]);
|
||||
let params = serde_json::json!({"thickness": 1.0, "tintReduction": 100});
|
||||
g.appearance.effects.push(Effect { id: crate::trap::TRAP.into(), params, visible: true });
|
||||
let out = pathfinder_children(&g, None).unwrap();
|
||||
let out = pathfinder_children(None, &g, None).unwrap();
|
||||
assert_eq!(out.len(), 3, "both squares and one trap");
|
||||
assert_eq!((out[0].id, out[1].id), (NodeId(1), NodeId(2)));
|
||||
let b = out[2].geometric_bounds().unwrap();
|
||||
@@ -89,17 +89,17 @@ fn soft_mix_blends_cmyk_bottom_to_top_and_drops_strokes() {
|
||||
|
||||
#[test]
|
||||
fn shape_modes_follow_the_pathfinder_panel() {
|
||||
let add = pathfinder_children(&group_with("pathfinder.add"), None).unwrap();
|
||||
let add = pathfinder_children(None, &group_with("pathfinder.add"), None).unwrap();
|
||||
assert_eq!(add.len(), 1);
|
||||
assert!((area(&add[0]) - 150.0).abs() < 1e-3);
|
||||
// Add keeps the front object's paint, Subtract the back one's.
|
||||
assert_eq!(add[0].id, NodeId(2));
|
||||
let sub = pathfinder_children(&group_with("pathfinder.subtract"), None).unwrap();
|
||||
let sub = pathfinder_children(None, &group_with("pathfinder.subtract"), None).unwrap();
|
||||
assert_eq!(sub[0].id, NodeId(1));
|
||||
assert!((area(&sub[0]) - 50.0).abs() < 1e-3);
|
||||
let int = pathfinder_children(&group_with("pathfinder.intersect"), None).unwrap();
|
||||
let int = pathfinder_children(None, &group_with("pathfinder.intersect"), None).unwrap();
|
||||
assert!((area(&int[0]) - 50.0).abs() < 1e-3);
|
||||
let div = pathfinder_children(&group_with("pathfinder.divide"), None).unwrap();
|
||||
let div = pathfinder_children(None, &group_with("pathfinder.divide"), None).unwrap();
|
||||
assert_eq!(div.len(), 3);
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ fn divide_and_outline_draw_nothing_for_unpainted_members() {
|
||||
for effect in ["pathfinder.divide", "pathfinder.outline"] {
|
||||
let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), unpainted.clone()]);
|
||||
g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({}), visible: true });
|
||||
let out = pathfinder_children(&g, None).unwrap();
|
||||
let out = pathfinder_children(None, &g, None).unwrap();
|
||||
assert!(out.iter().any(|n| n.id == NodeId(1)) && out.iter().any(|n| n.id == NodeId(2)), "{effect}: {out:#?}");
|
||||
for n in out.iter().filter(|n| n.id == NodeId(2)) {
|
||||
assert!(n.appearance.items.iter().all(|i| i.paint().is_none()), "{effect}: {n:#?}");
|
||||
@@ -138,7 +138,7 @@ fn square_and(front: Option<Node>, effect: &str) -> Node {
|
||||
|
||||
/// Returns the Pathfinder results of `g`, with type outlined as the renderer outlines it.
|
||||
fn results(g: &Node) -> Vec<Arc<Node>> {
|
||||
pathfinder_children(g, crate::text_outliner()).unwrap()
|
||||
pathfinder_children(None, g, crate::text_outliner()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -167,7 +167,7 @@ fn type_changes_the_result_of_every_pathfinder_effect() {
|
||||
assert!((with_type("pathfinder.intersect") + with_type("pathfinder.minusBack") - glyph_area).abs() < 0.5, "{glyph_area}");
|
||||
// Outline art nested one group deeper takes part as well.
|
||||
let nested: OutlineHook = &|n: &Node| crate::outline_text(n).map(|g| Node::group(n.id, vec![Arc::new(g)]));
|
||||
let sub = pathfinder_children(&square_and(Some(type_h()), "pathfinder.subtract"), Some(nested)).unwrap();
|
||||
let sub = pathfinder_children(None, &square_and(Some(type_h()), "pathfinder.subtract"), Some(nested)).unwrap();
|
||||
assert!((sub.iter().map(|n| area(n)).sum::<f64>() - with_type("pathfinder.subtract")).abs() < 1e-6);
|
||||
}
|
||||
|
||||
@@ -243,12 +243,12 @@ fn type_in_a_group_keeps_its_look_when_the_groups_geometry_effects_outline_it()
|
||||
fn hidden_effect_or_plain_group_is_untouched() {
|
||||
let mut g = group_with("pathfinder.add");
|
||||
g.appearance.effects[0].visible = false;
|
||||
assert!(pathfinder_children(&g, None).is_none());
|
||||
assert!(pathfinder_children(None, &g, None).is_none());
|
||||
assert!(!has_pathfinder(&sq(1, 0.0, Color::BLACK)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transform_on_a_group_moves_the_gradients_of_its_type_and_not_those_placed_on_its_paths() {
|
||||
fn a_transform_on_a_group_moves_the_gradients_of_its_type_and_those_placed_on_its_paths() {
|
||||
if skip_without_craft_fonts() {
|
||||
return;
|
||||
}
|
||||
@@ -273,7 +273,393 @@ fn a_transform_on_a_group_moves_the_gradients_of_its_type_and_not_those_placed_o
|
||||
let members = art.children().unwrap();
|
||||
let after = start(&members[1].children().unwrap()[0]);
|
||||
assert!((after - before - 30.0).abs() < 1e-6, "the type's gradient starts at {before}, then {after}");
|
||||
assert_eq!(start(&members[0]), 0.0, "the square's gradient stays where it was placed");
|
||||
assert!((start(&members[0]) - 30.0).abs() < 1e-6, "the square's gradient moves with it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_groups_transform_moves_the_gradient_of_its_own_fill() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
|
||||
let geom = GradientGeom { start: (0.0, 5.0).into(), end: (15.0, 5.0).into(), aspect: 1.0, focal: None };
|
||||
let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, Color::BLACK), sq(2, 5.0, Color::BLACK)]);
|
||||
g.appearance
|
||||
.items
|
||||
.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp })))));
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30}), visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mut starts = vec![];
|
||||
art.walk(&mut |c: &Node| {
|
||||
if let Paint::Gradient(p) = c.appearance.fill_paint() {
|
||||
starts.push(p.geom.unwrap().start.x);
|
||||
}
|
||||
});
|
||||
assert!(!starts.is_empty() && starts.iter().all(|s| (s - 30.0).abs() < 1e-6), "{starts:?}");
|
||||
}
|
||||
|
||||
/// The art Pathfinder and compound shapes take (`shape_art`) paints as the canvas does: a path's
|
||||
/// gradient and a group's own fill move with a Transform effect.
|
||||
#[test]
|
||||
fn shape_art_moves_gradients_with_a_transform_effect() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
|
||||
let geom = GradientGeom { start: (0.0, 5.0).into(), end: (10.0, 5.0).into(), aspect: 1.0, focal: None };
|
||||
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }));
|
||||
let moved = || Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 40}), visible: true };
|
||||
let starts = |art: &Node| {
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |c: &Node| {
|
||||
for item in &c.appearance.items {
|
||||
if let Paint::Gradient(p) = item.paint() {
|
||||
out.push(p.geom.unwrap().start.x);
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
};
|
||||
let mut path = Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(placed.clone(), Paint::None, 0.0));
|
||||
path.appearance.effects.push(moved());
|
||||
let got = starts(&shape_art(None, &path, None).unwrap());
|
||||
assert!(got.len() == 1 && (got[0] - 40.0).abs() < 1e-6, "the path's gradient: {got:?}");
|
||||
let mut g = Node::group(NodeId(10), vec![sq(2, 0.0, Color::BLACK)]);
|
||||
g.appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(placed)));
|
||||
g.appearance.effects.push(moved());
|
||||
let got = starts(&shape_art(None, &g, None).unwrap());
|
||||
assert!(!got.is_empty() && got.iter().all(|s| (s - 40.0).abs() < 1e-6), "the group's own fill: {got:?}");
|
||||
}
|
||||
|
||||
/// A symbol instance's Transform effect moves the gradient placed on its art's own fill in the
|
||||
/// art Pathfinder takes, as it moves its members.
|
||||
#[test]
|
||||
fn shape_art_moves_the_gradient_of_a_symbol_instances_art_with_its_transform() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
|
||||
let geom = GradientGeom { start: (0.0, 5.0).into(), end: (10.0, 5.0).into(), aspect: 1.0, focal: None };
|
||||
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }));
|
||||
let mut art = Node::group(NodeId(20), vec![sq(21, 0.0, Color::BLACK)]);
|
||||
art.appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(placed)));
|
||||
let hook = move |_: &Node| Some(art.clone());
|
||||
let mut instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
instance.appearance.effects.push(Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30}), visible: true });
|
||||
let out = shape_art(None, &instance, Some(&hook)).unwrap();
|
||||
let Paint::Gradient(g) = out.appearance.fill_paint() else { panic!("a gradient: {:?}", out.appearance) };
|
||||
assert!((g.geom.unwrap().start.x - 30.0).abs() < 1e-6, "{:?}", g.geom);
|
||||
assert!((out.geometric_bounds().unwrap().x0 - 30.0).abs() < 1e-6, "the art moves");
|
||||
}
|
||||
|
||||
/// Under a Warp effect, the gradient placed on a symbol instance's art's own fill follows the art's
|
||||
/// bounds, and the gradient placed on a compound shape follows its area's bounds, each from before
|
||||
/// the warp to after it, in the art Pathfinder takes.
|
||||
#[test]
|
||||
fn shape_art_moves_the_gradients_of_a_symbol_instances_art_and_a_compound_shape_with_a_warp() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
|
||||
let geom = GradientGeom { start: (2.0, 3.0).into(), end: (9.0, 3.0).into(), aspect: 1.0, focal: None };
|
||||
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }));
|
||||
let follow = |p: Point, from: Rect, to: Rect| {
|
||||
Point::new(to.x0 + (p.x - from.x0) / from.width() * to.width(), to.y0 + (p.y - from.y0) / from.height() * to.height())
|
||||
};
|
||||
let check = |out: &Node, from: Rect, what: &str| {
|
||||
let to = out.geometric_bounds().unwrap();
|
||||
assert_ne!(from, to, "{what}: the warp changes the bounds");
|
||||
let Paint::Gradient(g) = out.appearance.fill_paint() else { panic!("{what}: a gradient: {:?}", out.appearance) };
|
||||
let got = g.geom.unwrap();
|
||||
let (s, e) = (follow(geom.start, from, to), follow(geom.end, from, to));
|
||||
assert!(got.start.distance(s) < 1e-6 && got.end.distance(e) < 1e-6, "{what}: {got:?}, want {s:?} {e:?}");
|
||||
};
|
||||
for style in ["arc", "rise", "bulge"] {
|
||||
let warp = || Effect { id: format!("warp.{style}"), params: serde_json::json!({"bend": 40.0}), visible: true };
|
||||
let mut art = Node::group(NodeId(20), vec![sq(21, 0.0, Color::BLACK)]);
|
||||
art.appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(placed.clone())));
|
||||
let hook = move |_: &Node| Some(art.clone());
|
||||
let mut instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
instance.appearance.effects.push(warp());
|
||||
check(&shape_art(None, &instance, Some(&hook)).unwrap(), Rect::new(0.0, 0.0, 10.0, 10.0), &format!("warp.{style} on a symbol instance"));
|
||||
let mut shape = compound_shape(ShapeMode::Add);
|
||||
shape.appearance = Appearance::basic(placed.clone(), Paint::None, 0.0).into();
|
||||
shape.appearance.effects.push(warp());
|
||||
check(&shape_art(None, &shape, None).unwrap(), Rect::new(0.0, 0.0, 15.0, 10.0), &format!("warp.{style} on a compound shape"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_groups_transform_and_free_distort_move_the_gradients_placed_on_its_paths() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
|
||||
let geom = GradientGeom { start: (0.0, 5.0).into(), end: (10.0, 5.0).into(), aspect: 1.0, focal: None };
|
||||
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }));
|
||||
let ends = |e: Effect| {
|
||||
let square =
|
||||
Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(placed.clone(), Paint::None, 0.0)));
|
||||
let mut g = Node::group(NodeId(10), vec![square, sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(e);
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
match art.children().unwrap()[0].appearance.fill_paint() {
|
||||
Paint::Gradient(g) => g.geom.map(|g| (g.start, g.end)).unwrap(),
|
||||
p => panic!("a gradient: {p:?}"),
|
||||
}
|
||||
};
|
||||
let near = |a: Point, b: Point| a.distance(b) < 1e-6;
|
||||
// A quarter turn about the group's center (15, 5) takes (0, 5) to (15, 20) and (10, 5) to (15, 10).
|
||||
let (s, e) = ends(Effect { id: "distort.transform".into(), params: serde_json::json!({"rotate": 90}), visible: true });
|
||||
assert!(near(s, Point::new(15.0, 20.0)) && near(e, Point::new(15.0, 10.0)), "{s:?} {e:?}");
|
||||
// Free Distort moving the group's top corners 10 pt right slants the square to 0..20 across:
|
||||
// its gradient follows its own bounds (0..10 to 0..20), not the group's (0..30 to 0..40).
|
||||
let corners = serde_json::json!({"corners": [[1.0 / 3.0, 0.0], [4.0 / 3.0, 0.0], [1.0, 1.0], [0.0, 1.0]]});
|
||||
let (s, e) = ends(Effect { id: "distort.freeDistort".into(), params: corners, visible: true });
|
||||
assert!(near(s, Point::new(0.0, 5.0)) && near(e, Point::new(20.0, 5.0)), "{s:?} {e:?}");
|
||||
}
|
||||
|
||||
/// A group's Warp effect moves and scales the gradient placed on each of its paths from that path's
|
||||
/// bounds before the warp to its bounds after it, not by the group's bounds.
|
||||
#[test]
|
||||
fn a_groups_warp_moves_the_gradients_placed_on_its_paths_by_each_paths_bounds() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
|
||||
let geom = |x: f64| GradientGeom { start: (x + 2.0, 3.0).into(), end: (x + 8.0, 3.0).into(), aspect: 1.0, focal: None };
|
||||
let placed = |x: f64| Paint::Gradient(Box::new(GradientPaint { geom: Some(geom(x)), ..ramp.clone() }));
|
||||
let square = |id: u64, x: f64| {
|
||||
Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::basic(placed(x), Paint::None, 0.0)))
|
||||
};
|
||||
for style in ["arc", "bulge", "rise", "twist"] {
|
||||
let mut g = Node::group(NodeId(10), vec![square(1, 0.0), square(2, 20.0)]);
|
||||
g.appearance.effects.push(Effect { id: format!("warp.{style}"), params: serde_json::json!({"bend": 40.0}), visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mut moved = false;
|
||||
for (i, x) in [0.0, 20.0].into_iter().enumerate() {
|
||||
let m = &art.children().unwrap()[i];
|
||||
let b = m.geometric_bounds().unwrap();
|
||||
let follow = |p: Point| Point::new(b.x0 + (p.x - x) / 10.0 * b.width(), b.y0 + p.y / 10.0 * b.height());
|
||||
let Paint::Gradient(gp) = m.appearance.fill_paint() else { panic!("a gradient") };
|
||||
let got = gp.geom.unwrap();
|
||||
let want = geom(x);
|
||||
assert!(
|
||||
got.start.distance(follow(want.start)) < 1e-6 && got.end.distance(follow(want.end)) < 1e-6,
|
||||
"warp.{style} path {i}: {got:?} in {b:?}"
|
||||
);
|
||||
moved |= got.start.distance(want.start) > 0.1;
|
||||
}
|
||||
assert!(moved, "warp.{style} moves a gradient");
|
||||
}
|
||||
}
|
||||
|
||||
/// Under a group's Warp effect, the group's own placed gradients follow the group's bounds, a
|
||||
/// nested group's own placed gradients follow the nested group's bounds, and a compound path's
|
||||
/// placed gradients follow the compound path's bounds, each from before the warp to after it (a
|
||||
/// stroke's: those bounds inflated by the stroke).
|
||||
#[test]
|
||||
fn a_groups_warp_moves_its_own_a_nested_groups_and_a_compound_paths_gradients_by_their_bounds() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
|
||||
let geom = GradientGeom { start: (12.0, 4.0).into(), end: (26.0, 4.0).into(), aspect: 1.0, focal: None };
|
||||
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }));
|
||||
let own_fill = |n: &mut Node| {
|
||||
n.appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(placed.clone())));
|
||||
n.appearance.items.push(AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(placed.clone(), 3.0)));
|
||||
};
|
||||
let follow = |p: Point, from: Rect, to: Rect| {
|
||||
Point::new(to.x0 + (p.x - from.x0) / from.width() * to.width(), to.y0 + (p.y - from.y0) / from.height() * to.height())
|
||||
};
|
||||
for style in ["arc", "bulge", "rise", "flag"] {
|
||||
let mut inner = Node::group(NodeId(5), vec![sq(1, 0.0, Color::BLACK)]);
|
||||
own_fill(&mut inner);
|
||||
let ring = vec![
|
||||
Arc::new(Node::path(NodeId(6), shapes::rectangle(Rect::new(20.0, 0.0, 30.0, 14.0)), Appearance::default())),
|
||||
Arc::new(Node::path(NodeId(7), shapes::rectangle(Rect::new(23.0, 3.0, 27.0, 7.0)), Appearance::default())),
|
||||
];
|
||||
let mut compound = Node::new(NodeId(3), NodeKind::Compound { children: ring, rule: FillRule::EvenOdd });
|
||||
compound.appearance = Appearance::basic(placed.clone(), placed.clone(), 2.0).into();
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner), Arc::new(compound), sq(2, 40.0, Color::BLACK)]);
|
||||
own_fill(&mut g);
|
||||
let mut before = std::collections::HashMap::new();
|
||||
g.walk(&mut |c: &Node| {
|
||||
before.insert(c.id, c.geometric_bounds().unwrap());
|
||||
});
|
||||
g.appearance.effects.push(Effect { id: format!("warp.{style}"), params: serde_json::json!({"bend": 40.0}), visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
// The bounds after the warp of the group, the nested group and the compound path (the paths
|
||||
// a group's own fill paints carry the group's id).
|
||||
let mut after = std::collections::HashMap::new();
|
||||
art.walk(&mut |c: &Node| {
|
||||
if matches!(c.kind, NodeKind::Group { .. } | NodeKind::Compound { .. }) {
|
||||
after.entry(c.id).or_insert_with(|| c.geometric_bounds().unwrap());
|
||||
}
|
||||
});
|
||||
let mut checked = vec![];
|
||||
art.walk(&mut |c: &Node| {
|
||||
if ![NodeId(3), NodeId(5), NodeId(10)].contains(&c.id) {
|
||||
return;
|
||||
}
|
||||
for item in &c.appearance.items {
|
||||
let Paint::Gradient(gp) = item.paint() else { continue };
|
||||
let (from, to) = (before[&c.id], after[&c.id]);
|
||||
assert_ne!(from, to, "warp.{style} {:?}: the warp changes the bounds", c.id);
|
||||
let stroke = match item {
|
||||
AppearanceItem::Stroke(s) => Some(s),
|
||||
AppearanceItem::Fill(_) => None,
|
||||
};
|
||||
let (from, to) = match stroke {
|
||||
Some(s) => (s.paint_bounds(from), s.paint_bounds(to)),
|
||||
None => (from, to),
|
||||
};
|
||||
let got = gp.geom.unwrap();
|
||||
let (s, e) = (follow(geom.start, from, to), follow(geom.end, from, to));
|
||||
assert!(
|
||||
got.start.distance(s) < 1e-6 && got.end.distance(e) < 1e-6,
|
||||
"warp.{style} {:?} (stroke: {}): {got:?}, want {s:?} {e:?} ({from:?} to {to:?})",
|
||||
c.id,
|
||||
stroke.is_some()
|
||||
);
|
||||
checked.push((c.id, stroke.is_some()));
|
||||
}
|
||||
});
|
||||
checked.sort();
|
||||
checked.dedup();
|
||||
let want: Vec<_> = [NodeId(3), NodeId(5), NodeId(10)].into_iter().flat_map(|id| [(id, false), (id, true)]).collect();
|
||||
assert_eq!(checked, want, "warp.{style}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A group nested in a group with a Transform effect or Free Distort keeps its own placed gradient
|
||||
/// on its members: the Transform's map moves it, and Free Distort moves and scales it from the
|
||||
/// nested group's bounds before the effect to its bounds after it.
|
||||
#[test]
|
||||
fn a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_distort() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
|
||||
let geom = GradientGeom { start: (0.0, 5.0).into(), end: (10.0, 5.0).into(), aspect: 1.0, focal: None };
|
||||
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }));
|
||||
let ends = |e: Effect| {
|
||||
let mut inner = Node::group(NodeId(5), vec![sq(1, 0.0, Color::BLACK)]);
|
||||
inner.appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(placed.clone())));
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(e);
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
match art.children().unwrap()[0].appearance.fill_paint() {
|
||||
Paint::Gradient(g) => g.geom.map(|g| (g.start, g.end)).unwrap(),
|
||||
p => panic!("a gradient: {p:?}"),
|
||||
}
|
||||
};
|
||||
let near = |a: Point, b: Point| a.distance(b) < 1e-6;
|
||||
let (s, e) = ends(Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30}), visible: true });
|
||||
assert!(near(s, Point::new(30.0, 5.0)) && near(e, Point::new(40.0, 5.0)), "{s:?} {e:?}");
|
||||
let corners = serde_json::json!({"corners": [[1.0 / 3.0, 0.0], [4.0 / 3.0, 0.0], [1.0, 1.0], [0.0, 1.0]]});
|
||||
let (s, e) = ends(Effect { id: "distort.freeDistort".into(), params: corners, visible: true });
|
||||
assert!(near(s, Point::new(0.0, 5.0)) && near(e, Point::new(20.0, 5.0)), "{s:?} {e:?}");
|
||||
}
|
||||
|
||||
/// An image or a symbol instance that a group's Transform effect moves takes the placed gradients
|
||||
/// of its own fills along, as a path does, and each copy takes them as many times as it takes the
|
||||
/// transform.
|
||||
#[test]
|
||||
fn a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
use vectorcraft_doc::ImageObject;
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
|
||||
let geom = GradientGeom { start: (0.0, 5.0).into(), end: (10.0, 5.0).into(), aspect: 1.0, focal: None };
|
||||
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }));
|
||||
let image = || {
|
||||
NodeKind::Image(Box::new(ImageObject {
|
||||
key: "k".into(),
|
||||
width: 10,
|
||||
height: 10,
|
||||
xf: vectorcraft_geom::Affine::IDENTITY,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
}))
|
||||
};
|
||||
let instance = || NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY };
|
||||
let starts = |kind: NodeKind, params: serde_json::Value| {
|
||||
let mut object = Node::new(NodeId(1), kind);
|
||||
object.appearance = Appearance::basic(placed.clone(), Paint::None, 0.0).into();
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(object), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |c: &Node| {
|
||||
if let (NodeKind::Image(_) | NodeKind::SymbolInstance { .. }, Paint::Gradient(p)) = (&c.kind, c.appearance.fill_paint()) {
|
||||
out.push(p.geom.unwrap().start.x);
|
||||
}
|
||||
});
|
||||
out
|
||||
};
|
||||
for kind in [image as fn() -> NodeKind, instance] {
|
||||
assert_eq!(starts(kind(), serde_json::json!({"moveH": 30})), [30.0], "{:?}", kind());
|
||||
assert_eq!(starts(kind(), serde_json::json!({"moveH": 30, "copies": 2})), [0.0, 30.0, 60.0], "{:?}", kind());
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's Transform effect that turns its art turns the gradients fitted to its paths, to the
|
||||
/// group's own fill, to a nested group's own fill and to an image's and a symbol instance's own
|
||||
/// fills: each is fixed to its fit on its own object first. A move leaves the members' gradients
|
||||
/// fitted.
|
||||
#[test]
|
||||
fn a_groups_transform_turns_the_gradients_fitted_to_its_members_and_its_own_fill() {
|
||||
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
use vectorcraft_doc::ImageObject;
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let fitted = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
let square = |id: u64, x: f64| {
|
||||
Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::basic(fitted.clone(), Paint::None, 0.0)))
|
||||
};
|
||||
let mut image = Node::new(
|
||||
NodeId(4),
|
||||
NodeKind::Image(Box::new(ImageObject {
|
||||
key: "k".into(),
|
||||
width: 10,
|
||||
height: 10,
|
||||
xf: vectorcraft_geom::Affine::translate((30.0, 0.0)),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
})),
|
||||
);
|
||||
image.appearance = Appearance::basic(fitted.clone(), Paint::None, 0.0).into();
|
||||
// A symbol instance whose symbol is not in a document is measured as the 20 pt square about
|
||||
// its origin: here 22.5..27.5 across and 2.5..7.5 down.
|
||||
let at = vectorcraft_geom::Affine::translate((25.0, 5.0)) * vectorcraft_geom::Affine::scale(0.25);
|
||||
let mut instance = Node::new(NodeId(6), NodeKind::SymbolInstance { symbol: "s".into(), xf: at });
|
||||
instance.appearance = Appearance::basic(fitted.clone(), Paint::None, 0.0).into();
|
||||
// Ends of each gradient by object id; none for a gradient still fitted.
|
||||
let ends = |params: serde_json::Value| {
|
||||
let mut inner = Node::group(NodeId(5), vec![square(2, 10.0)]);
|
||||
inner.appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(fitted.clone())));
|
||||
let mut g = Node::group(NodeId(10), vec![square(1, 0.0), Arc::new(inner), Arc::new(image.clone()), Arc::new(instance.clone())]);
|
||||
g.appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(fitted.clone())));
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mut out = std::collections::BTreeMap::new();
|
||||
art.walk(&mut |c: &Node| {
|
||||
if let Paint::Gradient(p) = c.appearance.fill_paint() {
|
||||
out.insert(c.id.0, p.geom.map(|g| (g.start, g.end)));
|
||||
}
|
||||
});
|
||||
out
|
||||
};
|
||||
let near = |a: Point, b: Point| a.distance(b) < 1e-6;
|
||||
// A quarter turn about the group's center (20, 5): (x, 5) goes to (20, 5 + 20 - x), so a ramp
|
||||
// from (x0, 5) to (x1, 5) runs from (20, 25 - x0) up to (20, 25 - x1).
|
||||
let turned = ends(serde_json::json!({"rotate": 90}));
|
||||
let want = [(1, 0.0, 10.0), (2, 10.0, 20.0), (5, 10.0, 20.0), (4, 30.0, 40.0), (6, 22.5, 27.5), (10, 0.0, 40.0)];
|
||||
for (id, x0, x1) in want {
|
||||
let got = turned.get(&id).copied().flatten();
|
||||
let ok = got.is_some_and(|(s, e)| near(s, Point::new(20.0, 25.0 - x0)) && near(e, Point::new(20.0, 25.0 - x1)));
|
||||
assert!(ok, "object {id}: {got:?} in {turned:?}");
|
||||
}
|
||||
// The group's own fill is fixed to its fit on the art it paints, which the move took to 30..70.
|
||||
let moved = ends(serde_json::json!({"moveH": 30}));
|
||||
let group = moved.get(&10).copied().flatten();
|
||||
assert!(group.is_some_and(|(s, e)| near(s, Point::new(30.0, 5.0)) && near(e, Point::new(70.0, 5.0))), "{moved:?}");
|
||||
assert!(moved.len() == 6 && [1, 2, 4, 5, 6].iter().all(|id| moved[id].is_none()), "{moved:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -328,7 +714,7 @@ fn pathfinder_past_its_budget_draws_the_source_art() {
|
||||
// n² crossings past the cap: no evaluation (#3591), the source art as it is.
|
||||
for n in [130, 800] {
|
||||
let g = crossing_bars(n, "pathfinder.divide");
|
||||
let out = pathfinder_children(&g, None).unwrap();
|
||||
let out = pathfinder_children(None, &g, None).unwrap();
|
||||
assert_eq!(out.len(), 2 * n, "{n} x {n} bars");
|
||||
let ids: Vec<NodeId> = out.iter().map(|c| c.id).collect();
|
||||
let src: Vec<NodeId> = g.children().unwrap().iter().map(|c| c.id).collect();
|
||||
@@ -343,7 +729,7 @@ fn pathfinder_within_its_budget_still_divides() {
|
||||
// n x n bars divide into 3·n² pieces, and 128 x 128 bars, which overlap in exactly
|
||||
// `PATHFINDER_MAX_OVERLAPS` pairs, must still divide.
|
||||
for n in [8, 128] {
|
||||
let out = pathfinder_children(&crossing_bars(n, "pathfinder.divide"), None).unwrap();
|
||||
let out = pathfinder_children(None, &crossing_bars(n, "pathfinder.divide"), None).unwrap();
|
||||
assert_eq!(out.len(), 3 * n * n, "{n} x {n} bars");
|
||||
}
|
||||
}
|
||||
@@ -361,7 +747,7 @@ fn pathfinder_on_many_stacked_bars_still_runs() {
|
||||
.collect();
|
||||
let mut g = Node::group(NodeId(10), children);
|
||||
g.appearance.effects.push(Effect { id: "pathfinder.add".into(), params: serde_json::json!({}), visible: true });
|
||||
let out = pathfinder_children(&g, None).unwrap();
|
||||
let out = pathfinder_children(None, &g, None).unwrap();
|
||||
assert_eq!(out.len(), 1);
|
||||
}
|
||||
|
||||
@@ -382,9 +768,9 @@ fn compound_shapes_draw_the_area_their_shape_modes_make() {
|
||||
for (mode, want) in [(ShapeMode::Add, 150.0), (ShapeMode::Subtract, 50.0), (ShapeMode::Intersect, 50.0), (ShapeMode::Exclude, 100.0)] {
|
||||
let g = compound_shape(mode);
|
||||
assert!(has_pathfinder(&g), "{mode:?}");
|
||||
let area_path = compound_shape_area(&g, None).unwrap();
|
||||
let area_path = compound_shape_area(None, &g, None).unwrap();
|
||||
assert!((po::area(&area_path, FillRule::NonZero).abs() - want).abs() < 0.01, "{mode:?}");
|
||||
let out = pathfinder_children(&g, None).unwrap();
|
||||
let out = pathfinder_children(None, &g, None).unwrap();
|
||||
assert_eq!(out.len(), 1, "{mode:?}");
|
||||
assert!(out[0].appearance.items.is_empty(), "the group's own appearance paints it");
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
@@ -401,7 +787,7 @@ fn compound_shapes_draw_the_area_their_shape_modes_make() {
|
||||
back.extras_mut().shape_mode = ShapeMode::Subtract;
|
||||
ch[0] = Arc::new(back);
|
||||
}
|
||||
assert!((po::area(&compound_shape_area(&g, None).unwrap(), FillRule::NonZero).abs() - 150.0).abs() < 0.01);
|
||||
assert!((po::area(&compound_shape_area(None, &g, None).unwrap(), FillRule::NonZero).abs() - 150.0).abs() < 0.01);
|
||||
// Hidden members take no part; the mark on a clip group is ignored.
|
||||
let mut g = compound_shape(ShapeMode::Subtract);
|
||||
if let Some(ch) = g.children_mut() {
|
||||
@@ -409,10 +795,10 @@ fn compound_shapes_draw_the_area_their_shape_modes_make() {
|
||||
front.visible = false;
|
||||
ch[1] = Arc::new(front);
|
||||
}
|
||||
assert!((po::area(&compound_shape_area(&g, None).unwrap(), FillRule::NonZero).abs() - 100.0).abs() < 0.01);
|
||||
assert!((po::area(&compound_shape_area(None, &g, None).unwrap(), FillRule::NonZero).abs() - 100.0).abs() < 0.01);
|
||||
let mut clip = compound_shape(ShapeMode::Add);
|
||||
clip.kind = NodeKind::Group { children: clip.children().unwrap().clone(), clip: true };
|
||||
assert!(!clip.is_compound_shape() && compound_shape_area(&clip, None).is_none());
|
||||
assert!(!clip.is_compound_shape() && compound_shape_area(None, &clip, None).is_none());
|
||||
}
|
||||
|
||||
/// A compound shape inside another (and inside an Effect › Pathfinder group) takes part as its area,
|
||||
@@ -425,10 +811,10 @@ fn nested_compound_shapes_take_part_as_their_area() {
|
||||
let mut outer = Node::group(NodeId(20), vec![Arc::new(inner.clone()), Arc::new(cutter)]);
|
||||
outer.extras_mut().compound_shape = true;
|
||||
// (0–5 of the inner area) ∩ (2–12) = 2–5 by 10 high.
|
||||
assert!((po::area(&compound_shape_area(&outer, None).unwrap(), FillRule::NonZero).abs() - 30.0).abs() < 0.01);
|
||||
assert!((po::area(&compound_shape_area(None, &outer, None).unwrap(), FillRule::NonZero).abs() - 30.0).abs() < 0.01);
|
||||
let mut effect = Node::group(NodeId(30), vec![Arc::new(inner)]);
|
||||
effect.appearance.effects.push(Effect { id: "pathfinder.add".into(), params: serde_json::json!({}), visible: true });
|
||||
let out = pathfinder_children(&effect, None).unwrap();
|
||||
let out = pathfinder_children(None, &effect, None).unwrap();
|
||||
assert_eq!(out.len(), 1);
|
||||
assert!((area(&out[0]) - 50.0).abs() < 0.01);
|
||||
assert_eq!(out[0].appearance.fill_paint().color(), Some(Color::rgb(0.0, 1.0, 0.0)), "styled like the compound shape");
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
//! Warp) rewrite a path: [`apply_geometry`] evaluates them in stack order.
|
||||
//! - **Raster effects** (Drop Shadow, Inner/Outer Glow, Feather, Gaussian Blur, Rasterize, and the
|
||||
//! Photoshop-style filters of [`pixel`]: Radial Blur, Smart Blur, Color Halftone, Crystallize, Mezzotint, Pointillize, Halftone Pattern,
|
||||
//! Unsharp Mask and Glowing Edges) are described by
|
||||
//! Unsharp Mask and Glowing Edges, and the SVG filters of [`svg_filter`]) are described by
|
||||
//! [`raster_effects`] and painted by the renderer; [`outset`] says how far they reach beyond
|
||||
//! the geometry.
|
||||
//! - **Stroke geometry** ([`stroke`]): arrowheads, dash patterns and width profiles, shared by the
|
||||
@@ -52,6 +52,7 @@ mod revolve;
|
||||
mod solids;
|
||||
pub mod stroke;
|
||||
mod stylize;
|
||||
pub mod svg_filter;
|
||||
pub mod trap;
|
||||
mod util;
|
||||
mod warp;
|
||||
@@ -79,16 +80,19 @@ 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, outset, raster_effects};
|
||||
pub use reshape::{
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, has_gradient_copies, has_item_geometry, has_transform_art, has_transform_copies, has_transform_options,
|
||||
image_paint, needs_outline, outline_art, outline_text, reshape,
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects, has_transform_art,
|
||||
has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape,
|
||||
};
|
||||
pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_revolve};
|
||||
pub use solids::{
|
||||
EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SOLIDS, THREE_D_TYPES, extrude_options, has_solid, inflate_options, is_three_d, solid_art,
|
||||
three_d_params_as, validate_solid, validate_three_d, view_options,
|
||||
CLASSIC_EXTRUDE, EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options,
|
||||
classic_shading, extrude_options, has_solid, inflate_options, is_three_d, solid_art, three_d_meshes, three_d_meshes_of, three_d_params_as,
|
||||
validate_solid, validate_three_d, validate_three_d_params, view_options,
|
||||
};
|
||||
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
|
||||
pub use svg_filter::SVG_FILTER;
|
||||
pub use trap::TRAP;
|
||||
pub use vectorcraft_three_d::Mesh;
|
||||
pub use warp::{WarpStyle, warp_point};
|
||||
|
||||
mod catalog;
|
||||
@@ -97,9 +101,12 @@ mod params;
|
||||
|
||||
pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range};
|
||||
pub(crate) use geometry::{Budget, apply_one};
|
||||
pub use geometry::{GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_with};
|
||||
pub use geometry::{
|
||||
Carry, GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_bez_carrying, apply_geometry_carrying, apply_geometry_with,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use geometry::{MAX_EFFECT_LINES, apply_geometry_within};
|
||||
pub use params::{
|
||||
default_params, has_geometry, has_plugin_effect, is_geometry, is_raster, merged_params, new_effect, plugin_revision, scale_effect, upgrade_params,
|
||||
any_plugin_paints_output, default_params, has_geometry, has_painted_plugin_effect, has_plugin_effect, is_geometry, is_raster, merged_params,
|
||||
new_effect, plugin_revision, scale_effect, upgrade_params,
|
||||
};
|
||||
@@ -43,7 +43,8 @@ fn with_hooks<R>(doc: Option<&Document>, f: impl FnOnce(Hooks) -> R) -> R {
|
||||
vectorcraft_text::register_envelope_ink();
|
||||
let outline = |n: &Node| outline_object(doc, n);
|
||||
let tiles = |name: &str, xf: Affine, region: Rect| Some(doc?.pattern(name)?.instances_in(xf, region));
|
||||
f(Hooks { outline: Some(&outline), appearance: Some(&bake_appearance), pattern: Some(&tiles), symbols: doc })
|
||||
let appearance = |n: &Node| bake_appearance(doc, n);
|
||||
f(Hooks { outline: Some(&outline), appearance: Some(&appearance), pattern: Some(&tiles), symbols: doc })
|
||||
}
|
||||
|
||||
/// One level of evaluation of live object `n` ([`live::expand_live_hooks`]).
|
||||
|
||||
@@ -119,6 +119,7 @@ pub fn scale_effect(e: &mut Effect, s: f64) {
|
||||
pub fn is_raster(id: &str) -> bool {
|
||||
matches!(id, "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow" | "stylize.feather" | "blur.gaussian" | RASTERIZE)
|
||||
|| PIXEL_EFFECTS.contains(&id)
|
||||
|| id == crate::SVG_FILTER
|
||||
}
|
||||
|
||||
/// Does `id` change geometry? (Crop Marks and Vector Halftone add art of their own instead,
|
||||
@@ -147,6 +148,19 @@ pub fn has_plugin_effect(n: &Node) -> bool {
|
||||
n.appearance.effects.iter().any(plugin) || n.appearance.items.iter().any(|i| i.effects().iter().any(plugin))
|
||||
}
|
||||
|
||||
/// Does `n` have a visible live-effect plug-in effect, its own or a fill's or stroke's, whose
|
||||
/// plug-in paints the pieces it returns? What such an effect draws also depends on the document's
|
||||
/// swatches and patterns, which its pieces may name.
|
||||
pub fn has_painted_plugin_effect(n: &Node) -> bool {
|
||||
let painted = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some_and(vectorcraft_plugins::effect::paints_output);
|
||||
n.appearance.effects.iter().any(painted) || n.appearance.items.iter().any(|i| i.effects().iter().any(painted))
|
||||
}
|
||||
|
||||
/// Is a live-effect plug-in that paints the pieces it returns installed?
|
||||
pub fn any_plugin_paints_output() -> bool {
|
||||
vectorcraft_plugins::registry::list().iter().any(|p| vectorcraft_plugins::effect::paints_output(&p.manifest().id))
|
||||
}
|
||||
|
||||
/// The plug-in registry's revision, which changes whenever a plug-in is installed or removed.
|
||||
pub fn plugin_revision() -> u64 {
|
||||
vectorcraft_plugins::registry::revision()
|
||||
|
||||
@@ -287,6 +287,8 @@ pub enum PixelFx {
|
||||
DeInterlace { even: bool, interpolate: bool },
|
||||
/// Video › NTSC Colors: colours a television signal can't carry made less saturated.
|
||||
NtscColors,
|
||||
/// Effect › SVG Filters: an SVG `<filter>` element run on the pixels.
|
||||
Svg(crate::svg_filter::SvgFilterFx),
|
||||
}
|
||||
|
||||
/// What a raster's colour channels hold, for the filters that treat them apart (Color Halftone
|
||||
@@ -598,6 +600,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
interpolate: text(p, "create", "duplication").eq_ignore_ascii_case("interpolation"),
|
||||
},
|
||||
"video.ntscColors" => PixelFx::NtscColors,
|
||||
crate::SVG_FILTER => PixelFx::Svg(crate::svg_filter::SvgFilterFx::parse(p)?),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -666,6 +669,7 @@ impl PixelFx {
|
||||
PixelFx::Crystallize { cell } | PixelFx::Pointillize { cell } | PixelFx::StainedGlass { cell, .. } => 1.5 * cell,
|
||||
// A square whose centre is on the object is drawn whole.
|
||||
PixelFx::Patchwork { square, .. } => square.max(1.0),
|
||||
PixelFx::Svg(ref f) => f.outset(bounds),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -745,12 +749,17 @@ impl PixelFx {
|
||||
// The lines above and below.
|
||||
PixelFx::DeInterlace { .. } => Some(video::MAX_LINE),
|
||||
PixelFx::NtscColors => Some(0.0),
|
||||
// A filter's object bounding box is the whole object's.
|
||||
PixelFx::Svg(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the effect on `data`, `w` × `h` premultiplied RGBA8 pixels lying in the document as
|
||||
/// `space` says. Does nothing when the sizes don't match.
|
||||
pub fn apply(&self, data: &mut [u8], w: usize, h: usize, space: &PixelSpace) {
|
||||
if let PixelFx::Svg(f) = self {
|
||||
return f.apply(data, w, h, space);
|
||||
}
|
||||
let Some(px) = pixels(data, w, h) else { return };
|
||||
let to_px = |len: f64| len / space.px.max(1e-9);
|
||||
match *self {
|
||||
@@ -829,6 +838,7 @@ impl PixelFx {
|
||||
}
|
||||
PixelFx::DeInterlace { even, interpolate } => video::deinterlace(px, w, h, space, even, interpolate),
|
||||
PixelFx::NtscColors => video::ntsc(px),
|
||||
PixelFx::Svg(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+492
-77
@@ -11,6 +11,7 @@
|
||||
//! strokes paint only the shape that a Convert to Shape or Outline Object effect on them gives
|
||||
//! them ([`image_rows`]).
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::live::Hooks;
|
||||
@@ -102,10 +103,27 @@ fn reaches_appearance(e: &Effect) -> bool {
|
||||
}
|
||||
|
||||
/// Is `n` a path or compound path that its Transform effects make into art of separate objects
|
||||
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`])? It is drawn, baked and expanded through
|
||||
/// that art ([`reshape`]).
|
||||
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`]), or whose
|
||||
/// live-effect plug-ins paint what they return ([`has_painted_effects`])? It is drawn, baked and
|
||||
/// expanded through that art ([`reshape`]).
|
||||
pub fn has_transform_art(n: &Node) -> bool {
|
||||
has_gradient_copies(n) || has_layered_copies(n) || has_transform_options(n)
|
||||
has_gradient_copies(n) || has_layered_copies(n) || has_transform_options(n) || has_painted_effects(n)
|
||||
}
|
||||
|
||||
/// Is `e` a visible live-effect plug-in whose manifest declares `paintOutput`: its id's plug-in id,
|
||||
/// else `None`.
|
||||
fn painted_plugin(e: &Effect) -> Option<&str> {
|
||||
let id = vectorcraft_plugins::effect::plugin_id(&e.id).filter(|_| e.visible)?;
|
||||
vectorcraft_plugins::effect::paints_output(id).then_some(id)
|
||||
}
|
||||
|
||||
/// Is `n` a path or compound path with a live-effect plug-in that paints what it returns
|
||||
/// ([`painted_plugin`]), its own or on a fill or stroke that paints? Each piece the plug-in returns
|
||||
/// is then an object of its own with its own paints ([`paint_leaf`], [`transform_item_leaf`]).
|
||||
pub fn has_painted_effects(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. })
|
||||
&& (n.appearance.effects.iter().any(|e| painted_plugin(e).is_some())
|
||||
|| n.appearance.items.iter().any(|i| crate::paints(i) && i.effects().iter().any(|e| painted_plugin(e).is_some())))
|
||||
}
|
||||
|
||||
/// Is `n` type without inline graphics that has a fill or stroke of its own that paints and has a
|
||||
@@ -132,7 +150,13 @@ fn gives_shape(e: &Effect) -> bool {
|
||||
/// Does `item`, a fill or stroke of an image, paint something: does it paint and carry an effect
|
||||
/// that gives it a shape ([`gives_shape`])?
|
||||
fn shapes_image(item: &AppearanceItem) -> bool {
|
||||
crate::paints(item) && item.effects().iter().any(gives_shape)
|
||||
crate::paints(item) && gives_image_shape(item.effects())
|
||||
}
|
||||
|
||||
/// Do `effects`, those of an image's fill or stroke, give that fill or stroke a shape to paint
|
||||
/// ([`gives_shape`])?
|
||||
pub fn gives_image_shape(effects: &[Effect]) -> bool {
|
||||
effects.iter().any(gives_shape)
|
||||
}
|
||||
|
||||
/// The fills and strokes of `items` (an image's own) that paint something ([`shapes_image`]), each
|
||||
@@ -156,17 +180,18 @@ fn image_rows(items: &[AppearanceItem]) -> Vec<AppearanceItem> {
|
||||
/// The shapes that the image `n`'s own fills and strokes paint ([`image_rows`]), each with its fill
|
||||
/// rule and the fill or stroke that paints it: the paths (or compound paths) along its frame that
|
||||
/// [`reshape`] makes, with each fill's or stroke's geometry effects applied as the renderer applies
|
||||
/// them. Empty for anything but an image with such fills or strokes.
|
||||
pub fn image_paint(n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
|
||||
/// them. Empty for anything but an image with such fills or strokes. The swatches and patterns that
|
||||
/// live-effect plug-ins painting their pieces name are looked up in `doc`.
|
||||
pub fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
|
||||
if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) {
|
||||
return vec![];
|
||||
}
|
||||
let Some(art) = reshape(None, n, None) else { return vec![] };
|
||||
let Some(art) = reshape(doc, n, None) else { return vec![] };
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |c| {
|
||||
let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return };
|
||||
let Some(g) = c.stroke_path() else { return };
|
||||
let ctx = GeomContext::of(c);
|
||||
let ctx = GeomContext { doc, ..GeomContext::of(c) };
|
||||
for item in c.appearance.items.iter().filter(|i| crate::paints(i)) {
|
||||
let fx = item.effects();
|
||||
let shape = if crate::has_geometry(fx) && !g.elements().is_empty() {
|
||||
@@ -279,14 +304,17 @@ fn with_id(art: &Node, id: NodeId) -> Node {
|
||||
/// through the guides could hold more than [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects. A Repeat counts the Repeats in the art of
|
||||
/// `doc`'s symbols that its instances show toward its instance budget.
|
||||
pub fn outline_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
|
||||
outline_art_with(doc, n, symbol_art, &outline_text, &SymbolNodes::default(), false)
|
||||
outline_art_with(doc, doc, n, symbol_art, &outline_text, &SymbolNodes::default(), false)
|
||||
}
|
||||
|
||||
/// [`outline_art`] with live objects evaluated through `outline` ([`evaluated_with`]); with
|
||||
/// `apart`, also a path or compound path whose Transform effect makes copies
|
||||
/// ([`has_transform_copies`]), as the one piece the copies are made from.
|
||||
/// ([`has_transform_copies`]), as the one piece the copies are made from. `symbols` is the document
|
||||
/// the symbols of the art come from; `paint_doc` is the one the swatches and patterns of painted
|
||||
/// pieces are looked up in.
|
||||
fn outline_art_with(
|
||||
doc: Option<&Document>,
|
||||
symbols: Option<&Document>,
|
||||
paint_doc: Option<&Document>,
|
||||
n: &Node,
|
||||
symbol_art: Option<&Node>,
|
||||
outline: OutlineHook,
|
||||
@@ -296,7 +324,7 @@ fn outline_art_with(
|
||||
let mut art = match &n.kind {
|
||||
NodeKind::Text(_) => outline_text(n)?,
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
let a = match doc {
|
||||
let a = match symbols {
|
||||
Some(d) => d.place_symbol_art(symbol, symbol_art?, *xf)?,
|
||||
None => {
|
||||
let mut a = symbol_art?.clone();
|
||||
@@ -316,10 +344,10 @@ fn outline_art_with(
|
||||
one.appearance.effects.clear();
|
||||
Node::group(n.id, vec![Arc::new(one)])
|
||||
}
|
||||
_ if vectorcraft_doc::live::is_live(n) => evaluated_with(doc, n, outline, nodes),
|
||||
_ if vectorcraft_doc::live::is_live(n) => evaluated_with(symbols, n, outline, nodes),
|
||||
_ => return None,
|
||||
};
|
||||
outline_nested_text(&mut art, false);
|
||||
outline_nested_text(paint_doc, &mut art, false);
|
||||
art.opacity = 1.0;
|
||||
art.blend = Default::default();
|
||||
art.isolate = false;
|
||||
@@ -426,21 +454,22 @@ fn instances_as_art(doc: Option<&Document>, n: &mut Node, outline: OutlineHook,
|
||||
/// Replace type anywhere inside `n` by its outlines, as art that keeps the type's look
|
||||
/// ([`as_art`]). Type in a clip group's clipping path (all of `n` when `clipping` is set) becomes
|
||||
/// its plain outlines ([`outline_text`]) with its visibility, which is what
|
||||
/// [`crate::clip_outline`] clips by.
|
||||
pub(crate) fn outline_nested_text(n: &mut Node, clipping: bool) {
|
||||
/// [`crate::clip_outline`] clips by. The swatches and patterns that live-effect plug-ins painting
|
||||
/// their pieces name are looked up in `doc`.
|
||||
pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping: bool) {
|
||||
let clips = n.clips();
|
||||
let Some(ch) = n.children_mut() else { return };
|
||||
for (i, c) in ch.iter_mut().enumerate() {
|
||||
let clipping = clipping || (clips && i == 0);
|
||||
let art = match &c.kind {
|
||||
NodeKind::Text(_) if clipping => outline_text(c).map(|o| Node { visible: c.visible, ..o }),
|
||||
NodeKind::Text(_) => as_art(None, c, None),
|
||||
NodeKind::Text(_) => as_art(doc, c, None),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(o) = art {
|
||||
*c = Arc::new(o);
|
||||
} else if c.children().is_some() {
|
||||
outline_nested_text(Arc::make_mut(c), clipping);
|
||||
outline_nested_text(doc, Arc::make_mut(c), clipping);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -473,7 +502,7 @@ pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Nod
|
||||
// effect in a group of their own (copies of copies nest), as the reference app expands them
|
||||
// (#5612).
|
||||
if has_transform_art(n) || has_transform_copies(n) {
|
||||
return as_art_opts(doc, n, symbol_art, &outline_text, &SymbolNodes::default(), true);
|
||||
return as_art_opts(doc, doc, n, symbol_art, &outline_text, &SymbolNodes::default(), true);
|
||||
}
|
||||
let own_paint = match n.kind {
|
||||
NodeKind::Text(_) => !n.appearance.items.is_empty(),
|
||||
@@ -487,17 +516,34 @@ pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Nod
|
||||
|
||||
/// [`reshape`] without its checks (no geometry effects: just the art).
|
||||
pub(crate) fn as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
|
||||
as_art_with(doc, n, symbol_art, &outline_text, &SymbolNodes::default())
|
||||
as_art_with(doc, doc, n, symbol_art, &outline_text, &SymbolNodes::default())
|
||||
}
|
||||
|
||||
/// [`as_art`] with live objects evaluated through `outline` ([`evaluated_with`]).
|
||||
pub(crate) fn as_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes) -> Option<Node> {
|
||||
as_art_opts(doc, n, symbol_art, outline, nodes, false)
|
||||
/// [`as_art`] with live objects evaluated through `outline` ([`evaluated_with`]). `symbols` is the
|
||||
/// document the symbols of the art come from; `paint_doc` is the one the swatches and patterns of
|
||||
/// painted pieces are looked up in.
|
||||
pub(crate) fn as_art_with(
|
||||
symbols: Option<&Document>,
|
||||
paint_doc: Option<&Document>,
|
||||
n: &Node,
|
||||
symbol_art: Option<&Node>,
|
||||
outline: OutlineHook,
|
||||
nodes: &SymbolNodes,
|
||||
) -> Option<Node> {
|
||||
as_art_opts(symbols, paint_doc, n, symbol_art, outline, nodes, false)
|
||||
}
|
||||
|
||||
/// [`as_art_with`]; with `apart`, a path's or compound path's Transform effects make each copy an
|
||||
/// object of its own ([`copy_leaf`]) rather than one path of every copy.
|
||||
fn as_art_opts(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes, apart: bool) -> Option<Node> {
|
||||
fn as_art_opts(
|
||||
symbols: Option<&Document>,
|
||||
paint_doc: Option<&Document>,
|
||||
n: &Node,
|
||||
symbol_art: Option<&Node>,
|
||||
outline: OutlineHook,
|
||||
nodes: &SymbolNodes,
|
||||
apart: bool,
|
||||
) -> Option<Node> {
|
||||
let fx = geometry_effects(n);
|
||||
let mut art = match &n.kind {
|
||||
NodeKind::Image(im) => {
|
||||
@@ -525,13 +571,13 @@ fn as_art_opts(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outl
|
||||
Node::group(n.id, rows(below).into_iter().chain([Arc::new(image)]).chain(rows(above)).collect())
|
||||
}
|
||||
}
|
||||
_ => outline_art_with(doc, n, symbol_art, outline, nodes, apart)?,
|
||||
_ => outline_art_with(symbols, paint_doc, n, symbol_art, outline, nodes, apart)?,
|
||||
};
|
||||
reshape_leaves_apart(&mut art, &fx, Budget::EFFECTS, apart);
|
||||
reshape_leaves_apart(&mut art, &fx, Budget::EFFECTS, apart, paint_doc);
|
||||
if apart {
|
||||
hoist_copies(&mut art);
|
||||
}
|
||||
transform_items(&mut art);
|
||||
transform_items(&mut art, paint_doc);
|
||||
// Type and symbols in perspective: the art projected onto their plane.
|
||||
if let Some(h) = n.projection() {
|
||||
project_leaves(&mut art, &h);
|
||||
@@ -589,14 +635,22 @@ pub(crate) fn geometry_effects(n: &Node) -> Vec<&Effect> {
|
||||
/// symbol instances follow a Transform effect the same way ([`transform_placed`]); other geometry
|
||||
/// effects leave them as they are (a raster follows a non-affine map only as a mesh warp). The
|
||||
/// paths keep to one [`Budget::EFFECTS`] together (or to what they cost, when that is more): a path
|
||||
/// whose effect would pass what the others leave of it keeps its shape.
|
||||
pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect]) {
|
||||
reshape_leaves_within(art, fx, Budget::EFFECTS);
|
||||
/// whose effect would pass what the others leave of it keeps its shape. The swatches and patterns
|
||||
/// that live-effect plug-ins painting their pieces name are looked up in `doc`
|
||||
/// ([`reshape_leaves_apart`]).
|
||||
pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect], doc: Option<&Document>) {
|
||||
reshape_leaves_within(art, fx, Budget::EFFECTS, doc);
|
||||
}
|
||||
|
||||
/// [`reshape_leaves`] whose paths keep to `budget` together, or to what they cost.
|
||||
pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget) {
|
||||
reshape_leaves_apart(art, fx, budget, false);
|
||||
/// [`reshape_leaves`], and how gradients that paint the art as a whole (a group's own fills and
|
||||
/// strokes) follow the effects ([`crate::Carry`]).
|
||||
pub(crate) fn reshape_leaves_carrying(art: &mut Node, fx: &[&Effect], doc: Option<&Document>) -> crate::Carry {
|
||||
reshape_leaves_within(art, fx, Budget::EFFECTS, doc)
|
||||
}
|
||||
|
||||
/// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost.
|
||||
pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget, doc: Option<&Document>) -> crate::Carry {
|
||||
reshape_leaves_apart(art, fx, budget, false, doc)
|
||||
}
|
||||
|
||||
/// `art`, the group of the one piece a path's copies are made from ([`outline_art_with`]), holding
|
||||
@@ -616,10 +670,14 @@ fn hoist_copies(art: &mut Node) {
|
||||
}
|
||||
|
||||
/// [`reshape_leaves_within`]; with `apart`, a Transform effect's copies of each path are objects
|
||||
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them.
|
||||
fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: bool) {
|
||||
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. A live-effect
|
||||
/// plug-in that paints what it returns makes each path a group of its pieces ([`paint_leaf`]),
|
||||
/// whose swatches and patterns must be in `doc` (without one, pieces that name one are refused).
|
||||
/// Returns how gradients that paint the art as a whole follow the effects.
|
||||
fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: bool, doc: Option<&Document>) -> crate::Carry {
|
||||
let mut whole = crate::Carry::default();
|
||||
if fx.is_empty() {
|
||||
return;
|
||||
return whole;
|
||||
}
|
||||
let mut leaves_safe = true;
|
||||
for_each_leaf(art, &mut |leaf| {
|
||||
@@ -638,15 +696,43 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
|
||||
let opt_fx = crate::geometry::optimize_geometry_effects(fx, style_safe);
|
||||
let fx = opt_fx.as_slice();
|
||||
let seed = art.id.0;
|
||||
// The placed gradients of type's outlines in `art` (`outline_text`) move and scale with the
|
||||
// pieces, from the outlines' bounds before the effects to their bounds after them.
|
||||
let mut outlines = vec![];
|
||||
type_outline_bounds(art, &mut outlines);
|
||||
let mut used = art_cost(art);
|
||||
let max = budget.at_least(used);
|
||||
for e in fx {
|
||||
let Some(bounds) = art.geometric_bounds() else { break };
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
if let Some(plugin) = painted_plugin(e) {
|
||||
for_each_leaf(art, &mut |leaf| {
|
||||
let Some((path, _)) = leaf_geometry(leaf) else { return };
|
||||
let before = Budget::of(&path);
|
||||
let room = max.minus(used.minus(before));
|
||||
if let Some(made) = paint_leaf(leaf, plugin, ¶ms, bounds, room, doc) {
|
||||
used = used.minus(before).plus(made);
|
||||
}
|
||||
});
|
||||
continue;
|
||||
}
|
||||
// Placed gradients follow a Transform effect, Free Distort and the Warp effects
|
||||
// ([`crate::Carry`]): under Free Distort and Warp (`boxes`) each path's move and scale from
|
||||
// its bounds before the effect to its bounds after it. Under those and the other effects,
|
||||
// the placed gradients of type's outlines in `art` (`outline_text`) move and scale with
|
||||
// the outlines' bounds.
|
||||
let follows = crate::Carry::follows(&e.id, ¶ms, bounds, seed);
|
||||
let boxes = follows && crate::Carry::by_bounds(&e.id);
|
||||
let mut outlines = vec![];
|
||||
if !follows || boxes {
|
||||
type_outline_bounds(art, &mut outlines);
|
||||
}
|
||||
let mut leaves = vec![];
|
||||
if boxes {
|
||||
leaf_bounds(art, &mut leaves);
|
||||
}
|
||||
let mut groups = vec![];
|
||||
if follows {
|
||||
group_marks(art, &mut vec![], &HashSet::new(), &mut groups);
|
||||
}
|
||||
// The ids of the paths that kept their shape (past the budget).
|
||||
let mut kept_ids = HashSet::new();
|
||||
let transform = (e.id == "distort.transform").then(|| {
|
||||
let (m, copies) = crate::distort::transform_map(bounds, ¶ms, seed);
|
||||
let options = crate::distort::TransformOptions::of(¶ms);
|
||||
@@ -668,29 +754,58 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
|
||||
|| leaf.appearance.has_placed_gradient()
|
||||
|| paints_copies_apart(&leaf.appearance, rule));
|
||||
if options.reach_appearance() {
|
||||
let made = transform_leaf(leaf, &path, map, copies, options, room);
|
||||
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room);
|
||||
used = used.minus(before).plus(made);
|
||||
if !moved {
|
||||
kept_ids.insert(leaf.id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if separate {
|
||||
let made = copy_leaf(leaf, &path, m, copies, vectorcraft_doc::Scaling::default(), room);
|
||||
let scaling = vectorcraft_doc::Scaling { keep_fit_when_flat: true, ..Default::default() };
|
||||
let made = copy_leaf(leaf, &path, m, copies, scaling, room);
|
||||
used = used.minus(before).plus(made);
|
||||
return;
|
||||
}
|
||||
}
|
||||
let Some(out) = apply_one(&e.id, ¶ms, &path, bounds, &GeomContext { seed, ..GeomContext::of(leaf) }, room) else { return };
|
||||
let Some(out) = apply_one(&e.id, ¶ms, &path, bounds, &GeomContext { seed, ..GeomContext::of(leaf) }, room) else {
|
||||
kept_ids.insert(leaf.id);
|
||||
return;
|
||||
};
|
||||
used = used.minus(before).plus(Budget::of(&out));
|
||||
if follows && !boxes {
|
||||
// A gradient fitted to the path fits the path's own bounds.
|
||||
let carry = crate::Carry::of(&e.id, ¶ms, bounds, path.bounds(), None, seed);
|
||||
if carry.moves(&leaf.appearance) {
|
||||
carry.apply(&mut leaf.appearance);
|
||||
}
|
||||
}
|
||||
set_geometry(leaf, out, rule);
|
||||
});
|
||||
if boxes {
|
||||
rebase_leaves(art, &mut leaves.into_iter());
|
||||
}
|
||||
if let Some((m, copies, options, _)) = transform
|
||||
&& options.objects
|
||||
{
|
||||
transform_placed(art, m, copies);
|
||||
}
|
||||
if outlines.iter().any(Option::is_some) {
|
||||
rebase_type_outlines(art, &mut outlines.into_iter());
|
||||
}
|
||||
// What paints the art as a whole, and the own fills and strokes of the groups inside it,
|
||||
// follow their bounds under Free Distort and Warp (they stay when no path changed them).
|
||||
// Each stays when a path under it that its bounds measure kept its shape (past the budget).
|
||||
let mut after = vec![];
|
||||
let held = (!groups.is_empty() || !kept_ids.is_empty()) && group_marks(art, &mut vec![], &kept_ids, &mut after).1;
|
||||
if !groups.is_empty() {
|
||||
carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, ¶ms, bounds, from, to, seed));
|
||||
}
|
||||
if follows && !held {
|
||||
whole.push(crate::Carry::of(&e.id, ¶ms, bounds, Some(bounds), art.geometric_bounds(), seed));
|
||||
}
|
||||
}
|
||||
if outlines.iter().any(Option::is_some) {
|
||||
rebase_type_outlines(art, &mut outlines.into_iter());
|
||||
}
|
||||
whole
|
||||
}
|
||||
|
||||
/// Largest factor a Transform effect's Scale Strokes & Effects scales one object's strokes by
|
||||
@@ -704,12 +819,22 @@ const MAX_STROKE_SCALE: f64 = 1.0e6;
|
||||
/// and the distances of the effects on its fills and strokes scale by `m`'s mean scale, and its
|
||||
/// pattern paints transform by `m`. With copies, the original keeps them and copy `k` takes them
|
||||
/// `k` times, each copy an object of its own ([`copy_leaf`], within `budget`). With Transform
|
||||
/// Objects off the geometry stays and the options apply once. Returns what the leaf costs after.
|
||||
fn transform_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, options: crate::distort::TransformOptions, budget: Budget) -> Budget {
|
||||
/// Objects off the geometry stays and the options apply once. Returns what the leaf costs after,
|
||||
/// and `false` when the path kept its shape because the moved path would pass `budget`.
|
||||
fn transform_leaf(
|
||||
leaf: &mut Node,
|
||||
path: &PathData,
|
||||
m: Affine,
|
||||
copies: usize,
|
||||
options: crate::distort::TransformOptions,
|
||||
budget: Budget,
|
||||
) -> (Budget, bool) {
|
||||
let scaling = vectorcraft_doc::Scaling {
|
||||
strokes: options.strokes,
|
||||
effects: options.strokes.then_some(crate::scale_effect as fn(&mut Effect, f64)),
|
||||
patterns: options.patterns,
|
||||
// A map that flattens the path leaves its fitted gradients fitted, as `fixes_fit` does.
|
||||
keep_fit_when_flat: true,
|
||||
..Default::default()
|
||||
};
|
||||
if !options.objects {
|
||||
@@ -722,18 +847,18 @@ fn transform_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, op
|
||||
if options.patterns {
|
||||
vectorcraft_doc::pattern::transform_pattern_paints(leaf, m);
|
||||
}
|
||||
return Budget::of(path);
|
||||
return (Budget::of(path), true);
|
||||
}
|
||||
if copies == 0 {
|
||||
// A path scaled up is drawn with more lines; past the budget it keeps its shape.
|
||||
let moved = path.transformed(m);
|
||||
if !budget.fits(Budget::of(&moved)) {
|
||||
return Budget::of(path);
|
||||
return (Budget::of(path), false);
|
||||
}
|
||||
leaf.transform(m, scaling);
|
||||
return Budget::of(&moved);
|
||||
return (Budget::of(&moved), true);
|
||||
}
|
||||
copy_leaf(leaf, path, m, copies, scaling, budget)
|
||||
(copy_leaf(leaf, path, m, copies, scaling, budget), true)
|
||||
}
|
||||
|
||||
/// Replace `leaf` (a path or compound path with geometry `path`) by a group of it and `copies`
|
||||
@@ -772,15 +897,118 @@ fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling
|
||||
made
|
||||
}
|
||||
|
||||
/// Live-effect plug-in `plugin` (one that paints what it returns) with `params` run on `leaf`, a
|
||||
/// path or compound path, as one of its object's effects with reference box `bounds`: `leaf`
|
||||
/// becomes a group with its id and name of one object for each piece returned, in order, each with
|
||||
/// the piece's geometry and the leaf's appearance with the piece's fills and strokes in place of
|
||||
/// its own ([`vectorcraft_plugins::painted::appearance`]). The swatches and patterns the pieces
|
||||
/// name must be in `doc`, and without one the pieces may name none. Returns what the pieces cost
|
||||
/// ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails, the pieces are
|
||||
/// refused, or they would pass `budget`.
|
||||
fn paint_leaf(leaf: &mut Node, plugin: &str, params: &serde_json::Value, bounds: Rect, budget: Budget, doc: Option<&Document>) -> Option<Budget> {
|
||||
let (path, rule) = leaf_geometry(leaf)?;
|
||||
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: None };
|
||||
let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?;
|
||||
let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
|
||||
if !budget.fits(made) {
|
||||
return None;
|
||||
}
|
||||
let children = pieces
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let mut one = leaf.clone();
|
||||
one.name = None;
|
||||
one.appearance = vectorcraft_plugins::painted::appearance(&leaf.appearance, p).into();
|
||||
set_geometry(&mut one, p.path.clone(), p.rule);
|
||||
Arc::new(one)
|
||||
})
|
||||
.collect();
|
||||
let mut g = Node::group(leaf.id, children);
|
||||
g.name = leaf.name.clone();
|
||||
*leaf = g;
|
||||
Some(made)
|
||||
}
|
||||
|
||||
/// What a painted piece with geometry `path` costs: its anchors and lines, plus a share of the
|
||||
/// effects' budget for the object it becomes, so that a budget of [`Budget::EFFECTS`] holds at most
|
||||
/// [`MAX_OBJECTS`](vectorcraft_plugins::objects::MAX_OBJECTS) pieces however small their paths.
|
||||
fn piece_cost(path: &PathData) -> Budget {
|
||||
let max = vectorcraft_plugins::objects::MAX_OBJECTS;
|
||||
Budget::of(path).plus(Budget { anchors: Budget::EFFECTS.anchors / max, lines: Budget::EFFECTS.lines / max })
|
||||
}
|
||||
|
||||
/// Live-effect plug-in `plugin` (one that paints what it returns) with `params`, a later effect of
|
||||
/// `item`, run on `leaf`, a path of [`transform_piece`] painted by copies of `item`, with reference
|
||||
/// box `bounds`: `leaf` becomes a group of one path for each piece returned, in order. A piece that
|
||||
/// gives fills (on a fill) or strokes (on a stroke) is painted by copies of `item`, the leaf's first
|
||||
/// fill or stroke, with those paints ([`vectorcraft_plugins::painted::items`]), under the leaf's
|
||||
/// other fills and strokes; one that gives none keeps the leaf's. Returns
|
||||
/// what the paths cost ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails,
|
||||
/// the pieces are refused (a swatch or pattern not in `doc`, or any without one), or they would pass
|
||||
/// `budget`.
|
||||
fn paint_piece(
|
||||
leaf: &mut Node,
|
||||
item: &AppearanceItem,
|
||||
plugin: &str,
|
||||
params: &serde_json::Value,
|
||||
bounds: Rect,
|
||||
budget: Budget,
|
||||
doc: Option<&Document>,
|
||||
) -> Option<Budget> {
|
||||
let (path, rule) = leaf_geometry(leaf)?;
|
||||
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: Some(0) };
|
||||
let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?;
|
||||
let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
|
||||
if !budget.fits(made) {
|
||||
return None;
|
||||
}
|
||||
let mut children = vec![];
|
||||
for p in pieces.iter() {
|
||||
let gives = match item {
|
||||
AppearanceItem::Fill(_) => p.fills.is_some(),
|
||||
AppearanceItem::Stroke(_) => p.strokes.is_some(),
|
||||
};
|
||||
let items = if gives {
|
||||
let mut items = vectorcraft_plugins::painted::items(item, p);
|
||||
items.extend_from_slice(leaf.appearance.items.get(1..).unwrap_or_default());
|
||||
items
|
||||
} else {
|
||||
leaf.appearance.items.clone()
|
||||
};
|
||||
if items.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut one = leaf.clone();
|
||||
one.appearance.items = items;
|
||||
set_geometry(&mut one, p.path.clone(), p.rule);
|
||||
children.push(Arc::new(one));
|
||||
}
|
||||
*leaf = Node::group(leaf.id, children);
|
||||
Some(made)
|
||||
}
|
||||
|
||||
/// Every path and compound path under `art` (other than clipping paths) with a fill or stroke whose
|
||||
/// own Transform effect has Transform Patterns or Scale Strokes & Effects on
|
||||
/// ([`item_transform_options`]), made into a group of objects of its own ([`transform_item_leaf`]).
|
||||
/// The new paths keep to one [`Budget::EFFECTS`] together (or to what `art` costs, when that is
|
||||
/// more).
|
||||
fn transform_items(art: &mut Node) {
|
||||
/// ([`item_transform_options`]), or whose own live-effect plug-in paints what it returns
|
||||
/// ([`painted_plugin`]), made into a group of objects of its own ([`transform_item_leaf`]). The
|
||||
/// new paths keep to one [`Budget::EFFECTS`] together (or to what `art` costs, when that is more).
|
||||
/// The swatches and patterns painted pieces name must be in `doc`; without one they may name none.
|
||||
fn transform_items(art: &mut Node, doc: Option<&Document>) {
|
||||
let mut used = art_cost(art);
|
||||
let max = Budget::EFFECTS.at_least(used);
|
||||
for_each_leaf(art, &mut |leaf| transform_item_leaf(leaf, max, &mut used));
|
||||
for_each_leaf(art, &mut |leaf| transform_item_leaf(leaf, max, &mut used, doc));
|
||||
}
|
||||
|
||||
/// Is `e` an effect that makes a fill's or stroke's piece of a path an object of its own: a
|
||||
/// Transform effect that [`reaches_appearance`], or a live-effect plug-in that paints what it
|
||||
/// returns ([`painted_plugin`])?
|
||||
fn makes_piece(e: &Effect) -> bool {
|
||||
reaches_appearance(e) || painted_plugin(e).is_some()
|
||||
}
|
||||
|
||||
/// Does `item` paint and carry an effect that [`makes_piece`]?
|
||||
fn item_makes_piece(item: &AppearanceItem) -> bool {
|
||||
crate::paints(item) && item.effects().iter().any(makes_piece)
|
||||
}
|
||||
|
||||
/// `leaf`, a path or compound path with a fill or stroke whose own Transform effect has Transform
|
||||
@@ -795,8 +1023,17 @@ fn transform_items(art: &mut Node) {
|
||||
/// effects stay on each of them. The other fills and strokes stay together on paths of the leaf's
|
||||
/// geometry between them, with their own effects. `max` is the budget of the whole art and `used`
|
||||
/// what it has spent.
|
||||
fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget) {
|
||||
if matches!(leaf.kind, NodeKind::Path { clipping: true, .. }) || !leaf.appearance.items.iter().any(item_transform_options) {
|
||||
///
|
||||
/// A fill or stroke whose first such effect is a live-effect plug-in that paints what it returns
|
||||
/// ([`painted_plugin`]) becomes, in place of a transformed path, one path for each piece the
|
||||
/// plug-in returns, painted by copies of the fill or stroke with the piece's paints
|
||||
/// ([`vectorcraft_plugins::painted::items`]); the plug-in is given the geometry before it and told
|
||||
/// which fill or stroke it is on. When it fails (or names a swatch or pattern not in `doc`, or any
|
||||
/// without a document), the
|
||||
/// fill or stroke paints that geometry as it is. The geometry effects after it then apply to all
|
||||
/// the pieces as one ([`transform_piece`]).
|
||||
fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Option<&Document>) {
|
||||
if matches!(leaf.kind, NodeKind::Path { clipping: true, .. }) || !leaf.appearance.items.iter().any(item_makes_piece) {
|
||||
return;
|
||||
}
|
||||
let Some((path, rule)) = leaf_geometry(leaf) else { return };
|
||||
@@ -824,12 +1061,12 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget) {
|
||||
let mut pieces: Vec<Arc<Node>> = vec![];
|
||||
let mut plain: Vec<AppearanceItem> = vec![];
|
||||
// Which items become a transformed piece of their own; every other run of items is one plain piece.
|
||||
let transformed: Vec<bool> = original.appearance.items.iter().map(|i| crate::paints(i) && i.effects().iter().any(reaches_appearance)).collect();
|
||||
let transformed: Vec<bool> = original.appearance.items.iter().map(item_makes_piece).collect();
|
||||
// The number of pieces after item `i` in paint order: each costs at least the leaf's geometry.
|
||||
let later = |i: usize| (i + 1..transformed.len()).filter(|&j| transformed[j] || j == i + 1 || transformed[j - 1]).count();
|
||||
for (i, item) in original.appearance.items.iter().enumerate() {
|
||||
let fx = item.effects();
|
||||
let Some(at) = fx.iter().position(reaches_appearance).filter(|_| crate::paints(item)) else {
|
||||
let Some(at) = fx.iter().position(makes_piece).filter(|_| crate::paints(item)) else {
|
||||
plain.push(item.clone());
|
||||
continue;
|
||||
};
|
||||
@@ -843,13 +1080,42 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget) {
|
||||
let reserved = (0..later(i)).fold(Budget { anchors: 0, lines: 0 }, |r, _| r.plus(cost));
|
||||
let limit = max.minus(reserved);
|
||||
let room = limit.minus(*used);
|
||||
// The fill's or stroke's gradient follows the geometry effects before the Transform effect.
|
||||
let mut carry = crate::Carry::default();
|
||||
let g = if crate::has_geometry(before) && !path.is_empty() {
|
||||
crate::geometry::apply_geometry_within(before, &path, bounds, &ctx.item(item), room)
|
||||
crate::geometry::apply_geometry_carrying_within(before, &path, bounds, &ctx.item(item), room, Some(&mut carry))
|
||||
} else {
|
||||
path.clone()
|
||||
};
|
||||
let Some(tb) = g.bounds() else { continue };
|
||||
let params = merged_params(&fx[at].id, &fx[at].params);
|
||||
if let Some(plugin) = painted_plugin(&fx[at]) {
|
||||
let mut it = item.clone();
|
||||
let rest: Vec<Effect> = before.iter().filter(|e| !is_geometry(&e.id)).chain(&fx[at + 1..]).cloned().collect();
|
||||
*it.effects_mut() = rest;
|
||||
let mut one = Appearance { items: vec![it.clone()], ..Default::default() };
|
||||
if carry.moves(&one) {
|
||||
carry.apply(&mut one);
|
||||
}
|
||||
let it = one.items.pop().unwrap_or(it);
|
||||
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&original.appearance), item: Some(i) };
|
||||
let painted = vectorcraft_plugins::effect::apply_painted(plugin, ¶ms, &g, tb, rule, paints, doc)
|
||||
.map(|pieces| pieces.iter().map(|p| (p.path.clone(), p.rule, vectorcraft_plugins::painted::items(&it, p))).collect::<Vec<_>>())
|
||||
.filter(|pieces| room.fits(pieces.iter().map(|(p, ..)| piece_cost(p)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus)));
|
||||
// A failed run draws the fill or stroke on the geometry it was given.
|
||||
let returned = painted.unwrap_or_else(|| vec![(g.clone(), rule, vec![it])]);
|
||||
let mut group: Vec<Arc<Node>> = vec![];
|
||||
for (path, rule, items) in returned.into_iter().filter(|(_, _, items)| !items.is_empty()) {
|
||||
*used = used.plus(piece_cost(&path));
|
||||
let mut p = piece(items);
|
||||
set_geometry(&mut p, path, rule);
|
||||
group.push(Arc::new(p));
|
||||
}
|
||||
let mut p = Node::group(leaf.id, group);
|
||||
transform_piece(&mut p, ctx.seed, limit, used, doc);
|
||||
pieces.push(Arc::new(p));
|
||||
continue;
|
||||
}
|
||||
let (_, copies) = crate::distort::transform_map(tb, ¶ms, ctx.seed);
|
||||
let options = crate::distort::TransformOptions::of(¶ms);
|
||||
let map = crate::distort::transform_affine(tb, ¶ms, ctx.seed);
|
||||
@@ -857,10 +1123,13 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget) {
|
||||
let rest: Vec<Effect> = before.iter().filter(|e| !is_geometry(&e.id)).chain(&fx[at + 1..]).cloned().collect();
|
||||
*it.effects_mut() = rest;
|
||||
let mut p = piece(vec![it]);
|
||||
if carry.moves(&p.appearance) {
|
||||
carry.apply(&mut p.appearance);
|
||||
}
|
||||
set_geometry(&mut p, g.clone(), rule);
|
||||
let made = transform_leaf(&mut p, &g, map, copies, options, room);
|
||||
let (made, _) = transform_leaf(&mut p, &g, map, copies, options, room);
|
||||
*used = used.plus(made);
|
||||
transform_piece(&mut p, ctx.seed, limit, used);
|
||||
transform_piece(&mut p, ctx.seed, limit, used, doc);
|
||||
pieces.push(Arc::new(p));
|
||||
}
|
||||
if !plain.is_empty() {
|
||||
@@ -879,9 +1148,11 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget) {
|
||||
/// own effects reshape all its paths ([`reshape_leaves_within`]). Each path applies its own copy of
|
||||
/// the effect, whose distances its Scale Strokes & Effects scaled. A Transform effect with
|
||||
/// Transform Patterns or Scale Strokes & Effects on transforms each path as [`transform_leaf`] does.
|
||||
/// The geometry effects then leave the fills and strokes; their other effects stay. The paths keep
|
||||
/// to `max` together with the rest of the art (`used`).
|
||||
fn transform_piece(p: &mut Node, seed: u64, max: Budget, used: &mut Budget) {
|
||||
/// A live-effect plug-in that paints what it returns ([`painted_plugin`]) makes each path one path
|
||||
/// for each piece it returns ([`paint_piece`]). The geometry effects then leave the fills and
|
||||
/// strokes; their other effects stay. The paths keep to `max` together with the rest of the art
|
||||
/// (`used`), and the swatches and patterns painted pieces name must be in `doc`.
|
||||
fn transform_piece(p: &mut Node, seed: u64, max: Budget, used: &mut Budget, doc: Option<&Document>) {
|
||||
let mut count = 0;
|
||||
for_each_leaf(p, &mut |l| {
|
||||
if let Some(item) = l.appearance.items.first() {
|
||||
@@ -897,12 +1168,18 @@ fn transform_piece(p: &mut Node, seed: u64, max: Budget, used: &mut Budget) {
|
||||
// What the other paths leave of the budget.
|
||||
let before = Budget::of(&path);
|
||||
let room = max.minus(used.minus(before));
|
||||
if let Some(plugin) = painted_plugin(&e) {
|
||||
if let Some(made) = paint_piece(leaf, &item, plugin, &merged_params(&e.id, &e.params), bounds, room, doc) {
|
||||
*used = used.minus(before).plus(made);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if reaches_appearance(&e) {
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
let (_, copies) = crate::distort::transform_map(bounds, ¶ms, seed);
|
||||
let options = crate::distort::TransformOptions::of(¶ms);
|
||||
let map = crate::distort::transform_affine(bounds, ¶ms, seed);
|
||||
let made = transform_leaf(leaf, &path, map, copies, options, room);
|
||||
let (made, _) = transform_leaf(leaf, &path, map, copies, options, room);
|
||||
*used = used.minus(before).plus(made);
|
||||
return;
|
||||
}
|
||||
@@ -911,9 +1188,14 @@ fn transform_piece(p: &mut Node, seed: u64, max: Budget, used: &mut Budget) {
|
||||
AppearanceItem::Stroke(s) => Some(s),
|
||||
AppearanceItem::Fill(_) => None,
|
||||
};
|
||||
let ctx = GeomContext { stroke, rule, seed, appearance: Some(&appearance), item: Some(0) };
|
||||
let out = crate::geometry::apply_geometry_within(std::slice::from_ref(&e), &path, bounds, &ctx, room);
|
||||
let ctx = GeomContext { stroke, rule, seed, appearance: Some(&appearance), item: Some(0), doc };
|
||||
let mut carry = crate::Carry::default();
|
||||
let out = crate::geometry::apply_geometry_carrying_within(std::slice::from_ref(&e), &path, bounds, &ctx, room, Some(&mut carry));
|
||||
*used = used.minus(before).plus(Budget::of(&out));
|
||||
// The fill's or stroke's gradient follows the effect as the object's does.
|
||||
if carry.moves(&leaf.appearance) {
|
||||
carry.apply(&mut leaf.appearance);
|
||||
}
|
||||
set_geometry(leaf, out, rule);
|
||||
});
|
||||
}
|
||||
@@ -950,18 +1232,136 @@ fn rebase_type_outlines(n: &mut Node, before: &mut std::vec::IntoIter<Option<Rec
|
||||
&& from != to
|
||||
{
|
||||
for_each_leaf(n, &mut |leaf| {
|
||||
if leaf.appearance.has_placed_gradient() {
|
||||
if leaf.appearance.has_positioned_gradient() {
|
||||
follow_boxes(&mut leaf.appearance, from, to);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The geometric bounds of each path under `n` that [`for_each_leaf`] visits, outside groups of
|
||||
/// type's outlines (those follow the outlines' bounds, [`rebase_type_outlines`]).
|
||||
fn leaf_bounds(n: &Node, out: &mut Vec<Option<Rect>>) {
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => out.push(n.geometric_bounds()),
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } if !n.extras().type_outlines => {
|
||||
for c in children {
|
||||
leaf_bounds(c, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group inside the art whose own fills and strokes [`carry_groups`] moves (groups of type's
|
||||
/// outlines follow the outlines' bounds, [`rebase_type_outlines`]).
|
||||
fn is_member_group(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.extras().type_outlines
|
||||
}
|
||||
|
||||
/// A group below the art that [`is_member_group`] takes and whose own fills or strokes hold a
|
||||
/// gradient: the child indices that lead to it from the art, its geometric bounds, and
|
||||
/// whether a path below it that its bounds measure kept its shape.
|
||||
type GroupMark = (Vec<usize>, Option<Rect>, bool);
|
||||
|
||||
/// The geometric bounds of `n` (as [`Node::geometric_bounds`] gives them) and whether a path or
|
||||
/// compound path below it that those bounds measure is in `kept`, measured in one walk. Each group below `n` that
|
||||
/// [`GroupMark`] describes goes into `out`, reached from `n` through `at`.
|
||||
fn group_marks(n: &Node, at: &mut Vec<usize>, kept: &HashSet<NodeId>, out: &mut Vec<GroupMark>) -> (Option<Rect>, bool) {
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => (n.geometric_bounds(), kept.contains(&n.id)),
|
||||
NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } if !n.extras().type_outlines => {
|
||||
let layer = matches!(n.kind, NodeKind::Layer { .. });
|
||||
let skip = children.len().saturating_sub(n.editing_children().len());
|
||||
let (mut bounds, mut held) = (None, false);
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
at.push(i);
|
||||
let (b, h) = group_marks(c, at, kept, out);
|
||||
if is_member_group(c) && (c.appearance.has_positioned_gradient() || c.appearance.has_unplaced_gradient()) {
|
||||
out.push((at.clone(), b, h));
|
||||
}
|
||||
at.pop();
|
||||
// Only members measured in the bounds hold the group's gradients in place.
|
||||
let counts = if *clip { i == 0 } else { i >= skip && (c.visible || !layer) };
|
||||
if counts {
|
||||
bounds = vectorcraft_geom::union_opt(bounds, b);
|
||||
held |= h;
|
||||
}
|
||||
}
|
||||
(bounds, held)
|
||||
}
|
||||
// Type's outlines: measured as a whole, with each outline that kept its shape counted.
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } => (n.geometric_bounds(), !kept.is_empty() && holds_kept(n, kept)),
|
||||
_ => (n.geometric_bounds(), false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Is a path or compound path below `n` (`n` included) in `kept`?
|
||||
fn holds_kept(n: &Node, kept: &HashSet<NodeId>) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => kept.contains(&n.id),
|
||||
_ => n.children().into_iter().flatten().any(|c| holds_kept(c, kept)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the placed gradients of the own fills and strokes of each group in `after` (the groups of
|
||||
/// `before`, measured again once the paths changed) by what `carry` gives for its bounds before
|
||||
/// and after. A group with a path below it that kept its shape keeps them in place.
|
||||
fn carry_groups(art: &mut Node, before: Vec<GroupMark>, after: Vec<GroupMark>, carry: &dyn Fn(Option<Rect>, Option<Rect>) -> crate::Carry) {
|
||||
for ((at, from, _), (at_after, to, held)) in before.into_iter().zip(after) {
|
||||
if held || at != at_after {
|
||||
continue;
|
||||
}
|
||||
let k = carry(from, to);
|
||||
if k.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(n) = node_at(art, &at)
|
||||
&& is_member_group(n)
|
||||
&& k.moves(&n.appearance)
|
||||
{
|
||||
k.apply(&mut n.appearance);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The node below `n` that the child indices `at` lead to.
|
||||
fn node_at<'a>(n: &'a mut Node, at: &[usize]) -> Option<&'a mut Node> {
|
||||
let Some((first, rest)) = at.split_first() else { return Some(n) };
|
||||
let c = n.children_mut()?.get_mut(*first)?;
|
||||
node_at(Arc::make_mut(c), rest)
|
||||
}
|
||||
|
||||
/// Move and scale the placed gradients of each path under `n` that [`leaf_bounds`] lists from its
|
||||
/// bounds in `before` (before its geometry changed) to its bounds now.
|
||||
fn rebase_leaves(n: &mut Node, before: &mut std::vec::IntoIter<Option<Rect>>) {
|
||||
if matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. }) {
|
||||
if let Some(Some(from)) = before.next()
|
||||
&& let Some(to) = n.geometric_bounds()
|
||||
&& from != to
|
||||
&& n.appearance.has_positioned_gradient()
|
||||
{
|
||||
follow_boxes(&mut n.appearance, from, to);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if n.extras().type_outlines {
|
||||
return;
|
||||
}
|
||||
if let NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } = &mut n.kind {
|
||||
for c in children.iter_mut() {
|
||||
if matches!(c.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } | NodeKind::Group { .. } | NodeKind::Layer { .. }) {
|
||||
rebase_leaves(Arc::make_mut(c), before);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Map the placed gradients of `ap` from box `from` to box `to` through the map that takes one box
|
||||
/// onto the other (strokes: their stroke-inflated boxes). The start and end go where
|
||||
/// [`Appearance::rebase_gradients`] puts them, and a radial's ellipse and a linear's isolines are
|
||||
/// mapped with them.
|
||||
fn follow_boxes(ap: &mut Appearance, from: Rect, to: Rect) {
|
||||
pub(crate) fn follow_boxes(ap: &mut Appearance, from: Rect, to: Rect) {
|
||||
for i in &mut ap.items {
|
||||
match i {
|
||||
AppearanceItem::Fill(f) => {
|
||||
@@ -1031,11 +1431,19 @@ fn copy_placed(n: &mut Node, m: Affine, copies: usize, room: &mut usize) {
|
||||
let src = (**c).clone();
|
||||
let placed = |xf: Affine| {
|
||||
let mut one = src.clone();
|
||||
// Gradients fitted to it are fixed to their fit first when a refit would not match.
|
||||
if crate::geometry::fixes_fit(xf) {
|
||||
one.pin_gradients();
|
||||
}
|
||||
match &mut one.kind {
|
||||
NodeKind::Image(im) => im.xf = xf * im.xf,
|
||||
NodeKind::SymbolInstance { xf: at, .. } => *at = xf * *at,
|
||||
_ => {}
|
||||
}
|
||||
// The placed gradients of its own fills and strokes move with it, as a path's do.
|
||||
if xf != Affine::IDENTITY && one.appearance.has_positioned_gradient() {
|
||||
one.appearance.transform_gradients(xf);
|
||||
}
|
||||
one
|
||||
};
|
||||
if copies == 0 {
|
||||
@@ -1069,14 +1477,21 @@ fn placed_count(n: &Node) -> usize {
|
||||
/// `n` with type anywhere inside it outlined and live objects evaluated, so geometry effects on
|
||||
/// it reach every member.
|
||||
pub(crate) fn outlined_members(doc: Option<&Document>, n: &Node) -> Node {
|
||||
outlined_members_with(doc, n, &outline_text, &SymbolNodes::default())
|
||||
outlined_members_with(doc, doc, n, &outline_text, &SymbolNodes::default())
|
||||
}
|
||||
|
||||
/// [`outlined_members`] with live objects and symbol instances given as art through `outline`
|
||||
/// ([`evaluated_with`]).
|
||||
pub(crate) fn outlined_members_with(doc: Option<&Document>, n: &Node, outline: OutlineHook, nodes: &SymbolNodes) -> Node {
|
||||
let mut art = evaluated_with(doc, n, outline, nodes);
|
||||
outline_nested_text(&mut art, false);
|
||||
/// ([`evaluated_with`]), with the symbols of the art from `symbols` and the swatches and patterns
|
||||
/// of painted pieces looked up in `paint_doc`.
|
||||
pub(crate) fn outlined_members_with(
|
||||
symbols: Option<&Document>,
|
||||
paint_doc: Option<&Document>,
|
||||
n: &Node,
|
||||
outline: OutlineHook,
|
||||
nodes: &SymbolNodes,
|
||||
) -> Node {
|
||||
let mut art = evaluated_with(symbols, n, outline, nodes);
|
||||
outline_nested_text(paint_doc, &mut art, false);
|
||||
art
|
||||
}
|
||||
|
||||
|
||||
@@ -66,19 +66,25 @@ pub fn revolve_options(p: &Value) -> Revolve {
|
||||
/// Validate before a command mutates the document. Loading external files is still bounded
|
||||
/// by the evaluator; unsupported source kinds remain unchanged when rendered.
|
||||
pub fn validate_revolve(n: &Node, p: &Value) -> Result<(), String> {
|
||||
crate::lighting::validate(p)?;
|
||||
validate_revolve_params(p)?;
|
||||
let path = profile(n).ok_or("Revolve currently requires a path or compound path. Select a profile drawn with the Pen tool.")?;
|
||||
let b = path.bounds().ok_or("Revolve requires a profile with at least two anchors")?;
|
||||
if !path.subpaths.iter().any(|sp| sp.anchors.len() >= 2) {
|
||||
return Err("Revolve requires at least two anchors".into());
|
||||
}
|
||||
vectorcraft_three_d::revolve(&path, b, revolve_options(p)).map(|_| ())
|
||||
}
|
||||
|
||||
/// Check Revolve's parameter values `p` alone: its lights, `edge` and `cap`.
|
||||
pub(crate) fn validate_revolve_params(p: &Value) -> Result<(), String> {
|
||||
crate::lighting::validate(p)?;
|
||||
if p.get("edge").is_some_and(|v| v.as_str() != Some("left") && v.as_str() != Some("right")) {
|
||||
return Err("Revolve edge must be left or right".into());
|
||||
}
|
||||
if p.get("cap").is_some_and(|v| v.as_bool().is_none()) {
|
||||
return Err("Revolve cap must be a boolean".into());
|
||||
}
|
||||
vectorcraft_three_d::revolve(&path, b, revolve_options(p)).map(|_| ())
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn profile(n: &Node) -> Option<PathData> {
|
||||
@@ -226,6 +232,48 @@ pub(crate) fn expand_revolve_art(n: &Node) -> Option<Node> {
|
||||
art(n, true)
|
||||
}
|
||||
|
||||
/// The surfaces [`revolve_art`] draws, as meshes ([`crate::three_d_meshes`]): with the effect on
|
||||
/// the object, one in its top visible fill (else its stroke); with it on fills and strokes, one for
|
||||
/// each of them. Each mesh adds its triangles to `total` as it is built, and the first that takes
|
||||
/// `total` past `limit` stops with an error before the next is built.
|
||||
pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::SolidMesh>, String> {
|
||||
let path = profile(n).ok_or("Revolve currently requires a path or compound path")?;
|
||||
let ctx = GeomContext::of(n);
|
||||
let mesh = |path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result<crate::SolidMesh, String> {
|
||||
let b = path.bounds().ok_or("Revolve requires a profile with at least two anchors")?;
|
||||
let (paint, opacity, _) = paint_of(item);
|
||||
let mesh = vectorcraft_three_d::revolve_mesh(path, b, revolve_options(&merged_params(REVOLVE, &fx.params)))?;
|
||||
Ok(crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity) })
|
||||
};
|
||||
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE) {
|
||||
let before = n.appearance.effects.get(..index).unwrap_or_default();
|
||||
let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) };
|
||||
let path = geometry(&path, before, &ctx);
|
||||
let item = n
|
||||
.appearance
|
||||
.items
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|i| matches!(i, AppearanceItem::Fill(_)) && crate::paints(i))
|
||||
.or_else(|| n.appearance.items.iter().rev().find(|i| crate::paints(i)))
|
||||
.ok_or("the revolved object has no fill or stroke")?;
|
||||
let mut out = vec![];
|
||||
crate::solids::keep_mesh(&mut out, total, mesh(&path, fx, item)?, limit)?;
|
||||
return Ok(out);
|
||||
}
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
let mut out = vec![];
|
||||
for item in n.appearance.items.iter().filter(|i| crate::paints(i)) {
|
||||
if let Some(index) = item.effects().iter().position(|e| e.visible && e.id == REVOLVE)
|
||||
&& let Some(fx) = item.effects().get(index)
|
||||
{
|
||||
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
|
||||
crate::solids::keep_mesh(&mut out, total, mesh(&p, fx, item)?, limit)?;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn art(n: &Node, expand: bool) -> Option<Node> {
|
||||
if !has_revolve(n) {
|
||||
return None;
|
||||
@@ -434,7 +482,7 @@ mod tests {
|
||||
let expanded = expand_revolve_art(&n).unwrap();
|
||||
let count = |n: &Node| n.children().unwrap()[0].children().unwrap().len();
|
||||
assert!(count(&expanded) < count(&live) * 3 / 4, "hidden back surfaces are removed");
|
||||
assert_eq!(crate::bake_appearance(&n), Some(live.clone()), "other baking retains the full surface");
|
||||
assert_eq!(crate::bake_appearance(None, &n), Some(live.clone()), "other baking retains the full surface");
|
||||
n.appearance.effects[0].params["expandVisibleOnly"] = json!(false);
|
||||
assert_eq!(revolve_art(&n), Some(live.clone()), "the live view ignores the expansion setting");
|
||||
assert_eq!(expand_revolve_art(&n), Some(live));
|
||||
|
||||
+231
-31
@@ -1,12 +1,12 @@
|
||||
//! Extrude & Bevel, Inflate and Rotate as live, shaded vector art, shared by the canvas and every
|
||||
//! exporter. Like Revolve, the source path stays editable and the effect draws its 3D faces.
|
||||
//! Extrude & Bevel, Inflate, Rotate and Extrude & Bevel (Classic) as live, shaded vector art,
|
||||
//! shared by the canvas and every exporter. Like Revolve, the source path stays editable and the effect draws its 3D faces.
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Effect, Node, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{FillRule, PathData, Rect};
|
||||
use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, View};
|
||||
use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, View};
|
||||
|
||||
#[cfg(test)]
|
||||
use vectorcraft_doc::color::Color;
|
||||
@@ -14,11 +14,14 @@ use vectorcraft_doc::color::Color;
|
||||
use crate::util::{flag, num, text};
|
||||
use crate::{GeomContext, apply_geometry_with, is_geometry};
|
||||
|
||||
mod classic;
|
||||
pub use classic::{CLASSIC_EXTRUDE, SHADING_COLORS, classic_extrude_options, classic_shading};
|
||||
|
||||
pub const EXTRUDE: &str = "threeD.extrude";
|
||||
pub const INFLATE: &str = "threeD.inflate";
|
||||
pub const ROTATE: &str = "threeD.rotate";
|
||||
/// The 3D effects this module draws (Revolve has its own).
|
||||
pub const SOLIDS: [&str; 3] = [EXTRUDE, INFLATE, ROTATE];
|
||||
pub const SOLIDS: [&str; 4] = [EXTRUDE, INFLATE, ROTATE, CLASSIC_EXTRUDE];
|
||||
|
||||
/// Is `id` one of the 3D and Materials effects (Revolve included)?
|
||||
pub fn is_three_d(id: &str) -> bool {
|
||||
@@ -119,6 +122,7 @@ pub fn extrude_options(p: &Value) -> Extrude {
|
||||
inside: flag(p, "bevelInside", false),
|
||||
both_sides: flag(p, "bevelBothSides", false),
|
||||
}),
|
||||
hidden: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,21 +176,32 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) ->
|
||||
let view = view_options(p);
|
||||
match id {
|
||||
EXTRUDE => vectorcraft_three_d::extrude(path, rule, bounds, extrude_options(p), view),
|
||||
CLASSIC_EXTRUDE => vectorcraft_three_d::extrude(path, rule, bounds, classic_extrude_options(p), view),
|
||||
INFLATE => vectorcraft_three_d::inflate(path, rule, bounds, inflate_options(p), view),
|
||||
_ => vectorcraft_three_d::plane(path, rule, bounds, view),
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate before a command changes the document; the evaluator bounds loaded files too.
|
||||
pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> {
|
||||
/// Check solid `id`'s parameter values `p` alone: the part of [`validate_solid`] that does not
|
||||
/// need the object.
|
||||
fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> {
|
||||
if id == CLASSIC_EXTRUDE {
|
||||
classic::validate(p)?;
|
||||
}
|
||||
crate::lighting::validate(p)?;
|
||||
let label = crate::effect_info(id).map_or("This effect", |e| e.label.trim_end_matches('…'));
|
||||
if let Some(v) = p.get("bevel")
|
||||
&& !v.as_str().is_some_and(|s| s == "none" || BevelShape::parse(s).is_some())
|
||||
{
|
||||
let names: Vec<_> = BevelShape::ALL.iter().map(|b| b.id()).collect();
|
||||
return Err(format!("bevel must be none or one of {}", names.join(", ")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate before a command changes the document; the evaluator bounds loaded files too.
|
||||
pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> {
|
||||
validate_solid_params(id, p)?;
|
||||
let label = crate::effect_info(id).map_or("This effect", |e| e.label.trim_end_matches('…'));
|
||||
if is_container(n) {
|
||||
let shapes = members(n, label)?;
|
||||
let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?;
|
||||
@@ -221,6 +236,10 @@ fn union_bounds(shapes: &[Profile]) -> Option<Rect> {
|
||||
/// The most members a 3D effect on a group builds solids from.
|
||||
const MAX_MEMBERS: usize = 4096;
|
||||
|
||||
/// The most triangles the meshes of one 3D effect hold together (about 290 MB of corners and
|
||||
/// normals): past it the object is too complex to export.
|
||||
const MAX_MESH_TRIANGLES: usize = 2_000_000;
|
||||
|
||||
/// The shapes a 3D effect on group or layer `n` builds its solids from: every visible path,
|
||||
/// compound path and type in it, at any depth of its groups, each through its own geometry
|
||||
/// effects and painted with its own fills and strokes. Like the effect on a group in the
|
||||
@@ -269,6 +288,13 @@ pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> {
|
||||
if id == crate::REVOLVE { crate::validate_revolve(n, p) } else { validate_solid(n, id, p) }
|
||||
}
|
||||
|
||||
/// Are 3D effect `id`'s parameter values `p` valid? The checks of [`validate_three_d`] that do not
|
||||
/// build the art, for an edit that hides the effect: hidden, it draws nothing, so its object does
|
||||
/// not need to fit.
|
||||
pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> {
|
||||
if id == crate::REVOLVE { crate::revolve::validate_revolve_params(p) } else { validate_solid_params(id, p) }
|
||||
}
|
||||
|
||||
/// One surface: each facet a path shaded from `paint`, as a group with the paint's opacity and
|
||||
/// blend mode (so overlapping facets don't add up their transparency).
|
||||
fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool) -> Node {
|
||||
@@ -338,6 +364,38 @@ fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData,
|
||||
}
|
||||
}
|
||||
|
||||
/// The parts Extrude & Bevel and Inflate build solids from: each shape's top fill and its strokes,
|
||||
/// a group's members from the back up, each with its shape's opacity and the region it paints.
|
||||
/// The solids share the bounds of all their parts (`fallback` when none has any): one center to
|
||||
/// turn, twist and taper about, and Inflate's grid reaches over the strokes' outlines.
|
||||
fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<(&AppearanceItem, f32, PathData, FillRule)>, Rect) {
|
||||
let parts: Vec<(&AppearanceItem, f32, PathData, FillRule)> = shapes
|
||||
.iter()
|
||||
.flat_map(|s| {
|
||||
let top_fill = s.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_)));
|
||||
s.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(|(_, i)| {
|
||||
let (area, rule) = region(&s.path, s.rule, i);
|
||||
(i, s.opacity, area, rule)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let bounds = parts.iter().filter_map(|(_, _, area, _)| area.bounds()).reduce(|a, c| a.union(c)).unwrap_or(fallback);
|
||||
(parts, bounds)
|
||||
}
|
||||
|
||||
/// `shapes`, the members of group or layer `n`, reshaped by the visible geometry effects `before`
|
||||
/// its 3D effect, about the bounds of all of them.
|
||||
fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile]) {
|
||||
if before.iter().any(|e| e.visible && is_geometry(&e.id))
|
||||
&& let Some(b) = union_bounds(shapes)
|
||||
{
|
||||
let ctx = GeomContext::of(n);
|
||||
for s in shapes {
|
||||
s.path = apply_geometry_with(before, &s.path, b, &ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The 3D art of one effect `fx` on `path` (already through the effects before it).
|
||||
/// Rotate turns every fill and stroke, each in its own paint. Extrude & Bevel and Inflate build a
|
||||
/// solid from the path for the top visible fill and one from the outline of each visible stroke,
|
||||
@@ -348,7 +406,8 @@ fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData,
|
||||
fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
|
||||
let b = union_bounds(shapes)?;
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let colored = view_options(&p).has_colored_lights();
|
||||
let classic = fx.id == CLASSIC_EXTRUDE;
|
||||
let colored = !classic && view_options(&p).has_colored_lights();
|
||||
if fx.id == ROTATE {
|
||||
// Every part turns about the centre of the object's own bounds (a group's members about
|
||||
// the centre of theirs), so they stay together.
|
||||
@@ -363,20 +422,7 @@ fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>>
|
||||
}
|
||||
return Some(out);
|
||||
}
|
||||
// Each shape's top fill and its strokes, a group's members from the back up.
|
||||
let parts: Vec<(&AppearanceItem, f32, PathData, FillRule)> = shapes
|
||||
.iter()
|
||||
.flat_map(|s| {
|
||||
let top_fill = s.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_)));
|
||||
s.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(|(_, i)| {
|
||||
let (area, rule) = region(&s.path, s.rule, i);
|
||||
(i, s.opacity, area, rule)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
// The solids share the bounds of all their shapes: one center to turn, twist and taper about,
|
||||
// and Inflate's grid reaches over the strokes' outlines.
|
||||
let bounds = parts.iter().filter_map(|(_, _, area, _)| area.bounds()).reduce(|a, c| a.union(c)).unwrap_or(b);
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
let built = if fx.id == INFLATE {
|
||||
// One eye for every puff, as far away as the highest needs.
|
||||
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule)| (area, *rule)).collect();
|
||||
@@ -409,7 +455,8 @@ fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>>
|
||||
.map(|(item, member, f)| {
|
||||
let depths: Vec<f64> = f.iter().map(|f| f.depth).collect();
|
||||
let (paint, opacity, blend) = paint_of(item, member);
|
||||
(depths, surface(n, f, &paint, opacity, blend, colored))
|
||||
let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) };
|
||||
(depths, art)
|
||||
})
|
||||
.collect();
|
||||
// One order takes a plain group of faces from each solid, one face for each facet. With
|
||||
@@ -493,14 +540,7 @@ pub fn solid_art(n: &Node) -> Option<Node> {
|
||||
fn group_solid_art(n: &Node) -> Option<Node> {
|
||||
let (index, fx) = solid(&n.appearance.effects)?;
|
||||
let mut shapes = members(n, "").ok()?;
|
||||
let before = n.appearance.effects.get(..index)?;
|
||||
if before.iter().any(|e| e.visible && is_geometry(&e.id)) {
|
||||
let b = union_bounds(&shapes)?;
|
||||
let ctx = GeomContext::of(n);
|
||||
for s in &mut shapes {
|
||||
s.path = apply_geometry_with(before, &s.path, b, &ctx);
|
||||
}
|
||||
}
|
||||
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
|
||||
let children = art_for(n, fx, &shapes)?;
|
||||
let remaining =
|
||||
n.appearance.effects.iter().enumerate().filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index)).map(|(_, e)| e.clone()).collect();
|
||||
@@ -510,5 +550,165 @@ fn group_solid_art(n: &Node) -> Option<Node> {
|
||||
Some(art)
|
||||
}
|
||||
|
||||
/// One solid of a 3D object as a mesh, with the color it is painted.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SolidMesh {
|
||||
pub mesh: Mesh,
|
||||
/// The paint's display color (sRGB, 0..1) and its opacity: a gradient's stops averaged, gray
|
||||
/// for a pattern.
|
||||
pub color: [f32; 4],
|
||||
}
|
||||
|
||||
/// The color a mesh of `paint` at `opacity` takes ([`SolidMesh::color`]).
|
||||
pub(crate) fn mesh_color(paint: &Paint, opacity: f32) -> [f32; 4] {
|
||||
let (rgb, alpha) = match paint {
|
||||
Paint::Solid { color, .. } => (color.to_rgb(), 1.0),
|
||||
Paint::Gradient(g) if !g.gradient.stops.is_empty() => {
|
||||
let n = g.gradient.stops.len() as f32;
|
||||
let mut sum = [0.0f32; 4];
|
||||
for s in &g.gradient.stops {
|
||||
let [r, gr, b] = s.color.to_rgb();
|
||||
sum = [sum[0] + r, sum[1] + gr, sum[2] + b, sum[3] + s.opacity];
|
||||
}
|
||||
([sum[0] / n, sum[1] / n, sum[2] / n], sum[3] / n)
|
||||
}
|
||||
_ => ([0.5; 3], 1.0),
|
||||
};
|
||||
let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
[unit(rgb[0]), unit(rgb[1]), unit(rgb[2]), unit(alpha * opacity)]
|
||||
}
|
||||
|
||||
/// Add `mesh` to `out`, counting its triangles into `total`, or an error when that passes `limit`.
|
||||
pub(crate) fn keep_mesh(out: &mut Vec<SolidMesh>, total: &mut usize, mesh: SolidMesh, limit: usize) -> Result<(), String> {
|
||||
*total = total.saturating_add(mesh.mesh.triangles.len());
|
||||
if *total > limit {
|
||||
return Err("The 3D object is too complex to export".into());
|
||||
}
|
||||
out.push(mesh);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The solids effect `fx` builds from `shapes`, as [`art_for`] draws them, as meshes: Rotate turns
|
||||
/// every fill and stroke; Extrude & Bevel and Inflate build one from each shape's top fill and one
|
||||
/// from the outline of each stroke. A stroke whose solid is past the limits is left out. Each mesh
|
||||
/// is counted against `limit` ([`keep_mesh`]) before the next is built.
|
||||
fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) -> Result<Vec<SolidMesh>, String> {
|
||||
let label = crate::effect_info(&fx.id).map_or("This effect", |e| e.label.trim_end_matches('…'));
|
||||
let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?;
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let view = view_options(&p);
|
||||
let mut out = vec![];
|
||||
let mut keep = |out: &mut Vec<SolidMesh>, mesh: Mesh, color: [f32; 4]| keep_mesh(out, total, SolidMesh { mesh, color }, limit);
|
||||
if fx.id == ROTATE {
|
||||
for s in shapes {
|
||||
for item in &s.items {
|
||||
let (paint, opacity, _) = paint_of(item, s.opacity);
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, mesh_color(&paint, opacity))?;
|
||||
}
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
// Inflate lays out every puff at once (they share one eye); each Inflate and Extrude & Bevel
|
||||
// solid and its mesh are built as the loop reaches them.
|
||||
let mut inflated = (fx.id == INFLATE).then(|| {
|
||||
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule)| (area, *rule)).collect();
|
||||
vectorcraft_three_d::inflate_meshes(&shapes, bounds, inflate_options(&p), view)
|
||||
});
|
||||
let extrude = extrude_options(&p);
|
||||
for (item, member, area, rule) in &parts {
|
||||
let item: &AppearanceItem = item;
|
||||
let mesh = match inflated.as_mut() {
|
||||
Some(built) => built.next().unwrap_or_else(|| Ok(Mesh::default())),
|
||||
None => vectorcraft_three_d::extrude_mesh(area, *rule, bounds, extrude, view),
|
||||
};
|
||||
match mesh {
|
||||
Ok(mesh) => {
|
||||
let (paint, opacity, _) = paint_of(item, *member);
|
||||
keep(&mut out, mesh, mesh_color(&paint, opacity))?;
|
||||
}
|
||||
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The solids `n`'s Extrude & Bevel, Inflate, Rotate or Revolve effect builds, as meshes with the
|
||||
/// colors they are painted ([`SolidMesh`]), faces turned away from the viewer included; meshes
|
||||
/// with no triangles are left out. On a group or layer, the effect's solids of its members
|
||||
/// ([`members`]). The object's opacity multiplies every color's. An error when `n` carries no
|
||||
/// such effect, its solids can't be built, none has a triangle, or together they have more than
|
||||
/// [`MAX_MESH_TRIANGLES`].
|
||||
pub fn three_d_meshes(n: &Node) -> Result<Vec<SolidMesh>, String> {
|
||||
meshes_within(n, &mut 0, MAX_MESH_TRIANGLES)
|
||||
}
|
||||
|
||||
/// The meshes of every object in `nodes` ([`three_d_meshes`]), in order, as one 3D asset exports
|
||||
/// them: the objects share one budget of [`MAX_MESH_TRIANGLES`].
|
||||
pub fn three_d_meshes_of<'a>(nodes: impl IntoIterator<Item = &'a Node>) -> Result<Vec<SolidMesh>, String> {
|
||||
meshes_of_within(nodes, MAX_MESH_TRIANGLES)
|
||||
}
|
||||
|
||||
/// [`three_d_meshes_of`] with a budget of `limit` triangles.
|
||||
fn meshes_of_within<'a>(nodes: impl IntoIterator<Item = &'a Node>, limit: usize) -> Result<Vec<SolidMesh>, String> {
|
||||
let mut total = 0usize;
|
||||
let mut out = vec![];
|
||||
for n in nodes {
|
||||
out.extend(meshes_within(n, &mut total, limit)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// [`three_d_meshes`], with the triangles of every solid added to `total` as it is built and an
|
||||
/// error as soon as `total` passes `limit`.
|
||||
fn meshes_within(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<SolidMesh>, String> {
|
||||
let meshes = if crate::has_revolve(n) {
|
||||
crate::revolve::revolve_meshes(n, total, limit)?
|
||||
} else if !has_solid(n) {
|
||||
return Err("the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate)".into());
|
||||
} else if is_container(n) {
|
||||
let (index, fx) = solid(&n.appearance.effects).ok_or("a 3D effect on a group's fill or stroke draws nothing to export")?;
|
||||
let label = crate::effect_info(&fx.id).map_or("This effect", |e| e.label.trim_end_matches('…'));
|
||||
let mut shapes = members(n, label)?;
|
||||
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
|
||||
meshes_for(fx, &shapes, total, limit)?
|
||||
} else {
|
||||
let (path, rule) = profile(n).ok_or("3D export needs a path, compound path, type or group")?;
|
||||
let ctx = GeomContext::of(n);
|
||||
let paints = solid_paints(n);
|
||||
if let Some((index, fx)) = solid(&n.appearance.effects) {
|
||||
let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx);
|
||||
meshes_for(fx, &[Profile { path, rule, items: paints, opacity: 1.0 }], total, limit)?
|
||||
} else {
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
let mut out = vec![];
|
||||
for item in &paints {
|
||||
if let Some((index, fx)) = solid(item.effects()) {
|
||||
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
|
||||
out.extend(meshes_for(fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0 }], total, limit)?);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
};
|
||||
let meshes: Vec<SolidMesh> = meshes
|
||||
.into_iter()
|
||||
.filter(|m| !m.mesh.is_empty())
|
||||
.map(|mut m| {
|
||||
m.color[3] *= n.opacity.clamp(0.0, 1.0);
|
||||
m
|
||||
})
|
||||
.collect();
|
||||
if meshes.is_empty() {
|
||||
return Err("its 3D effect builds no solid".into());
|
||||
}
|
||||
Ok(meshes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_mesh;
|
||||
@@ -0,0 +1,220 @@
|
||||
//! Extrude & Bevel (Classic): the solid Extrude & Bevel builds from a path, drawn with the classic
|
||||
//! surfaces (Wireframe, No Shading, Diffuse and Plastic), their highlight, blend steps and shading
|
||||
//! color.
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node, StrokeLayer};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_three_d::{Bevel, BevelShape, ClassicShading, ClassicSurface, Extrude, Facet, Light};
|
||||
|
||||
use crate::util::{flag, num, text};
|
||||
|
||||
pub const CLASSIC_EXTRUDE: &str = "threeD.classicExtrude";
|
||||
|
||||
/// The width of a Wireframe edge, in points.
|
||||
const WIRE: f64 = 0.5;
|
||||
|
||||
/// The Shading Color choices: black, a custom color, or none.
|
||||
pub const SHADING_COLORS: [&str; 3] = ["black", "custom", "none"];
|
||||
|
||||
/// The surface settings of Extrude & Bevel (Classic)'s parameters.
|
||||
pub fn classic_shading(p: &Value) -> ClassicShading {
|
||||
let d = ClassicShading::default();
|
||||
ClassicShading {
|
||||
surface: ClassicSurface::parse(text(p, "surface", "plastic")).unwrap_or_default(),
|
||||
ambient: num(p, "ambient", d.ambient * 100.0) / 100.0,
|
||||
highlight_intensity: num(p, "highlightIntensity", d.highlight_intensity * 100.0) / 100.0,
|
||||
highlight_size: num(p, "highlightSize", d.highlight_size * 100.0) / 100.0,
|
||||
blend_steps: num(p, "blendSteps", f64::from(d.blend_steps)).round().clamp(1.0, 256.0) as u32,
|
||||
}
|
||||
}
|
||||
|
||||
/// The solid of Extrude & Bevel (Classic)'s parameters: its depth, cap and bevel (as tall as it is
|
||||
/// wide, added around the shape or carved into it), with the faces turned away from the viewer kept
|
||||
/// for Draw Hidden Faces and for the Wireframe surface.
|
||||
pub fn classic_extrude_options(p: &Value) -> Extrude {
|
||||
let height = num(p, "bevelHeight", 4.0);
|
||||
Extrude {
|
||||
depth: num(p, "depth", 50.0),
|
||||
cap: flag(p, "cap", true),
|
||||
bevel: BevelShape::parse(text(p, "bevel", "none")).map(|shape| Bevel {
|
||||
shape,
|
||||
width: height,
|
||||
height,
|
||||
inside: flag(p, "bevelInside", false),
|
||||
..Bevel::default()
|
||||
}),
|
||||
hidden: flag(p, "drawHiddenFaces", false) || classic_shading(p).surface == ClassicSurface::Wireframe,
|
||||
..Extrude::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The color faces darken toward: black, the custom color, or none (faces keep their paint and only
|
||||
/// the highlight lightens them).
|
||||
fn shading_color(p: &Value) -> Option<Color> {
|
||||
match text(p, "shadingColor", "black") {
|
||||
"none" => None,
|
||||
"custom" => Some(p.get("shadingCustom").and_then(Value::as_str).and_then(parse_hex).unwrap_or(Color::BLACK)),
|
||||
_ => Some(Color::BLACK),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_hex(s: &str) -> Option<Color> {
|
||||
(s.len() == 7 && s.starts_with('#') && s.bytes().skip(1).all(|b| b.is_ascii_hexdigit())).then(|| Color::from_hex(s)).flatten()
|
||||
}
|
||||
|
||||
/// The lights: the `lights` list when it is given, else the one light of `lightRotation`,
|
||||
/// `lightHeight`, `lightBehind` and `lightIntensity`. Each is its direction toward the light in view
|
||||
/// space and its intensity (0..1).
|
||||
fn lights(p: &Value) -> Vec<([f64; 3], f64)> {
|
||||
if let Some(list) = crate::lighting::lights(p) {
|
||||
return list.iter().map(|l| (l.direction(), l.intensity)).collect();
|
||||
}
|
||||
let light = Light {
|
||||
rotation: num(p, "lightRotation", vectorcraft_three_d::DEFAULT_LIGHT.0),
|
||||
height: num(p, "lightHeight", vectorcraft_three_d::DEFAULT_LIGHT.1),
|
||||
behind: flag(p, "lightBehind", false),
|
||||
..Light::default()
|
||||
};
|
||||
vec![(light.direction(), num(p, "lightIntensity", 100.0) / 100.0)]
|
||||
}
|
||||
|
||||
/// The numeric parameters: (key, lowest, highest, whole numbers only).
|
||||
const RANGES: [(&str, f64, f64, bool); 13] = [
|
||||
("depth", 0.0, 2000.0, false),
|
||||
("bevelHeight", 1.0, 100.0, false),
|
||||
("rotationX", -180.0, 180.0, false),
|
||||
("rotationY", -180.0, 180.0, false),
|
||||
("rotationZ", -180.0, 180.0, false),
|
||||
("perspectiveAngle", 0.0, 160.0, false),
|
||||
("lightRotation", -180.0, 180.0, false),
|
||||
("lightHeight", 0.0, 90.0, false),
|
||||
("lightIntensity", 0.0, 100.0, false),
|
||||
("ambient", 0.0, 100.0, false),
|
||||
("highlightIntensity", 0.0, 100.0, false),
|
||||
("highlightSize", 0.0, 100.0, false),
|
||||
("blendSteps", 1.0, 256.0, true),
|
||||
];
|
||||
|
||||
const FLAGS: [&str; 4] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces"];
|
||||
|
||||
/// 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
|
||||
/// `shadingCustom` name a surface, a shading color and a #rrggbb color.
|
||||
pub fn validate(p: &Value) -> Result<(), String> {
|
||||
let Some(map) = p.as_object() else { return Ok(()) };
|
||||
let defaults = crate::default_params(CLASSIC_EXTRUDE).unwrap_or(Value::Null);
|
||||
let known: Vec<&str> = defaults.as_object().map(|m| m.keys().map(String::as_str).collect()).unwrap_or_default();
|
||||
for key in map.keys() {
|
||||
if !known.contains(&key.as_str()) {
|
||||
let keys = known.join(", ");
|
||||
return Err(format!("unknown parameter `{key}`; the command takes: {keys}"));
|
||||
}
|
||||
}
|
||||
for (key, min, max, whole) in RANGES {
|
||||
let Some(v) = map.get(key) else { continue };
|
||||
let Some(x) = v.as_f64() else { return Err(format!("`{key}` must be a number")) };
|
||||
if whole && (x.fract() != 0.0 || !(min..=max).contains(&x)) {
|
||||
return Err(format!("`{key}` must be a whole number between {min} and {max} (got {x})"));
|
||||
}
|
||||
if !(min..=max).contains(&x) {
|
||||
return Err(format!("`{key}` must be between {min} and {max} (got {x})"));
|
||||
}
|
||||
}
|
||||
for key in FLAGS {
|
||||
if map.get(key).is_some_and(|v| !v.is_boolean()) {
|
||||
return Err(format!("`{key}` must be true or false"));
|
||||
}
|
||||
}
|
||||
let one_of = |key: &str, ids: &[&str]| -> Result<(), String> {
|
||||
match map.get(key) {
|
||||
Some(v) if !v.as_str().is_some_and(|s| ids.contains(&s)) => Err(format!("`{key}` must be one of {}", ids.join(", "))),
|
||||
_ => Ok(()),
|
||||
}
|
||||
};
|
||||
let surfaces: Vec<&str> = ClassicSurface::ALL.iter().map(|s| s.id()).collect();
|
||||
one_of("surface", &surfaces)?;
|
||||
one_of("shadingColor", &SHADING_COLORS)?;
|
||||
let key = "shadingCustom";
|
||||
if map.get(key).is_some_and(|v| !v.as_str().is_some_and(|s| parse_hex(s).is_some())) {
|
||||
return Err(format!("`{key}` must be a #rrggbb color"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `c` with tone `tone` (0 the shading color, 1 the color itself) and highlight `spec` (toward
|
||||
/// white) on top.
|
||||
fn shaded(c: Color, tone: f64, spec: f64, shade: Option<Color>) -> Color {
|
||||
let base = c.to_rgb();
|
||||
let dark = shade.map_or(base, |s| s.to_rgb());
|
||||
let (tone, spec) = (tone as f32, spec as f32);
|
||||
let [r, g, b] = [0, 1, 2].map(|i| {
|
||||
let mixed = dark[i] + (base[i] - dark[i]) * tone;
|
||||
(mixed + (1.0 - mixed) * spec).clamp(0.0, 1.0)
|
||||
});
|
||||
Color::rgb(r, g, b)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub(super) 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 wire = shading.surface == ClassicSurface::Wireframe;
|
||||
let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_paint(source) };
|
||||
let paint = &paint;
|
||||
let children = facets
|
||||
.into_iter()
|
||||
.map(|face| {
|
||||
if wire {
|
||||
let mut edge = StrokeLayer::new(paint.clone(), WIRE);
|
||||
edge.join = vectorcraft_doc::LineJoin::Round;
|
||||
return Arc::new(Node::path(n.id, face.path(), Appearance { items: vec![AppearanceItem::Stroke(edge)], ..Default::default() }));
|
||||
}
|
||||
let (tone, spec) = shading.tone(face.normal, &lights);
|
||||
// A narrow stroke of the face's own paint closes the hairline seams between faces.
|
||||
let seam = (face.thickness() / 2.0).clamp(0.05, 0.75);
|
||||
let items = match paint.color() {
|
||||
// Unshaded (No Shading, no shading color, or a face in full light) with no
|
||||
// highlight: the paint itself, its color space and swatch kept.
|
||||
Some(_) if (tone >= 1.0 || shade.is_none()) && spec <= 0.0 => {
|
||||
vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(StrokeLayer::new(paint.clone(), seam))]
|
||||
}
|
||||
Some(c) => {
|
||||
let fill = Paint::solid(shaded(c, tone, spec, shade));
|
||||
vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(StrokeLayer::new(fill, seam))]
|
||||
}
|
||||
// Gradients and patterns keep their paint, darkened by a layer of the shading color
|
||||
// and lightened by one of white. As with the other 3D effects' pattern shadow, the
|
||||
// layers cover the whole face, transparent pattern cells included.
|
||||
None => {
|
||||
let mut items =
|
||||
vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(StrokeLayer::new(paint.clone(), seam))];
|
||||
for (color, share) in [(shade, 1.0 - tone), (Some(Color::WHITE), spec)] {
|
||||
if let Some(color) = color.filter(|_| share > 0.0) {
|
||||
let mut layer = FillLayer::new(Paint::solid(color));
|
||||
layer.opacity = share as f32;
|
||||
items.push(AppearanceItem::Fill(layer));
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
};
|
||||
Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() }))
|
||||
})
|
||||
.collect();
|
||||
let mut group = Node::group(n.id, children);
|
||||
group.opacity = opacity;
|
||||
group.blend = blend;
|
||||
if let Some(mask) = mask {
|
||||
let bounds = group.visual_bounds().unwrap_or(Rect::ZERO).inflate(1.0, 1.0);
|
||||
let coverage = Node::path(n.id, vectorcraft_geom::shapes::rectangle(bounds), Appearance::basic(mask, Paint::None, 0.0));
|
||||
group.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(coverage, true)));
|
||||
}
|
||||
group
|
||||
}
|
||||
@@ -45,10 +45,15 @@ fn every_solid_draws_shaded_faces_and_leaves_the_source_editable() {
|
||||
assert_eq!(n.path_data(), Some(&source), "{id}");
|
||||
assert!(!faces(&art).is_empty(), "{id}");
|
||||
// The faces are the fill's red or the stroke's black, shaded: never brighter, never another
|
||||
// hue.
|
||||
// hue. The classic Plastic surface, its default, also lightens a face toward white, which
|
||||
// scales every channel's distance from white by the same factor and so keeps r - g to
|
||||
// r - b at 6 to 7.
|
||||
for f in faces(&art) {
|
||||
let [r, g, b] = fill_rgb(f);
|
||||
assert!(r <= 0.8 + 1e-6 && (g * 4.0 - r).abs() < 1e-4 && (b * 8.0 - r).abs() < 1e-4 || id == ROTATE, "{id}: {r} {g} {b}");
|
||||
let shaded = r <= 0.8 + 1e-6 && (g * 4.0 - r).abs() < 1e-4 && (b * 8.0 - r).abs() < 1e-4;
|
||||
let highlighted =
|
||||
id == CLASSIC_EXTRUDE && [r, g, b].iter().all(|c| (0.0..=1.0).contains(c)) && ((r - g) * 7.0 - (r - b) * 6.0).abs() < 1e-4;
|
||||
assert!(shaded || highlighted || id == ROTATE, "{id}: {r} {g} {b}");
|
||||
}
|
||||
// The art follows the source when it moves.
|
||||
let before = art.visual_bounds().unwrap();
|
||||
@@ -325,7 +330,7 @@ fn export_and_expand_bake_faces_with_their_own_ids() {
|
||||
let mut n = square_node();
|
||||
n.id = d.alloc_id();
|
||||
n.appearance.effects.push(fx(id, json!({"bevel": "rounded"})));
|
||||
assert_eq!(crate::bake_appearance(&n), solid_art(&n), "{id}");
|
||||
assert_eq!(crate::bake_appearance(None, &n), solid_art(&n), "{id}");
|
||||
let mut stroke = |_: &mut Document, _: &PathData, _: FillRule, _: &StrokeLayer| None;
|
||||
let art = crate::expand_leaf(&mut d, &n, &mut stroke).unwrap();
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
@@ -351,7 +356,7 @@ fn a_twisted_tapered_hollow_inflate_exports_and_expands() {
|
||||
let params = json!({"twist": 120, "taper": 50, "cap": false, "bothSides": true, "rotationX": -20, "rotationY": 35});
|
||||
n.appearance.effects.push(fx(INFLATE, params));
|
||||
let art = solid_art(&n).unwrap();
|
||||
assert_eq!(crate::bake_appearance(&n), Some(art.clone()));
|
||||
assert_eq!(crate::bake_appearance(None, &n), Some(art.clone()));
|
||||
assert!(faces(&art).len() > 20, "{} faces", faces(&art).len());
|
||||
let mut stroke = |_: &mut Document, _: &PathData, _: FillRule, _: &StrokeLayer| None;
|
||||
let expanded = crate::expand_leaf(&mut d, &n, &mut stroke).unwrap();
|
||||
@@ -595,3 +600,160 @@ fn a_3d_effect_on_a_group_turns_every_member_about_one_shared_axis() {
|
||||
assert!(err.contains("clipping groups"), "{err}");
|
||||
assert!(solid_art(&g).is_none(), "drawn as the group it is");
|
||||
}
|
||||
|
||||
/// The red square without its stroke, with Extrude & Bevel (Classic) and `params`.
|
||||
fn classic(params: Value) -> Node {
|
||||
let mut n = square_node();
|
||||
n.appearance.items.retain(|i| matches!(i, AppearanceItem::Fill(_)));
|
||||
n.appearance.effects.push(fx(CLASSIC_EXTRUDE, params));
|
||||
n
|
||||
}
|
||||
|
||||
fn classic_faces(params: Value) -> Vec<Node> {
|
||||
let art = solid_art(&classic(params)).unwrap();
|
||||
faces(&art).into_iter().cloned().collect()
|
||||
}
|
||||
|
||||
fn close3(a: [f32; 3], b: [f32; 3]) -> bool {
|
||||
a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-4)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_surfaces_draw_edges_flat_paint_soft_light_and_a_highlight() {
|
||||
// Wireframe: the edges of every face, the hidden ones too, in the paint; no fills.
|
||||
let wire = classic_faces(json!({"surface": "wireframe"}));
|
||||
let plastic = classic_faces(json!({}));
|
||||
assert_eq!(plastic.len(), 3, "a box shows three faces");
|
||||
assert_eq!(wire.len(), 6, "and has six");
|
||||
for f in &wire {
|
||||
let [AppearanceItem::Stroke(s)] = &f.appearance.items[..] else { panic!("a stroke alone: {:?}", f.appearance.items) };
|
||||
assert_eq!(s.paint, Paint::solid(RED));
|
||||
}
|
||||
// No Shading: every face in the art's own paint, a CMYK color kept as it is.
|
||||
assert!(classic_faces(json!({"surface": "none"})).iter().all(|f| close3(fill_rgb(f), RED.to_rgb())));
|
||||
let cmyk = Paint::solid(Color::Cmyk { c: 0.1, m: 0.9, y: 0.8, k: 0.0 });
|
||||
let mut n = classic(json!({"surface": "none"}));
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.paint = cmyk.clone();
|
||||
}
|
||||
for f in faces(&solid_art(&n).unwrap()) {
|
||||
let AppearanceItem::Fill(fill) = &f.appearance.items[0] else { panic!("a fill first") };
|
||||
assert_eq!(fill.paint, cmyk);
|
||||
}
|
||||
// Diffuse: the red darkened toward black by how far each face turns from the light, so the
|
||||
// faces differ but keep their hue.
|
||||
let diffuse: Vec<[f32; 3]> = classic_faces(json!({"surface": "diffuse"})).iter().map(fill_rgb).collect();
|
||||
assert!(diffuse.iter().all(|[r, g, b]| *r <= 0.8 + 1e-6 && (g * 4.0 - r).abs() < 1e-4 && (b * 8.0 - r).abs() < 1e-4), "{diffuse:?}");
|
||||
assert!(diffuse.windows(2).any(|w| !close3(w[0], w[1])), "{diffuse:?}");
|
||||
// Plastic: the same faces, one of them lightened toward white by the highlight.
|
||||
let shiny: Vec<[f32; 3]> =
|
||||
classic_faces(json!({"highlightIntensity": 100, "highlightSize": 100, "lightHeight": 60})).iter().map(fill_rgb).collect();
|
||||
let soft: Vec<[f32; 3]> = classic_faces(json!({"surface": "diffuse", "lightHeight": 60})).iter().map(fill_rgb).collect();
|
||||
assert!(shiny.iter().zip(&soft).any(|(s, d)| s[1] > d[1] + 0.01), "{shiny:?} {soft:?}");
|
||||
assert!(shiny.iter().zip(&soft).all(|(s, d)| s[1] >= d[1] - 1e-4));
|
||||
// Without highlight, Plastic shades as Diffuse.
|
||||
let dull: Vec<[f32; 3]> = classic_faces(json!({"highlightIntensity": 0, "lightHeight": 60})).iter().map(fill_rgb).collect();
|
||||
assert!(dull.iter().zip(&soft).all(|(a, b)| close3(*a, *b)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_shading_color_blend_steps_and_lights() {
|
||||
let base = json!({"surface": "diffuse", "ambient": 20});
|
||||
let with = |extra: Value| {
|
||||
let mut p = base.clone();
|
||||
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
classic_faces(p).iter().map(fill_rgb).collect::<Vec<_>>()
|
||||
};
|
||||
// A custom shading color darkens toward that color; None keeps the paint.
|
||||
assert!(with(json!({"shadingColor": "custom", "shadingCustom": "#0000ff"})).iter().any(|c| c[2] > c[0] / 8.0 + 0.01));
|
||||
assert!(with(json!({"shadingColor": "none"})).iter().all(|c| close3(*c, RED.to_rgb())));
|
||||
// One blend step: every face fully lit or fully in shadow.
|
||||
let stepped = with(json!({"blendSteps": 1, "ambient": 0}));
|
||||
assert!(stepped.iter().all(|c| close3(*c, RED.to_rgb()) || close3(*c, [0.0; 3])), "{stepped:?}");
|
||||
// No light: the ambient share of the red. Two lights add up.
|
||||
let dark = with(json!({"lightIntensity": 0, "blendSteps": 256}));
|
||||
assert!(dark.iter().all(|c| (c[0] - 0.8 * 0.2).abs() < 0.01), "{dark:?}");
|
||||
let one = with(json!({"lights": [{"intensity": 30}], "blendSteps": 256}));
|
||||
let two = with(json!({"lights": [{"intensity": 30}, {"intensity": 30}], "blendSteps": 256}));
|
||||
assert!(one.iter().zip(&two).all(|(a, b)| b[0] >= a[0] - 1e-4) && one.iter().zip(&two).any(|(a, b)| b[0] > a[0] + 0.01));
|
||||
// Draw Hidden Faces keeps the faces turned away, drawn first.
|
||||
assert_eq!(with(json!({"drawHiddenFaces": true})).len(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_bevel_height_extent_and_cap_shape_the_solid() {
|
||||
let bounds = |p: Value| solid_art(&classic(p)).unwrap().visual_bounds().unwrap();
|
||||
let front = json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "bevel": "classic", "bevelHeight": 10});
|
||||
let out = bounds(front.clone());
|
||||
let mut inside = front.clone();
|
||||
inside["bevelInside"] = json!(true);
|
||||
// Straight on, a bevel added around the shape widens it; one carved into it keeps its size.
|
||||
assert!(out.width() > 100.0 + 15.0, "{out:?}");
|
||||
let carved = bounds(inside);
|
||||
assert!((carved.width() - 100.0).abs() < 2.0, "{carved:?}");
|
||||
// Hollow: no caps, so the walls seen from inside show too.
|
||||
assert!(classic_faces(json!({"cap": false})).len() > classic_faces(json!({})).len());
|
||||
// The depth sets how far back the solid goes.
|
||||
let side = json!({"rotationX": 0, "rotationY": 90, "rotationZ": 0});
|
||||
let mut deep = side.clone();
|
||||
deep["depth"] = json!(120);
|
||||
assert!((bounds(deep).width() - 120.0).abs() < 1.0);
|
||||
}
|
||||
|
||||
/// A gradient fill with a transparent stop is shaded opaque and masked by its own transparency, so
|
||||
/// the shading does not cover the transparent part; an opaque gradient needs no mask.
|
||||
#[test]
|
||||
fn classic_shading_keeps_a_gradients_transparency() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
for (end, masked) in [(0.25, true), (1.0, false)] {
|
||||
let mut stop = GradientStop::new(1.0, RED);
|
||||
stop.opacity = end;
|
||||
let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, RED), stop]));
|
||||
let mut n = classic(json!({}));
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.paint = Paint::Gradient(Box::new(gradient));
|
||||
}
|
||||
let art = solid_art(&n).unwrap();
|
||||
let surface = &art.children().unwrap()[0];
|
||||
assert_eq!(surface.extras().mask.is_some(), masked, "{end}");
|
||||
let mut opaque = true;
|
||||
surface.walk(&mut |c| {
|
||||
for item in &c.appearance.items {
|
||||
if let AppearanceItem::Fill(f) = item
|
||||
&& let Paint::Gradient(g) = &f.paint
|
||||
{
|
||||
opaque &= g.gradient.stops.iter().all(|s| s.opacity == 1.0);
|
||||
}
|
||||
}
|
||||
});
|
||||
assert!(opaque, "{end}: the faces are drawn opaque");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_parameters_are_checked() {
|
||||
let n = classic(json!({}));
|
||||
let check = |p: Value| validate_solid(&n, CLASSIC_EXTRUDE, &crate::merged_params(CLASSIC_EXTRUDE, &p));
|
||||
assert!(check(json!({})).is_ok());
|
||||
assert!(check(json!({"surface": "wireframe", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 256, "bevel": "ogee"})).is_ok());
|
||||
for (p, says) in [
|
||||
(json!({"surface": "glossy"}), "`surface` must be one of wireframe, none, diffuse, plastic"),
|
||||
(json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"),
|
||||
(json!({"shadingCustom": "blue"}), "`shadingCustom` must be a #rrggbb color"),
|
||||
(json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"),
|
||||
(json!({"depth": 2001}), "`depth` must be between 0 and 2000 (got 2001)"),
|
||||
(json!({"bevelHeight": 0}), "`bevelHeight` must be between 1 and 100 (got 0)"),
|
||||
(json!({"ambient": -1}), "`ambient` must be between 0 and 100 (got -1)"),
|
||||
(json!({"blendSteps": 2.5}), "`blendSteps` must be a whole number between 1 and 256 (got 2.5)"),
|
||||
(json!({"blendSteps": 0}), "`blendSteps` must be a whole number between 1 and 256 (got 0)"),
|
||||
(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!({"bevel": "fancy"}), "bevel must be none or one of"),
|
||||
(json!({"twist": 10}), "unknown parameter `twist`"),
|
||||
(json!({"lights": []}), "lights must contain one to ten lights"),
|
||||
] {
|
||||
let err = check(p.clone()).unwrap_err();
|
||||
assert!(err.starts_with(says), "{p}: {err}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_doc::color::{Color, Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
use vectorcraft_geom::BezPath;
|
||||
|
||||
use super::*;
|
||||
|
||||
const RED: Color = Color::Rgb { r: 0.8, g: 0.2, b: 0.1 };
|
||||
|
||||
fn square_node(id: u64, x: f64) -> Node {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((x, 100.0));
|
||||
b.line_to((x + 100.0, 100.0));
|
||||
b.line_to((x + 100.0, 200.0));
|
||||
b.line_to((x, 200.0));
|
||||
b.close_path();
|
||||
Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::solid(Color::BLACK), 4.0))
|
||||
}
|
||||
|
||||
fn fx(id: &str, params: Value) -> Effect {
|
||||
crate::new_effect(id, ¶ms).unwrap()
|
||||
}
|
||||
|
||||
fn close(a: [f32; 4], b: [f32; 4]) -> bool {
|
||||
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-5)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_3d_effect_gives_a_mesh_for_its_fill_and_its_stroke() {
|
||||
for id in SOLIDS {
|
||||
let mut n = square_node(1, 100.0);
|
||||
n.appearance.effects.push(fx(id, json!({})));
|
||||
let meshes = three_d_meshes(&n).unwrap_or_else(|e| panic!("{id}: {e}"));
|
||||
assert_eq!(meshes.len(), 2, "{id}: the fill's solid and the stroke's");
|
||||
assert!(close(meshes[0].color, [0.8, 0.2, 0.1, 1.0]), "{id}: {:?}", meshes[0].color);
|
||||
assert!(close(meshes[1].color, [0.0, 0.0, 0.0, 1.0]), "{id}: {:?}", meshes[1].color);
|
||||
assert!(meshes.iter().all(|m| !m.mesh.is_empty()), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_meshes_of_one_object_share_one_triangle_budget() {
|
||||
let mut n = square_node(1, 100.0);
|
||||
n.appearance.effects.push(fx(EXTRUDE, json!({})));
|
||||
let meshes = three_d_meshes(&n).unwrap();
|
||||
let first = meshes[0].mesh.triangles.len();
|
||||
assert!(first > 0);
|
||||
// Every mesh counts against what the ones before it used.
|
||||
let (mut out, mut total) = (vec![], 0);
|
||||
keep_mesh(&mut out, &mut total, meshes[0].clone(), first).unwrap();
|
||||
assert!(keep_mesh(&mut out, &mut total, meshes[1].clone(), first).is_err());
|
||||
assert_eq!(out.len(), 1);
|
||||
// Building past the budget stops with an error instead of holding every mesh.
|
||||
let shapes = [Profile { path: profile(&n).unwrap().0, rule: FillRule::NonZero, items: solid_paints(&n), opacity: 1.0 }];
|
||||
let Some(effect) = n.appearance.effects.first() else { panic!("no effect") };
|
||||
let mut total = 0;
|
||||
assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES).is_ok());
|
||||
let mut total = MAX_MESH_TRIANGLES - first + 1;
|
||||
assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES).is_err_and(|e| e.contains("too complex")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revolve_stops_at_the_first_mesh_past_the_budget() {
|
||||
// The fill revolves into a mesh; the stroke's profile, copied 1000 times, is too complex to
|
||||
// revolve at all.
|
||||
let mut n = square_node(1, 100.0);
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.get_mut(0) {
|
||||
f.effects.push(fx(crate::REVOLVE, json!({})));
|
||||
}
|
||||
let fill_only = n.clone();
|
||||
if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.get_mut(1) {
|
||||
s.effects.push(fx("distort.transform", json!({ "moveH": 1.0, "copies": 1000 })));
|
||||
s.effects.push(fx(crate::REVOLVE, json!({})));
|
||||
}
|
||||
let fill = three_d_meshes(&fill_only).unwrap();
|
||||
let triangles = fill[0].mesh.triangles.len();
|
||||
assert!(triangles > 1);
|
||||
let whole = three_d_meshes(&n);
|
||||
assert!(whole.as_ref().is_err_and(|e| !e.contains("to export")), "the stroke's own error: {whole:?}");
|
||||
// With room for less than the fill's mesh, the stroke's is never built.
|
||||
let mut total = 0;
|
||||
let capped = meshes_within(&n, &mut total, triangles - 1);
|
||||
assert!(capped.as_ref().is_err_and(|e| e.contains("too complex to export")), "{capped:?}");
|
||||
assert_eq!(total, triangles);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_objects_of_one_asset_share_one_triangle_budget() {
|
||||
let mut a = square_node(1, 0.0);
|
||||
a.appearance.effects.push(fx(EXTRUDE, json!({})));
|
||||
let mut b = square_node(2, 300.0);
|
||||
b.appearance.effects.push(fx(EXTRUDE, json!({})));
|
||||
let triangles = |n: &Node| three_d_meshes(n).unwrap().iter().map(|m| m.mesh.triangles.len()).sum::<usize>();
|
||||
let (ta, tb) = (triangles(&a), triangles(&b));
|
||||
assert!(meshes_of_within([&a], ta).is_ok());
|
||||
assert!(meshes_of_within([&b], tb).is_ok());
|
||||
assert!(meshes_of_within([&a, &b], ta.max(tb)).is_err_and(|e| e.contains("too complex to export")));
|
||||
assert_eq!(meshes_of_within([&a, &b], ta + tb).map(|m| m.len()), Ok(4));
|
||||
assert_eq!(three_d_meshes_of([&a, &b]).map(|m| m.len()), Ok(4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_extruded_mesh_is_as_deep_as_the_effect() {
|
||||
let mut n = square_node(1, 100.0);
|
||||
n.appearance.items.truncate(1);
|
||||
n.appearance.effects.push(fx(EXTRUDE, json!({ "depth": 30.0, "rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0 })));
|
||||
let meshes = three_d_meshes(&n).unwrap();
|
||||
let (lo, hi) = meshes[0].mesh.bounds().unwrap();
|
||||
assert!((hi[2] - lo[2] - 30.0).abs() < 1e-9 && (hi[0] - lo[0] - 100.0).abs() < 1e-9, "{lo:?} {hi:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revolve_gives_a_mesh_in_the_top_fill() {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((100.0, 40.0));
|
||||
b.line_to((130.0, 60.0));
|
||||
b.line_to((130.0, 140.0));
|
||||
b.line_to((100.0, 160.0));
|
||||
let mut n = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0));
|
||||
n.appearance.effects.push(fx(crate::REVOLVE, json!({})));
|
||||
let meshes = three_d_meshes(&n).unwrap();
|
||||
assert_eq!(meshes.len(), 1);
|
||||
assert!(close(meshes[0].color, [0.8, 0.2, 0.1, 1.0]));
|
||||
assert!(meshes[0].mesh.triangles.len() >= 64 * 3, "three profile edges swept in 64 steps");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_without_a_3d_effect_has_no_mesh() {
|
||||
let mut n = square_node(1, 100.0);
|
||||
assert!(three_d_meshes(&n).is_err());
|
||||
n.appearance.effects.push(fx(EXTRUDE, json!({})));
|
||||
n.appearance.effects[0].visible = false;
|
||||
assert!(three_d_meshes(&n).is_err(), "a hidden effect builds nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_object_and_the_paint_opacities_multiply() {
|
||||
let mut n = square_node(1, 100.0);
|
||||
n.appearance.items.truncate(1);
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.opacity = 0.5;
|
||||
}
|
||||
n.opacity = 0.5;
|
||||
n.appearance.effects.push(fx(EXTRUDE, json!({})));
|
||||
let meshes = three_d_meshes(&n).unwrap();
|
||||
assert!((meshes[0].color[3] - 0.25).abs() < 1e-6, "{:?}", meshes[0].color);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_effect_on_one_fill_gives_that_fills_mesh_alone() {
|
||||
let mut n = square_node(1, 100.0);
|
||||
if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.get_mut(1) {
|
||||
s.effects.push(fx(EXTRUDE, json!({})));
|
||||
}
|
||||
let meshes = three_d_meshes(&n).unwrap();
|
||||
assert_eq!(meshes.len(), 1);
|
||||
assert!(close(meshes[0].color, [0.0, 0.0, 0.0, 1.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_gives_a_mesh_for_each_member() {
|
||||
let mut g = Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(square_node(2, 300.0))]);
|
||||
g.appearance.effects.push(fx(EXTRUDE, json!({ "rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0 })));
|
||||
let meshes = three_d_meshes(&g).unwrap();
|
||||
assert_eq!(meshes.len(), 4, "each member's fill and stroke");
|
||||
// The members turn about their shared centre: the first is left of it, the second right.
|
||||
let (lo, _) = meshes[0].mesh.bounds().unwrap();
|
||||
let (_, hi) = meshes[2].mesh.bounds().unwrap();
|
||||
assert!(lo[0] < -150.0 && hi[0] > 150.0, "{lo:?} {hi:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_takes_the_average_of_its_stops() {
|
||||
let stops =
|
||||
vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop { opacity: 0.5, ..GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0)) }];
|
||||
let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
assert!(close(mesh_color(&paint, 1.0), [0.5, 0.0, 0.5, 0.75]));
|
||||
let pattern = Paint::Pattern { pattern: "x".into(), xf: vectorcraft_geom::Affine::IDENTITY };
|
||||
assert!(close(mesh_color(&pattern, 0.5), [0.5, 0.5, 0.5, 0.5]));
|
||||
}
|
||||
@@ -13,6 +13,8 @@
|
||||
//! fill them ([`gradient_slices`]); Outline Stroke turns the strip into a gradient mesh
|
||||
//! ([`gradient_meshes`]).
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use kurbo::{BezPath, Point, Shape, Vec2};
|
||||
use vectorcraft_doc::color::{Gradient, GradientGeom, GradientPaint, Paint};
|
||||
use vectorcraft_doc::live::{H_DOWN, H_LEFT, H_RIGHT, H_UP};
|
||||
@@ -78,14 +80,26 @@ struct Lay<'a> {
|
||||
st: &'a StrokeLayer,
|
||||
/// Half the stroked width ([`aligned_width`]).
|
||||
hw: f64,
|
||||
/// How far ribs reach either side of the path where nothing wider is near.
|
||||
cover: f64,
|
||||
/// How far ribs reach past the stroke's edge.
|
||||
margin: f64,
|
||||
/// How far a strip runs on past the start and end of an open subpath (caps and heads).
|
||||
ext: (f64, f64),
|
||||
}
|
||||
|
||||
impl Lay<'_> {
|
||||
/// How far the stroke reaches either side of the path at fraction `t` of a subpath: its wider
|
||||
/// side, just before or just after a step there.
|
||||
fn half(&self, t: f64) -> f64 {
|
||||
let Some(p) = &self.st.profile else { return self.hw };
|
||||
let ((bl, br), (al, ar)) = p.around(t);
|
||||
self.hw * bl.max(br).max(al).max(ar).max(0.0)
|
||||
}
|
||||
|
||||
/// How far a rib at fraction `t` reaches either side of the path to cover the stroke there.
|
||||
fn cover(&self, t: f64) -> f64 {
|
||||
self.half(t) + self.margin
|
||||
}
|
||||
|
||||
/// The across band at fraction `t` of a subpath whose visible side is `side` (`Some(true)`:
|
||||
/// left; `None`: both, a centred stroke).
|
||||
fn band(&self, t: f64, side: Option<bool>) -> (f64, f64) {
|
||||
@@ -147,10 +161,11 @@ fn strips(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64,
|
||||
if !(hw > 0.0 && hw.is_finite()) {
|
||||
return vec![];
|
||||
}
|
||||
let full = hw * st.profile_max();
|
||||
let heads = (st.head_reach(false), st.head_reach(true));
|
||||
let cap = cap_extent(st.cap, 2.0 * full);
|
||||
let lay = Lay { st, hw, cover: full + margin, margin, ext: (cap.max(heads.0) + margin, cap.max(heads.1) + margin) };
|
||||
let mut lay = Lay { st, hw, margin, ext: (0.0, 0.0) };
|
||||
// Caps reach as far past the ends as the stroke is wide there.
|
||||
let cap = |t: f64| cap_extent(st.cap, 2.0 * lay.half(t));
|
||||
lay.ext = (cap(0.0).max(heads.0) + margin, cap(1.0).max(heads.1) + margin);
|
||||
let subs = subpaths(bp);
|
||||
let count = subs.len();
|
||||
let mut out = vec![];
|
||||
@@ -165,7 +180,8 @@ fn strips(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64,
|
||||
// A subpath of no length: a dot (round and projecting caps paint it).
|
||||
1 => {
|
||||
let (d, b, e) = (Vec2::new(1.0, 0.0), lay.band(0.0, side), lay.ext.0.max(lay.ext.1));
|
||||
vec![Rib::square(pts[0] - d * e, d, lay.cover, 0.0, b), Rib::square(pts[0] + d * e, d, lay.cover, 0.0, b)]
|
||||
let r = lay.cover(0.0);
|
||||
vec![Rib::square(pts[0] - d * e, d, r, 0.0, b), Rib::square(pts[0] + d * e, d, r, 0.0, b)]
|
||||
}
|
||||
_ => {
|
||||
let total = length(&pts, closed);
|
||||
@@ -215,9 +231,37 @@ fn strip(lay: &Lay, pts: &[Point], closed: bool, total: f64, side: Option<bool>,
|
||||
let n = pts.len();
|
||||
let seg_count = if closed { n } else { n - 1 };
|
||||
let dir: Vec<Vec2> = (0..seg_count).map(|i| unit(pts[(i + 1) % n] - pts[i])).collect();
|
||||
// Ribs near an arrowhead reach across it.
|
||||
let reach = |s: f64| {
|
||||
let mut r = lay.cover;
|
||||
// How far each point is from the next, and along the subpath.
|
||||
let seg: Vec<f64> = (0..n).map(|i| pts[i].distance(pts[(i + 1) % n])).collect();
|
||||
let along: Vec<f64> = seg
|
||||
.iter()
|
||||
.scan(0.0, |s, l| {
|
||||
let at = *s;
|
||||
*s += l;
|
||||
Some(at)
|
||||
})
|
||||
.collect();
|
||||
// How far the ribs at point `i` reach: past the stroke there and on its way to the points
|
||||
// either side, where it is no wider than at one of the two (each side of a width profile
|
||||
// stays between its widths at the points of a span, and its points have points here). The
|
||||
// caps and dots of a dashed stroke reach along the path as far as it is wide where they sit,
|
||||
// so there the ribs cover the widest the stroke gets that far either way. Not as far as the
|
||||
// stroke is wide anywhere: where a stroke crosses or runs close by itself, a narrow part
|
||||
// reaching that far would paint over a wide part beside it (#5960). The start of a closed
|
||||
// subpath is also its end. Ribs near an arrowhead reach across it.
|
||||
let cover: Vec<f64> = (0..n).map(|i| if closed && i == 0 { lay.cover(0.0).max(lay.cover(1.0)) } else { lay.cover(along[i] / total) }).collect();
|
||||
let window = match lay.st.dash {
|
||||
Some(_) if lay.st.profile.is_some() => cap_extent(lay.st.cap, 2.0 * lay.hw * lay.st.profile_max()),
|
||||
_ => 0.0,
|
||||
};
|
||||
let ahead = widest_ahead(&cover, &seg, closed, window);
|
||||
// Behind a point is ahead of it on the subpath run backwards.
|
||||
let back_seg: Vec<f64> = (0..n).map(|i| seg[(2 * n - 2 - i) % n]).collect();
|
||||
let back_cover: Vec<f64> = cover.iter().rev().copied().collect();
|
||||
let behind: Vec<f64> = widest_ahead(&back_cover, &back_seg, closed, window).into_iter().rev().collect();
|
||||
let reach = |i: usize| {
|
||||
let mut r = cover[i].max(ahead[i]).max(behind[i]);
|
||||
let s = along[i];
|
||||
if heads.0 > 0.0 && s <= heads.0 {
|
||||
r = r.max(heads.0 + lay.margin);
|
||||
}
|
||||
@@ -227,29 +271,69 @@ fn strip(lay: &Lay, pts: &[Point], closed: bool, total: f64, side: Option<bool>,
|
||||
r
|
||||
};
|
||||
let mut out = Vec::with_capacity(n + 4);
|
||||
let mut s = 0.0;
|
||||
if !closed {
|
||||
let (d, b) = (dir[0], lay.band(0.0, side));
|
||||
out.push(Rib::square(pts[0] - d * lay.ext.0, d, reach(0.0), 0.0, b));
|
||||
out.push(Rib::square(pts[0], d, reach(0.0), 0.0, b));
|
||||
s = pts[0].distance(pts[1]);
|
||||
out.push(Rib::square(pts[0] - d * lay.ext.0, d, reach(0), 0.0, b));
|
||||
out.push(Rib::square(pts[0], d, reach(0), 0.0, b));
|
||||
}
|
||||
let (first, last) = if closed { (0, n) } else { (1, n - 1) };
|
||||
for i in first..last {
|
||||
let v = i % n;
|
||||
let t = s / total;
|
||||
let ribs = lay.turn(pts[v], dir[(v + seg_count - 1) % seg_count], dir[v % seg_count], reach(s), t, lay.band(t, side));
|
||||
let t = along[v] / total;
|
||||
let ribs = lay.turn(pts[v], dir[(v + seg_count - 1) % seg_count], dir[v % seg_count], reach(v), t, lay.band(t, side));
|
||||
// A closed subpath starts after the fan of its first corner and ends with it.
|
||||
let skip = if closed && i == 0 { ribs.len() - 1 } else { 0 };
|
||||
out.extend(ribs.into_iter().skip(skip));
|
||||
s += pts[v].distance(pts[(v + 1) % n]);
|
||||
}
|
||||
if closed {
|
||||
out.extend(lay.turn(pts[0], dir[seg_count - 1], dir[0], reach(total), 1.0, lay.band(1.0, side)));
|
||||
out.extend(lay.turn(pts[0], dir[seg_count - 1], dir[0], reach(0), 1.0, lay.band(1.0, side)));
|
||||
} else {
|
||||
let (d, b) = (dir[seg_count - 1], lay.band(1.0, side));
|
||||
out.push(Rib::square(pts[n - 1], d, reach(total), 1.0, b));
|
||||
out.push(Rib::square(pts[n - 1] + d * lay.ext.1, d, reach(total), 1.0, b));
|
||||
out.push(Rib::square(pts[n - 1], d, reach(n - 1), 1.0, b));
|
||||
out.push(Rib::square(pts[n - 1] + d * lay.ext.1, d, reach(n - 1), 1.0, b));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// For each of the points of a subpath, how far the ribs of the points ahead of it reach
|
||||
/// (`cover`), out to the first point more than `window` along (or the end of an open subpath,
|
||||
/// or once round a closed one): `seg[i]` is how far point `i` is from the next (past the last,
|
||||
/// the first when `closed`). Both ends of the window only move forward, so a queue of the
|
||||
/// points that reach farther than every point after them gives each maximum, and a subpath
|
||||
/// costs time in proportion to its points however many a window spans.
|
||||
pub(super) fn widest_ahead(cover: &[f64], seg: &[f64], closed: bool, window: f64) -> Vec<f64> {
|
||||
let n = cover.len().min(seg.len());
|
||||
if n == 0 {
|
||||
return vec![];
|
||||
}
|
||||
// A closed subpath's points ahead are numbered on round it once more.
|
||||
let last = if closed { 2 * n - 1 } else { n - 1 };
|
||||
let mut pos = Vec::with_capacity(last + 1);
|
||||
let mut s = 0.0;
|
||||
for k in 0..=last {
|
||||
pos.push(s);
|
||||
s += seg[k % n];
|
||||
}
|
||||
let mut out = Vec::with_capacity(n);
|
||||
let mut queue: VecDeque<usize> = VecDeque::new();
|
||||
let mut next = 1;
|
||||
for i in 0..n {
|
||||
next = next.max(i + 1);
|
||||
let stop = if closed { i + n } else { last };
|
||||
let mut past = next > i + 1 && pos[next - 1] - pos[i] > window;
|
||||
while !past && next <= stop {
|
||||
let r = cover[next % n];
|
||||
while queue.back().is_some_and(|&k| cover[k % n] <= r) {
|
||||
queue.pop_back();
|
||||
}
|
||||
queue.push_back(next);
|
||||
past = pos[next] - pos[i] > window;
|
||||
next += 1;
|
||||
}
|
||||
while queue.front().is_some_and(|&k| k <= i) {
|
||||
queue.pop_front();
|
||||
}
|
||||
out.push(queue.front().map_or(0.0, |&k| cover[k % n]));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -237,3 +237,113 @@ fn slices_cover_an_arrowhead_on_a_long_straight_leg() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Does the last slice holding `p` (the one filled last there) lay its gradient piece on a part of
|
||||
/// the path running across the page (left or right), for a gradient in `mode`? Along, the piece
|
||||
/// runs the way the path does; across, square to it.
|
||||
fn painted_by_level_part(slices: &[Slice], p: Point, mode: StrokeGradientMode) -> Option<bool> {
|
||||
slices.iter().rev().find(|s| s.shape.contains(p)).map(|s| {
|
||||
let d = s.to - s.from;
|
||||
(d.x.abs() > d.y.abs()) == (mode == StrokeGradientMode::Along)
|
||||
})
|
||||
}
|
||||
|
||||
/// #5960: where a variable-width stroke crosses itself, the later pass paints over the earlier one
|
||||
/// only where the two overlap. Its slices reach as far as the stroke is wide there, not as far as
|
||||
/// it is wide anywhere, so a narrow later pass leaves the wide earlier one its own colour beside it.
|
||||
#[test]
|
||||
fn a_narrow_pass_over_a_wide_one_paints_only_where_they_overlap() {
|
||||
// Right along y = 50, round, then down through the first leg at x = 50, near the narrow end.
|
||||
let crossing = poly(&[(0.0, 50.0), (100.0, 50.0), (100.0, 100.0), (50.0, 100.0), (50.0, 0.0)], false);
|
||||
for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] {
|
||||
let mut st = stroke(10.0, mode);
|
||||
st.profile = Some(WidthProfile::taper_end());
|
||||
let sl = slices(&crossing, &st);
|
||||
// In the first leg (about 4 pt either side of it there) but 4 pt beside the second leg,
|
||||
// which is less than 1 pt either side of itself there.
|
||||
let level = painted_by_level_part(&sl, Point::new(54.0, 52.0), mode);
|
||||
assert_eq!(level, Some(true), "{mode:?}: painted by the second leg");
|
||||
// Where the two overlap, the second leg is on top.
|
||||
let level = painted_by_level_part(&sl, Point::new(50.5, 52.0), mode);
|
||||
assert_eq!(level, Some(false), "{mode:?}: painted by the first leg");
|
||||
assert_covered(&crossing, &st);
|
||||
}
|
||||
}
|
||||
|
||||
/// #5960: a narrow pass running close beside a wide one doesn't paint the wide one's edge.
|
||||
#[test]
|
||||
fn a_narrow_pass_beside_a_wide_one_leaves_its_edge_alone() {
|
||||
// Right along y = 0, then back along y = 7: the way back is the narrow end of a taper.
|
||||
let hairpin = poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 7.0), (0.0, 7.0)], false);
|
||||
let total = 207.0;
|
||||
let mut st = stroke(10.0, StrokeGradientMode::Along);
|
||||
st.profile = Some(WidthProfile::taper_end());
|
||||
let sl = slices(&hairpin, &st);
|
||||
// Half way along the first leg, 3 pt off it (it is about 3.8 pt wide there either side); the
|
||||
// way back is about 1.2 pt wide either side there, so it reaches no nearer than 5.8.
|
||||
let p = Point::new(50.0, 3.0);
|
||||
let t = param(&sl, p).expect("in a slice");
|
||||
assert!((t - 50.0 / total).abs() < 1e-6, "painted with {t}, not the first leg's {}", 50.0 / total);
|
||||
assert_covered(&hairpin, &st);
|
||||
}
|
||||
|
||||
/// #5960: with dashes, the ribs reach as far as the stroke gets wide within a cap's length along
|
||||
/// the path, however many points lie that far: not as far as it is wide anywhere when more than
|
||||
/// 256 do.
|
||||
#[test]
|
||||
fn a_densely_flattened_dashed_pass_beside_a_wide_one_leaves_its_edge_alone() {
|
||||
// The hairpin above, the way back in 0.01 pt steps: 500 points within a round cap's 5 pt.
|
||||
let mut pts = vec![(0.0, 0.0), (100.0, 0.0)];
|
||||
pts.extend((0..=10_000).map(|i| (100.0 - i as f64 * 0.01, 7.0)));
|
||||
let hairpin = poly(&pts, false);
|
||||
let total = 207.0;
|
||||
let mut st = stroke(10.0, StrokeGradientMode::Along);
|
||||
st.profile = Some(WidthProfile::taper_end());
|
||||
st.cap = LineCap::Round;
|
||||
st.dash = Some(Dash { pattern: vec![12.0, 6.0], ..Default::default() });
|
||||
let sl = slices(&hairpin, &st);
|
||||
let p = Point::new(50.0, 3.0);
|
||||
let t = param(&sl, p).expect("in a slice");
|
||||
assert!((t - 50.0 / total).abs() < 1e-6, "painted with {t}, not the first leg's {}", 50.0 / total);
|
||||
}
|
||||
|
||||
/// The widest the ribs ahead reach is the widest over the points out to the first one more than
|
||||
/// the window along, as a walk along the subpath finds it, open and closed.
|
||||
#[test]
|
||||
fn widest_ahead_is_the_widest_within_the_window() {
|
||||
let mut seed = 0x9e37_79b9_u64;
|
||||
let mut rnd = move || {
|
||||
seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
|
||||
(seed >> 11) as f64 / (1u64 << 53) as f64
|
||||
};
|
||||
for _ in 0..200 {
|
||||
let n = 1 + (rnd() * 40.0) as usize;
|
||||
let cover: Vec<f64> = (0..n).map(|_| rnd() * 10.0).collect();
|
||||
// Some points on top of each other.
|
||||
let seg: Vec<f64> = (0..n).map(|_| if rnd() < 0.2 { 0.0 } else { rnd() * 3.0 }).collect();
|
||||
let window = [0.0, rnd() * 5.0, rnd() * 200.0][(rnd() * 3.0) as usize];
|
||||
for closed in [false, true] {
|
||||
let got = super::gradient::widest_ahead(&cover, &seg, closed, window);
|
||||
assert_eq!(got.len(), n);
|
||||
for (i, &got) in got.iter().enumerate() {
|
||||
let (mut j, mut d, mut want) = (i, 0.0, 0.0_f64);
|
||||
for _ in 0..n {
|
||||
let k = if closed {
|
||||
(j + 1) % n
|
||||
} else if j + 1 < n {
|
||||
j + 1
|
||||
} else {
|
||||
break;
|
||||
};
|
||||
want = want.max(cover[k]);
|
||||
d += seg[j];
|
||||
j = k;
|
||||
if d > window {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(got, want, "n {n}, closed {closed}, window {window}, point {i}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,725 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::Effect;
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
|
||||
use super::*;
|
||||
use crate::pixel::Channels;
|
||||
use crate::{PixelFx, RasterFx, raster_effects};
|
||||
|
||||
/// A `w` × `h` raster whose pixels are `px` points wide (origin top-left), at a raster effects
|
||||
/// resolution whose pixels are `line` points wide.
|
||||
fn space(w: usize, h: usize, px: f64, line: f64) -> PixelSpace {
|
||||
let (wd, hd) = (w as f64 * px, h as f64 * px);
|
||||
PixelSpace { to_doc: Affine::scale(px), px, center: Point::new(wd / 2.0, hd / 2.0), channels: Channels::Rgb, line, extent: 0.5 * wd.hypot(hd) }
|
||||
}
|
||||
|
||||
/// `w` × `h` premultiplied pixels: `f(x, y)` each.
|
||||
fn image(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 4]) -> Vec<u8> {
|
||||
(0..h).flat_map(|y| (0..w).map(move |x| (x, y))).flat_map(|(x, y)| f(x, y)).collect()
|
||||
}
|
||||
|
||||
fn at(d: &[u8], w: usize, x: usize, y: usize) -> [u8; 4] {
|
||||
let i = (y * w + x) * 4;
|
||||
[d[i], d[i + 1], d[i + 2], d[i + 3]]
|
||||
}
|
||||
|
||||
/// The effect `svg.filter` with `params`, as the renderer reads it.
|
||||
fn filter(params: serde_json::Value) -> SvgFilterFx {
|
||||
let e = Effect { id: SVG_FILTER.into(), params, visible: true };
|
||||
match raster_effects(&[e]).first() {
|
||||
Some(RasterFx::Pixel(PixelFx::Svg(f))) => f.clone(),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A blue square of `size` pixels inset by `inset` in a transparent raster `w` wide.
|
||||
fn blue_square(w: usize, inset: usize) -> Vec<u8> {
|
||||
image(w, w, |x, y| if (inset..w - inset).contains(&x) && (inset..w - inset).contains(&y) { [0, 0, 255, 255] } else { [0; 4] })
|
||||
}
|
||||
|
||||
const RED_FLOOD: &str = r##"<filter id="Red"><feFlood flood-color="#ff0000"/><feComposite in2="SourceGraphic" operator="in"/></filter>"##;
|
||||
|
||||
#[test]
|
||||
fn check_names_a_filter_by_its_id() {
|
||||
assert_eq!(check(RED_FLOOD), Ok("Red".into()));
|
||||
assert_eq!(check(&format!(" {RED_FLOOD}\n")), Ok("Red".into()), "spaces around the element");
|
||||
let linked = r#"<filter id=" Shadow 1 "><feImage xlink:href="data:image/png;base64,AAAA"/></filter>"#;
|
||||
assert_eq!(check(linked), Ok("Shadow 1".into()), "the xlink prefix is declared for it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_refuses_what_is_not_one_drawable_filter() {
|
||||
for (xml, why) in [
|
||||
("", "give one <filter> element"),
|
||||
("<filter id=\"a\">", "isn't valid XML"),
|
||||
("<g id=\"a\"><feFlood/></g>", "give one <filter> element"),
|
||||
("<filter id=\"a\"><feFlood/></filter><filter id=\"b\"><feFlood/></filter>", "give one <filter> element"),
|
||||
("text<filter id=\"a\"><feFlood/></filter>", "give one <filter> element"),
|
||||
("<filter><feFlood/></filter>", "needs an id"),
|
||||
("<filter id=\" \"><feFlood/></filter>", "needs an id"),
|
||||
("<filter id=\"a\"></filter>", "no primitives"),
|
||||
("<filter id=\"a\"><feTurbulence numOctaves=\"11\"/></filter>", "numOctaves is at most 10"),
|
||||
("<filter id=\"a\"><feConvolveMatrix order=\"3 12\" kernelMatrix=\"1\"/></filter>", "order is at most 9"),
|
||||
("<filter id=\"a\"><feConvolveMatrix order=\"65536+65536\" kernelMatrix=\"1\"/></filter>", "order is at most 9"),
|
||||
("<filter id=\"a\"><feConvolveMatrix order=\"3 x\" kernelMatrix=\"1\"/></filter>", "order is at most 9"),
|
||||
("<filter id=\"a\"><notAPrimitive/></filter>", "<notAPrimitive> isn't an element of an SVG filter"),
|
||||
("<filter id=\"a\"><feOffset/><script>alert(1)</script></filter>", "<script> isn't an element"),
|
||||
("<filter id=\"a\"><feMerge><feMergeNode/><a/></feMerge></filter>", "<a> isn't an element"),
|
||||
("<filter id=\"a\" onload=\"x()\"><feOffset/></filter>", "no event attributes such as onload"),
|
||||
("<filter id=\"a\"><feOffset ONCLICK=\"x()\"/></filter>", "no event attributes such as ONCLICK"),
|
||||
("<filter id=\"a\"><feImage xlink:href=\"javascript:x()\"/></filter>", "WebP data: URLs"),
|
||||
("<filter id=\"a\"><feImage href=\"photo.png\"/></filter>", "WebP data: URLs"),
|
||||
("<filter id=\"a\"><feImage href=\"data:image/svg+xml;base64,PHN2Zy8+\"/></filter>", "WebP data: URLs"),
|
||||
("<filter id=\"a\"><feImage href=\"data:application/gzip;base64,H4sI\"/></filter>", "WebP data: URLs"),
|
||||
("<filter id=\"a\"><feImage href=\"data:;base64,AAAA\"/></filter>", "WebP data: URLs"),
|
||||
("<filter id=\"a\" width=\"0\"><feOffset/></filter>", "can't be drawn"),
|
||||
] {
|
||||
let e = check(xml).expect_err(xml);
|
||||
assert!(e.contains(why), "{xml}: {e}");
|
||||
}
|
||||
let many = format!("<filter id=\"a\">{}</filter>", "<feOffset/>".repeat(MAX_PRIMITIVES + 1));
|
||||
assert!(check(&many).is_err_and(|e| e.contains("at most 64 primitives")));
|
||||
let titled = format!("<filter id=\"a\"><title>T</title><desc>D</desc>{}</filter>", "<feOffset/>".repeat(MAX_PRIMITIVES));
|
||||
assert_eq!(check(&titled), Ok("a".into()), "a title and a description aren't primitives");
|
||||
assert!(check("<filter id=\"a\"><title>T</title></filter>").is_err_and(|e| e.contains("no primitives")));
|
||||
let long = format!("<filter id=\"{}\"><feOffset/></filter>", "x".repeat(MAX_NAME + 1));
|
||||
assert!(check(&long).is_err_and(|e| e.contains("at most 255 characters")));
|
||||
let big = format!("<filter id=\"a\"><feOffset/><!--{}--></filter>", " ".repeat(SvgFilter::MAX_XML));
|
||||
assert!(check(&big).is_err_and(|e| e.contains("at most 64 KB")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_id_renames_only_the_filter() {
|
||||
let xml = r#"<filter id="Old" x="0"><feOffset result="Old"/></filter>"#;
|
||||
assert_eq!(with_id(xml, "New").as_deref(), Some(r#"<filter id="New" x="0"><feOffset result="Old"/></filter>"#));
|
||||
assert_eq!(with_id("<filter><feOffset/></filter>", "New"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_in_lists_the_documents_filters_it_takes() {
|
||||
let svg = format!(
|
||||
"<?xml version=\"1.0\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"><svg xmlns=\"http://www.w3.org/2000/svg\"><defs>{RED_FLOOD}<filter id=\"Empty\"/><filter id=\"Off\"><feOffset dx=\"2\"/></filter></defs></svg>"
|
||||
);
|
||||
let (found, skipped) = filters_in(&svg);
|
||||
assert_eq!(found.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Red", "Off"]);
|
||||
assert_eq!(found[0].1, RED_FLOOD, "each filter's XML as it is written");
|
||||
assert_eq!(skipped, 1, "the filter without primitives");
|
||||
}
|
||||
|
||||
/// [`filters_of`] on `svg` read as SVG import reads it (with DTDs).
|
||||
fn filters_in(svg: &str) -> (Vec<(String, String)>, usize) {
|
||||
let doc = roxmltree::Document::parse_with_options(svg, roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }).unwrap();
|
||||
filters_of(&doc, svg, usize::MAX, |_| false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_of_stops_at_the_room_left_and_skips_taken_and_styled_filters() {
|
||||
let many = format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\">{}</svg>",
|
||||
(0..200).map(|i| format!("<filter id=\"f{i}\"><feOffset/></filter>")).collect::<String>()
|
||||
);
|
||||
let doc = roxmltree::Document::parse(&many).unwrap();
|
||||
let (found, skipped) = filters_of(&doc, &many, 3, |name| name == "f1");
|
||||
assert_eq!(found.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["f0", "f2", "f3"]);
|
||||
assert_eq!(skipped, 197);
|
||||
// A filter whose look comes from the document's styles isn't taken.
|
||||
for styled in [
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>.r{flood-color:red}</style><filter id=\"a\"><feFlood class=\"r\"/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><filter id=\"a\"><feFlood flood-color=\"currentColor\"/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><filter id=\"a\"><feFlood flood-color=\"CURRENTcolor\"/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><defs color-interpolation-filters=\"sRGB\"><filter id=\"a\"><feGaussianBlur stdDeviation=\"2\"/></filter></defs></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>@media screen { feFlood { flood-color: red } }</style><filter id=\"a\"><feFlood/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>#a feOffset{dx:2}</style><filter id=\"a\"><feOffset/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>.s { content: \"{ /*\" } feFlood { flood-color: red }</style><filter id=\"a\"><feFlood/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>.outer { fill: blue; & #a { color: red } }</style><filter id=\"a\"><feFlood/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>@scope (#a) { :scope { color: red } }</style><filter id=\"a\"><feFlood/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>svg { color-interpolation-filters: sRGB }</style><filter id=\"a\"><feGaussianBlur stdDeviation=\"2\"/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>feFlood[data-t=\\;] { flood-color: red }</style><filter id=\"a\"><feFlood/></filter></svg>",
|
||||
] {
|
||||
let doc = roxmltree::Document::parse(styled).unwrap();
|
||||
assert_eq!(filters_of(&doc, styled, usize::MAX, |_| false), (vec![], 1), "{styled}");
|
||||
}
|
||||
// A style sheet for the shapes alone (as CSS export writes), applying the filter to them
|
||||
// included, doesn't reach the filter.
|
||||
for shapes in [
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>.cls-1{fill:#f00}</style><filter id=\"a\"><feOffset/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>/* #a */ .shape { filter: url(#a) }</style><filter id=\"a\"><feOffset/></filter></svg>",
|
||||
// An identifier named currentColor takes no color.
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><filter id=\"currentColor\"><feOffset result=\"currentColor\"/></filter></svg>",
|
||||
] {
|
||||
let doc = roxmltree::Document::parse(shapes).unwrap();
|
||||
assert_eq!(filters_of(&doc, shapes, usize::MAX, |_| false).0.len(), 1, "{shapes}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deeply_nested_filters_are_refused_before_they_are_parsed() {
|
||||
let deep = format!("<filter id=\"a\"><feMerge>{}<feMergeNode/>{}</feMerge></filter>", "<g>".repeat(20), "</g>".repeat(20));
|
||||
assert!(check(&deep).is_err_and(|e| e.contains("nest at most 16 deep")));
|
||||
assert_eq!(with_id(&deep, "b"), None);
|
||||
let e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": deep }), visible: true };
|
||||
assert!(raster_effects(&[e]).is_empty(), "drawn without it");
|
||||
// Markup in comments, CDATA and attribute values doesn't count.
|
||||
let quoted =
|
||||
format!("<filter id=\"a\" x=\"{}\"><!--{}--><feOffset/><![CDATA[{}]]></filter>", "<g>".repeat(20), "<g>".repeat(20), "<g>".repeat(20));
|
||||
assert_eq!(check("ed), Ok("a".into()));
|
||||
let gt = format!("<filter id=\"a\" title='{}'>{}<feOffset/></filter>", "x>".repeat(20), "<!-- > -->".repeat(3));
|
||||
assert_eq!(check(>), Ok("a".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filter_replaces_the_pixels_with_its_result() {
|
||||
let w = 20;
|
||||
let mut data = blue_square(w, 5);
|
||||
filter(json!({ "xml": RED_FLOOD })).apply(&mut data, w, w, &space(w, w, 1.0, 1.0));
|
||||
assert_eq!(at(&data, w, 10, 10), [255, 0, 0, 255], "inside: the flood, cut to the source");
|
||||
assert_eq!(at(&data, w, 1, 1), [0; 4], "outside the source");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lengths_are_in_points_times_scale() {
|
||||
let w = 40;
|
||||
let shift = r#"<filter id="Shift" x="-1" y="-1" width="3" height="3"><feOffset dx="4"/></filter>"#;
|
||||
let run = |px: f64, scale: f64| {
|
||||
let n = (w as f64 / px) as usize;
|
||||
let mut data = image(n, n, |x, y| {
|
||||
let (x, y) = (x as f64 * px, y as f64 * px);
|
||||
if (10.0..20.0).contains(&x) && (10.0..20.0).contains(&y) { [0, 0, 255, 255] } else { [0; 4] }
|
||||
});
|
||||
filter(json!({ "xml": shift, "scale": scale })).apply(&mut data, n, n, &space(n, n, px, px));
|
||||
let column = |x: f64| at(&data, n, (x / px) as usize, (15.0 / px) as usize)[3];
|
||||
(column(9.5), column(21.0), column(23.5), column(25.0))
|
||||
};
|
||||
// The square spans 10..20 pt: moved by 4 pt, 14..24.
|
||||
assert_eq!(run(1.0, 1.0), (0, 255, 255, 0));
|
||||
assert_eq!(run(0.5, 1.0), (0, 255, 255, 0), "the same in points at another zoom");
|
||||
// One unit of the filter is half a point: moved by 2 pt, 12..22.
|
||||
assert_eq!(run(1.0, 0.5), (0, 255, 0, 0));
|
||||
}
|
||||
|
||||
/// A user-space region is placed from the effect's origin.
|
||||
#[test]
|
||||
fn user_space_starts_at_the_origin() {
|
||||
let w = 40;
|
||||
// Flood the square, cut to the region x 0..20 of the filter's user space.
|
||||
let half = r##"<filter id="Half" filterUnits="userSpaceOnUse" x="0" y="0" width="20" height="40"><feFlood flood-color="#ff0000"/><feComposite in2="SourceGraphic" operator="in"/></filter>"##;
|
||||
let run = |origin: [f64; 2]| {
|
||||
let mut data = image(w, w, |_, _| [0, 0, 255, 255]);
|
||||
filter(json!({ "xml": half, "origin": origin })).apply(&mut data, w, w, &space(w, w, 1.0, 1.0));
|
||||
(at(&data, w, 5, 20)[3], at(&data, w, 25, 20)[3])
|
||||
};
|
||||
assert_eq!(run([0.0, 0.0]), (255, 0));
|
||||
assert_eq!(run([20.0, 0.0]), (0, 255), "the region 20 pt to the right");
|
||||
let b = Rect::new(0.0, 0.0, 40.0, 40.0);
|
||||
assert!((filter(json!({ "xml": half, "origin": [-10.0, 0.0] })).outset(b) - 10.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_no_finer_than_the_raster_effects_resolution() {
|
||||
let w = 16;
|
||||
// Columns one view pixel wide, alternately opaque and clear.
|
||||
let stripes = image(w, w, |x, _| if x % 2 == 0 { [0, 0, 255, 255] } else { [0; 4] });
|
||||
let keep = r#"<filter id="Keep" x="0" y="0" width="1" height="1"><feOffset/></filter>"#;
|
||||
let mut fine = stripes.clone();
|
||||
filter(json!({ "xml": keep })).apply(&mut fine, w, w, &space(w, w, 0.25, 0.25));
|
||||
assert_eq!(at(&fine, w, 4, 4)[3], 255);
|
||||
assert_eq!(at(&fine, w, 5, 4)[3], 0, "at the view's resolution the stripes stay");
|
||||
let mut coarse = stripes.clone();
|
||||
filter(json!({ "xml": keep })).apply(&mut coarse, w, w, &space(w, w, 0.25, 1.0));
|
||||
let (a, b) = (at(&coarse, w, 4, 4)[3], at(&coarse, w, 5, 4)[3]);
|
||||
assert!(a < 255 && b > 0, "four view pixels to a raster pixel: the stripes blend ({a}, {b})");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draws_nothing_new_without_content_or_a_readable_filter() {
|
||||
let w = 8;
|
||||
let mut empty = vec![0; w * w * 4];
|
||||
filter(json!({ "xml": RED_FLOOD })).apply(&mut empty, w, w, &space(w, w, 1.0, 1.0));
|
||||
assert!(empty.iter().all(|v| *v == 0), "a flood cut to a source that draws nothing");
|
||||
// A filter that doesn't read the source draws on art that draws no pixels: the raster is its box.
|
||||
let mut clear = vec![0; w * w * 4];
|
||||
filter(json!({ "xml": "<filter id=\"G\"><feFlood flood-color=\"#00ff00\"/></filter>" })).apply(&mut clear, w, w, &space(w, w, 1.0, 1.0));
|
||||
assert_eq!(at(&clear, w, 4, 4), [0, 255, 0, 255]);
|
||||
let e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": "<g/>" }), visible: true };
|
||||
assert!(raster_effects(&[e]).is_empty(), "not a filter: the object is drawn without it");
|
||||
let e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": "<filter id=\"x\" width=\"0\"><feOffset/></filter>" }), visible: true };
|
||||
assert!(raster_effects(&[e]).is_empty(), "a filter resvg can't draw: the object is drawn without it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outset_is_how_far_the_region_reaches() {
|
||||
let b = Rect::new(0.0, 0.0, 100.0, 50.0);
|
||||
assert!((filter(json!({ "xml": RED_FLOOD })).outset(b) - 10.0).abs() < 1e-9, "the default region: 10% of the width");
|
||||
let wide = r#"<filter id="w" x="-50%" y="0" width="200%" height="100%"><feOffset/></filter>"#;
|
||||
assert!((filter(json!({ "xml": wide })).outset(b) - 50.0).abs() < 1e-9);
|
||||
let user = r#"<filter id="u" filterUnits="userSpaceOnUse" x="-10" y="0" width="60" height="25"><feOffset/></filter>"#;
|
||||
assert!((filter(json!({ "xml": user, "scale": 2.0 })).outset(b) - 20.0).abs() < 1e-9, "user units times scale");
|
||||
let inside = r#"<filter id="i" x="0" y="0" width="1" height="1"><feOffset/></filter>"#;
|
||||
assert_eq!(filter(json!({ "xml": inside })).outset(b), 0.0);
|
||||
// User-space lengths in points: -30 pt is -40 user units.
|
||||
let points = r#"<filter id="p" filterUnits="userSpaceOnUse" x="-30pt" y="0" width="100" height="50"><feOffset/></filter>"#;
|
||||
assert!((filter(json!({ "xml": points })).outset(b) - 40.0).abs() < 1e-9);
|
||||
// In user space, a percentage is a share of the object's box; em, ex and a missing length
|
||||
// take the default region's share of it.
|
||||
let viewport = r#"<filter id="v" filterUnits="userSpaceOnUse" x="-50%" y="0" width="10" height="10"><feOffset/></filter>"#;
|
||||
assert!((filter(json!({ "xml": viewport })).outset(b) - 50.0).abs() < 1e-9);
|
||||
let far = r#"<filter id="r" filterUnits="userSpaceOnUse" x="-1000%" y="0" width="3000%" height="10"><feOffset/></filter>"#;
|
||||
assert!((filter(json!({ "xml": far })).outset(b) - 1900.0).abs() < 1e-9, "however far it reaches");
|
||||
let font = r#"<filter id="f" filterUnits="userSpaceOnUse" x="-100em" y="0" width="10" height="10"><feOffset/></filter>"#;
|
||||
assert!((filter(json!({ "xml": font })).outset(b) - 10.0).abs() < 1e-9, "relative to the font");
|
||||
let default = r#"<filter id="d" filterUnits="userSpaceOnUse"><feOffset/></filter>"#;
|
||||
assert!((filter(json!({ "xml": default })).outset(b) - 10.0).abs() < 1e-9);
|
||||
// In the bounding box, a length with a unit is invalid: the default.
|
||||
let unit = r#"<filter id="u" x="-5mm"><feOffset/></filter>"#;
|
||||
assert!((filter(json!({ "xml": unit })).outset(b) - 10.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filter_keeps_the_prefixes_an_ancestor_declares() {
|
||||
let svg = r#"<svg:svg xmlns:svg="http://www.w3.org/2000/svg" xmlns:x="urn:other"><svg:defs><svg:filter id="Pre"><svg:feOffset dx="1"/></svg:filter></svg:defs></svg:svg>"#;
|
||||
let (found, skipped) = filters_in(svg);
|
||||
assert_eq!((found.len(), skipped), (1, 0));
|
||||
assert_eq!(
|
||||
found[0].1, r#"<svg:filter xmlns:svg="http://www.w3.org/2000/svg" id="Pre"><svg:feOffset dx="1"/></svg:filter>"#,
|
||||
"only the prefix it uses"
|
||||
);
|
||||
// A declaration on the filter itself, with spaces around its `=`, is kept as it is.
|
||||
let own = r#"<svg xmlns="http://www.w3.org/2000/svg"><defs><s:filter xmlns:s = "http://www.w3.org/2000/svg" id="Own"><s:feOffset/></s:filter></defs></svg>"#;
|
||||
let (found, skipped) = filters_in(own);
|
||||
assert_eq!((found.len(), skipped), (1, 0));
|
||||
assert_eq!(found[0].1, r#"<s:filter xmlns:s = "http://www.w3.org/2000/svg" id="Own"><s:feOffset/></s:filter>"#);
|
||||
// The same declaration again on the filter, and text like one inside an attribute's value.
|
||||
let again = r#"<s:svg xmlns:s="http://www.w3.org/2000/svg"><s:filter xmlns:s="http://www.w3.org/2000/svg" id="A"><s:feOffset/></s:filter><s:filter id="B" color-profile=" xmlns:s = x"><s:feOffset/></s:filter></s:svg>"#;
|
||||
let (found, skipped) = filters_in(again);
|
||||
assert_eq!((found.len(), skipped), (2, 0), "{found:?}");
|
||||
assert!(found[1].1.starts_with(r#"<s:filter xmlns:s="http://www.w3.org/2000/svg" id="B""#), "{found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn primitive_forms_tell_filters_with_the_same_primitives_apart() {
|
||||
let a = primitive_forms(r#"<filter id="a"><feOffset dx="1"/></filter>"#).unwrap();
|
||||
let b = primitive_forms(r#"<filter id="b"><feOffset dx="2"/></filter>"#).unwrap();
|
||||
assert_eq!(a.len(), 1);
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(primitive_forms(r#"<filter id="c"><feOffset dx="1"/></filter>"#), Some(a), "the id doesn't count");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn costly_parameters_are_capped() {
|
||||
for (xml, why) in [
|
||||
("<filter id=\"a\"><feMorphology radius=\"101\"/></filter>", "radius is at most 100"),
|
||||
("<filter id=\"a\"><feMorphology radius=\"2 1e9\"/></filter>", "radius is at most 100"),
|
||||
("<filter id=\"a\"><feMorphology radius=\"50+500\"/></filter>", "radius is at most 100"),
|
||||
("<filter id=\"a\"><feGaussianBlur stdDeviation=\"501\"/></filter>", "stdDeviation is at most 500"),
|
||||
("<filter id=\"a\"><feDropShadow stdDeviation=\"1 9e9\"/></filter>", "stdDeviation is at most 500"),
|
||||
(
|
||||
"<filter id=\"a\"><feDiffuseLighting kernelUnitLength=\"101\"><feDistantLight/></feDiffuseLighting></filter>",
|
||||
"kernelUnitLength is at most 100",
|
||||
),
|
||||
] {
|
||||
let e = check(xml).expect_err(xml);
|
||||
assert!(e.contains(why), "{xml}: {e}");
|
||||
}
|
||||
assert_eq!(check("<filter id=\"a\"><feMorphology radius=\"100\"/></filter>"), Ok("a".into()));
|
||||
// usvg also reads attributes in the SVG, XLink and XML namespaces by their local names.
|
||||
for prefixed in [
|
||||
"<filter id=\"a\" xmlns:s=\"http://www.w3.org/2000/svg\"><feMorphology s:radius=\"1000\"/></filter>",
|
||||
"<filter id=\"a\" xmlns:s=\"http://www.w3.org/2000/svg\"><feGaussianBlur s:stdDeviation=\"1e6\"/></filter>",
|
||||
] {
|
||||
assert!(check(prefixed).is_err(), "{prefixed}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A filter is drawn and written rebuilt from its filter elements and their filter attributes:
|
||||
/// no comments, text, descriptions, other attributes or prefixes.
|
||||
#[test]
|
||||
fn the_filter_is_drawn_and_written_from_its_filter_parts_alone() {
|
||||
let xml = concat!(
|
||||
"<filter id=\"a\" xmlns:s=\"http://www.w3.org/2000/svg\" data-x=\"1\"><!-- note --><desc><script></desc><title>T</title>",
|
||||
"<feFlood flood-color=\"blue\" style=\"flood-color: red; fill: url(#x); flood-opacity: url(#y)\" foo=\""\"/>",
|
||||
"<feMorphology s:radius=\"2\"/><feImage xlink:href=\"data:image/png;base64,AAAA\"/></filter>",
|
||||
);
|
||||
let f = filter(json!({ "xml": xml }));
|
||||
assert_eq!(
|
||||
f.xml(),
|
||||
"<filter id=\"a\"><feFlood flood-color=\"red\"/><feMorphology radius=\"2\"/><feImage href=\"data:image/png;base64,AAAA\"/></filter>"
|
||||
);
|
||||
// An image keeps how it is scaled, as a style declaration.
|
||||
for image in [
|
||||
"<filter id=\"i\"><feImage image-rendering=\"pixelated\" href=\"data:image/png;base64,AAAA\"/></filter>",
|
||||
"<filter id=\"i\"><feImage style=\"image-rendering: pixelated; fill: red\" href=\"data:image/png;base64,AAAA\"/></filter>",
|
||||
] {
|
||||
assert_eq!(
|
||||
filter(json!({ "xml": image })).xml(),
|
||||
"<filter id=\"i\"><feImage href=\"data:image/png;base64,AAAA\" style=\"image-rendering:pixelated\"/></filter>",
|
||||
"{image}"
|
||||
);
|
||||
}
|
||||
// `currentColor` keeps the color it names.
|
||||
let colored = filter(json!({ "xml": "<filter id=\"c\" color=\"red\"><feFlood flood-color=\"currentColor\" style=\"color: blue\"/></filter>" }));
|
||||
assert_eq!(colored.xml(), "<filter id=\"c\" color=\"red\"><feFlood flood-color=\"currentColor\" color=\"blue\"/></filter>");
|
||||
}
|
||||
|
||||
/// An image of a filter is a PNG, JPEG, GIF or WebP, by its bytes, within the pixel cap by its header.
|
||||
#[test]
|
||||
fn filter_images_are_small_raster_images() {
|
||||
fn png(w: u32, h: u32) -> Vec<u8> {
|
||||
let mut out = vec![];
|
||||
image::ImageEncoder::write_image(
|
||||
image::codecs::png::PngEncoder::new(&mut out),
|
||||
&vec![0; (w * h * 4) as usize],
|
||||
w,
|
||||
h,
|
||||
image::ExtendedColorType::Rgba8,
|
||||
)
|
||||
.unwrap();
|
||||
out
|
||||
}
|
||||
let raster_image = |data| raster_image_sized(data).map(|(kind, _)| kind);
|
||||
assert!(matches!(raster_image(Arc::new(png(2, 2))), Some(usvg::ImageKind::PNG(_))));
|
||||
assert_eq!(raster_image_sized(Arc::new(png(3, 2))).map(|(_, n)| n), Some(6), "its pixel count");
|
||||
// A header that claims more pixels than the cap: the IHDR's width, with its CRC fixed.
|
||||
let mut big = png(2, 2);
|
||||
big[16..20].copy_from_slice(&5000u32.to_be_bytes());
|
||||
big[20..24].copy_from_slice(&5000u32.to_be_bytes());
|
||||
let crc = crc32(&big[12..29]);
|
||||
big[29..33].copy_from_slice(&crc.to_be_bytes());
|
||||
assert!(raster_image(Arc::new(big)).is_none(), "past the pixel cap");
|
||||
assert!(raster_image(Arc::new(b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>".to_vec())).is_none(), "SVG");
|
||||
assert!(raster_image(Arc::new(vec![0x1f, 0x8b, 8, 0, 0, 0, 0, 0])).is_none(), "compressed SVG");
|
||||
}
|
||||
|
||||
/// A 2 × 2 PNG whose header claims `w` × `h` pixels (its IHDR rewritten, with the CRC fixed).
|
||||
fn png_claiming(w: u32, h: u32) -> Vec<u8> {
|
||||
let mut out = vec![];
|
||||
image::ImageEncoder::write_image(image::codecs::png::PngEncoder::new(&mut out), &[0; 16], 2, 2, image::ExtendedColorType::Rgba8).unwrap();
|
||||
out[16..20].copy_from_slice(&w.to_be_bytes());
|
||||
out[20..24].copy_from_slice(&h.to_be_bytes());
|
||||
let crc = crc32(&out[12..29]);
|
||||
out[29..33].copy_from_slice(&crc.to_be_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// A filter's images share the pixel cap: images that are each within it but pass it together
|
||||
/// are refused.
|
||||
#[test]
|
||||
fn a_filters_images_share_the_pixel_cap() {
|
||||
let img = |w: u32, h: u32| format!("<feImage href=\"data:image/png;base64,{}\"/>", base64(&png_claiming(w, h)));
|
||||
let half = img(4096, 2048);
|
||||
let err = check(&format!("<filter id=\"a\">{half}{}</filter>", img(4096, 2049))).unwrap_err();
|
||||
assert!(err.contains("pixels in all"), "{err}");
|
||||
let err = check(&format!("<filter id=\"a\">{half}{half}{}</filter>", img(1, 1))).unwrap_err();
|
||||
assert!(err.contains("pixels in all"), "{err}");
|
||||
assert!(check(&format!("<filter id=\"a\">{half}{half}</filter>")).is_ok(), "two halves fill the cap exactly");
|
||||
}
|
||||
|
||||
/// The image limit is for a filter's own images: the object it runs on is its source graphic
|
||||
/// whatever its size.
|
||||
#[test]
|
||||
fn a_large_object_is_still_the_source_graphic() {
|
||||
let w = 4097;
|
||||
let mut d = blue_square(w, 0);
|
||||
filter(json!({ "xml": RED_FLOOD })).apply(&mut d, w, w, &space(w, w, 1.0, 1.0));
|
||||
assert_eq!(at(&d, w, w / 2, w / 2), [255, 0, 0, 255]);
|
||||
}
|
||||
|
||||
fn crc32(bytes: &[u8]) -> u32 {
|
||||
let mut c = !0u32;
|
||||
for b in bytes {
|
||||
c ^= u32::from(*b);
|
||||
for _ in 0..8 {
|
||||
c = if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };
|
||||
}
|
||||
}
|
||||
!c
|
||||
}
|
||||
|
||||
/// A user-space region in percentages is written in user units, measured against the object's box.
|
||||
#[test]
|
||||
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(),
|
||||
Some(r#"<filter id="r" filterUnits="userSpaceOnUse" x="-10" y="0" width="40" height="10"><feOffset/></filter>"#)
|
||||
);
|
||||
let plain = filter(json!({ "xml": RED_FLOOD }));
|
||||
assert_eq!(plain.written_xml(Rect::new(0.0, 0.0, 1.0, 1.0)).as_deref(), Some(plain.xml()));
|
||||
}
|
||||
|
||||
/// A filter at the size limit whose region is measured against the box still draws: written in
|
||||
/// user units, the region can make the drawn form longer than the limit.
|
||||
#[test]
|
||||
fn a_filter_at_the_size_limit_draws_with_its_measured_region() {
|
||||
let open = r#"<filter id="r" filterUnits="userSpaceOnUse" x="-1%" y="-1%" width="1%" height="1%"><feOffset result=""#;
|
||||
let close = r#""/><feOffset/></filter>"#;
|
||||
let xml = format!("{open}{}{close}", "a".repeat(SvgFilter::MAX_XML - open.len() - close.len()));
|
||||
assert_eq!(xml.len(), SvgFilter::MAX_XML);
|
||||
assert_eq!(check(&xml), Ok("r".into()));
|
||||
let f = filter(json!({ "xml": xml }));
|
||||
let drawn = f.drawn_xml(Rect::new(0.123456789, 0.123456789, 1000.987654321, 1000.987654321)).unwrap();
|
||||
assert!(drawn.len() > SvgFilter::MAX_XML, "the region written out is longer: {} bytes", drawn.len());
|
||||
assert!(with_id(&drawn, DRAWN_ID).is_some(), "the drawn form is read");
|
||||
}
|
||||
|
||||
/// SVG output writes a filter live only when the form it writes, with its region and id, is one
|
||||
/// SVG import reads back: at most [`SvgFilter::MAX_XML`] bytes. A filter at the limit whose region
|
||||
/// is measured against the box, one at the limit whose id is a character long, and one whose
|
||||
/// shadows make its SVG 1.1 form longer are left to be written as other pixel effects are.
|
||||
#[test]
|
||||
fn svg_output_writes_a_filter_only_in_a_form_import_reads() {
|
||||
let at_limit = |open: &str, close: &str| {
|
||||
let xml = format!("{open}{}{close}", "a".repeat(SvgFilter::MAX_XML - open.len() - close.len()));
|
||||
assert_eq!((xml.len(), check(&xml).is_ok()), (SvgFilter::MAX_XML, true));
|
||||
filter(json!({ "xml": xml }))
|
||||
};
|
||||
let measured = at_limit(
|
||||
r#"<filter id="r" filterUnits="userSpaceOnUse" x="-1%" y="-1%" width="1%" height="1%"><feOffset result=""#,
|
||||
r#""/><feOffset/></filter>"#,
|
||||
);
|
||||
let short_id = at_limit(r#"<filter id="r"><feOffset result=""#, r#""/><feOffset/></filter>"#);
|
||||
let shadows = format!(r#"<filter id="s">{}<feOffset result="{}"/></filter>"#, "<feDropShadow/>".repeat(12), "a".repeat(SvgFilter::MAX_XML - 400));
|
||||
assert!(check(&shadows).is_ok() && shadows.len() <= SvgFilter::MAX_XML);
|
||||
for f in [measured, short_id, filter(json!({ "xml": shadows }))] {
|
||||
assert!(!f.writes_as_svg11() && f.written_xml(Rect::new(0.0, 0.0, 10.0, 10.0)).is_none(), "{} bytes", f.xml().len());
|
||||
}
|
||||
// Room for the id and the longest region: still written, and read back.
|
||||
let open = r#"<filter id="r" filterUnits="userSpaceOnUse" x="-1%" y="-1%" width="1%" height="1%"><feOffset result=""#;
|
||||
let close = r#""/><feOffset/></filter>"#;
|
||||
let xml = format!("{open}{}{close}", "a".repeat(MAX_WRITTEN_XML - REGION_ROOM - open.len() - close.len()));
|
||||
let f = filter(json!({ "xml": xml }));
|
||||
assert!(f.writes_as_svg11());
|
||||
let id = format!("u_vc_unique_-filter-{}", usize::MAX);
|
||||
let out = with_id(&f.written_xml(Rect::new(0.123456789, 0.123456789, 1000.987654321, 1000.987654321)).unwrap(), &id).unwrap();
|
||||
assert!(out.len() <= SvgFilter::MAX_XML && check(&out).is_ok(), "{} bytes", out.len());
|
||||
// The longest numbers a region can take still fit.
|
||||
let far = f.written_xml(Rect::new(-f64::MIN_POSITIVE, -f64::MIN_POSITIVE, f64::MAX / 4.0, f64::MAX / 4.0)).unwrap();
|
||||
assert!(with_id(&far, &id).is_some_and(|out| out.len() <= SvgFilter::MAX_XML));
|
||||
for v in [-f64::MIN_POSITIVE, -5e-324, -2.225073858507201e-308, f64::MIN, -1.0 / 3.0] {
|
||||
assert!(format!("{v}").len() <= MAX_NUMBER_TEXT, "{v:e}");
|
||||
}
|
||||
assert_eq!(format!("{}", -f64::MIN_POSITIVE).len(), MAX_NUMBER_TEXT);
|
||||
}
|
||||
|
||||
/// Only a type selector naming a filter or one of its elements, or `*`, lets a style sheet reach
|
||||
/// filters: class, id, attribute and pseudo-class names that contain "filter" or "fe" don't.
|
||||
#[test]
|
||||
fn style_sheets_reach_filters_only_through_their_type_selectors() {
|
||||
let reaches = |sheet: &str| {
|
||||
let svg = format!("<svg xmlns=\"http://www.w3.org/2000/svg\"><style>{sheet}</style></svg>");
|
||||
Styles::of(&roxmltree::Document::parse(&svg).unwrap()).reach_filters
|
||||
};
|
||||
for sheet in
|
||||
[".filter-button { color: red }", "#feature, .fe-icon { fill: blue }", "[data-filter] { fill: red }", "a:hover, rect.filter { stroke: red }"]
|
||||
{
|
||||
assert!(!reaches(sheet), "{sheet}");
|
||||
}
|
||||
for sheet in
|
||||
["filter { x: 0 }", "FeFlood { flood-color: red }", "svg|feBlend { mode: multiply }", "* { color: red }", "g :is(feGaussianBlur) { x: 0 }"]
|
||||
{
|
||||
assert!(reaches(sheet), "{sheet}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An attribute selector styles a filter whose elements carry that attribute, whatever its value
|
||||
/// or namespace prefix; a filter without it is not affected.
|
||||
#[test]
|
||||
fn an_attribute_selector_styles_a_filter_with_that_attribute() {
|
||||
let depends = |sheet: &str, filter: &str| {
|
||||
let svg = format!("<svg xmlns=\"http://www.w3.org/2000/svg\"><style>{sheet}</style><defs>{filter}</defs></svg>");
|
||||
let doc = roxmltree::Document::parse(&svg).unwrap();
|
||||
let f = doc.descendants().find(|n| n.tag_name().name() == "filter").unwrap();
|
||||
depends_on_styles(f, &Styles::of(&doc))
|
||||
};
|
||||
let tagged = r#"<filter id="a"><feFlood data-tone="warm"/></filter>"#;
|
||||
let plain = r#"<filter id="a"><feFlood/></filter>"#;
|
||||
for sheet in ["[data-tone] { flood-color: red }", "[data-tone=\"warm\"] { flood-color: red }", "[svg|data-tone ~= warm] { x: 0 }"] {
|
||||
assert!(depends(sheet, tagged), "{sheet}");
|
||||
assert!(!depends(sheet, plain), "{sheet}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_of_reads_at_most_256_filters() {
|
||||
let many = format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\">{}</svg>",
|
||||
(0..300).map(|i| format!("<filter id=\"f{i}\"><feOffset/></filter>")).collect::<String>()
|
||||
);
|
||||
let doc = roxmltree::Document::parse(&many).unwrap();
|
||||
let (found, skipped) = filters_of(&doc, &many, usize::MAX, |_| false);
|
||||
assert_eq!((found.len(), skipped), (MAX_FILTERS_READ, 300 - MAX_FILTERS_READ));
|
||||
}
|
||||
|
||||
/// However large `scale` makes them, a morphology radius spans at most 32 pixels of the raster the
|
||||
/// filter runs on, and a standard deviation at most 512.
|
||||
#[test]
|
||||
fn costly_lengths_are_clamped_in_pixels() {
|
||||
let sp = space(10, 10, 0.5, 0.5);
|
||||
let morph = filter(json!({ "xml": "<filter id=\"m\"><feMorphology radius=\"100\"/></filter>", "scale": 1000.0 }));
|
||||
let s = morph.resolution(&sp, 10.0);
|
||||
assert!(100.0 * 1000.0 / 0.5 * s <= 32.0 + 1e-6, "{s}");
|
||||
let blur = filter(json!({ "xml": "<filter id=\"b\"><feGaussianBlur stdDeviation=\"500\"/></filter>", "scale": 1000.0 }));
|
||||
let s = blur.resolution(&sp, 10.0);
|
||||
assert!(500.0 * 1000.0 / 0.5 * s <= 512.0 + 1e-6, "{s}");
|
||||
// At a fine raster too (1200 ppi): the cap holds.
|
||||
let fine = space(10, 10, 0.06, 0.06);
|
||||
let s = morph.resolution(&fine, 10.0);
|
||||
assert!(100.0 * 1000.0 / 0.06 * s <= 32.0 + 1e-6, "{s}");
|
||||
let small = filter(json!({ "xml": "<filter id=\"s\"><feMorphology radius=\"1\"/></filter>" }));
|
||||
assert_eq!(small.resolution(&sp, 10.0), 1.0, "a small radius runs at the raster's own pixels");
|
||||
// In the object's bounding box, a radius is a fraction of its box: half a 4096-pixel box.
|
||||
let boxed = filter(json!({ "xml": "<filter id=\"o\" primitiveUnits=\"objectBoundingBox\"><feMorphology radius=\"0.5\"/></filter>" }));
|
||||
let s = boxed.resolution(&sp, 4096.0);
|
||||
assert!(0.5 * 4096.0 * s <= 32.0 + 1e-6, "{s}");
|
||||
}
|
||||
|
||||
/// A filter that `check` refuses is never drawn, whatever path put it in an effect.
|
||||
#[test]
|
||||
fn an_unchecked_filter_is_not_drawn() {
|
||||
for xml in [
|
||||
"<filter id=\"a\"><feOffset/><script>alert(1)</script></filter>",
|
||||
"<filter id=\"a\"><feMorphology radius=\"1e6\"/></filter>",
|
||||
"<filter id=\"a\" onload=\"x()\"><feOffset/></filter>",
|
||||
] {
|
||||
let e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": xml }), visible: true };
|
||||
assert!(raster_effects(&[e]).is_empty(), "{xml}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Scale Strokes & Effects scales the filter's lengths with the art: the points a unit measures.
|
||||
#[test]
|
||||
fn scaling_the_effect_scales_its_units() {
|
||||
let mut e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": RED_FLOOD }), visible: true };
|
||||
crate::scale_effect(&mut e, 2.0);
|
||||
assert_eq!(e.params["scale"], json!(2.0));
|
||||
crate::scale_effect(&mut e, 0.25);
|
||||
assert_eq!(e.params["scale"], json!(0.5));
|
||||
}
|
||||
|
||||
/// The form SVG output writes, for a filter that fills a 10 × 10 point box.
|
||||
fn written(xml: &str) -> Option<String> {
|
||||
filter(json!({ "xml": xml })).written_xml(Rect::new(0.0, 0.0, 10.0, 10.0))
|
||||
}
|
||||
|
||||
/// SVG 1.1 output writes an image's reference as `xlink:href`; the filter as it is drawn and
|
||||
/// listed keeps `href`.
|
||||
#[test]
|
||||
fn an_image_is_written_with_an_xlink_reference() {
|
||||
let data = format!("data:image/png;base64,{}", base64(&png_claiming(2, 2)));
|
||||
let f = filter(json!({ "xml": format!(r#"<filter id="i"><feImage href="{data}"/></filter>"#) }));
|
||||
assert_eq!(f.xml(), format!(r#"<filter id="i"><feImage href="{data}"/></filter>"#));
|
||||
let out = f.written_xml(Rect::new(0.0, 0.0, 10.0, 10.0)).unwrap();
|
||||
assert_eq!(out, format!(r#"<filter id="i"><feImage xlink:href="{data}"/></filter>"#));
|
||||
assert!(f.writes_as_svg11());
|
||||
assert_eq!(check(&out), Ok("i".into()), "the written form reads back");
|
||||
}
|
||||
|
||||
/// SVG 1.1 has no `feDropShadow`: it is written as the primitives Filter Effects gives as its
|
||||
/// equivalent, with its defaults, input, result and subregion, and results no other primitive uses.
|
||||
#[test]
|
||||
fn a_drop_shadow_is_written_as_svg_1_1_primitives() {
|
||||
assert_eq!(
|
||||
written(r#"<filter id="s"><feDropShadow/></filter>"#).as_deref(),
|
||||
Some(concat!(
|
||||
r#"<filter id="s"><feGaussianBlur in="SourceGraphic" stdDeviation="2"/><feOffset dx="2" dy="2" result="vcShadow0"/><feFlood/>"#,
|
||||
r#"<feComposite in2="vcShadow0" operator="in" result="vcShadow1"/><feMerge><feMergeNode in="vcShadow1"/><feMergeNode in="SourceGraphic"/></feMerge></filter>"#,
|
||||
))
|
||||
);
|
||||
// Its input, result, subregion, color space and flood; a name the filter uses is not taken.
|
||||
let given = r#"<filter id="s"><feOffset dx="1" result="vcShadow0"/><feDropShadow in="vcShadow0" result="r" x="1" width="5" dx="3" dy="-1" stdDeviation="1 2" flood-color="rgba(255,0,0,0.5)" flood-opacity="50%" color-interpolation-filters="sRGB"/></filter>"#;
|
||||
assert_eq!(
|
||||
written(given).as_deref(),
|
||||
Some(concat!(
|
||||
r#"<filter id="s"><feOffset dx="1" result="vcShadow0"/>"#,
|
||||
r#"<feGaussianBlur in="vcShadow0" stdDeviation="1 2" color-interpolation-filters="sRGB"/><feOffset dx="3" dy="-1" result="vcShadow1" color-interpolation-filters="sRGB"/>"#,
|
||||
r##"<feFlood flood-color="#ff0000" flood-opacity="0.25098" color-interpolation-filters="sRGB"/>"##,
|
||||
r#"<feComposite in2="vcShadow1" operator="in" result="vcShadow2" color-interpolation-filters="sRGB"/>"#,
|
||||
r#"<feMerge x="1" width="5" result="r" color-interpolation-filters="sRGB"><feMergeNode in="vcShadow2"/><feMergeNode in="vcShadow0"/></feMerge></filter>"#,
|
||||
))
|
||||
);
|
||||
// An implicit input, or a result no earlier primitive has, is the previous result, named.
|
||||
for shadow in [r#"<feDropShadow dx="1"/>"#, r#"<feDropShadow in="nowhere" dx="1"/>"#] {
|
||||
let out = written(&format!(r#"<filter id="s"><feFlood flood-color="blue"/>{shadow}</filter>"#)).unwrap();
|
||||
assert!(out.starts_with(r##"<filter id="s"><feFlood flood-color="#0000ff" result="vcShadow0"/><feGaussianBlur in="vcShadow0""##), "{out}");
|
||||
assert!(out.ends_with(r#"<feMergeNode in="vcShadow0"/></feMerge></filter>"#), "{out}");
|
||||
assert_eq!(check(&out), Ok("s".into()), "the written form reads back");
|
||||
}
|
||||
// What SVG 1.1 can't hold leaves the filter to be written as other pixel effects are.
|
||||
for xml in [
|
||||
r#"<filter id="s"><feDropShadow flood-color="currentColor"/></filter>"#,
|
||||
r#"<filter id="s" primitiveUnits="objectBoundingBox"><feDropShadow/></filter>"#,
|
||||
] {
|
||||
let f = filter(json!({ "xml": xml }));
|
||||
assert!(!f.writes_as_svg11() && f.written_xml(Rect::new(0.0, 0.0, 10.0, 10.0)).is_none(), "{xml}");
|
||||
}
|
||||
// An offset that isn't a number is the shadow's default, which an `feOffset` doesn't share.
|
||||
let out = written(r#"<filter id="s"><feDropShadow dx="bad" dy="-3"/></filter>"#).unwrap();
|
||||
assert!(out.contains(r#"<feOffset dx="2" dy="-3""#), "{out}");
|
||||
// Expanded shadows past the primitive cap.
|
||||
let many = format!(r#"<filter id="s">{}</filter>"#, "<feDropShadow/>".repeat(13));
|
||||
assert!(!filter(json!({ "xml": many })).writes_as_svg11());
|
||||
}
|
||||
|
||||
/// Each input is written as the primitive it reads when drawn: a result name only usvg gives (to
|
||||
/// a primitive without a `result`, here the shadow), and the inputs usvg draws as `SourceGraphic`.
|
||||
#[test]
|
||||
fn inputs_are_written_as_the_primitives_they_read() {
|
||||
let xml = r#"<filter id="s"><feOffset dx="1"/><feDropShadow in="BackgroundImage"/><feOffset dx="2"/><feMerge><feMergeNode in="result2"/><feMergeNode in="FillPaint"/></feMerge><feComposite in="result1" in2="StrokePaint"/></filter>"#;
|
||||
let out = written(xml).unwrap();
|
||||
assert_eq!(
|
||||
out,
|
||||
concat!(
|
||||
r#"<filter id="s"><feOffset dx="1" result="vcShadow1"/>"#,
|
||||
r#"<feGaussianBlur in="SourceGraphic" stdDeviation="2"/><feOffset dx="2" dy="2" result="vcShadow2"/><feFlood/>"#,
|
||||
r#"<feComposite in2="vcShadow2" operator="in" result="vcShadow3"/><feMerge result="vcShadow0"><feMergeNode in="vcShadow3"/><feMergeNode in="SourceGraphic"/></feMerge>"#,
|
||||
r#"<feOffset dx="2"/><feMerge><feMergeNode in="vcShadow0"/><feMergeNode in="SourceGraphic"/></feMerge>"#,
|
||||
r#"<feComposite in="vcShadow1" in2="SourceGraphic"/></filter>"#,
|
||||
)
|
||||
);
|
||||
assert_eq!(check(&out), Ok("s".into()), "the written form reads back");
|
||||
}
|
||||
|
||||
/// Other values SVG 1.1 lacks: SVG 1.1 values that draw alike, or no SVG 1.1 form.
|
||||
#[test]
|
||||
fn values_svg_1_1_lacks_are_written_as_resvg_draws_them() {
|
||||
// `lighter` (Filter Effects) is drawn as the default `over`, and a blur has no `edgeMode`.
|
||||
assert_eq!(
|
||||
written(r#"<filter id="c"><feComposite in2="SourceAlpha" operator="lighter"/><feGaussianBlur stdDeviation="1" edgeMode="wrap"/></filter>"#)
|
||||
.as_deref(),
|
||||
Some(r#"<filter id="c"><feComposite in2="SourceAlpha"/><feGaussianBlur stdDeviation="1"/></filter>"#)
|
||||
);
|
||||
assert_eq!(
|
||||
written(r#"<filter id="c"><feBlend in2="SourceAlpha" mode="multiply"/></filter>"#).as_deref(),
|
||||
Some(r#"<filter id="c"><feBlend in2="SourceAlpha" mode="multiply"/></filter>"#)
|
||||
);
|
||||
// CSS colors as `#rrggbb`, a flood color's alpha in its opacity, a lighting color's dropped.
|
||||
assert_eq!(
|
||||
written(r#"<filter id="c" color="hsl(120, 100%, 50%)"><feFlood flood-color="transparent"/><feDiffuseLighting lighting-color="rgba(0,0,255,0.5)"><feDistantLight/></feDiffuseLighting></filter>"#)
|
||||
.as_deref(),
|
||||
Some(
|
||||
r##"<filter id="c" color="#00ff00"><feFlood flood-color="#000000" flood-opacity="0"/><feDiffuseLighting lighting-color="#0000ff"><feDistantLight/></feDiffuseLighting></filter>"##
|
||||
)
|
||||
);
|
||||
// Image scaling as an SVG 1.1 keyword.
|
||||
let data = format!("data:image/png;base64,{}", base64(&png_claiming(2, 2)));
|
||||
for (given, kept) in
|
||||
[("pixelated", "optimizeSpeed"), ("crisp-edges", "optimizeSpeed"), ("smooth", "optimizeQuality"), ("auto", "optimizeQuality")]
|
||||
{
|
||||
let out = written(&format!(r#"<filter id="i"><feImage style="image-rendering:{given}" href="{data}"/></filter>"#)).unwrap();
|
||||
assert!(out.contains(&format!(r#"style="image-rendering:{kept}""#)), "{given}: {out}");
|
||||
}
|
||||
// The blend modes SVG 1.1 lacks have no SVG 1.1 form.
|
||||
for mode in LATER_BLEND_MODES {
|
||||
let f = filter(json!({ "xml": format!(r#"<filter id="b"><feBlend in2="SourceAlpha" mode="{mode}"/></filter>"#) }));
|
||||
assert!(!f.writes_as_svg11(), "{mode}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base64_pads_as_rfc_4648_does() {
|
||||
assert_eq!(base64(b""), "");
|
||||
assert_eq!(base64(b"f"), "Zg==");
|
||||
assert_eq!(base64(b"fo"), "Zm8=");
|
||||
assert_eq!(base64(b"foo"), "Zm9v");
|
||||
assert_eq!(base64(b"foobar"), "Zm9vYmFy");
|
||||
}
|
||||
+157
-5
@@ -180,6 +180,24 @@ fn warp_zero_bend_is_identity_ish() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `warp::bends` says a warp moves placed gradients exactly when the warp moves the outline:
|
||||
/// Arc leaves the outline as it is under a bend of 0.0001 % and moves it above that, and the other
|
||||
/// styles move it at any bend.
|
||||
#[test]
|
||||
fn warp_bends_when_the_warp_moves_the_outline() {
|
||||
// A star: Fisheye moves nothing on the edge of the box, where an ellipse or a rectangle lies.
|
||||
let oval = shapes::star(Point::new(51.7, 34.3), 40.9, 17.3, 5, 7.0);
|
||||
for (s, _) in WARP_STYLES {
|
||||
let id = format!("warp.{s}");
|
||||
let flat = run(&id, json!({"bend": 0}), &oval);
|
||||
for bend in [0.0, 1e-5, -1e-5, 0.9e-4, -0.9e-4, 1.1e-4, -1.1e-4] {
|
||||
let p = json!({ "bend": bend });
|
||||
let moved = run(&id, p.clone(), &oval) != flat;
|
||||
assert_eq!(crate::warp::bends(&id, &p), moved, "{id} at {bend} %");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warp_arc_bends_the_top_edge() {
|
||||
let out = run("warp.arc", json!({"bend": 50}), &square());
|
||||
@@ -394,7 +412,7 @@ fn stacked_effects_on_art_stay_within_the_anchor_budget() {
|
||||
let leaf = |x: f64| Arc::new(Node::path(id, shapes::rectangle(Rect::new(x, 0.0, x + 100.0, 100.0)), Appearance::default()));
|
||||
let mut art = Node::group(id, (0..10).map(|k| leaf(k as f64 * 120.0)).collect());
|
||||
let rough = fx("distort.roughen", json!({"size": 50, "detail": 100}));
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&rough, &rough, &rough], Budget { anchors: 5_000, lines: usize::MAX });
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&rough, &rough, &rough], Budget { anchors: 5_000, lines: usize::MAX }, None);
|
||||
let mut total = 0;
|
||||
let mut reshaped = 0;
|
||||
for c in art.children().into_iter().flatten() {
|
||||
@@ -407,6 +425,140 @@ fn stacked_effects_on_art_stay_within_the_anchor_budget() {
|
||||
assert_eq!(reshaped, 10);
|
||||
}
|
||||
|
||||
/// A path that keeps its shape because its Transform effect would pass the budget keeps the
|
||||
/// gradients that paint the art as a whole in place too, also with Scale Strokes & Effects on.
|
||||
#[test]
|
||||
fn art_past_the_budget_keeps_its_own_gradients_in_place() {
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
use vectorcraft_doc::{AppearanceItem, FillLayer, NodeId, color::Paint};
|
||||
let id = NodeId(9);
|
||||
let stops = vec![GradientStop::new(0.0, vectorcraft_color::Color::BLACK), GradientStop::new(1.0, vectorcraft_color::Color::WHITE)];
|
||||
let geom = GradientGeom { start: (0.0, 50.0).into(), end: (100.0, 50.0).into(), aspect: 1.0, focal: None };
|
||||
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..GradientPaint::new(Gradient::new(GradientKind::Linear, stops)) }));
|
||||
let circle = || Arc::new(Node::path(id, shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default()));
|
||||
// The group's own fill, a gradient placed across the circle, after `carry` moves it.
|
||||
let own_end = |carry: &crate::Carry| {
|
||||
let mut ap = Appearance::default();
|
||||
ap.items.push(AppearanceItem::Fill(FillLayer::new(placed.clone())));
|
||||
carry.apply(&mut ap);
|
||||
match ap.fill_paint() {
|
||||
Paint::Gradient(g) => g.geom.map(|g| g.end.x),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
for params in [json!({"scaleH": 1000, "scaleV": 1000}), json!({"scaleH": 1000, "scaleV": 1000, "strokes": true})] {
|
||||
let grow = fx("distort.transform", params.clone());
|
||||
let mut art = Node::group(id, vec![circle()]);
|
||||
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&grow], Budget::EFFECTS, None);
|
||||
let end = own_end(&carry).unwrap();
|
||||
assert!((end - 550.0).abs() < 1e-6, "{params}: within the budget the group's gradient grows with the circle: {end}");
|
||||
// No room beyond what the circle costs: scaled up, it would be drawn with more lines.
|
||||
let mut art = Node::group(id, vec![circle()]);
|
||||
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&grow], Budget { anchors: usize::MAX, lines: 0 }, None);
|
||||
let b = art.geometric_bounds().unwrap();
|
||||
assert!(b.width() < 101.0 && b.height() < 101.0, "{params}: the circle keeps its shape: {b:?}");
|
||||
assert_eq!(own_end(&carry), Some(100.0), "{params}: the group's gradient stays where it was placed");
|
||||
// A group inside the art whose square took the effect moves its own gradient all the same.
|
||||
let square = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default()));
|
||||
let mut inner = Node::group(NodeId(2), vec![square]);
|
||||
inner.appearance.items.push(AppearanceItem::Fill(FillLayer::new(placed.clone())));
|
||||
let mut art = Node::group(id, vec![circle(), Arc::new(inner)]);
|
||||
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&grow], Budget { anchors: usize::MAX, lines: 0 }, None);
|
||||
assert_eq!(own_end(&carry), Some(100.0), "{params}: the art's own gradient stays");
|
||||
let inner = &art.children().unwrap()[1];
|
||||
let Paint::Gradient(g) = inner.appearance.fill_paint() else { panic!("a gradient") };
|
||||
assert!((g.geom.unwrap().end.x - 550.0).abs() < 1e-6, "{params}: the inner group's gradient: {:?}", g.geom);
|
||||
}
|
||||
}
|
||||
|
||||
/// A hidden path in a layer that keeps its shape past the budget does not hold the layer's
|
||||
/// gradients in place: the layer's bounds leave it out, so the layer's own gradient moves with
|
||||
/// the visible art under a Transform effect and Free Distort, as does the art's when the layer is
|
||||
/// the art.
|
||||
#[test]
|
||||
fn a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move() {
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
use vectorcraft_doc::{AppearanceItem, FillLayer, LayerColor, NodeId, NodeKind, color::Paint};
|
||||
let stops = vec![GradientStop::new(0.0, vectorcraft_color::Color::BLACK), GradientStop::new(1.0, vectorcraft_color::Color::WHITE)];
|
||||
let geom = GradientGeom { start: (0.0, 50.0).into(), end: (100.0, 50.0).into(), aspect: 1.0, focal: None };
|
||||
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..GradientPaint::new(Gradient::new(GradientKind::Linear, stops)) }));
|
||||
let end = |ap: &Appearance| match ap.fill_paint() {
|
||||
Paint::Gradient(g) => g.geom.map(|g| g.end.x),
|
||||
_ => None,
|
||||
};
|
||||
// A layer with a visible square and a hidden circle, both 0..100, and a gradient fill of its own.
|
||||
let layer = || {
|
||||
let square = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default()));
|
||||
let mut circle = Node::path(NodeId(4), shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default());
|
||||
circle.visible = false;
|
||||
let mut layer = Node::layer(NodeId(2), "Layer 1", LayerColor::Preset(0));
|
||||
if let NodeKind::Layer { children, .. } = &mut layer.kind {
|
||||
*children = vec![square, Arc::new(circle)];
|
||||
}
|
||||
layer.appearance.items.push(AppearanceItem::Fill(FillLayer::new(placed.clone())));
|
||||
layer
|
||||
};
|
||||
// No room beyond what the paths cost: the square takes each effect, the circle would be drawn
|
||||
// with more lines and keeps its shape.
|
||||
let budget = Budget { anchors: usize::MAX, lines: 0 };
|
||||
// Each scales the art ten times about its center: 0..100 becomes -450..550.
|
||||
let corners = json!({"corners": [[-4.5, -4.5], [5.5, -4.5], [5.5, 5.5], [-4.5, 5.5]]});
|
||||
for grow in [fx("distort.transform", json!({"scaleH": 1000, "scaleV": 1000})), fx("distort.freeDistort", corners)] {
|
||||
let mut art = layer();
|
||||
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&grow], budget, None);
|
||||
let circle = art.children().unwrap()[1].geometric_bounds().unwrap();
|
||||
assert!(circle.width() < 101.0, "{}: the hidden circle keeps its shape: {circle:?}", grow.id);
|
||||
let square = art.children().unwrap()[0].geometric_bounds().unwrap();
|
||||
assert!((square.x1 - 550.0).abs() < 1e-6, "{}: the square takes the effect: {square:?}", grow.id);
|
||||
let mut own = Appearance::clone(&art.appearance);
|
||||
carry.apply(&mut own);
|
||||
assert_eq!(end(&own), Some(550.0), "{}: the layer's gradient, as the art", grow.id);
|
||||
let mut art = Node::group(NodeId(9), vec![Arc::new(layer())]);
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&grow], budget, None);
|
||||
assert_eq!(end(&art.children().unwrap()[0].appearance), Some(550.0), "{}: the layer's gradient, inside the art", grow.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// A freeform gradient whose points were edited (its vector still fitted to the bounds) moves its
|
||||
/// points with a Transform effect and Free Distort, on a path, on a group inside the art and on the
|
||||
/// art itself, as a placed gradient does.
|
||||
#[test]
|
||||
fn edited_freeform_points_follow_a_transform_effect_and_free_distort() {
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{Color, Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint};
|
||||
use vectorcraft_doc::{AppearanceItem, FillLayer, NodeId, color::Paint};
|
||||
let mut ramp = GradientPaint::new(Gradient { kind: GradientKind::Freeform, ..Gradient::default() });
|
||||
let pt = |x: f64, c| FreeformPoint::new(Point::new(x, 50.0), c);
|
||||
ramp.set_freeform(Freeform { points: vec![pt(0.0, Color::BLACK), pt(100.0, Color::WHITE)], ..Default::default() });
|
||||
assert!(ramp.geom.is_none() && !ramp.is_placed());
|
||||
let freeform = Paint::Gradient(Box::new(ramp));
|
||||
let xs = |ap: &Appearance| match ap.fill_paint() {
|
||||
Paint::Gradient(g) => g.freeform.as_ref().map(|f| f.points.iter().map(|p| p.at.x).collect::<Vec<_>>()),
|
||||
_ => None,
|
||||
};
|
||||
let square = |ap: Appearance| Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), ap));
|
||||
// Each moves the art 30 pt right.
|
||||
let corners = json!({"corners": [[0.3, 0.0], [1.3, 0.0], [1.3, 1.0], [0.3, 1.0]]});
|
||||
for e in [fx("distort.transform", json!({"moveH": 30})), fx("distort.freeDistort", corners)] {
|
||||
let mut inner = Node::group(NodeId(2), vec![square(Appearance::default())]);
|
||||
inner.appearance.items.push(AppearanceItem::Fill(FillLayer::new(freeform.clone())));
|
||||
let mut art = Node::group(NodeId(9), vec![square(Appearance::basic(freeform.clone(), Paint::None, 0.0)), Arc::new(inner)]);
|
||||
art.appearance.items.push(AppearanceItem::Fill(FillLayer::new(freeform.clone())));
|
||||
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&e], Budget::EFFECTS, None);
|
||||
let members = art.children().unwrap();
|
||||
assert_eq!(xs(&members[0].appearance), Some(vec![30.0, 130.0]), "{}: the path's points", e.id);
|
||||
assert_eq!(xs(&members[1].appearance), Some(vec![30.0, 130.0]), "{}: the inner group's points", e.id);
|
||||
let mut own = Appearance::clone(&art.appearance);
|
||||
carry.apply(&mut own);
|
||||
assert_eq!(xs(&own), Some(vec![30.0, 130.0]), "{}: the art's own points", e.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// #3578: a large Roughen draws each of its points as many lines; they stay within the budget,
|
||||
/// the Roughen built again with fewer points where they wouldn't.
|
||||
#[test]
|
||||
@@ -473,7 +625,7 @@ fn reshape_leaves_within_optimizes_transform_before_terminal_offset_path() {
|
||||
let offset = fx("path.offsetPath", json!({"offset": 4.0, "joins": "round"}));
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&transform, &offset], Budget::EFFECTS);
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&transform, &offset], Budget::EFFECTS, None);
|
||||
let elapsed = start.elapsed();
|
||||
assert!(elapsed < std::time::Duration::from_secs(2));
|
||||
|
||||
@@ -500,7 +652,7 @@ fn reshape_leaves_within_preserves_order_when_not_terminal_or_not_style_safe() {
|
||||
let mut art_evenodd = Node::group(id, vec![Arc::new(leaf)]);
|
||||
let transform = fx("distort.transform", json!({"moveH": 2.0, "moveV": 2.0, "copies": 2}));
|
||||
let offset = fx("path.offsetPath", json!({"offset": 4.0}));
|
||||
crate::reshape::reshape_leaves_within(&mut art_evenodd, &[&transform, &offset], Budget::EFFECTS);
|
||||
crate::reshape::reshape_leaves_within(&mut art_evenodd, &[&transform, &offset], Budget::EFFECTS, None);
|
||||
let p = art_evenodd.children().unwrap()[0].path_data().unwrap();
|
||||
assert_eq!(p.subpaths.len(), 1, "EvenOdd does not swap; copies union into 1 outer subpath");
|
||||
|
||||
@@ -508,7 +660,7 @@ fn reshape_leaves_within_preserves_order_when_not_terminal_or_not_style_safe() {
|
||||
let leaf_round = Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default()));
|
||||
let mut art_round = Node::group(id, vec![leaf_round]);
|
||||
let round_corners = fx("stylize.roundCorners", json!({"radius": 2.0}));
|
||||
crate::reshape::reshape_leaves_within(&mut art_round, &[&transform, &offset, &round_corners], Budget::EFFECTS);
|
||||
crate::reshape::reshape_leaves_within(&mut art_round, &[&transform, &offset, &round_corners], Budget::EFFECTS, None);
|
||||
let p = art_round.children().unwrap()[0].path_data().unwrap();
|
||||
assert_eq!(p.subpaths.len(), 1, "Non-terminal Offset Path does not swap; copies union into 1 outer subpath");
|
||||
|
||||
@@ -516,7 +668,7 @@ fn reshape_leaves_within_preserves_order_when_not_terminal_or_not_style_safe() {
|
||||
let leaf_miter = Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default()));
|
||||
let mut art_miter = Node::group(id, vec![leaf_miter]);
|
||||
let offset_miter = fx("path.offsetPath", json!({"offset": 4.0, "joins": "miter"}));
|
||||
crate::reshape::reshape_leaves_within(&mut art_miter, &[&transform, &offset_miter], Budget::EFFECTS);
|
||||
crate::reshape::reshape_leaves_within(&mut art_miter, &[&transform, &offset_miter], Budget::EFFECTS, None);
|
||||
let p = art_miter.children().unwrap()[0].path_data().unwrap();
|
||||
assert_eq!(p.subpaths.len(), 1, "Miter join does not swap; copies union into 1 outer subpath");
|
||||
}
|
||||
|
||||
@@ -32,3 +32,14 @@ pub fn warp(path: &PathData, b: Rect, style: WarpStyle, p: &Value, max: usize) -
|
||||
let piece = b.width().hypot(b.height()) / 24.0;
|
||||
map_nonlinear_within(path, piece, max, f)
|
||||
}
|
||||
|
||||
/// Does warp effect `id` with params `p` move any point? Every style leaves the box as it is with
|
||||
/// no bend and no distortion, and Arc (`warp.arc`) takes a bend under 0.0001 % as none: the
|
||||
/// threshold must match the one in [`warp_point`]'s Arc case (`warp_bends_when_the_warp_moves_the_outline`
|
||||
/// tests both sides of it).
|
||||
pub(crate) fn bends(id: &str, p: &Value) -> bool {
|
||||
let share = |key: &str, default: f64| num(p, key, default).clamp(-100.0, 100.0) / 100.0;
|
||||
let bend = share("bend", 50.0);
|
||||
let bent = if id == "warp.arc" { bend.abs() >= 1e-6 } else { bend != 0.0 };
|
||||
bent || share("horizontal", 0.0) != 0.0 || share("vertical", 0.0) != 0.0
|
||||
}
|
||||
@@ -9,10 +9,14 @@ description = "VectorCraft engine: sessions, history, selection, the command reg
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = ["bundled-fonts"]
|
||||
default = ["bundled-fonts", "heif"]
|
||||
# The fonts vectorcraft-text bundles (see its `bundled-fonts`). Embedders that supply every font at
|
||||
# run time (`vectorcraft_text::FontDb::add_font`) build with `default-features = false`.
|
||||
bundled-fonts = ["vectorcraft-text/bundled-fonts"]
|
||||
# HEIC and HEIF images open and place, decoded by heic-rs (an HEVC decoder). A build without this
|
||||
# feature still recognizes the files and refuses them with a message. The apps list it beside
|
||||
# `bundled-fonts`.
|
||||
heif = ["dep:heic-rs", "dep:rayon"]
|
||||
|
||||
[dependencies]
|
||||
# Which paths stored in documents may be opened.
|
||||
@@ -37,7 +41,12 @@ vectorcraft-plugins = { workspace = true }
|
||||
vectorcraft-affinity = { workspace = true }
|
||||
vectorcraft-scriptcheck = { workspace = true }
|
||||
image = { workspace = true }
|
||||
jxl-oxide = { workspace = true }
|
||||
jxl-color = { workspace = true }
|
||||
jxl-grid = { workspace = true }
|
||||
hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"] }
|
||||
# Pure Rust, no unsafe; pinned at the version photocraft-heif uses.
|
||||
heic-rs = { version = "=0.1.4", default-features = false, features = ["std"], optional = true }
|
||||
flate2 = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
# The XML parts of Word documents placed as type (place/docx.rs).
|
||||
@@ -55,6 +64,11 @@ log = { workspace = true }
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { workspace = true, features = ["std", "process"] }
|
||||
|
||||
# The tiles of a HEIC photo decode in parallel on native; wasm stays single-threaded.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true }
|
||||
rayon = { version = "1.12", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
vectorcraft-affinity = { workspace = true, features = ["synth"] }
|
||||
crc32fast = { workspace = true }
|
||||
@@ -67,5 +81,8 @@ vectorcraft-pdf = { workspace = true, features = ["read-count"] }
|
||||
wat = { workspace = true }
|
||||
# Zstandard streams for the Illustrator editing data fuzz tests.
|
||||
ruzstd = { workspace = true }
|
||||
# JPEG XL files for the `.jxl` open and place tests.
|
||||
zune-jpegxl = { workspace = true }
|
||||
zune-core = { workspace = true }
|
||||
# The JavaScript parser's lexer, compared with the script checker's on the same scripts.
|
||||
vectorcraft-js = { workspace = true }
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The command registry. Ids follow Illustrator's menu structure.
|
||||
|
||||
pub mod actionset;
|
||||
mod addons;
|
||||
pub(crate) mod appearance;
|
||||
mod assets;
|
||||
@@ -11,6 +12,7 @@ pub mod clipboard;
|
||||
mod colorcmds;
|
||||
pub mod colormgmt;
|
||||
pub mod colortheme;
|
||||
pub mod compositefonts;
|
||||
mod compoundshape;
|
||||
pub(crate) mod create;
|
||||
mod css;
|
||||
@@ -84,6 +86,7 @@ pub mod spelling;
|
||||
mod stroke;
|
||||
mod style;
|
||||
pub mod stylelib;
|
||||
mod svgfilter;
|
||||
mod swatch;
|
||||
pub mod swatchlib;
|
||||
pub(crate) mod symboledit;
|
||||
@@ -285,6 +288,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(inline::specs());
|
||||
v.extend(textstyles::specs());
|
||||
v.extend(fonts::specs());
|
||||
v.extend(compositefonts::specs());
|
||||
v.extend(fontfiles::specs());
|
||||
v.extend(help::specs());
|
||||
v.extend(threads::specs());
|
||||
@@ -319,6 +323,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(attributes::specs());
|
||||
v.extend(interactivity::specs());
|
||||
v.extend(spelling::specs());
|
||||
v.extend(svgfilter::specs());
|
||||
v.extend(newart::specs());
|
||||
v.extend(colortheme::specs());
|
||||
v.extend(fileio::pdf::specs());
|
||||
@@ -346,14 +351,23 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(halftone::specs());
|
||||
v.extend(perspgrid::specs());
|
||||
v.extend(shortcutset::specs());
|
||||
v.extend(actionset::specs());
|
||||
v.extend(importmatches::specs());
|
||||
v.extend(addons::specs());
|
||||
v
|
||||
})
|
||||
}
|
||||
|
||||
/// The command `id`: a built-in one, or a command an installed plug-in adds
|
||||
/// ([`plugin::command_specs`]).
|
||||
pub fn find_command(id: &str) -> Option<&'static CommandSpec> {
|
||||
command_specs().iter().find(|c| c.id == id)
|
||||
command_specs().iter().find(|c| c.id == id).or_else(|| plugin::find_spec(id))
|
||||
}
|
||||
|
||||
/// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in
|
||||
/// ([`plugin::run_command`]), which needs the command's id.
|
||||
pub(crate) fn run_spec(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result<Value> {
|
||||
if plugin::is_command_id(spec.id) { plugin::run_command(s, spec.id, p) } else { (spec.run)(s, p) }
|
||||
}
|
||||
|
||||
// ---------- param helpers ----------
|
||||
@@ -418,8 +432,22 @@ pub(crate) fn text_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<Optio
|
||||
pub(crate) fn id_param(p: &Value, key: &str) -> Option<NodeId> {
|
||||
p.get(key).and_then(Value::as_u64).map(NodeId)
|
||||
}
|
||||
pub(crate) fn ids_param(p: &Value, key: &str) -> Option<Vec<NodeId>> {
|
||||
p.get(key).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).map(NodeId).collect())
|
||||
/// The object ids `p` gives for `key`, or `None` when `p` leaves it out or gives null. A value that
|
||||
/// is not an array, or an entry that is not a non-negative integer, is an error with the message
|
||||
/// [`checked_ids_param`] gives, so no entry is dropped. Whether each id names an object is left to
|
||||
/// the caller.
|
||||
pub(crate) fn ids_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Vec<NodeId>>> {
|
||||
let values = match p.get(key) {
|
||||
None | Some(Value::Null) => return Ok(None),
|
||||
Some(Value::Array(a)) => a,
|
||||
Some(_) => return Err(bad(cmd, format!("{key} must be an array of non-negative integer object ids"))),
|
||||
};
|
||||
values.iter().enumerate().map(|(index, value)| id_entry(value, key, index, cmd)).collect::<Result<Vec<_>>>().map(Some)
|
||||
}
|
||||
/// Entry `index` (from 0) of the `key` list as an object id: anything but a non-negative integer is
|
||||
/// an error naming the key, the entry and its value.
|
||||
fn id_entry(value: &Value, key: &str, index: usize, cmd: &str) -> Result<NodeId> {
|
||||
value.as_u64().map(NodeId).ok_or_else(|| bad(cmd, format!("`{key}` entry {index} is {value}, not a non-negative integer object id")))
|
||||
}
|
||||
/// The objects `p` gives `command`: its `ids`, else its `id` as `ids` of one (as [`targets`] reads
|
||||
/// them), each checked ([`checked_id`]): a malformed one, or one naming no object, is an error,
|
||||
@@ -445,7 +473,7 @@ pub(crate) fn index(v: u64) -> usize {
|
||||
pub(crate) fn checked_ids_param(s: &Session, p: &Value, key: &str, command: &str) -> Result<Vec<NodeId>> {
|
||||
let values =
|
||||
p.get(key).and_then(Value::as_array).ok_or_else(|| bad(command, format!("{key} must be an array of non-negative integer object ids")))?;
|
||||
values.iter().map(|value| checked_id(s, value, command)).collect()
|
||||
values.iter().enumerate().map(|(index, value)| id_entry(value, key, index, command).and_then(|_| checked_id(s, value, command))).collect()
|
||||
}
|
||||
|
||||
/// The objects a command acts on: `ids` when given (every one checked, and those inside another
|
||||
@@ -592,11 +620,16 @@ pub(crate) fn object_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Nod
|
||||
}
|
||||
|
||||
/// Objects a command targets: its `ids`, else its `id` as `ids` of one ([`named_ids`]), else the
|
||||
/// selection. An `ids` or `id` that isn't an object id is an error, never the selection.
|
||||
/// selection. An `ids` or `id` that isn't an object id is an error, never the selection. The
|
||||
/// selection is refused while an object of a dynamic symbol instance's art is selected, as by
|
||||
/// [`edit::selected_roots`].
|
||||
pub(crate) fn targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
match named_ids(p)? {
|
||||
Some(ids) => Ok(ids),
|
||||
None => Ok(s.doc()?.selection.objects.clone()),
|
||||
None => {
|
||||
edit::refuse_symbol_part(s)?;
|
||||
Ok(s.doc()?.selection.objects.clone())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -669,6 +702,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
|
||||
|
||||
pub(crate) use edit::{settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
|
||||
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
|
||||
|
||||
@@ -0,0 +1,560 @@
|
||||
//! Action sets another app saves as text (`.aia` files that start `/version`), read into their
|
||||
//! actions and steps without changing anything (`actionSet.read`).
|
||||
//!
|
||||
//! The text is a set of fields and blocks. A slash name followed by a value sets a field, and a
|
||||
//! slash name followed by `{` opens a block that `}` closes. A value is a decimal number, text in
|
||||
//! parentheses, a byte count and hexadecimal bytes in square brackets (`[ 5 48656c6c6f ]`, UTF-8
|
||||
//! text, which can run over several words), or a byte count and hexadecimal bytes in angle brackets
|
||||
//! (`< 3 0a0b0c >`, raw bytes). The set's `/version` comes first, and its `/name` is hexadecimal
|
||||
//! 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`
|
||||
//! 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
|
||||
//! "Made a two-way aia to json converter"
|
||||
//! (https://community.adobe.com/t5/illustrator-discussions/made-a-two-way-aia-to-json-converter/m-p/13751909),
|
||||
//! sttk3's article on names as UTF-8 hexadecimal
|
||||
//! (https://sttk3.com/blog/tips/illustrator/dynamic-generate-action.html), and the MIT-licensed
|
||||
//! reader in zachshallbetter/adobe-mcp (https://github.com/zachshallbetter/adobe-mcp). The raw form
|
||||
//! follows the forum thread "Creating a dynamic action"
|
||||
//! (https://community.adobe.com/questions-652/creating-a-dynamic-action-to-use-with-app-doscript-method-814406).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, text_param};
|
||||
|
||||
/// The most bytes of a file read.
|
||||
const MAX_BYTES: usize = 8 << 20;
|
||||
/// The most bytes taken in: [`MAX_BYTES`] after a byte order mark, and one more that shows the text
|
||||
/// goes on.
|
||||
const READ_LIMIT: usize = MAX_BYTES + 4;
|
||||
/// The most blocks open at once.
|
||||
const MAX_DEPTH: usize = 16;
|
||||
/// The most actions read.
|
||||
const MAX_ACTIONS: usize = 1000;
|
||||
/// The most steps read in one action.
|
||||
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 longest name kept (bytes).
|
||||
const MAX_NAME: usize = 1024;
|
||||
/// The most tokens listed as unread.
|
||||
const MAX_UNREAD: usize = 1000;
|
||||
/// The longest unread token shown (characters).
|
||||
const UNREAD_SHOWN: usize = 80;
|
||||
|
||||
/// The extensions of action sets other apps save.
|
||||
pub const EXTS: &[&str] = &["aia"];
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
query "actionSet.read",
|
||||
"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",
|
||||
always,
|
||||
read
|
||||
)]
|
||||
}
|
||||
|
||||
/// A step of an action: an `/event-N` block.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AiaStep {
|
||||
/// Its `/internalName`.
|
||||
pub name: String,
|
||||
/// Its `/localizedName`, if it has one.
|
||||
pub label: Option<String>,
|
||||
/// Its `/isOn`, if it has one.
|
||||
pub on: Option<i64>,
|
||||
/// How many `/parameter-N` blocks it has.
|
||||
pub params: usize,
|
||||
/// Its `/parameterCount`, if it has one.
|
||||
pub declared: Option<i64>,
|
||||
/// The line its block opens on (from 1).
|
||||
pub line: usize,
|
||||
}
|
||||
|
||||
/// An action: an `/action-N` block.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AiaAction {
|
||||
pub name: String,
|
||||
pub steps: Vec<AiaStep>,
|
||||
/// Its `/eventCount`, if it has one.
|
||||
pub declared: Option<i64>,
|
||||
}
|
||||
|
||||
/// An action set read from text.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AiaSet {
|
||||
pub version: i64,
|
||||
/// The set's `/name`, if it has one.
|
||||
pub name: Option<String>,
|
||||
pub actions: Vec<AiaAction>,
|
||||
/// Its `/actionCount`, if it has one.
|
||||
pub declared: Option<i64>,
|
||||
/// The tokens that weren't read, with their lines.
|
||||
pub unread: Vec<(usize, String)>,
|
||||
/// A cap stopped the reading or cut a name, the text ends inside a block or a value or after a
|
||||
/// field's name, its counts differ from the actions, steps and recorded values read (a negative
|
||||
/// count, one too large for an `i64` and one that isn't a number always differ), or a hexadecimal
|
||||
/// name, label or recorded `/value` isn't as many bytes as its count says.
|
||||
pub truncated: bool,
|
||||
/// How many steps were read in all the actions.
|
||||
steps: usize,
|
||||
}
|
||||
|
||||
/// A token of the text.
|
||||
enum Token {
|
||||
/// A slash name.
|
||||
Name(Vec<u8>),
|
||||
/// An integer; `None` when it doesn't fit an `i64`.
|
||||
Int(Option<i64>),
|
||||
/// Text in parentheses, a backslash taking the next byte as it is.
|
||||
Text(Vec<u8>),
|
||||
/// The bytes of `[ count hex… ]`; `None` when the hexadecimal digits don't make whole bytes or
|
||||
/// as many bytes as the count says.
|
||||
Hex(Option<Vec<u8>>),
|
||||
/// `< count hex… >`.
|
||||
Raw,
|
||||
Open,
|
||||
Close,
|
||||
/// Anything else, as written.
|
||||
Other(Vec<u8>),
|
||||
}
|
||||
|
||||
/// The tokens of `text`, each with its line.
|
||||
struct Tokens<'a> {
|
||||
text: &'a [u8],
|
||||
at: usize,
|
||||
line: usize,
|
||||
/// The text ended inside a value in parentheses, square brackets or angle brackets.
|
||||
unclosed: bool,
|
||||
}
|
||||
|
||||
impl<'a> Tokens<'a> {
|
||||
/// Past one byte, counting a line at LF, at CR alone, and once for CRLF.
|
||||
fn step(&mut self) -> Option<u8> {
|
||||
let b = *self.text.get(self.at)?;
|
||||
if b == b'\n' || b == b'\r' && self.text.get(self.at + 1) != Some(&b'\n') {
|
||||
self.line += 1;
|
||||
}
|
||||
self.at += 1;
|
||||
Some(b)
|
||||
}
|
||||
|
||||
/// The bytes up to `end` (not taken in); `None` when the text ends first.
|
||||
fn until(&mut self, end: u8) -> Option<&'a [u8]> {
|
||||
let (text, start) = (self.text, self.at);
|
||||
while text.get(self.at).is_some_and(|&b| b != end) {
|
||||
self.step();
|
||||
}
|
||||
let inside = text.get(start..self.at)?;
|
||||
text.get(self.at)?;
|
||||
self.at += 1;
|
||||
Some(inside)
|
||||
}
|
||||
|
||||
fn next_token(&mut self) -> Option<(usize, Token)> {
|
||||
while self.text.get(self.at).is_some_and(|&b| b.is_ascii_whitespace() || b == 0) {
|
||||
self.step();
|
||||
}
|
||||
let line = self.line;
|
||||
let b = *self.text.get(self.at)?;
|
||||
let ends = |b: u8| b.is_ascii_whitespace() || b == 0 || b"{}[]()<>/".contains(&b);
|
||||
let token = match b {
|
||||
b'{' | b'}' => {
|
||||
self.at += 1;
|
||||
if b == b'{' { Token::Open } else { Token::Close }
|
||||
}
|
||||
b'(' => {
|
||||
self.at += 1;
|
||||
let (mut text, mut depth) = (vec![], 0usize);
|
||||
self.unclosed = true;
|
||||
while let Some(c) = self.step() {
|
||||
match c {
|
||||
b'\\' => text.extend(self.step()),
|
||||
b'(' => {
|
||||
depth += 1;
|
||||
text.push(c);
|
||||
}
|
||||
b')' if depth == 0 => {
|
||||
self.unclosed = false;
|
||||
break;
|
||||
}
|
||||
b')' => {
|
||||
depth -= 1;
|
||||
text.push(c);
|
||||
}
|
||||
_ => text.push(c),
|
||||
}
|
||||
}
|
||||
Token::Text(text)
|
||||
}
|
||||
b'[' | b'<' => {
|
||||
self.at += 1;
|
||||
let close = if b == b'[' { b']' } else { b'>' };
|
||||
let inside = self.until(close);
|
||||
self.unclosed = inside.is_none();
|
||||
let inside = inside.unwrap_or_default().to_vec();
|
||||
if b == b'<' {
|
||||
Token::Raw
|
||||
} else {
|
||||
// The first word is the byte count; the bytes follow in one or more words.
|
||||
let mut words = inside.split(|c| c.is_ascii_whitespace()).filter(|w| !w.is_empty());
|
||||
let count = words.next().and_then(|w| std::str::from_utf8(w).ok()).and_then(|w| w.parse::<usize>().ok());
|
||||
let digits: Vec<u8> = words.flatten().copied().collect();
|
||||
Token::Hex(hex_bytes(&digits).filter(|b| Some(b.len()) == count))
|
||||
}
|
||||
}
|
||||
b'/' => {
|
||||
self.at += 1;
|
||||
let start = self.at;
|
||||
while self.text.get(self.at).is_some_and(|&c| !ends(c)) {
|
||||
self.at += 1;
|
||||
}
|
||||
Token::Name(self.text.get(start..self.at).unwrap_or_default().to_vec())
|
||||
}
|
||||
_ => {
|
||||
let start = self.at;
|
||||
while self.text.get(self.at).is_some_and(|&c| !ends(c)) {
|
||||
self.at += 1;
|
||||
}
|
||||
// Always past at least one byte.
|
||||
self.at = self.at.max(start + 1);
|
||||
let word = self.text.get(start..self.at).unwrap_or_default();
|
||||
let number = word.strip_prefix(b"-").or_else(|| word.strip_prefix(b"+")).unwrap_or(word);
|
||||
if !number.is_empty() && number.iter().all(u8::is_ascii_digit) {
|
||||
Token::Int(std::str::from_utf8(word).ok().and_then(|s| s.parse().ok()))
|
||||
} else {
|
||||
Token::Other(word.to_vec())
|
||||
}
|
||||
}
|
||||
};
|
||||
Some((line, token))
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes hexadecimal `digits` stand for, two digits a byte.
|
||||
fn hex_bytes(digits: &[u8]) -> Option<Vec<u8>> {
|
||||
let nibble = |c: u8| (c as char).to_digit(16).and_then(|d| u8::try_from(d).ok());
|
||||
if !digits.len().is_multiple_of(2) {
|
||||
return None;
|
||||
}
|
||||
digits.chunks(2).map(|pair| Some((nibble(*pair.first()?)? << 4) | nibble(*pair.get(1)?)?)).collect()
|
||||
}
|
||||
|
||||
/// What a block is.
|
||||
enum Kind {
|
||||
Action,
|
||||
Step,
|
||||
Param,
|
||||
/// A block that isn't read, or one past a cap.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// `name` ends with `-` and a number after `prefix`, as `/action-1` does.
|
||||
fn numbered(name: &[u8], prefix: &[u8]) -> bool {
|
||||
name.strip_prefix(prefix).is_some_and(|n| !n.is_empty() && n.iter().all(u8::is_ascii_digit))
|
||||
}
|
||||
|
||||
/// A name as text: at most [`MAX_NAME`] bytes, read as UTF-8 with replacement characters.
|
||||
fn name_text(name: &[u8], set: &mut AiaSet) -> String {
|
||||
if name.len() > MAX_NAME {
|
||||
set.truncated = true;
|
||||
}
|
||||
let mut s = String::from_utf8_lossy(name.get(..MAX_NAME).unwrap_or(name)).into_owned();
|
||||
// A character cut at the limit reads as one replacement character.
|
||||
if name.len() > MAX_NAME && s.ends_with('\u{FFFD}') {
|
||||
s.pop();
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// How the unread list shows a value in square brackets that isn't as many bytes as its count says.
|
||||
const BAD_HEX: &str = "[ … ] (not the hexadecimal bytes its count says)";
|
||||
|
||||
/// List a token that isn't read.
|
||||
fn unread(set: &mut AiaSet, line: usize, text: impl AsRef<[u8]>) {
|
||||
if set.unread.len() < MAX_UNREAD {
|
||||
let text: String = String::from_utf8_lossy(text.as_ref()).chars().take(UNREAD_SHOWN).collect();
|
||||
set.unread.push((line, text));
|
||||
}
|
||||
}
|
||||
|
||||
/// What the block `name` that opens on `line` inside the blocks `stack` is: a new action, step or
|
||||
/// recorded value of `set`, or a block that isn't read (listed when it is out of place).
|
||||
fn open_block(set: &mut AiaSet, stack: &[Kind], name: &[u8], line: usize) -> Kind {
|
||||
match stack.last() {
|
||||
_ if stack.len() >= MAX_DEPTH => {
|
||||
set.truncated = true;
|
||||
Kind::Other
|
||||
}
|
||||
None if numbered(name, b"action-") => {
|
||||
if set.actions.len() < MAX_ACTIONS {
|
||||
set.actions.push(AiaAction::default());
|
||||
Kind::Action
|
||||
} else {
|
||||
set.truncated = true;
|
||||
Kind::Other
|
||||
}
|
||||
}
|
||||
Some(Kind::Action) if numbered(name, b"event-") => match set.actions.last_mut() {
|
||||
Some(a) if a.steps.len() < MAX_STEPS && set.steps < MAX_SET_STEPS => {
|
||||
a.steps.push(AiaStep { line, ..AiaStep::default() });
|
||||
set.steps += 1;
|
||||
Kind::Step
|
||||
}
|
||||
_ => {
|
||||
set.truncated = true;
|
||||
Kind::Other
|
||||
}
|
||||
},
|
||||
Some(Kind::Step) if numbered(name, b"parameter-") => {
|
||||
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
|
||||
s.params += 1;
|
||||
}
|
||||
Kind::Param
|
||||
}
|
||||
Some(Kind::Param | Kind::Other) => Kind::Other,
|
||||
_ => {
|
||||
unread(set, line, format!("/{} {{", String::from_utf8_lossy(name)));
|
||||
Kind::Other
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the field `name` of the block `kind` (the set when `None`) to the hexadecimal text `bytes`
|
||||
/// on `line`: the set's or an action's `/name`, or a step's `/localizedName`.
|
||||
fn set_hex(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>, bytes: Option<Vec<u8>>, line: usize) {
|
||||
let Some(bytes) = bytes else {
|
||||
set.truncated = true;
|
||||
unread(set, line, BAD_HEX);
|
||||
return;
|
||||
};
|
||||
match (kind, name) {
|
||||
(None, Some(b"name")) => set.name = Some(name_text(&bytes, set)),
|
||||
(Some(Kind::Action), Some(b"name")) => {
|
||||
let text = name_text(&bytes, set);
|
||||
if let Some(a) = set.actions.last_mut() {
|
||||
a.name = text;
|
||||
}
|
||||
}
|
||||
(Some(Kind::Step), Some(b"localizedName")) => {
|
||||
let text = name_text(&bytes, set);
|
||||
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
|
||||
s.label = Some(text);
|
||||
}
|
||||
}
|
||||
(_, Some(_)) => {}
|
||||
(_, None) => unread(set, line, "[ … ]"),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.truncated = true;
|
||||
unread(set, line, BAD_HEX);
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark `set` truncated when the field `name` of the block `kind` (the set when `None`) is a count
|
||||
/// (the set's `/actionCount`, an action's `/eventCount` or a step's `/parameterCount`) whose value is
|
||||
/// not a number that fits an `i64`.
|
||||
fn bad_count(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>) {
|
||||
if matches!((kind, name), (None, Some(b"actionCount")) | (Some(Kind::Action), Some(b"eventCount")) | (Some(Kind::Step), Some(b"parameterCount")))
|
||||
{
|
||||
set.truncated = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the field `name` of the block `kind` (the set when `None`) to the integer `value` on `line`:
|
||||
/// the set's `/actionCount`, an action's `/eventCount`, a step's `/parameterCount`, or a step's
|
||||
/// `/isOn`. A count too large for an `i64` marks the set truncated.
|
||||
fn set_int(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>, value: Option<i64>, line: usize) {
|
||||
if value.is_none() {
|
||||
bad_count(set, kind, name);
|
||||
}
|
||||
match (kind, name) {
|
||||
(None, Some(b"actionCount")) => set.declared = value,
|
||||
(Some(Kind::Action), Some(b"eventCount")) => {
|
||||
if let Some(a) = set.actions.last_mut() {
|
||||
a.declared = value;
|
||||
}
|
||||
}
|
||||
(Some(Kind::Step), Some(b"parameterCount")) => {
|
||||
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
|
||||
s.declared = value;
|
||||
}
|
||||
}
|
||||
(Some(Kind::Step), Some(b"isOn")) => {
|
||||
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
|
||||
s.on = value;
|
||||
}
|
||||
}
|
||||
(_, Some(_)) => {}
|
||||
(_, None) => unread(set, line, value.map_or_else(|| "(a number too large)".to_string(), |v| v.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read an action set saved as text. An error when the text isn't one: it doesn't start with
|
||||
/// `/version` and an integer.
|
||||
pub fn read_aia(bytes: &[u8]) -> std::result::Result<AiaSet, String> {
|
||||
let mut set = AiaSet::default();
|
||||
let text = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes);
|
||||
let text = match text.get(..MAX_BYTES) {
|
||||
Some(head) if text.len() > MAX_BYTES => {
|
||||
set.truncated = true;
|
||||
head
|
||||
}
|
||||
_ => text,
|
||||
};
|
||||
let mut tokens = Tokens { text, at: 0, line: 1, unclosed: false };
|
||||
match (tokens.next_token(), tokens.next_token()) {
|
||||
(Some((_, Token::Name(n))), Some((_, Token::Int(Some(v))))) if n == b"version" => set.version = v,
|
||||
_ => return Err("not an action set: the text doesn't start with /version and a number".into()),
|
||||
}
|
||||
let mut stack: Vec<Kind> = vec![];
|
||||
// A slash name waiting for its value or its `{`: (line, name).
|
||||
let mut pending: Option<(usize, Vec<u8>)> = None;
|
||||
while let Some((line, token)) = tokens.next_token() {
|
||||
let in_step = matches!(stack.last(), Some(Kind::Step));
|
||||
let field = |pending: &mut Option<(usize, Vec<u8>)>| pending.take().map(|(_, n)| n);
|
||||
match token {
|
||||
Token::Name(name) => {
|
||||
if let Some((l, n)) = pending.replace((line, name)) {
|
||||
bad_count(&mut set, stack.last(), Some(&n));
|
||||
unread(&mut set, l, [b"/".as_slice(), &n].concat());
|
||||
}
|
||||
}
|
||||
Token::Open => {
|
||||
let (l, name) = pending.take().unwrap_or((line, vec![]));
|
||||
bad_count(&mut set, stack.last(), Some(&name));
|
||||
let kind = open_block(&mut set, &stack, &name, l);
|
||||
stack.push(kind);
|
||||
}
|
||||
Token::Close => {
|
||||
if let Some((l, n)) = pending.take() {
|
||||
bad_count(&mut set, stack.last(), Some(&n));
|
||||
unread(&mut set, l, [b"/".as_slice(), &n].concat());
|
||||
}
|
||||
if stack.pop().is_none() {
|
||||
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);
|
||||
}
|
||||
}
|
||||
// The other values inside a recorded value, or a block that isn't read.
|
||||
_ if matches!(stack.last(), Some(Kind::Param | Kind::Other)) => {
|
||||
pending = None;
|
||||
}
|
||||
Token::Hex(bytes) => {
|
||||
let name = field(&mut pending);
|
||||
bad_count(&mut set, stack.last(), name.as_deref());
|
||||
set_hex(&mut set, stack.last(), name.as_deref(), bytes, line);
|
||||
}
|
||||
Token::Text(t) => {
|
||||
let name = field(&mut pending);
|
||||
bad_count(&mut set, stack.last(), name.as_deref());
|
||||
match name {
|
||||
Some(n) if in_step && n == b"internalName" => {
|
||||
let name = name_text(&t, &mut set);
|
||||
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
|
||||
s.name = name;
|
||||
}
|
||||
}
|
||||
Some(_) => {}
|
||||
None => unread(&mut set, line, [b"(".as_slice(), &t, b")"].concat()),
|
||||
}
|
||||
}
|
||||
Token::Int(v) => {
|
||||
let name = field(&mut pending);
|
||||
set_int(&mut set, stack.last(), name.as_deref(), v, line);
|
||||
}
|
||||
Token::Raw => {
|
||||
let name = field(&mut pending);
|
||||
bad_count(&mut set, stack.last(), name.as_deref());
|
||||
if name.is_none() {
|
||||
unread(&mut set, line, "< … >");
|
||||
}
|
||||
}
|
||||
Token::Other(word) => {
|
||||
// A real number, or another word as a field's value.
|
||||
let name = field(&mut pending);
|
||||
bad_count(&mut set, stack.last(), name.as_deref());
|
||||
if name.is_none() {
|
||||
unread(&mut set, line, word);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The text ends after a field's name, before its value.
|
||||
if let Some((l, n)) = pending {
|
||||
set.truncated = true;
|
||||
unread(&mut set, l, [b"/".as_slice(), &n].concat());
|
||||
}
|
||||
// An unclosed value is the last token: it takes the rest of the text.
|
||||
if tokens.unclosed {
|
||||
set.truncated = true;
|
||||
unread(&mut set, tokens.line, "a value not closed at the end");
|
||||
}
|
||||
if !stack.is_empty() {
|
||||
set.truncated = true;
|
||||
unread(&mut set, tokens.line, format!("blocks left open at the end: {}", stack.len()));
|
||||
}
|
||||
// Not as many actions, steps or recorded values as the counts give; a negative count never matches.
|
||||
let differs = |declared: Option<i64>, read: usize| declared.is_some_and(|d| !usize::try_from(d).is_ok_and(|d| d == read));
|
||||
let step_differs = |a: &AiaAction| a.steps.iter().any(|s| differs(s.declared, s.params));
|
||||
if differs(set.declared, set.actions.len()) || set.actions.iter().any(|a| differs(a.declared, a.steps.len()) || step_differs(a)) {
|
||||
set.truncated = true;
|
||||
unread(&mut set, tokens.line, "not as many actions, steps or recorded values as the counts give");
|
||||
}
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
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)?);
|
||||
let name = text_param(p, "name", C)?;
|
||||
let bytes: std::borrow::Cow<[u8]> = match (path, data, b64) {
|
||||
(Some(path), None, None) => super::fileio::read_file_head(path, READ_LIMIT)?.into(),
|
||||
(None, Some(text), None) => text.as_bytes().get(..READ_LIMIT).unwrap_or(text.as_bytes()).into(),
|
||||
(None, None, Some(b64)) => super::scripts::decode_head(b64, READ_LIMIT).ok_or_else(|| bad(C, "bad dataBase64"))?.into(),
|
||||
_ => return Err(bad(C, "give exactly one of `path`, `data` and `dataBase64`")),
|
||||
};
|
||||
let set = read_aia(&bytes).map_err(EngineError::Other)?;
|
||||
let file = name.or(path).unwrap_or_default();
|
||||
let stem = std::path::Path::new(file).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let name = set.name.clone().filter(|n| !n.trim().is_empty()).unwrap_or(stem);
|
||||
let actions: Vec<Value> = set
|
||||
.actions
|
||||
.iter()
|
||||
.map(|a| {
|
||||
let steps: Vec<Value> = a
|
||||
.steps
|
||||
.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 })
|
||||
})
|
||||
.collect();
|
||||
json!({ "name": a.name, "steps": steps })
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({
|
||||
"set": name,
|
||||
"version": set.version,
|
||||
"actions": actions,
|
||||
"unread": set.unread.iter().map(|(line, text)| json!({ "line": line, "text": text })).collect::<Vec<_>>(),
|
||||
"truncated": set.truncated,
|
||||
}))
|
||||
}
|
||||
@@ -962,11 +962,9 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let default = CharStyle::default().font_family;
|
||||
let wanted = text_param(p, "font", C)?.filter(|f| !f.trim().is_empty()).unwrap_or(&default);
|
||||
let db = FontDb::global();
|
||||
// Any name of the family is stored as its own name.
|
||||
let family = match db.resolve(wanted, "Regular") {
|
||||
Some((f, m)) if m != FontMatch::Missing => f.family.clone(),
|
||||
_ => return Err(bad(C, "the replacement font is not available")),
|
||||
};
|
||||
// Any name of the family is stored as its own name, and a composite font as its own name.
|
||||
let composite = db.composite_font(wanted).is_some();
|
||||
let family = db.stored_family(wanted, "Regular").ok_or_else(|| bad(C, "the replacement font is not available"))?;
|
||||
let missing = |st: &CharStyle| db.resolve(&st.font_family, &st.font_style).is_none_or(|(_, m)| m == FontMatch::Missing);
|
||||
let lacks = |t: &TextObject| t.runs.iter().any(|r| missing(&r.style));
|
||||
let d = &s.doc()?.doc;
|
||||
@@ -988,8 +986,11 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut runs = 0;
|
||||
let mut replace = |t: &mut TextObject| {
|
||||
for r in t.runs.iter_mut().filter(|r| missing(&r.style)) {
|
||||
// The style the font has closest to the one the character had.
|
||||
r.style.font_style = db.face(&family, &r.style.font_style).map_or_else(|| r.style.font_style.clone(), |f| f.style.clone());
|
||||
// The style the font has closest to the one the character had (a composite font's
|
||||
// parts name their own styles: the character keeps its style).
|
||||
if !composite {
|
||||
r.style.font_style = db.face(&family, &r.style.font_style).map_or_else(|| r.style.font_style.clone(), |f| f.style.clone());
|
||||
}
|
||||
r.style.font_family = family.clone();
|
||||
r.style.font_version = None;
|
||||
r.style.font_axes.clear();
|
||||
@@ -1004,7 +1005,6 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
edit_symbol_texts(d, None, &|t, _| lacks(t), &mut replace);
|
||||
drop(replace);
|
||||
Ok(runs)
|
||||
})?;
|
||||
Ok(json!({ "runs": runs, "font": family }))
|
||||
|
||||
@@ -174,7 +174,7 @@ fn filter(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let label = effects::effect_info(id).map_or("Apply as Filter", |e| e.label.trim_end_matches('…'));
|
||||
let kinds = effects::addons::duotone::swatch_kinds(&s.doc()?.doc);
|
||||
let swatches = |name: &str| kinds.get(name).copied();
|
||||
recolor_links(s, &given, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches))
|
||||
recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches))
|
||||
}
|
||||
|
||||
/// Apply Fill to Stroke (`to_stroke`) or Apply Stroke to Fill: each target copies one of its own
|
||||
|
||||
@@ -189,7 +189,7 @@ pub(super) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let given = json!({
|
||||
"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "fill": fill, "stroke": stroke, "includeImages": false, "includePatterns": false,
|
||||
});
|
||||
let r = recolor_links(s, &given, "Apply Nearest Swatch", &|c| to(c).and_then(Paint::color).unwrap_or(c), &links)?;
|
||||
let r = recolor_links(s, &given, APPLY, "Apply Nearest Swatch", &|c| to(c).and_then(Paint::color).unwrap_or(c), &links)?;
|
||||
squash(s, undo, "Apply Nearest Swatch");
|
||||
Ok(json!({ "changed": r["changed"], "swatches": names, "added": added }))
|
||||
}
|
||||
|
||||
Loaded 100 of 710 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user