mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-28 01:10:54 +01:00
Merge remote-tracking branch 'upstream/main' into feat/g13-view-snapping
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
cabb0e52cd
484 files changed
+40965
-2549
No files matched your search
@@ -16,6 +16,15 @@
|
||||
| `crates/text/patterns/hyph-or.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-or.tex | MIT (selected option) | Unmodified; full license in file |
|
||||
| `crates/text/patterns/hyph-as.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-as.tex | MIT (selected option) | Unmodified; full license in file |
|
||||
|
||||
## Printing-condition characterization data
|
||||
|
||||
Fogra's terms (https://fogra.org/en/downloads/work-tools/characterisation-data): "Free use and redistribution of the Fogra characterisation data is permitted, including redistribution as part of commercial and non-commercial software, provided that the data are distributed unmodified and Fogra is identified as the source. The designation FOGRAxx may be used solely to identify the respective reference data. Such use does not imply certification, approval or endorsement by Fogra." VectorCraft computes its Coated CMYK (FOGRA51) and Uncoated CMYK (FOGRA52) working spaces from these files at run time; the files themselves are not changed.
|
||||
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `crates/color/data/FOGRA51.txt` | Fogra Forschungsgesellschaft Druck e.V. (www.fogra.org) | https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip | Fogra characterization data terms (above): redistribution of the unmodified data with Fogra named as the source | Unmodified, byte for byte (SHA-256 `ad472a1c0bdafd558597ff93eeda5175805086565af814cb6346e910e2f25aa5`, checked by a test) |
|
||||
| `crates/color/data/FOGRA52.txt` | Fogra Forschungsgesellschaft Druck e.V. (www.fogra.org) | https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip | Fogra characterization data terms (above): redistribution of the unmodified data with Fogra named as the source | Unmodified, byte for byte (SHA-256 `be4f0732328ed62ade63ec7f317d3b9e9dad6bbe2430fefddaf0f901d5ba13d6`, checked by a test) |
|
||||
|
||||
Every non-code asset in this repository (icons, images, fonts, example art, colour profiles, presets) is listed here with its author, source and licence. `cargo xtask assets` (part of `cargo xtask ci`) fails if an asset file is missing from this table.
|
||||
|
||||
**Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
|
||||
|
||||
Generated
+310
-24
@@ -123,10 +123,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cipher",
|
||||
"cipher 0.4.4",
|
||||
"cpufeatures 0.2.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aes"
|
||||
version = "0.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1"
|
||||
dependencies = [
|
||||
"cipher 0.5.2",
|
||||
"cpubits",
|
||||
"cpufeatures 0.3.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.8.12"
|
||||
@@ -247,6 +258,17 @@ version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "apple-native-keyring-store"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "02e465454e78fda6f7cd9dab7eb47518ca28c59b1bc392ca865af61452741dd3"
|
||||
dependencies = [
|
||||
"keyring-core",
|
||||
"log",
|
||||
"security-framework",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arboard"
|
||||
version = "3.7.0"
|
||||
@@ -606,6 +628,24 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-padding"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.5.1"
|
||||
@@ -718,6 +758,12 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "byteorder"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
|
||||
|
||||
[[package]]
|
||||
name = "byteorder-lite"
|
||||
version = "0.1.0"
|
||||
@@ -808,6 +854,15 @@ dependencies = [
|
||||
"winx",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cbc"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896"
|
||||
dependencies = [
|
||||
"cipher 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.9.0"
|
||||
@@ -902,8 +957,18 @@ version = "0.4.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"inout",
|
||||
"crypto-common 0.1.7",
|
||||
"inout 0.1.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cipher"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
|
||||
dependencies = [
|
||||
"crypto-common 0.2.2",
|
||||
"inout 0.2.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -935,6 +1000,12 @@ dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cmov"
|
||||
version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
|
||||
|
||||
[[package]]
|
||||
name = "cmpv2"
|
||||
version = "0.2.0"
|
||||
@@ -953,7 +1024,7 @@ version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7b77c319abfd5219629c45c34c89ba945ed3c5e49fcde9d16b6c3885f118a730"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der",
|
||||
"spki",
|
||||
"x509-cert",
|
||||
@@ -1029,6 +1100,12 @@ version = "0.9.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
|
||||
|
||||
[[package]]
|
||||
name = "cookie-factory"
|
||||
version = "0.3.3"
|
||||
@@ -1113,6 +1190,12 @@ dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpubits"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
@@ -1216,12 +1299,12 @@ dependencies = [
|
||||
"craft-ui",
|
||||
"egui",
|
||||
"getrandom 0.3.4",
|
||||
"hmac",
|
||||
"hmac 0.12.1",
|
||||
"log",
|
||||
"png 0.17.16",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"thiserror 2.0.21",
|
||||
"web-time",
|
||||
]
|
||||
@@ -1447,7 +1530,7 @@ dependencies = [
|
||||
"ruzstd",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"skrifa 0.47.0",
|
||||
"tar",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2154,7 +2237,7 @@ dependencies = [
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"ureq",
|
||||
@@ -2317,6 +2400,24 @@ dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ctutils"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
|
||||
dependencies = [
|
||||
"cmov",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cursor-icon"
|
||||
version = "1.2.0"
|
||||
@@ -2335,7 +2436,7 @@ version = "0.7.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der_derive",
|
||||
"flagset",
|
||||
"pem-rfc7468",
|
||||
@@ -2378,11 +2479,23 @@ version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
"block-buffer 0.10.4",
|
||||
"crypto-common 0.1.7",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
|
||||
dependencies = [
|
||||
"block-buffer 0.12.1",
|
||||
"const-oid 0.10.3",
|
||||
"crypto-common 0.2.2",
|
||||
"ctutils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dirs"
|
||||
version = "7.0.0"
|
||||
@@ -3597,13 +3710,31 @@ version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "hkdf"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"
|
||||
dependencies = [
|
||||
"hmac 0.13.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
||||
dependencies = [
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
|
||||
dependencies = [
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3645,6 +3776,15 @@ version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||
|
||||
[[package]]
|
||||
name = "hybrid-array"
|
||||
version = "0.4.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "1.12.0"
|
||||
@@ -4101,6 +4241,16 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9"
|
||||
dependencies = [
|
||||
"block-padding",
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inventory"
|
||||
version = "0.3.25"
|
||||
@@ -4458,6 +4608,15 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "keyring-core"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "281c851dbae0de36d405299dd463126df4826dc32665c1314e931696b8cdee77"
|
||||
dependencies = [
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "khronos-egl"
|
||||
version = "6.0.0"
|
||||
@@ -4721,7 +4880,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4952,12 +5111,75 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-complex",
|
||||
"num-integer",
|
||||
"num-iter",
|
||||
"num-rational",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-complex"
|
||||
version = "0.4.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-iter"
|
||||
version = "0.1.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-rational"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -6684,6 +6906,25 @@ dependencies = [
|
||||
"tiny-skia 0.11.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "secret-service"
|
||||
version = "5.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8"
|
||||
dependencies = [
|
||||
"aes 0.9.4",
|
||||
"cbc",
|
||||
"futures-util",
|
||||
"getrandom 0.4.3",
|
||||
"hkdf",
|
||||
"hybrid-array",
|
||||
"num",
|
||||
"once_cell",
|
||||
"serde",
|
||||
"sha2 0.11.1",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "security-framework"
|
||||
version = "3.7.0"
|
||||
@@ -6823,7 +7064,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.2.17",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6834,7 +7075,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.2.17",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.1",
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6894,12 +7146,12 @@ checksum = "da90c3d9af638898a5fdc347479b18f950bb0dde11ecf2244f94cd28135da53b"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"base64 0.22.1",
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
"pem",
|
||||
"rand_core 0.10.1",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"signature",
|
||||
"sigstore-types",
|
||||
"spki",
|
||||
@@ -6968,7 +7220,7 @@ dependencies = [
|
||||
"chrono",
|
||||
"cmpv2",
|
||||
"cms",
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der",
|
||||
"hex",
|
||||
"rand",
|
||||
@@ -7007,7 +7259,7 @@ dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"cms",
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"hex",
|
||||
"pem",
|
||||
"rustls-pki-types",
|
||||
@@ -8228,6 +8480,7 @@ dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
@@ -8277,6 +8530,7 @@ dependencies = [
|
||||
name = "vectorcraft-engine"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"apple-native-keyring-store",
|
||||
"cfb",
|
||||
"chrono",
|
||||
"craft-cdr",
|
||||
@@ -8290,12 +8544,15 @@ dependencies = [
|
||||
"crc32fast",
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
"hayro-ccitt",
|
||||
"heic-rs",
|
||||
"hmac 0.12.1",
|
||||
"image",
|
||||
"jxl-color",
|
||||
"jxl-grid",
|
||||
"jxl-oxide",
|
||||
"keyring-core",
|
||||
"kurbo 0.13.1",
|
||||
"log",
|
||||
"proptest",
|
||||
@@ -8305,6 +8562,7 @@ dependencies = [
|
||||
"same-file",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"skrifa 0.47.0",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
@@ -8331,6 +8589,8 @@ dependencies = [
|
||||
"vectorcraft-tools",
|
||||
"vectorcraft-trace",
|
||||
"wat",
|
||||
"windows-native-keyring-store",
|
||||
"zbus-secret-service-keyring-store",
|
||||
"zune-core",
|
||||
"zune-jpegxl",
|
||||
]
|
||||
@@ -8479,7 +8739,7 @@ dependencies = [
|
||||
name = "vectorcraft-pdf"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"aes 0.8.4",
|
||||
"chrono",
|
||||
"craft",
|
||||
"craft-image-codecs",
|
||||
@@ -8497,7 +8757,7 @@ dependencies = [
|
||||
"objc2-core-graphics",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"siphasher",
|
||||
"skrifa 0.47.0",
|
||||
"smallvec",
|
||||
@@ -8522,11 +8782,12 @@ dependencies = [
|
||||
"rustix 1.1.6",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"thiserror 2.0.21",
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-geom 0.24.1",
|
||||
"vectorcraft-js",
|
||||
"wasmi",
|
||||
"wasmparser 0.228.0",
|
||||
"wat",
|
||||
@@ -8671,6 +8932,7 @@ dependencies = [
|
||||
"vectorcraft-geom 0.24.1",
|
||||
"vectorcraft-pathops 0.24.1",
|
||||
"vectorcraft-text",
|
||||
"vectorcraft-tools",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9464,6 +9726,19 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-native-keyring-store"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "063426e76fdec7438d56bb777f67e318a84a25c707b07e575cb8b78e10c028f8"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"keyring-core",
|
||||
"regex",
|
||||
"windows-sys 0.61.2",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-numerics"
|
||||
version = "0.3.1"
|
||||
@@ -9821,7 +10096,7 @@ version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der",
|
||||
"sha1",
|
||||
"signature",
|
||||
@@ -10041,6 +10316,17 @@ dependencies = [
|
||||
"zvariant",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zbus-secret-service-keyring-store"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a"
|
||||
dependencies = [
|
||||
"keyring-core",
|
||||
"secret-service",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zbus_macros"
|
||||
version = "5.19.0"
|
||||
|
||||
@@ -152,6 +152,17 @@ Copyright (C) 2016 Santhosh Thottingal, used under the MIT license option.
|
||||
Original copyright and full license notices are preserved in each hyph-*.tex file.
|
||||
Source: hyphenation/tex-hyphen, commit 5684c0f51c0b81133db2efbe60a408b4155a3ff5.
|
||||
|
||||
FOGRA51 and FOGRA52 characterization data (crates/color/data/):
|
||||
Source: Fogra Forschungsgesellschaft Druck e.V., www.fogra.org,
|
||||
https://fogra.org/en/downloads/work-tools/characterisation-data. The files are distributed
|
||||
unmodified. Fogra's terms: "Free use and redistribution of the Fogra characterisation data is
|
||||
permitted, including redistribution as part of commercial and non-commercial software, provided
|
||||
that the data are distributed unmodified and Fogra is identified as the source. The designation
|
||||
FOGRAxx may be used solely to identify the respective reference data. Such use does not imply
|
||||
certification, approval or endorsement by Fogra." VectorCraft's Coated CMYK (FOGRA51) and
|
||||
Uncoated CMYK (FOGRA52) working spaces are computed from this data by VectorCraft's own code;
|
||||
they are not Fogra profiles.
|
||||
|
||||
|
||||
JPEG encoder dependency notices
|
||||
|
||||
|
||||
@@ -142,8 +142,10 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-19: Set Fold Angle in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and a Fold Angle field with Reset in the Fold Lines panel): a crease, partial cut or perforation line can fold at its own angle, from -180° to 180°, instead of its role's 90° away from or toward the print; native files keep the angle, and the Fold Preview folds each hinge at the angle of the line with the most length in it (`addon.packaging.setFoldAngle`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
|
||||
- 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-20: Curvature Circle Tool Options (double-click the Curvature Circle tool): Snap Tolerance sets how near a path pulls the pointer, Snap with Smart Guides Off unchecked keeps it within the selection tolerance while Smart Guides are off, Annotate Radius hides the radius label, Anchors at Standard Positions off puts an anchor where the circle touches the path and one every 90° from there, and Use the Radius of Circular Arcs off gives a circular arc's own cubic curvature (`tool.setOption {tool: "curvatureCircle"}`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
|
||||
- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged.
|
||||
@@ -151,6 +153,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged.
|
||||
- 2026-11-19: Quick Pen length handles: a handle beyond the start and the end of the path being drawn, or of the selected path, makes the line or arc there longer or shorter when dragged; a line keeps its direction and an arc its circle (`path.quickPenLength`, part of #2660). Headline numbers unchanged.
|
||||
- 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged.
|
||||
- 2026-11-19: Quick Pen editing: with no path being drawn, a drag on an anchor or a segment of a selected path moves it, a line staying a line and an arc an arc beside a moved corner anchor (at a smooth anchor the handles stay in line and the segments bend to meet); a click selects an anchor, Shift-click adds one, and the canvas context menu's Delete removes the selected anchors (`path.moveAnchors`, `edit.clear`; #2660). Headline numbers unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
|
||||
@@ -238,11 +238,13 @@ fn main() -> ExitCode {
|
||||
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
|
||||
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
|
||||
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
|
||||
/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there, keeps File Info's
|
||||
/// (`script.listInstalled`) and finds its Startup Scripts folder (`script.startup.run`, never run on its own), keeps each
|
||||
/// script's `Folder.userData` in the Script Data folder there, keeps File Info's
|
||||
/// metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
|
||||
/// `VECTORCRAFT_CONFIG_DIR` apply as they do there.
|
||||
fn with_stores(mut h: Headless) -> Headless {
|
||||
prefs_dir::attach_scripts_dir(&mut h.session);
|
||||
prefs_dir::attach_startup_scripts_dir(&mut h.session);
|
||||
prefs_dir::attach_script_data(&mut h.session);
|
||||
prefs_dir::attach_metadata_templates_dir(&mut h.session);
|
||||
prefs_dir::attach_new_doc_profiles(&mut h.session);
|
||||
|
||||
@@ -189,6 +189,10 @@ pub(crate) fn services(window: Parent) -> Services {
|
||||
open_in_application: Some(Box::new(open_in_application)),
|
||||
// File → Print: the system's printers and print queue.
|
||||
print: Some(Box::new(printing::SystemPrint)),
|
||||
// The tablet driver's Wintab context, which reads an airbrush pen's finger wheel, opens
|
||||
// only while the active tool uses the wheel.
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
stylus_wheel: Some(Box::new(super::windows_wintab::set_wheel_used)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,6 +74,7 @@ mod windows_cores;
|
||||
mod windows_display_size;
|
||||
mod windows_stylus;
|
||||
mod windows_symbol_chars;
|
||||
mod windows_wintab;
|
||||
mod xwayland;
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
@@ -823,6 +824,8 @@ fn main() -> std::process::ExitCode {
|
||||
prefs_dir::attach_plugin_store(&mut session);
|
||||
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
|
||||
prefs_dir::attach_scripts_dir(&mut session);
|
||||
// The startup scripts are in the Startup Scripts folder next to the preferences.
|
||||
prefs_dir::attach_startup_scripts_dir(&mut session);
|
||||
// File Info's metadata templates live in their own folder next to the preferences.
|
||||
prefs_dir::attach_metadata_templates_dir(&mut session);
|
||||
prefs_dir::attach_new_doc_profiles(&mut session);
|
||||
@@ -976,6 +979,9 @@ fn main() -> std::process::ExitCode {
|
||||
single_instance::set_ui(&cc.egui_ctx);
|
||||
}
|
||||
let held_files = file_access::unconfined(|| open_or_hold(&mut app, command_line_files));
|
||||
// With General › Run Startup Scripts on and Safe Mode off, the startup scripts run
|
||||
// now, as the person's own; in Safe Mode they wait for the choice that ends it.
|
||||
file_access::unconfined(|| vectorcraft_ui_egui::script_runs::run_at_launch(&mut app));
|
||||
// The first frame is due from now (`gpu::watch_first_frame`).
|
||||
#[cfg(feature = "wgpu")]
|
||||
created.ready();
|
||||
|
||||
@@ -50,9 +50,10 @@ pub fn attach_color_settings(session: &mut vectorcraft_engine::Session) {
|
||||
}
|
||||
|
||||
/// Install the plug-ins Install Plug-in kept in the `Plug-ins` folder (#2541), and keep the ones
|
||||
/// installed from now on there.
|
||||
/// installed from now on there. The key of the grants kept there is in the system's key store.
|
||||
pub fn attach_plugin_store(session: &mut vectorcraft_engine::Session) {
|
||||
if let Some(dir) = store_dir("Plug-ins") {
|
||||
vectorcraft_engine::store::grant_keys::use_os_grant_keys();
|
||||
session.attach_plugin_store(dir);
|
||||
}
|
||||
}
|
||||
@@ -65,6 +66,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Have `script.startup.run` run the scripts of the `Startup Scripts` folder. The folder is only
|
||||
/// read: the user makes it.
|
||||
pub fn attach_startup_scripts_dir(session: &mut vectorcraft_engine::Session) {
|
||||
if let Some(dir) = store_dir("Startup Scripts") {
|
||||
session.attach_startup_scripts_dir(dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template
|
||||
/// makes.
|
||||
pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Windows pen tablets: with Windows Ink, winit reports a pen in contact as a touch and drops its
|
||||
//! barrel button and which end of the pen is down. For each pointer message of a pen,
|
||||
//! [`msg_hook`] reads the pen's `POINTER_PEN_INFO` before winit handles the message and writes its
|
||||
//! pressure, end, tilt and rotation into the framework's [`PenSource`] ([`start`]):
|
||||
//! pressure, end, tilt and rotation, and an airbrush pen's finger wheel, into the framework's
|
||||
//! [`PenSource`] ([`start`]):
|
||||
//! `PEN_FLAG_INVERTED` ("The pen is inverted") or `PEN_FLAG_ERASER` ("The eraser button is
|
||||
//! pressed") is the eraser end
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/pen-flags-constants>). Pointer
|
||||
@@ -24,9 +25,12 @@
|
||||
//! `rotation` in degrees 0..359 clockwise
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-pointer_pen_info>).
|
||||
//! Toward the user is down the screen, so they are the sample's axes and direction as they come,
|
||||
//! converted to radians. `POINTER_PEN_INFO` has no field for an airbrush pen's finger wheel.
|
||||
//! converted to radians. `POINTER_PEN_INFO` has no field for an airbrush pen's finger wheel, which
|
||||
//! comes from the tablet driver's Wintab interface instead, when it has one
|
||||
//! ([`crate::windows_wintab`]).
|
||||
#![cfg_attr(not(windows), allow(dead_code))]
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use craft::behavior::PointerSample;
|
||||
@@ -38,6 +42,8 @@ const POINTER_MESSAGE_FLAG_SECONDBUTTON: usize = 0x0020;
|
||||
/// `POINTER_MESSAGE_FLAG_INRANGE` (`winuser.h`): not set on the message of a pointer that has left
|
||||
/// detection range.
|
||||
const POINTER_MESSAGE_FLAG_INRANGE: usize = 0x0002;
|
||||
/// `POINTER_MESSAGE_FLAG_CANCELED` (`winuser.h`): the pointer's input was canceled.
|
||||
const POINTER_MESSAGE_FLAG_CANCELED: usize = 0x8000;
|
||||
/// `PEN_FLAG_INVERTED` and `PEN_FLAG_ERASER` (`winuser.h`), in `POINTER_PEN_INFO::penFlags`.
|
||||
const PEN_FLAG_INVERTED: u32 = 0x0002;
|
||||
const PEN_FLAG_ERASER: u32 = 0x0004;
|
||||
@@ -65,6 +71,13 @@ const WM_POINTERLEAVE: u32 = 0x024A;
|
||||
/// A pen's tilt along x and y and its barrel rotation, in radians.
|
||||
type Pose = ([f32; 2], f32);
|
||||
|
||||
thread_local! {
|
||||
/// The pointer id of the pen whose leaving starts the Wintab wheel readings afresh: the pen that
|
||||
/// took them, or the pen whose message last asked for the wheel when none has
|
||||
/// ([`crate::windows_wintab::wheel_pen`]).
|
||||
static WHEEL_PEN: Cell<Option<u32>> = const { Cell::new(None) };
|
||||
}
|
||||
|
||||
/// The pen source [`msg_hook`] writes, once [`start`] has made it.
|
||||
static FEED: OnceLock<PenSource> = OnceLock::new();
|
||||
|
||||
@@ -89,14 +102,22 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
|
||||
let Some(pen) = FEED.get() else {
|
||||
return false;
|
||||
};
|
||||
crate::windows_wintab::msg_hook(msg);
|
||||
if forgets_wheel(msg.message, msg.wParam.0, WHEEL_PEN.get()) {
|
||||
crate::windows_wintab::forget();
|
||||
}
|
||||
let read_pen = || {
|
||||
let mut info = POINTER_PEN_INFO::default();
|
||||
let id = (msg.wParam.0 & 0xffff) as u32;
|
||||
// SAFETY: `info` is a `POINTER_PEN_INFO` that lives for the call. The call fails for a
|
||||
// pointer that is not a pen.
|
||||
unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?;
|
||||
unsafe { GetPointerPenInfo(id, &mut info) }.ok()?;
|
||||
let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0;
|
||||
let eraser = info.penFlags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0;
|
||||
let wheel = crate::windows_wintab::pen_wheel(msg.hwnd, msg.time, id, eraser);
|
||||
WHEEL_PEN.set(Some(crate::windows_wintab::wheel_pen(id)));
|
||||
let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation);
|
||||
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose))
|
||||
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose, wheel))
|
||||
};
|
||||
// SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message.
|
||||
let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32);
|
||||
@@ -111,8 +132,10 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
|
||||
/// What a pen whose `POINTER_PEN_INFO` holds `pressure` (0..1024), `pen_mask` and `pen_flags`
|
||||
/// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen
|
||||
/// in contact that reports none; the eraser end while it is inverted or its eraser button is
|
||||
/// pressed; and how it is held, `pose` ([`pen_pose`]).
|
||||
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (tilt, rotation): Pose) -> PointerSample {
|
||||
/// pressed; how it is held, `pose` ([`pen_pose`]); and `wheel`, the airbrush finger wheel the tablet
|
||||
/// driver's Wintab interface reported for the message, if any ([`crate::windows_wintab`]), kept
|
||||
/// within 0..1 and none when it is not a number.
|
||||
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (tilt, rotation): Pose, wheel: Option<f32>) -> PointerSample {
|
||||
let pressure = match pressure {
|
||||
1..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0,
|
||||
_ if in_contact => 1.0,
|
||||
@@ -122,6 +145,7 @@ fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (t
|
||||
sample.tilt = tilt;
|
||||
sample.rotation = rotation;
|
||||
sample.eraser = pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0;
|
||||
sample.wheel = wheel.filter(|w| w.is_finite()).map(|w| w.clamp(0.0, 1.0));
|
||||
sample
|
||||
}
|
||||
|
||||
@@ -134,6 +158,43 @@ fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> Pose {
|
||||
([along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)], turn)
|
||||
}
|
||||
|
||||
/// Whether a message with this `wParam` starts the Wintab wheel readings afresh: a pointer message
|
||||
/// of a pointer that has left detection range or whose press was canceled, or a pointer leaving the
|
||||
/// window, when the pointer is `pen`, the pen whose leaving starts them afresh. A touch or another
|
||||
/// pen leaving keeps the readings.
|
||||
fn forgets_wheel(message: u32, wparam: usize, pen: Option<u32>) -> bool {
|
||||
if pen != Some((wparam & 0xffff) as u32) {
|
||||
return false;
|
||||
}
|
||||
let flags = wparam >> 16;
|
||||
match message {
|
||||
WM_POINTERENTER | WM_POINTERUPDATE | WM_POINTERDOWN | WM_POINTERUP => {
|
||||
flags & POINTER_MESSAGE_FLAG_INRANGE == 0 || flags & POINTER_MESSAGE_FLAG_CANCELED != 0
|
||||
}
|
||||
WM_POINTERLEAVE => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a pointer message that Windows sends to the window procedure, so that winit's message hook
|
||||
/// never sees it, starts the Wintab wheel readings afresh ([`forgets_wheel`]): `WM_POINTERENTER` and
|
||||
/// `WM_POINTERLEAVE` are sent
|
||||
/// (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/wm-pointerleave>); the posted pointer
|
||||
/// messages are left to [`msg_hook`].
|
||||
fn sent_forgets_wheel(message: u32, wparam: usize, pen: Option<u32>) -> bool {
|
||||
matches!(message, WM_POINTERENTER | WM_POINTERLEAVE) && forgets_wheel(message, wparam, pen)
|
||||
}
|
||||
|
||||
/// A message Windows sent to a window procedure of the thread, from the Wintab reader's hook on
|
||||
/// them ([`crate::windows_wintab`]): a pen leaving the window starts the wheel readings afresh, as
|
||||
/// [`msg_hook`] does for the messages it sees.
|
||||
#[cfg(windows)]
|
||||
pub fn sent_message(message: u32, wparam: usize) {
|
||||
if sent_forgets_wheel(message, wparam, WHEEL_PEN.get()) {
|
||||
crate::windows_wintab::forget();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse,
|
||||
/// not from a pen or a touch.
|
||||
fn is_mouse(extra_info: u32) -> bool {
|
||||
@@ -175,7 +236,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn an_inverted_pen_or_its_eraser_button_is_the_eraser_end() {
|
||||
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, UPRIGHT).eraser;
|
||||
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, UPRIGHT, None).eraser;
|
||||
assert!(!eraser(0), "the tip");
|
||||
assert!(!eraser(PEN_FLAG_BARREL), "the barrel button");
|
||||
assert!(eraser(PEN_FLAG_INVERTED), "turned over");
|
||||
@@ -194,19 +255,77 @@ mod tests {
|
||||
assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), ([0.0, 0.0], deg(359.0)), "a 6D Art Pen's barrel");
|
||||
assert_eq!(pen_pose(all, 400, i32::MIN, 720), ([deg(90.0), deg(-90.0)], 0.0), "kept within the ranges");
|
||||
let pose = pen_pose(all, 10, 20, 180);
|
||||
let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose);
|
||||
let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose, None);
|
||||
assert_eq!((sample.tilt, sample.rotation), pose);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_airbrush_wheel_goes_into_the_sample() {
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, Some(0.25)).wheel, Some(0.25));
|
||||
let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION;
|
||||
let pose = pen_pose(all, 10, 20, 180);
|
||||
let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose, Some(0.75));
|
||||
assert_eq!((sample.tilt, sample.rotation, sample.wheel), (pose.0, pose.1, Some(0.75)), "with the tilt and rotation");
|
||||
assert_eq!(sample.pressure, 0.5, "the pressure as before");
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).wheel, None, "no wheel");
|
||||
assert_eq!(pen_sample(0, 0, 0, false, UPRIGHT, Some(f32::NAN)).wheel, None, "not a number");
|
||||
assert_eq!(pen_sample(0, 0, 0, false, UPRIGHT, Some(1.5)).wheel, Some(1.0), "kept within 0..1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaving_range_or_the_window_and_a_cancel_forget_the_wheel() {
|
||||
let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7;
|
||||
let canceled = ((POINTER_MESSAGE_FLAG_INRANGE | POINTER_MESSAGE_FLAG_CANCELED) << 16) | 7;
|
||||
let pen = Some(7);
|
||||
for m in [WM_POINTERENTER, WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] {
|
||||
assert!(!forgets_wheel(m, in_range, pen), "{m:#x}");
|
||||
assert!(forgets_wheel(m, 7, pen), "out of range: {m:#x}");
|
||||
assert!(forgets_wheel(m, canceled, pen), "canceled: {m:#x}");
|
||||
}
|
||||
assert!(forgets_wheel(WM_POINTERLEAVE, in_range, pen));
|
||||
// WM_MOUSEMOVE and WT_PACKET.
|
||||
assert!(!forgets_wheel(0x0200, 0, Some(0)));
|
||||
assert!(!forgets_wheel(0x7FF0, 7, pen));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_pointer_leaving_keeps_the_wheel() {
|
||||
// A touch, pointer 9, leaves the window and detection range while pen 7 hovers.
|
||||
let touch_leaves = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 9;
|
||||
assert!(!forgets_wheel(WM_POINTERLEAVE, touch_leaves, Some(7)));
|
||||
assert!(!forgets_wheel(WM_POINTERUPDATE, 9, Some(7)), "out of range");
|
||||
let canceled = (POINTER_MESSAGE_FLAG_CANCELED << 16) | 9;
|
||||
assert!(!forgets_wheel(WM_POINTERUP, canceled, Some(7)), "canceled");
|
||||
assert!(!forgets_wheel(WM_POINTERLEAVE, touch_leaves, None), "no pen has read the wheel");
|
||||
assert!(forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7, Some(7)), "the pen itself");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sent_leave_of_the_wheel_pen_forgets_the_wheel() {
|
||||
let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7;
|
||||
let pen = Some(7);
|
||||
assert!(sent_forgets_wheel(WM_POINTERLEAVE, in_range, pen), "the pen leaves the window");
|
||||
assert!(sent_forgets_wheel(WM_POINTERLEAVE, 7, pen), "or detection range");
|
||||
assert!(!sent_forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 9, pen), "another pointer leaves");
|
||||
assert!(!sent_forgets_wheel(WM_POINTERLEAVE, in_range, None), "no pen has read the wheel");
|
||||
assert!(!sent_forgets_wheel(WM_POINTERENTER, in_range, pen), "the pen comes over the window");
|
||||
// Posted messages, which the message hook already sees.
|
||||
for m in [WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] {
|
||||
assert!(!sent_forgets_wheel(m, 7, pen), "{m:#x}");
|
||||
}
|
||||
// WT_CTXCLOSE.
|
||||
assert!(!sent_forgets_wheel(0x7FF2, 7, pen));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pens_pressure_is_the_one_winit_gives_its_touch() {
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 0.5);
|
||||
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 1.0);
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, UPRIGHT), eraser_sample(0.0), "hovering");
|
||||
assert_eq!(pen_sample(0, 0, 0, true, UPRIGHT).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
|
||||
assert_eq!(pen_sample(300, 0, 0, true, UPRIGHT).pressure, 1.0, "a pressure without the pressure mask is not one");
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 1.0, "as winit, which gives no force for 0");
|
||||
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT).pressure, 0.0);
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 0.5);
|
||||
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0);
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, UPRIGHT, None), eraser_sample(0.0), "hovering");
|
||||
assert_eq!(pen_sample(0, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
|
||||
assert_eq!(pen_sample(300, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pressure without the pressure mask is not one");
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0, "as winit, which gives no force for 0");
|
||||
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT, None).pressure, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3" y="8" width="13" height="8" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M16 4V20" stroke-width="1" /></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="2" y="7" width="11" height="10" fill="currentColor" fill-opacity="0.55" stroke="none"/><path d="M13 3V21" stroke-width="1" /></svg>
|
||||
|
Before Width: | Height: | Size: 321 B After Width: | Height: | Size: 323 B |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 8H12A4 4 0 0 1 12 16H3Z" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M12 4V20" stroke-width="1" /></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M2 7H13A5 5 0 0 1 13 17H2Z" fill="currentColor" fill-opacity="0.55" stroke="none"/><path d="M13 3V21" stroke-width="1" /></svg>
|
||||
|
Before Width: | Height: | Size: 318 B After Width: | Height: | Size: 319 B |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3" y="8" width="17" height="8" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M16 4V20" stroke-width="1" /></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="2" y="7" width="16" height="10" fill="currentColor" fill-opacity="0.55" stroke="none"/><path d="M13 3V21" stroke-width="1" /></svg>
|
||||
|
Before Width: | Height: | Size: 321 B After Width: | Height: | Size: 323 B |
@@ -22,3 +22,4 @@ moxcms = "0.8"
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
sha2 = { version = "0.10", default-features = false }
|
||||
@@ -0,0 +1,2 @@
|
||||
# The characterization data files are kept byte for byte as published (CRLF line endings).
|
||||
*.txt -text
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+41
-6
@@ -5,7 +5,9 @@
|
||||
//! (1998 primaries), Display P3, ProPhoto RGB) or user `.icc` files. Display output is sRGB;
|
||||
//! the desktop canvas converts it into the display's own profile last, in the app.
|
||||
//! * **CMYK spaces:** [`GENERIC_CMYK`] is our own documented parametric press model
|
||||
//! ([`generic`]); [`DEVICE_CMYK`] is the old profile-free formula (kept for exact legacy numbers);
|
||||
//! ([`generic`]); [`FOGRA51_CMYK`] and [`FOGRA52_CMYK`] are the same model computed from
|
||||
//! Fogra's published characterization data ([`measured`]); [`DEVICE_CMYK`] is the old
|
||||
//! profile-free formula (kept for exact legacy numbers);
|
||||
//! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles).
|
||||
//! * The **active settings** are process-wide: the working settings (Edit → Color Settings), with
|
||||
//! the profiles [`use_document_profiles`] last put in place of the working spaces;
|
||||
@@ -16,6 +18,7 @@
|
||||
pub mod generic;
|
||||
pub mod icc;
|
||||
pub mod lab;
|
||||
pub mod measured;
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
@@ -36,6 +39,12 @@ pub const DISPLAY_P3: &str = "Display P3";
|
||||
pub const PROPHOTO_RGB: &str = "ProPhoto RGB";
|
||||
/// Our parametric press model (see [`generic`]). Not an Adobe/ECI profile.
|
||||
pub const GENERIC_CMYK: &str = "VectorCraft Generic CMYK (SWOP-like)";
|
||||
/// VectorCraft's own press model computed from Fogra's FOGRA51 characterization data (offset on
|
||||
/// premium coated paper, see [`measured`]).
|
||||
pub const FOGRA51_CMYK: &str = "VectorCraft Coated CMYK (FOGRA51)";
|
||||
/// VectorCraft's own press model computed from Fogra's FOGRA52 characterization data (offset on
|
||||
/// wood-free uncoated paper, see [`measured`]).
|
||||
pub const FOGRA52_CMYK: &str = "VectorCraft Uncoated CMYK (FOGRA52)";
|
||||
/// Profile-free CMYK (`rgb = (1−c)(1−k)` …): uncalibrated, kept for legacy numbers.
|
||||
pub const DEVICE_CMYK: &str = "Device CMYK (uncalibrated)";
|
||||
/// The grey space greyscale exports are written in: sRGB's tone curve (a grey shows as on screen).
|
||||
@@ -43,7 +52,7 @@ pub const GRAY: &str = "Gray (sRGB tone curve)";
|
||||
|
||||
/// Built-in RGB and CMYK working spaces, in menu order.
|
||||
const BUILTIN_RGB: [&str; 4] = [SRGB, WIDE_GAMUT_RGB, DISPLAY_P3, PROPHOTO_RGB];
|
||||
const BUILTIN_CMYK: [&str; 2] = [GENERIC_CMYK, DEVICE_CMYK];
|
||||
const BUILTIN_CMYK: [&str; 4] = [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK, DEVICE_CMYK];
|
||||
|
||||
/// Names earlier versions gave built-in profiles: (old name, current name). Settings, documents
|
||||
/// and commands that still use an old name get the current profile.
|
||||
@@ -239,6 +248,21 @@ fn generic() -> Arc<GenericCmyk> {
|
||||
G.get_or_init(|| Arc::new(GenericCmyk::new(generic::swop_like()))).clone()
|
||||
}
|
||||
|
||||
/// The working space of `condition`, computed from its data once and kept.
|
||||
fn measured_space(condition: &measured::Condition) -> Result<Arc<GenericCmyk>, CmsError> {
|
||||
static SPACES: [OnceLock<Option<Arc<GenericCmyk>>>; measured::CONDITIONS.len()] = [const { OnceLock::new() }; measured::CONDITIONS.len()];
|
||||
let slot = measured::CONDITIONS.iter().position(|c| c.name == condition.name).and_then(|i| SPACES.get(i));
|
||||
slot.and_then(|s| s.get_or_init(|| measured::model(condition).map(Arc::new)).clone())
|
||||
.ok_or_else(|| CmsError::BadProfile(format!("{}: the {} data does not give a press model", condition.name, condition.reference)))
|
||||
}
|
||||
|
||||
/// The registered printing condition a built-in CMYK working space characterizes: its reference
|
||||
/// name, the `/OutputConditionIdentifier` of a PDF/X output intent, and the registry it belongs
|
||||
/// to (by its current or legacy name). `None` for every other profile.
|
||||
pub fn characterization(name: &str) -> Option<(&'static str, &'static str)> {
|
||||
measured::condition(canonical_name(name)).map(|c| (c.reference, measured::REGISTRY))
|
||||
}
|
||||
|
||||
static USER: RwLock<Vec<Arc<IccProfile>>> = RwLock::new(Vec::new());
|
||||
/// Counts the profiles [`register_icc`] has registered ([`profiles_generation`]).
|
||||
static PROFILES_GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
@@ -259,7 +283,11 @@ fn user_profile(name: &str) -> Option<Arc<IccProfile>> {
|
||||
}
|
||||
|
||||
fn cmyk_space(name: &str) -> Result<CmykSpace, CmsError> {
|
||||
match canonical_name(name) {
|
||||
let canonical = canonical_name(name);
|
||||
if let Some(c) = measured::condition(canonical) {
|
||||
return measured_space(c).map(CmykSpace::Generic);
|
||||
}
|
||||
match canonical {
|
||||
GENERIC_CMYK => Ok(CmykSpace::Generic(generic())),
|
||||
DEVICE_CMYK => Ok(CmykSpace::Device),
|
||||
_ => match user_profile(name) {
|
||||
@@ -382,9 +410,13 @@ pub fn icc_bytes(name: &str) -> Result<Arc<[u8]>, CmsError> {
|
||||
CmykSpace::Generic(g) => g.paper_xyz(),
|
||||
CmykSpace::Device | CmykSpace::Icc(_) => lab::D50,
|
||||
};
|
||||
let copyright = match measured::condition(name) {
|
||||
Some(c) => format!("Computed by VectorCraft from the {} characterization data. Data source: Fogra, www.fogra.org", c.reference),
|
||||
None => icc::NO_COPYRIGHT.to_string(),
|
||||
};
|
||||
let to_lab = |c| cms.cmyk_to_lab(c);
|
||||
let shadows = |l| mapped.lab_to_cmyk(l, Intent::RelativeColorimetric);
|
||||
icc::encode(&icc::cmyk_profile(name, paper, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
|
||||
icc::encode(&icc::cmyk_profile(name, paper, ©right, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
|
||||
} else {
|
||||
icc::builtin_rgb_bytes(name)?
|
||||
}
|
||||
@@ -496,7 +528,8 @@ impl Cms {
|
||||
/// directly into the RGB profile: not through display sRGB, which would clip colours a wider
|
||||
/// RGB space holds (Wide Gamut RGB keeps CMYK cyan that sRGB can't show), and with the
|
||||
/// settings' black-point compensation. The built-in CMYK spaces go through sRGB as before
|
||||
/// (Generic CMYK compensates in its own model).
|
||||
/// (Generic CMYK compensates in its own model); with the absolute colorimetric intent the
|
||||
/// paper colour shows.
|
||||
pub fn cmyk_to_rgb(&self, cmyk: [f32; 4], intent: Intent) -> [f32; 3] {
|
||||
let cmyk = cmyk.map(|v| v.clamp(0.0, 1.0));
|
||||
let src = match &self.cmyk {
|
||||
@@ -509,7 +542,7 @@ impl Cms {
|
||||
};
|
||||
src.zip(dest)
|
||||
.and_then(|(s, d)| s.to_rgb_of(&d, &cmyk, intent, self.settings.bpc))
|
||||
.unwrap_or_else(|| self.srgb_to_rgb(self.cmyk_to_srgb(cmyk, false)))
|
||||
.unwrap_or_else(|| self.srgb_to_rgb(self.cmyk_to_srgb(cmyk, intent == Intent::AbsoluteColorimetric)))
|
||||
}
|
||||
/// Display sRGB → working CMYK with `intent`.
|
||||
pub fn srgb_to_cmyk(&self, srgb: [f32; 3], intent: Intent) -> [f32; 4] {
|
||||
@@ -1315,3 +1348,5 @@ pub(crate) fn cmyk_is_device() -> bool {
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod tests_icc;
|
||||
#[cfg(test)]
|
||||
mod tests_measured;
|
||||
@@ -30,6 +30,7 @@ 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};
|
||||
use super::measured::Lattice;
|
||||
|
||||
/// Black generation.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -129,6 +130,9 @@ pub struct GenericCmyk {
|
||||
paper_xyz: [f32; 3],
|
||||
/// Media-relative XYZ of the black point (for black-point compensation).
|
||||
black_rel: [f32; 3],
|
||||
/// A media-relative Lab correction added to the model, fitted to measured data
|
||||
/// ([`super::measured`]).
|
||||
correction: Option<Lattice>,
|
||||
gbd: OnceLock<Gbd>,
|
||||
}
|
||||
|
||||
@@ -139,6 +143,15 @@ impl GenericCmyk {
|
||||
}
|
||||
|
||||
pub fn new(params: GenericCmykParams) -> Self {
|
||||
Self::build(params, None)
|
||||
}
|
||||
|
||||
/// The model of `params` with `correction` added to its media-relative Lab.
|
||||
pub fn with_correction(params: GenericCmykParams, correction: Lattice) -> Self {
|
||||
Self::build(params, Some(correction))
|
||||
}
|
||||
|
||||
fn build(params: GenericCmykParams, correction: Option<Lattice>) -> Self {
|
||||
let paper_xyz = lab_to_xyz(params.paper);
|
||||
let mut prim = [D50; 16];
|
||||
for (p, lab) in prim[1..].iter_mut().zip(params.primaries.iter()) {
|
||||
@@ -149,7 +162,7 @@ impl GenericCmyk {
|
||||
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() };
|
||||
let mut g = Self { params, prim, skew, paper_xyz, black_rel: [0.0; 3], correction, gbd: OnceLock::new() };
|
||||
g.black_rel = g.to_xyz_rel(g.black_point_build());
|
||||
g
|
||||
}
|
||||
@@ -218,6 +231,14 @@ impl GenericCmyk {
|
||||
|
||||
/// Media-relative XYZ (paper = D50 white).
|
||||
pub fn to_xyz_rel(&self, cmyk: [f32; 4]) -> [f32; 3] {
|
||||
match &self.correction {
|
||||
Some(_) => lab_to_xyz(self.to_lab_rel(cmyk)),
|
||||
None => self.neugebauer(cmyk),
|
||||
}
|
||||
}
|
||||
|
||||
/// Media-relative XYZ of the Neugebauer model alone.
|
||||
fn neugebauer(&self, cmyk: [f32; 4]) -> [f32; 3] {
|
||||
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() {
|
||||
@@ -236,7 +257,14 @@ impl GenericCmyk {
|
||||
}
|
||||
|
||||
pub fn to_lab_rel(&self, cmyk: [f32; 4]) -> Lab {
|
||||
xyz_to_lab(self.to_xyz_rel(cmyk))
|
||||
let lab = xyz_to_lab(self.neugebauer(cmyk));
|
||||
match &self.correction {
|
||||
Some(c) => {
|
||||
let d = c.at(cmyk);
|
||||
Lab::new((lab.l + d[0]).max(0.0), lab.a + d[1], lab.b + d[2])
|
||||
}
|
||||
None => lab,
|
||||
}
|
||||
}
|
||||
pub fn to_lab_abs(&self, cmyk: [f32; 4]) -> Lab {
|
||||
xyz_to_lab(self.to_xyz(cmyk))
|
||||
|
||||
@@ -432,10 +432,17 @@ fn text_tag(s: &str) -> Option<ProfileText> {
|
||||
Some(ProfileText::Localizable(vec![LocalizableString::new("en".into(), "US".into(), s.into())]))
|
||||
}
|
||||
|
||||
/// The copyright text of profiles made here: they carry no copyright claim.
|
||||
pub(super) const NO_COPYRIGHT: &str = "No copyright, use freely";
|
||||
|
||||
/// Profiles made here carry their name and no copyright claim.
|
||||
fn labelled(mut p: ColorProfile, name: &str) -> ColorProfile {
|
||||
fn labelled(p: ColorProfile, name: &str) -> ColorProfile {
|
||||
with_copyright(p, name, NO_COPYRIGHT)
|
||||
}
|
||||
|
||||
fn with_copyright(mut p: ColorProfile, name: &str, copyright: &str) -> ColorProfile {
|
||||
p.description = text_tag(name);
|
||||
p.copyright = text_tag("No copyright, use freely");
|
||||
p.copyright = text_tag(copyright);
|
||||
p
|
||||
}
|
||||
|
||||
@@ -452,10 +459,11 @@ const GAMUT_GRID: usize = 9;
|
||||
/// It carries every tag ICC.1 requires of an output profile: the tables for all three intents
|
||||
/// and the gamut tag (Windows rejects a CMYK profile without them, so Photos couldn't show a CMYK
|
||||
/// TIFF that embedded one, #2707). The media white point is `paper` (absolute XYZ, D50), which
|
||||
/// the ICC-absolute colorimetric intent reproduces.
|
||||
/// the ICC-absolute colorimetric intent reproduces; the copyright tag holds `copyright`.
|
||||
pub(super) fn cmyk_profile(
|
||||
name: &str,
|
||||
paper: [f32; 3],
|
||||
copyright: &str,
|
||||
to_lab: impl Fn([f32; 4]) -> lab::Lab,
|
||||
mapped: impl Fn(lab::Lab) -> [f32; 4],
|
||||
colorimetric: impl Fn(lab::Lab) -> [f32; 4],
|
||||
@@ -520,7 +528,7 @@ pub(super) fn cmyk_profile(
|
||||
p.lut_b_to_a_saturation = Some(b2a_mapped);
|
||||
p.lut_b_to_a_colorimetric = Some(b2a);
|
||||
p.gamut = Some(gamut);
|
||||
labelled(p, name)
|
||||
with_copyright(p, name, copyright)
|
||||
}
|
||||
|
||||
/// The grey space of greyscale exports: sRGB's tone curve, D50 white.
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
//! CMYK working spaces computed from published characterization data.
|
||||
//!
|
||||
//! Fogra publishes the measured colors of its reference printing conditions
|
||||
//! (<https://fogra.org/en/downloads/work-tools/characterisation-data>) and allows the data to be
|
||||
//! redistributed unmodified, with Fogra named as the source. VectorCraft embeds the FOGRA51 and
|
||||
//! FOGRA52 files byte for byte (`crates/color/data/`) and computes each press model from them the
|
||||
//! first time it is used:
|
||||
//!
|
||||
//! * The paper is the measured blank patch. The 15 solids and overprints of the
|
||||
//! [`super::generic`] model are the measured patches of those builds, and each ink's tone curve
|
||||
//! is fitted to its single-ink ramp.
|
||||
//! * What that model still misses at each patch (in media-relative Lab) is fitted with a smoothed
|
||||
//! lattice over CMYK ([`Lattice`]), which [`GenericCmyk::to_xyz_rel`] adds to the model. The
|
||||
//! smoothing carries the fit into regions the patch set does not sample, such as dark builds
|
||||
//! with more than 60% black.
|
||||
//!
|
||||
//! The total ink limit and the black generation are VectorCraft's own values.
|
||||
|
||||
use super::generic::{GenericCmyk, GenericCmykParams, swop_like};
|
||||
use super::lab::{D50, Lab, lab_to_xyz, xyz_to_lab};
|
||||
|
||||
/// A printing condition with published characterization data.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Condition {
|
||||
/// The working space's name.
|
||||
pub name: &'static str,
|
||||
/// The reference name of the characterization data, which a PDF/X output intent uses as
|
||||
/// its `/OutputConditionIdentifier`.
|
||||
pub reference: &'static str,
|
||||
/// The characterization data file, as published.
|
||||
pub data: &'static [u8],
|
||||
/// Total area coverage limit (sum of inks, 1.0 = 100%): VectorCraft's own value.
|
||||
pub tac: f32,
|
||||
}
|
||||
|
||||
/// The registry that the reference names of [`CONDITIONS`] belong to
|
||||
/// (<https://registry.color.org/cmyk-registry/>).
|
||||
pub const REGISTRY: &str = "http://www.color.org";
|
||||
|
||||
/// The printing conditions VectorCraft computes working spaces for.
|
||||
pub const CONDITIONS: [Condition; 2] = [
|
||||
Condition { name: super::FOGRA51_CMYK, reference: "FOGRA51", data: include_bytes!("../../data/FOGRA51.txt"), tac: 3.0 },
|
||||
Condition { name: super::FOGRA52_CMYK, reference: "FOGRA52", data: include_bytes!("../../data/FOGRA52.txt"), tac: 3.0 },
|
||||
];
|
||||
|
||||
/// The condition a working space of [`CONDITIONS`] is computed for.
|
||||
pub fn condition(name: &str) -> Option<&'static Condition> {
|
||||
CONDITIONS.iter().find(|c| c.name == name)
|
||||
}
|
||||
|
||||
/// One measured patch: nominal inks (0..1) and absolute Lab (D50).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Patch {
|
||||
pub cmyk: [f32; 4],
|
||||
pub lab: Lab,
|
||||
}
|
||||
|
||||
/// The most patches [`parse`] reads.
|
||||
const MAX_PATCHES: usize = 20_000;
|
||||
|
||||
/// The patches of a CGATS / ISO 28178 characterization data file with `CMYK_C`, `CMYK_M`,
|
||||
/// `CMYK_Y`, `CMYK_K`, `LAB_L`, `LAB_A` and `LAB_B` fields. `None` when a field is missing, a
|
||||
/// row is short or holds a value that is not a finite number, an ink is outside 0 to 100, the
|
||||
/// file has no rows, the rows do not end with `END_DATA`, or a `NUMBER_OF_SETS` in the header is
|
||||
/// not the number of rows.
|
||||
pub fn parse(data: &[u8]) -> Option<Vec<Patch>> {
|
||||
let text = std::str::from_utf8(data).ok()?;
|
||||
let sets = text.lines().map(str::trim).take_while(|l| *l != "BEGIN_DATA").find_map(|l| {
|
||||
let mut words = l.split_whitespace();
|
||||
(words.next() == Some("NUMBER_OF_SETS")).then(|| words.next().map(|n| n.trim_matches('"')))
|
||||
});
|
||||
let sets = match sets {
|
||||
Some(n) => Some(n?.parse::<usize>().ok()?),
|
||||
None => None,
|
||||
};
|
||||
let mut lines = text.lines().map(str::trim);
|
||||
lines.by_ref().find(|l| *l == "BEGIN_DATA_FORMAT")?;
|
||||
let mut fields = vec![];
|
||||
for line in lines.by_ref() {
|
||||
if line == "END_DATA_FORMAT" {
|
||||
break;
|
||||
}
|
||||
fields.extend(line.split_whitespace());
|
||||
}
|
||||
let at = |f: &str| fields.iter().position(|x| *x == f);
|
||||
let cols = [at("CMYK_C")?, at("CMYK_M")?, at("CMYK_Y")?, at("CMYK_K")?, at("LAB_L")?, at("LAB_A")?, at("LAB_B")?];
|
||||
lines.by_ref().find(|l| *l == "BEGIN_DATA")?;
|
||||
let mut out = vec![];
|
||||
let mut ended = false;
|
||||
for line in lines {
|
||||
if line == "END_DATA" {
|
||||
ended = true;
|
||||
break;
|
||||
}
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if out.len() >= MAX_PATCHES {
|
||||
return None;
|
||||
}
|
||||
let row: Vec<&str> = line.split_whitespace().collect();
|
||||
let mut v = [0f32; 7];
|
||||
for (slot, &col) in v.iter_mut().zip(&cols) {
|
||||
*slot = row.get(col)?.parse::<f32>().ok().filter(|x| x.is_finite())?;
|
||||
}
|
||||
if v[..4].iter().any(|x| !(0.0..=100.0).contains(x)) {
|
||||
return None;
|
||||
}
|
||||
out.push(Patch { cmyk: [v[0], v[1], v[2], v[3]].map(|x| x / 100.0), lab: Lab::new(v[4], v[5], v[6]) });
|
||||
}
|
||||
(ended && !out.is_empty() && sets.is_none_or(|n| n == out.len())).then_some(out)
|
||||
}
|
||||
|
||||
/// Absolute Lab → media-relative Lab (`paper` maps to the D50 white).
|
||||
fn relative(lab: Lab, paper: [f32; 3]) -> Lab {
|
||||
let x = lab_to_xyz(lab);
|
||||
xyz_to_lab([0, 1, 2].map(|i| x[i] * D50[i] / paper[i]))
|
||||
}
|
||||
|
||||
/// The mean of the Lab values of the patches whose inks are `inks`, in XYZ.
|
||||
fn mean_lab(patches: &[Patch], inks: [f32; 4]) -> Option<Lab> {
|
||||
let mut sum = [0f32; 3];
|
||||
let mut n = 0;
|
||||
for p in patches.iter().filter(|p| p.cmyk.iter().zip(&inks).all(|(a, b)| (a - b).abs() < 1e-4)) {
|
||||
let x = lab_to_xyz(p.lab);
|
||||
for i in 0..3 {
|
||||
sum[i] += x[i];
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
(n > 0).then(|| xyz_to_lab(sum.map(|v| v / n as f32)))
|
||||
}
|
||||
|
||||
/// The tone value increase at 50% and 40% of ink `ink`, fitted to its single-ink ramp with the
|
||||
/// curve of [`super::generic`]: the effective area is `a + u·4a(1−a) + v·4a(1−a)(2a−1)`, so the
|
||||
/// 50% increase is `u` and the 40% increase is `0.96·u − 0.192·v`. Each patch's effective area
|
||||
/// comes from the Murray–Davies formula in the media-relative XYZ channel the ink darkens most
|
||||
/// (`paper` is the paper's absolute XYZ, `solid` the solid's media-relative XYZ).
|
||||
fn tone_increase(patches: &[Patch], ink: usize, paper: [f32; 3], solid: [f32; 3]) -> Option<(f32, f32)> {
|
||||
let ch = (0..3).max_by(|&a, &b| (D50[a] - solid[a]).abs().total_cmp(&(D50[b] - solid[b]).abs()))?;
|
||||
let span = D50[ch] - solid[ch];
|
||||
if span.abs() < 1e-4 {
|
||||
return None;
|
||||
}
|
||||
let (mut s11, mut s12, mut s22, mut r1, mut r2) = (0f64, 0f64, 0f64, 0f64, 0f64);
|
||||
for p in patches {
|
||||
let a = p.cmyk[ink];
|
||||
let alone = p.cmyk.iter().enumerate().all(|(i, v)| i == ink || *v == 0.0);
|
||||
if !alone || a <= 0.0 || a >= 1.0 {
|
||||
continue;
|
||||
}
|
||||
let e = (D50[ch] - relative_xyz(p.lab, paper)[ch]) / span;
|
||||
let (b1, b2) = (f64::from(4.0 * a * (1.0 - a)), f64::from(4.0 * a * (1.0 - a) * (2.0 * a - 1.0)));
|
||||
let d = f64::from(e - a);
|
||||
s11 += b1 * b1;
|
||||
s12 += b1 * b2;
|
||||
s22 += b2 * b2;
|
||||
r1 += b1 * d;
|
||||
r2 += b2 * d;
|
||||
}
|
||||
let det = s11 * s22 - s12 * s12;
|
||||
if det.abs() < 1e-12 {
|
||||
return None;
|
||||
}
|
||||
let u = ((r1 * s22 - r2 * s12) / det) as f32;
|
||||
let v = ((s11 * r2 - s12 * r1) / det) as f32;
|
||||
let tvi50 = u.clamp(0.0, 0.45);
|
||||
let tvi40 = (0.96 * u - 0.192 * v).clamp(0.0, 0.45);
|
||||
Some((tvi50, tvi40))
|
||||
}
|
||||
|
||||
/// Absolute Lab → media-relative XYZ.
|
||||
fn relative_xyz(lab: Lab, paper: [f32; 3]) -> [f32; 3] {
|
||||
let x = lab_to_xyz(lab);
|
||||
[0, 1, 2].map(|i| x[i] * D50[i] / paper[i])
|
||||
}
|
||||
|
||||
/// The press model of `condition`, computed from its data. `None` when the data does not parse,
|
||||
/// lacks the paper, a solid or overprint, or a single-ink ramp, or gives a paper whose XYZ is not
|
||||
/// positive and finite.
|
||||
pub fn model(condition: &Condition) -> Option<GenericCmyk> {
|
||||
fit(condition, &parse(condition.data)?, SMOOTHING)
|
||||
}
|
||||
|
||||
/// The press model of `condition` fitted to `patches`, with the lattice's `smoothing` (`None` in
|
||||
/// the cases [`model`] lists).
|
||||
pub(crate) fn fit(condition: &Condition, patches: &[Patch], smoothing: f64) -> Option<GenericCmyk> {
|
||||
let paper = mean_lab(patches, [0.0; 4])?;
|
||||
let paper_xyz = lab_to_xyz(paper);
|
||||
if paper_xyz.iter().any(|v| !v.is_finite() || *v <= 0.0) {
|
||||
return None;
|
||||
}
|
||||
let mut primaries = [Lab::new(0.0, 0.0, 0.0); 15];
|
||||
for (i, slot) in primaries.iter_mut().enumerate() {
|
||||
let bits = i + 1;
|
||||
let inks = [0, 1, 2, 3].map(|b| if bits & (1 << b) != 0 { 1.0 } else { 0.0 });
|
||||
*slot = relative(mean_lab(patches, inks)?, paper_xyz);
|
||||
}
|
||||
let mut tvi50 = [0f32; 4];
|
||||
let mut tvi40 = [0f32; 4];
|
||||
for ink in 0..4 {
|
||||
let solid = lab_to_xyz(primaries[(1 << ink) - 1]);
|
||||
(tvi50[ink], tvi40[ink]) = tone_increase(patches, ink, paper_xyz, solid)?;
|
||||
}
|
||||
let params = GenericCmykParams { name: condition.name, paper, primaries, tvi50, tvi40, tac: condition.tac, bg: swop_like().bg };
|
||||
let base = GenericCmyk::new(params.clone());
|
||||
let points: Vec<([f32; 4], [f32; 3])> = patches
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let want = relative(p.lab, paper_xyz);
|
||||
let got = base.to_lab_rel(p.cmyk);
|
||||
(p.cmyk, [want.l - got.l, want.a - got.a, want.b - got.b])
|
||||
})
|
||||
.collect();
|
||||
Some(GenericCmyk::with_correction(params, Lattice::fit(&points, smoothing)))
|
||||
}
|
||||
|
||||
/// Weight of the lattice's smoothness against its fit to the patches.
|
||||
pub(crate) const SMOOTHING: f64 = 0.02;
|
||||
|
||||
/// Knots of each ink's axis of the [`Lattice`]: the steps of the published single-ink ramps.
|
||||
const KNOTS: [f32; 9] = [0.0, 0.1, 0.2, 0.3, 0.4, 0.55, 0.7, 0.85, 1.0];
|
||||
const N: usize = KNOTS.len();
|
||||
const NODES: usize = N * N * N * N;
|
||||
|
||||
/// A Lab correction over CMYK, read by multilinear interpolation between nodes at [`KNOTS`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Lattice {
|
||||
values: Vec<[f32; 3]>,
|
||||
}
|
||||
|
||||
/// The cell of `v` along an axis and its position in it.
|
||||
fn locate(v: f32) -> (usize, f32) {
|
||||
let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let i = KNOTS.iter().skip(1).position(|k| v <= *k).unwrap_or(N - 2).min(N - 2);
|
||||
let (lo, hi) = (KNOTS[i], KNOTS[i + 1]);
|
||||
(i, ((v - lo) / (hi - lo)).clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
/// The 16 nodes around `cmyk` with their interpolation weights.
|
||||
fn corners(cmyk: [f32; 4]) -> [(usize, f32); 16] {
|
||||
let cells = cmyk.map(locate);
|
||||
let mut out = [(0, 0.0); 16];
|
||||
for (corner, slot) in out.iter_mut().enumerate() {
|
||||
let mut index = 0;
|
||||
let mut w = 1.0;
|
||||
for (axis, (cell, t)) in cells.iter().enumerate() {
|
||||
let up = corner & (1 << axis) != 0;
|
||||
index = index * N + cell + usize::from(up);
|
||||
w *= if up { *t } else { 1.0 - t };
|
||||
}
|
||||
*slot = (index, w);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Index strides of the four axes (C is the slowest).
|
||||
const STRIDES: [usize; 4] = [N * N * N, N * N, N, 1];
|
||||
|
||||
impl Lattice {
|
||||
/// The correction at `cmyk`.
|
||||
pub fn at(&self, cmyk: [f32; 4]) -> [f32; 3] {
|
||||
let mut out = [0f32; 3];
|
||||
for (i, w) in corners(cmyk) {
|
||||
if w == 0.0 {
|
||||
continue;
|
||||
}
|
||||
let v = self.values.get(i).copied().unwrap_or_default();
|
||||
for c in 0..3 {
|
||||
out[c] += w * v[c];
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The lattice that best fits `points` (inks, correction) in the least-squares sense, with
|
||||
/// `smoothing` times the squared second differences of the nodes along each axis added to the
|
||||
/// error. The node at no ink stays 0, so the paper keeps the model's color (white, media-
|
||||
/// relative). Solved by conjugate gradients, one Lab channel at a time.
|
||||
pub fn fit(points: &[([f32; 4], [f32; 3])], smoothing: f64) -> Lattice {
|
||||
let weights: Vec<[(usize, f32); 16]> = points.iter().map(|(cmyk, _)| corners(*cmyk)).collect();
|
||||
// The divided second difference at interior knot j, scaled to a unit spacing of 1/8.
|
||||
let curvature: Vec<[f64; 3]> = (1..N - 1)
|
||||
.map(|j| {
|
||||
let (h1, h2) = (f64::from(KNOTS[j] - KNOTS[j - 1]), f64::from(KNOTS[j + 1] - KNOTS[j]));
|
||||
let s = 0.125f64 * 0.125;
|
||||
[2.0 / (h1 * (h1 + h2)) * s, -2.0 / (h1 * h2) * s, 2.0 / (h2 * (h1 + h2)) * s]
|
||||
})
|
||||
.collect();
|
||||
let apply = |x: &[f64], out: &mut [f64]| {
|
||||
out.fill(0.0);
|
||||
for w in &weights {
|
||||
let v: f64 = w.iter().map(|(i, w)| f64::from(*w) * x.get(*i).copied().unwrap_or(0.0)).sum();
|
||||
for (i, w) in w {
|
||||
if let Some(o) = out.get_mut(*i) {
|
||||
*o += f64::from(*w) * v;
|
||||
}
|
||||
}
|
||||
}
|
||||
for node in 0..NODES {
|
||||
let mut rest = node;
|
||||
for stride in STRIDES {
|
||||
let j = rest / stride;
|
||||
rest %= stride;
|
||||
// Only interior knots (1 to N − 2) have a second difference.
|
||||
let Some(c) = j.checked_sub(1).and_then(|k| curvature.get(k)) else { continue };
|
||||
let idx = [node - stride, node, node + stride];
|
||||
let d: f64 = idx.iter().zip(c).map(|(i, c)| c * x.get(*i).copied().unwrap_or(0.0)).sum();
|
||||
for (i, c) in idx.iter().zip(c) {
|
||||
if let Some(o) = out.get_mut(*i) {
|
||||
*o += smoothing * c * d;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (o, v) in out.iter_mut().zip(x) {
|
||||
*o += 1e-9 * v;
|
||||
}
|
||||
// The paper's node is held: with its right-hand side 0 it stays 0 in every iterate.
|
||||
if let (Some(o), Some(v)) = (out.first_mut(), x.first()) {
|
||||
*o = *v;
|
||||
}
|
||||
};
|
||||
let mut values = vec![[0f32; 3]; NODES];
|
||||
for ch in 0..3 {
|
||||
let mut b = vec![0f64; NODES];
|
||||
for (w, (_, r)) in weights.iter().zip(points) {
|
||||
for (i, w) in w {
|
||||
if let Some(o) = b.get_mut(*i) {
|
||||
*o += f64::from(*w) * f64::from(r[ch]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(o) = b.first_mut() {
|
||||
*o = 0.0;
|
||||
}
|
||||
let x = conjugate_gradients(&apply, &b, 4000);
|
||||
for (v, x) in values.iter_mut().zip(&x) {
|
||||
v[ch] = *x as f32;
|
||||
}
|
||||
}
|
||||
Lattice { values }
|
||||
}
|
||||
}
|
||||
|
||||
/// Solve `A x = b` for the symmetric positive definite `A` that `apply` multiplies by.
|
||||
fn conjugate_gradients(apply: &dyn Fn(&[f64], &mut [f64]), b: &[f64], max_iterations: usize) -> Vec<f64> {
|
||||
let n = b.len();
|
||||
let mut x = vec![0f64; n];
|
||||
let mut r = b.to_vec();
|
||||
let mut p = r.clone();
|
||||
let mut ap = vec![0f64; n];
|
||||
let dot = |a: &[f64], b: &[f64]| a.iter().zip(b).map(|(a, b)| a * b).sum::<f64>();
|
||||
let mut rr = dot(&r, &r);
|
||||
let stop = rr * 1e-20;
|
||||
for _ in 0..max_iterations {
|
||||
if rr <= stop || rr == 0.0 {
|
||||
break;
|
||||
}
|
||||
apply(&p, &mut ap);
|
||||
let pap = dot(&p, &ap);
|
||||
if pap <= 0.0 || !pap.is_finite() {
|
||||
break;
|
||||
}
|
||||
let alpha = rr / pap;
|
||||
for i in 0..n {
|
||||
x[i] += alpha * p[i];
|
||||
r[i] -= alpha * ap[i];
|
||||
}
|
||||
let next = dot(&r, &r);
|
||||
let beta = next / rr;
|
||||
rr = next;
|
||||
for i in 0..n {
|
||||
p[i] = r[i] + beta * p[i];
|
||||
}
|
||||
}
|
||||
x
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
use super::*;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// The data files ship exactly as Fogra publishes them in
|
||||
/// https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip.
|
||||
#[test]
|
||||
fn characterization_data_is_the_published_files() {
|
||||
let want = [
|
||||
("FOGRA51", "ad472a1c0bdafd558597ff93eeda5175805086565af814cb6346e910e2f25aa5", 57_111),
|
||||
("FOGRA52", "be4f0732328ed62ade63ec7f317d3b9e9dad6bbe2430fefddaf0f901d5ba13d6", 56_781),
|
||||
];
|
||||
for (c, (reference, sha, len)) in measured::CONDITIONS.iter().zip(want) {
|
||||
assert_eq!(c.reference, reference);
|
||||
assert_eq!((c.data.len(), hex(c.data).as_str()), (len, sha), "{reference}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_data_parses_into_its_patches() {
|
||||
for c in &measured::CONDITIONS {
|
||||
let patches = measured::parse(c.data).unwrap();
|
||||
assert_eq!(patches.len(), 1617, "{}", c.reference);
|
||||
assert_eq!(patches[0].cmyk, [0.0; 4]);
|
||||
}
|
||||
let p = measured::parse(measured::CONDITIONS[0].data).unwrap();
|
||||
assert_eq!(p[0].lab, Lab::new(95.0, 1.5, -6.0));
|
||||
assert_eq!(p[1].cmyk, [0.0, 0.1, 0.0, 0.0]);
|
||||
assert_eq!(p[1].lab, Lab::new(90.08, 8.15, -7.42));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_data_is_refused() {
|
||||
let file = |format: &str, rows: &str| format!("ISO28178\nBEGIN_DATA_FORMAT\n{format}\nEND_DATA_FORMAT\nBEGIN_DATA\n{rows}\nEND_DATA\n");
|
||||
let fields = "SAMPLE_ID CMYK_C CMYK_M CMYK_Y CMYK_K LAB_L LAB_A LAB_B";
|
||||
let good = file(fields, "1 0 0 0 0 95 1 -6\n2 100 0 0 0 55 -37 -50");
|
||||
assert_eq!(measured::parse(good.as_bytes()).map(|p| p.len()), Some(2));
|
||||
for bad in [
|
||||
file("SAMPLE_ID CMYK_C CMYK_M CMYK_Y LAB_L LAB_A LAB_B", "1 0 0 0 95 1 -6"),
|
||||
file(fields, "1 0 0 0 0 95 1"),
|
||||
file(fields, "1 0 0 0 0 95 NaN -6"),
|
||||
file(fields, "1 0 0 0 0 95 x -6"),
|
||||
file(fields, "1 0 0 0 101 95 1 -6"),
|
||||
file(fields, "1 -1 0 0 0 95 1 -6"),
|
||||
file(fields, ""),
|
||||
"BEGIN_DATA\n1 0 0 0 0 95 1 -6\nEND_DATA\n".into(),
|
||||
] {
|
||||
assert_eq!(measured::parse(bad.as_bytes()), None, "{bad}");
|
||||
}
|
||||
assert_eq!(measured::parse(&[0xff, 0xfe, 0x00]), None);
|
||||
// The rows end with END_DATA, and a NUMBER_OF_SETS in the header counts them.
|
||||
let rows = "1 0 0 0 0 95 1 -6\n2 100 0 0 0 55 -37 -50";
|
||||
let header = |sets: &str| format!("ISO28178\nBEGIN_DATA_FORMAT\n{fields}\nEND_DATA_FORMAT\n{sets}\nBEGIN_DATA\n{rows}\n");
|
||||
assert_eq!(measured::parse(header("NUMBER_OF_SETS\t2").as_bytes()), None, "no END_DATA");
|
||||
for (sets, len) in [
|
||||
("NUMBER_OF_SETS\t2", Some(2)),
|
||||
("NUMBER_OF_SETS\t3", None),
|
||||
("NUMBER_OF_SETS\t1", None),
|
||||
("NUMBER_OF_SETS\tx", None),
|
||||
("NUMBER_OF_SETS", None),
|
||||
] {
|
||||
assert_eq!(measured::parse(format!("{}END_DATA\n", header(sets)).as_bytes()).map(|p| p.len()), len, "{sets}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A paper measured as black has no XYZ to make the other patches relative to.
|
||||
#[test]
|
||||
fn a_paper_without_light_is_refused() {
|
||||
let c = &measured::CONDITIONS[0];
|
||||
let mut patches = measured::parse(c.data).unwrap();
|
||||
for p in patches.iter_mut().filter(|p| p.cmyk == [0.0; 4]) {
|
||||
p.lab = Lab::new(0.0, 0.0, 0.0);
|
||||
}
|
||||
assert!(measured::fit(c, &patches, measured::SMOOTHING).is_none());
|
||||
}
|
||||
|
||||
/// ΔE2000 between each measured patch and the model's absolute Lab for its inks: (mean, max).
|
||||
fn accuracy(g: &GenericCmyk, patches: &[measured::Patch]) -> (f32, f32) {
|
||||
let errors: Vec<f32> = patches.iter().map(|p| delta_e2000(g.to_lab_abs(p.cmyk), p.lab)).collect();
|
||||
(errors.iter().sum::<f32>() / errors.len() as f32, errors.iter().copied().fold(0.0, f32::max))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_working_spaces_reproduce_the_measured_patches() {
|
||||
for c in &measured::CONDITIONS {
|
||||
let patches = measured::parse(c.data).unwrap();
|
||||
let start = std::time::Instant::now();
|
||||
let g = measured::model(c).unwrap();
|
||||
let took = start.elapsed();
|
||||
let (mean, max) = accuracy(&g, &patches);
|
||||
println!("{}: computed in {took:?}, mean ΔE2000 {mean:.3}, max {max:.3}", c.reference);
|
||||
assert!(mean < 0.1 && max < 0.6, "{}: mean {mean}, max {max}", c.reference);
|
||||
// The paper is the measured blank patch.
|
||||
assert!(delta_e2000(g.to_lab_abs([0.0; 4]), patches[0].lab) < 0.05);
|
||||
}
|
||||
}
|
||||
|
||||
/// A model fitted without every fourth patch (the paper and the solids and overprints stay in)
|
||||
/// predicts the patches it left out. The data repeats some builds, and every row of a build is
|
||||
/// on the side of the build's first row, so the fit never sees a left-out build.
|
||||
#[test]
|
||||
fn the_fit_predicts_patches_it_left_out() {
|
||||
for c in &measured::CONDITIONS {
|
||||
let patches = measured::parse(c.data).unwrap();
|
||||
let corner = |p: &measured::Patch| p.cmyk.iter().all(|v| *v == 0.0 || *v == 1.0);
|
||||
let first = |p: &measured::Patch| patches.iter().position(|q| q.cmyk == p.cmyk).unwrap_or(0);
|
||||
let (kept, left): (Vec<&measured::Patch>, Vec<_>) = patches.iter().partition(|p| first(p) % 4 != 3 || corner(p));
|
||||
assert!(left.iter().all(|l| kept.iter().all(|k| k.cmyk != l.cmyk)), "{}", c.reference);
|
||||
let kept: Vec<measured::Patch> = kept.into_iter().copied().collect();
|
||||
let left: Vec<measured::Patch> = left.into_iter().copied().collect();
|
||||
let g = measured::fit(c, &kept, measured::SMOOTHING).unwrap();
|
||||
let (mean, max) = accuracy(&g, &left);
|
||||
println!("{}: {} patches left out, mean ΔE2000 {mean:.3}, max {max:.3}", c.reference, left.len());
|
||||
assert!(mean < 0.3 && max < 2.5, "{}: mean {mean}, max {max}", c.reference);
|
||||
}
|
||||
}
|
||||
|
||||
/// More of any ink makes a build lighter by less than 0.3 L*, also where the data has few patches
|
||||
/// (black above 60%, and builds over the ink limit).
|
||||
#[test]
|
||||
fn more_ink_lightens_a_build_by_less_than_0_3_l() {
|
||||
let steps: Vec<f32> = (0..=20).map(|i| i as f32 / 20.0).collect();
|
||||
let coarse = [0.0, 0.25, 0.5, 0.75, 1.0];
|
||||
for c in &measured::CONDITIONS {
|
||||
let g = measured::model(c).unwrap();
|
||||
let mut worst = 0f32;
|
||||
for ink in 0..4 {
|
||||
for a in coarse {
|
||||
for b in coarse {
|
||||
for d in coarse {
|
||||
let mut others = [a, b, d].into_iter();
|
||||
let mut build = [0f32; 4];
|
||||
for (i, slot) in build.iter_mut().enumerate() {
|
||||
if i != ink {
|
||||
*slot = others.next().unwrap();
|
||||
}
|
||||
}
|
||||
let mut last = f32::INFINITY;
|
||||
for &v in &steps {
|
||||
build[ink] = v;
|
||||
let l = g.to_lab_rel(build).l;
|
||||
worst = worst.max(l - last);
|
||||
last = l;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
println!("{}: largest L* rise with more ink {worst:.3}", c.reference);
|
||||
assert!(worst < 0.3, "{}: {worst}", c.reference);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_working_spaces_follow_generic_cmyk_in_the_list() {
|
||||
let cmyk: Vec<String> = profiles().into_iter().filter(|p| p.kind == ProfileKind::Cmyk && p.builtin).map(|p| p.name).collect();
|
||||
assert_eq!(cmyk, [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK, DEVICE_CMYK]);
|
||||
assert_eq!(ColorSettings::default().cmyk, GENERIC_CMYK);
|
||||
assert_eq!(characterization(FOGRA51_CMYK), Some(("FOGRA51", "http://www.color.org")));
|
||||
assert_eq!(characterization(FOGRA52_CMYK), Some(("FOGRA52", "http://www.color.org")));
|
||||
assert_eq!(characterization(GENERIC_CMYK), None);
|
||||
assert!(matches!(register_icc(&icc_bytes(FOGRA51_CMYK).unwrap(), None), Err(CmsError::Unsupported(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colors_separate_and_come_back_in_the_measured_spaces() {
|
||||
for name in [FOGRA51_CMYK, FOGRA52_CMYK] {
|
||||
let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() }).unwrap();
|
||||
// A 50% gray (L* 53) lies well inside both measured gamuts (the darkest patches measure
|
||||
// L* 11.43 and 26.36), so it comes back whatever the gamut check says.
|
||||
let gray = [0.5, 0.5, 0.5];
|
||||
for srgb in [[0.8, 0.3, 0.2], [0.2, 0.5, 0.7], gray, [0.9, 0.85, 0.6], [0.1, 0.1, 0.1]] {
|
||||
let inks = cms.srgb_to_cmyk(srgb, Intent::RelativeColorimetric);
|
||||
assert!(inks.iter().sum::<f32>() <= 3.0 + 1e-3, "{name} {srgb:?}: {inks:?}");
|
||||
if srgb == gray || cms.gamut_error(&Color::Rgb { r: srgb[0], g: srgb[1], b: srgb[2] }) < GAMUT_THRESHOLD {
|
||||
let back = cms.cmyk_to_srgb(inks, false);
|
||||
let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(back));
|
||||
assert!(de < 1.5, "{name} {srgb:?}: {inks:?} -> {back:?} (ΔE {de})");
|
||||
}
|
||||
}
|
||||
// White is paper with no ink, and black is the darkest build within the ink limit.
|
||||
assert_eq!(cms.srgb_to_cmyk([1.0; 3], Intent::RelativeColorimetric), [0.0; 4]);
|
||||
let black = cms.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric);
|
||||
assert!(black[3] > 0.8 && black.iter().sum::<f32>() <= 3.0 + 1e-3, "{name}: {black:?}");
|
||||
}
|
||||
// The coated paper prints a larger gamut than the uncoated one.
|
||||
let blue = Color::Rgb { r: 0.1, g: 0.2, b: 0.6 };
|
||||
let coated = Cms::new(&ColorSettings { cmyk: FOGRA51_CMYK.into(), ..ColorSettings::default() }).unwrap();
|
||||
let uncoated = Cms::new(&ColorSettings { cmyk: FOGRA52_CMYK.into(), ..ColorSettings::default() }).unwrap();
|
||||
assert!(coated.gamut_error(&blue) < uncoated.gamut_error(&blue));
|
||||
}
|
||||
|
||||
/// Absolute Lab of `cmyk` in a context whose CMYK space is one of the Generic-type spaces.
|
||||
fn absolute_lab(cms: &Cms, cmyk: [f32; 4]) -> Lab {
|
||||
match &cms.cmyk {
|
||||
CmykSpace::Generic(g) => g.to_lab_abs(cmyk),
|
||||
CmykSpace::Device | CmykSpace::Icc(_) => panic!("not a Generic-type CMYK space"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_cmyk_to_rgb_shows_the_paper() {
|
||||
for name in [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK] {
|
||||
let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() }).unwrap();
|
||||
let paper = cms.cmyk_to_rgb([0.0; 4], Intent::AbsoluteColorimetric);
|
||||
assert_eq!(paper, cms.srgb_to_rgb(cms.cmyk_to_srgb([0.0; 4], true)), "{name}");
|
||||
assert_ne!(paper, cms.cmyk_to_rgb([0.0; 4], Intent::RelativeColorimetric), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_cmyk_conversion_keeps_the_source_paper() {
|
||||
// Generic CMYK's paper (L* 93, b* 2.5) is darker and yellower than FOGRA51's (L* 95, b* -6),
|
||||
// so printing it on FOGRA51 paper takes ink.
|
||||
let generic = Cms::new(&ColorSettings { cmyk: GENERIC_CMYK.into(), ..ColorSettings::default() }).unwrap();
|
||||
let coated = Cms::new(&ColorSettings { cmyk: FOGRA51_CMYK.into(), ..ColorSettings::default() }).unwrap();
|
||||
let Color::Cmyk { c, m, y, k } = generic.convert_into(&coated, &Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 0.0 }, Intent::AbsoluteColorimetric)
|
||||
else {
|
||||
panic!("a CMYK colour converts to CMYK");
|
||||
};
|
||||
let inks = [c, m, y, k];
|
||||
assert!(inks.iter().sum::<f32>() > 0.01, "{inks:?}");
|
||||
let de = delta_e2000(absolute_lab(&coated, inks), absolute_lab(&generic, [0.0; 4]));
|
||||
assert!(de < 2.0, "{inks:?}: ΔE {de}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_profiles_carry_the_paper_and_the_data_source() {
|
||||
for c in &measured::CONDITIONS {
|
||||
let start = std::time::Instant::now();
|
||||
let bytes = icc_bytes(c.name).unwrap();
|
||||
println!("{}: {} bytes in {:?}", c.reference, bytes.len(), start.elapsed());
|
||||
let p = moxcms::ColorProfile::new_from_slice(&bytes).unwrap();
|
||||
assert_eq!(
|
||||
(p.profile_class, p.color_space, p.pcs),
|
||||
(moxcms::ProfileClass::OutputDevice, moxcms::DataColorSpace::Cmyk, moxcms::DataColorSpace::Lab)
|
||||
);
|
||||
assert!(p.lut_a_to_b_perceptual.is_some() && p.lut_b_to_a_perceptual.is_some() && p.lut_a_to_b_colorimetric.is_some());
|
||||
let paper = lab::lab_to_xyz(measured::parse(c.data).unwrap()[0].lab);
|
||||
let white = p.media_white_point.unwrap();
|
||||
for (got, want) in [white.x, white.y, white.z].iter().zip(paper) {
|
||||
assert!((*got - f64::from(want)).abs() < 2e-3, "{}: {white:?} vs {paper:?}", c.reference);
|
||||
}
|
||||
let text = format!("{:?}", p.copyright);
|
||||
assert!(text.contains(c.reference) && text.contains("Fogra"), "{text}");
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ pub const CHROMA_FULL: f64 = 0.4;
|
||||
pub const POWERLESS_CHROMA: f64 = 0.000_004;
|
||||
|
||||
/// How far outside 0..=1 an sRGB component may be and still count as inside the gamut.
|
||||
const GAMUT_SLACK: f64 = 1e-4;
|
||||
const GAMUT_SLACK: f64 = 1e-5;
|
||||
|
||||
/// OKLCH `[l, c, h°]` of sRGB `rgb` (gamma encoded). Values outside 0..=1 are converted as they
|
||||
/// are. The hue is in 0..360, and 0 while the chroma is powerless.
|
||||
@@ -46,7 +46,7 @@ pub fn max_chroma(l: f64, h: f64) -> f64 {
|
||||
///
|
||||
/// The chromas sRGB holds along the ray can come in several stretches: at the lightness and hue of
|
||||
/// blue the ray leaves sRGB at a chroma of about 0.266 and comes back at blue itself, about 0.313,
|
||||
/// and near black the gamut slack opens stretches of its own. Each linear sRGB channel is a cubic
|
||||
/// and the ray can leave and return near black as well. Each linear sRGB channel is a cubic
|
||||
/// in the chroma, so every stretch ends where a channel's cubic meets a bound of the gamut. The
|
||||
/// search finds each such chroma between the cubic's turning points and takes the largest one that
|
||||
/// fits.
|
||||
@@ -69,8 +69,7 @@ fn largest_fitting_chroma(l: f64, h: f64, limit: f64) -> f64 {
|
||||
let y = [lin(0.0), lin(s), lin(2.0 * s), lin(3.0 * s)];
|
||||
let bounds = [-GAMUT_SLACK / 12.92, ((1.0 + GAMUT_SLACK + 0.055) / 1.055).powf(2.4)];
|
||||
let mut ends = vec![0.0];
|
||||
for ch in 0..3 {
|
||||
let [y0, y1, y2, y3] = [y[0][ch], y[1][ch], y[2][ch], y[3][ch]];
|
||||
for (((y0, y1), y2), y3) in y[0].into_iter().zip(y[1]).zip(y[2]).zip(y[3]) {
|
||||
let (d1, d2, d3) = (y1 - y0, y2 - 2.0 * y1 + y0, y3 - 3.0 * y2 + 3.0 * y1 - y0);
|
||||
let k = [y0, d1 - d2 / 2.0 + d3 / 3.0, d2 / 2.0 - d3 / 2.0, d3 / 6.0];
|
||||
let p = |t: f64| ((k[3] * t + k[2]) * t + k[1]) * t + k[0];
|
||||
@@ -113,11 +112,16 @@ fn turning_points(a: f64, b: f64, c: f64) -> Vec<f64> {
|
||||
|
||||
/// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered:
|
||||
/// a color outside sRGB keeps its lightness and hue and takes the largest chroma below it that
|
||||
/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more.
|
||||
/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more. Lightness 0 gives exactly black and
|
||||
/// lightness 1 exactly white, as CSS Color 4 specifies, and a positive chroma there counts as
|
||||
/// lowered.
|
||||
pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) {
|
||||
let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) };
|
||||
let c = if c.is_nan() { 0.0 } else { c.max(0.0) };
|
||||
let h = if h.is_finite() { h } else { 0.0 };
|
||||
if l == 0.0 || l == 1.0 {
|
||||
return ([l as f32; 3], c > 0.0);
|
||||
}
|
||||
let exact = oklch_to_srgb(l, c, h);
|
||||
let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, largest_fitting_chroma(l, h, c), h), true) };
|
||||
(rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered)
|
||||
@@ -240,12 +244,10 @@ mod tests {
|
||||
}
|
||||
|
||||
/// The largest chroma fits and is at least the largest one a scan in steps of 0.0005 finds, at
|
||||
/// every hue and at lightnesses near black too, where the ray can come back into sRGB away from
|
||||
/// any primary color's hue (L 0.02 and H 242° fit up to about 0.022 after leaving near 0.012).
|
||||
/// every hue and at lightnesses near black too.
|
||||
#[test]
|
||||
fn the_largest_chroma_is_never_below_a_scan_of_the_ray() {
|
||||
let scan = |l: f64, h: f64| (0..=1000).map(|i| f64::from(i) * 0.0005).filter(|c| in_srgb(oklch_to_srgb(l, *c, h))).fold(0.0, f64::max);
|
||||
assert!(max_chroma(0.02, 242.0) > 0.02, "{}", max_chroma(0.02, 242.0));
|
||||
for l in [0.005, 0.02, 0.05, 0.1, 0.3, 0.44, 0.6, 0.8, 0.95, 0.99] {
|
||||
for h in (0..72).map(|i| f64::from(i) * 5.0 + 2.0) {
|
||||
let max = max_chroma(l, h);
|
||||
@@ -263,4 +265,26 @@ mod tests {
|
||||
assert_eq!(eight(from_oklch(f64::NAN, f64::NAN, f64::NAN).0), [0, 0, 0]);
|
||||
assert_eq!(eight(from_oklch(2.0, -1.0, 0.0).0), [255, 255, 255]);
|
||||
}
|
||||
|
||||
/// The lightness endpoints give exactly black and white at any chroma and hue, and report a
|
||||
/// positive chroma as lowered. A rounded 8-bit comparison would hide a small leftover channel.
|
||||
#[test]
|
||||
fn the_lightness_endpoints_give_exact_black_and_white() {
|
||||
assert_eq!(from_oklch(0.0, 0.04, 0.0), ([0.0; 3], true));
|
||||
assert_eq!(from_oklch(0.0, 0.0, 120.0), ([0.0; 3], false));
|
||||
assert_eq!(from_oklch(1.0, 0.1, 250.0), ([1.0; 3], true));
|
||||
assert_eq!(from_oklch(1.0, 0.0, 0.0), ([1.0; 3], false));
|
||||
}
|
||||
|
||||
/// A color whose green is 0.000024 below sRGB is outside it: it is lowered to the chroma that
|
||||
/// fits, not clipped at its own chroma.
|
||||
#[test]
|
||||
fn a_channel_just_below_zero_is_outside_the_gamut() {
|
||||
assert!(!in_srgb(oklch_to_srgb(0.01, 0.01, 0.0)));
|
||||
let (rgb, lowered) = from_oklch(0.01, 0.01, 0.0);
|
||||
assert!(lowered, "{rgb:?}");
|
||||
let [_, c, _] = to_oklch(rgb);
|
||||
assert!(c < 0.01, "{c}");
|
||||
assert!(in_srgb(oklch_to_srgb(0.01, max_chroma(0.01, 0.0), 0.0)));
|
||||
}
|
||||
}
|
||||
@@ -406,8 +406,10 @@ impl Document {
|
||||
/// gives it. A line that stays vertical or horizontal stays a ruler guide, at its new place. A
|
||||
/// line at any other angle becomes a guide path with that line, on the guide's layer, named
|
||||
/// as the guide was; `sel` then holds the path as a selected object instead of the guide.
|
||||
/// Guides that cannot be edited ([`Self::guide_editable`]) stay as they are.
|
||||
pub fn transform_ruler_guides(&mut self, sel: &mut Selection, xf: Affine) {
|
||||
/// Guides that cannot be edited ([`Self::guide_editable`]) stay as they are. Returns the ids
|
||||
/// of the guide paths it adds, in the order it adds them.
|
||||
pub fn transform_ruler_guides(&mut self, sel: &mut Selection, xf: Affine) -> Vec<NodeId> {
|
||||
let mut paths = vec![];
|
||||
for id in sel.guides.clone() {
|
||||
let Some(g) = self.ruler_guide(id).filter(|g| self.guide_editable(g)) else { continue };
|
||||
let (a, b) = match self.transformed_guide(&g, xf) {
|
||||
@@ -431,7 +433,9 @@ impl Document {
|
||||
}
|
||||
self.retain_guides(sel, |g| g.id != Some(id));
|
||||
sel.objects.push(path);
|
||||
paths.push(path);
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
/// The ruler guide node `g` names, if this document has it.
|
||||
|
||||
@@ -116,7 +116,7 @@ pub use metadata::{CopyrightStatus, DocMetadata};
|
||||
pub use node::Knockout;
|
||||
pub use node::Scaling;
|
||||
pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask};
|
||||
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS};
|
||||
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
|
||||
pub use orient::OrientedBox;
|
||||
pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType};
|
||||
pub use perspective::PerspectiveAttachment;
|
||||
|
||||
@@ -278,6 +278,7 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
|
||||
if let Some(e) = n.extras_box() {
|
||||
b += ALLOC + size_of::<NodeExtras>();
|
||||
b += boxed(&e.mask) + boxed(&e.graph) + boxed(&e.shaper) + boxed(&e.attrs) + boxed(&e.slice) + boxed(&e.perspective);
|
||||
b += e.attrs.as_deref().map_or(0, attrs_bytes);
|
||||
b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize);
|
||||
b += e
|
||||
.color_mask
|
||||
@@ -404,6 +405,22 @@ fn swatches_bytes(s: &[Swatch]) -> usize {
|
||||
ALLOC + std::mem::size_of_val(s) + s.iter().map(|w| w.name.capacity() + paint_heap_bytes(&w.paint)).sum::<usize>()
|
||||
}
|
||||
|
||||
/// The heap an object's attributes own: their text, data, events, classes, foreign attributes and
|
||||
/// tags.
|
||||
fn attrs_bytes(a: &crate::ObjectAttributes) -> usize {
|
||||
let pairs = |v: &Vec<(String, String)>| vec_bytes(v) + v.iter().map(|(k, v)| k.capacity() + v.capacity()).sum::<usize>();
|
||||
a.url.capacity()
|
||||
+ a.note.capacity()
|
||||
+ pairs(&a.data)
|
||||
+ pairs(&a.events)
|
||||
+ vec_bytes(&a.classes)
|
||||
+ a.classes.iter().map(String::capacity).sum::<usize>()
|
||||
+ vec_bytes(&a.foreign)
|
||||
+ a.foreign.iter().map(|f| f.ns.capacity() + f.prefix.capacity() + f.name.capacity() + f.value.capacity()).sum::<usize>()
|
||||
+ vec_bytes(&a.tags)
|
||||
+ a.tags.iter().map(|t| t.name.capacity() + t.value.capacity()).sum::<usize>()
|
||||
}
|
||||
|
||||
/// A vector's buffer (not what its elements own).
|
||||
fn vec_bytes<T>(v: &Vec<T>) -> usize {
|
||||
if v.capacity() == 0 { 0 } else { ALLOC + v.capacity() * size_of::<T>() }
|
||||
@@ -490,6 +507,21 @@ mod tests {
|
||||
assert!((400..1200).contains(&per), "{per} bytes per moved rectangle");
|
||||
}
|
||||
|
||||
/// An object's attributes count with their text: a version of a rectangle with a long tag and
|
||||
/// a long note keeps both.
|
||||
#[test]
|
||||
fn tags_and_notes_count() {
|
||||
let before = doc_with_rects(1);
|
||||
let mut after = before.clone();
|
||||
let id = after.layers[0].children().unwrap()[0].id;
|
||||
after.node_mut(id).unwrap().edit_attrs(|a| {
|
||||
a.note = "n".repeat(30_000);
|
||||
a.tags.push(crate::ObjectTag { id: 1, name: "size".into(), value: "v".repeat(60_000) });
|
||||
});
|
||||
let bytes = after.retained_bytes(&before);
|
||||
assert!(bytes >= 90_000, "{bytes} bytes for a rectangle with 90,000 bytes of attributes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grouped_object_is_found_shared() {
|
||||
let before = doc_with_rects(100);
|
||||
|
||||
@@ -24,7 +24,7 @@ mod opacity;
|
||||
mod ops;
|
||||
mod wire;
|
||||
|
||||
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS};
|
||||
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
|
||||
pub use clip::{ClipPaint, Uniter};
|
||||
pub use extras::{Extras, ExtrasMut, NodeExtras};
|
||||
pub use ids::{LAYER_COLORS, LayerColor, NodeId};
|
||||
|
||||
@@ -38,6 +38,141 @@ pub struct ObjectAttributes {
|
||||
/// with it.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub foreign: Vec<ForeignAttribute>,
|
||||
/// The object's tags, in order: name and value pairs that scripts read and write
|
||||
/// (`object.tag.add`). Names may be empty or repeated. At most [`MAX_TAGS`], each name and
|
||||
/// value at most [`MAX_TAG_TEXT`] bytes.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub tags: Vec<ObjectTag>,
|
||||
}
|
||||
|
||||
/// The most tags one object has.
|
||||
pub const MAX_TAGS: usize = 64;
|
||||
|
||||
/// The longest name or value a tag has, in bytes.
|
||||
pub const MAX_TAG_TEXT: usize = 64 * 1024;
|
||||
|
||||
/// A tag on an object: a name and a value, with an id that tells it apart from the object's other
|
||||
/// tags while its name and value change.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ObjectTag {
|
||||
/// Distinct among the object's tags: a new tag takes an id from
|
||||
/// [`crate::Document::alloc_tag_id`], and deleting a tag raises the next node id above its id,
|
||||
/// so a deleted tag's id is not given out again.
|
||||
#[serde(default, deserialize_with = "lenient_tag_id")]
|
||||
pub id: u64,
|
||||
#[serde(default)]
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
/// Reading a native file never fails over a tag id that is not a whole number from 0 to
|
||||
/// `u64::MAX` (a negative one, a fraction, text): it reads as 0, and
|
||||
/// [`crate::Document::tidy_tags`] gives the tag a new id.
|
||||
fn lenient_tag_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
|
||||
Ok(serde_json::Value::deserialize(d)?.as_u64().unwrap_or(0))
|
||||
}
|
||||
|
||||
impl ObjectAttributes {
|
||||
/// Keeps the tags within the limits: the first [`MAX_TAGS`] whose name and value are at most
|
||||
/// [`MAX_TAG_TEXT`] bytes. → whether any was dropped.
|
||||
pub fn tidy_tags(&mut self) -> bool {
|
||||
let before = self.tags.len();
|
||||
self.tags.retain(|t| t.name.len() <= MAX_TAG_TEXT && t.value.len() <= MAX_TAG_TEXT);
|
||||
self.tags.truncate(MAX_TAGS);
|
||||
self.tags.len() != before
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Document {
|
||||
/// Keeps every object's tags within the limits ([`ObjectAttributes::tidy_tags`]) in the art of
|
||||
/// the layers, symbols, graph designs and pattern swatches (opacity-mask art included). A tag
|
||||
/// keeps its id when the id is from 1 to below [`crate::limits::MAX_NEXT_ID`] and no earlier
|
||||
/// tag of the object has it. Every other tag gets a new id: from the next node id on, above
|
||||
/// every kept id, when those ids stay below that limit; otherwise the smallest id the object's
|
||||
/// other tags do not have. The next node id is then raised past every tag id below the limit.
|
||||
/// It recurses through the art: call it on a document no deeper than
|
||||
/// [`crate::depth::MAX_DEPTH`].
|
||||
pub fn tidy_tags(&mut self) {
|
||||
fn keeps(t: &ObjectTag, earlier: &[ObjectTag]) -> bool {
|
||||
(1..crate::limits::MAX_NEXT_ID).contains(&t.id) && !earlier.iter().any(|o| o.id == t.id)
|
||||
}
|
||||
// The limits, the largest kept id and the number of new ids first, so that a new id never
|
||||
// meets a kept one.
|
||||
let mut next = self.peek_next_id();
|
||||
let mut fresh = 0u64;
|
||||
self.each_tagged(&mut |a| {
|
||||
a.tidy_tags();
|
||||
for (i, t) in a.tags.iter().enumerate() {
|
||||
if keeps(t, &a.tags[..i]) {
|
||||
next = next.max(t.id.saturating_add(1));
|
||||
} else {
|
||||
fresh = fresh.saturating_add(1);
|
||||
}
|
||||
}
|
||||
});
|
||||
if fresh == 0 {
|
||||
self.raise_next_id(next);
|
||||
return;
|
||||
}
|
||||
let in_range = next.saturating_add(fresh) <= crate::limits::MAX_NEXT_ID;
|
||||
self.each_tagged(&mut |a| {
|
||||
let kept: Vec<bool> = (0..a.tags.len()).map(|i| keeps(&a.tags[i], &a.tags[..i])).collect();
|
||||
let mut used: Vec<u64> = a.tags.iter().zip(&kept).filter(|(_, k)| **k).map(|(t, _)| t.id).collect();
|
||||
for (i, k) in kept.iter().enumerate() {
|
||||
if *k {
|
||||
continue;
|
||||
}
|
||||
let id = if in_range {
|
||||
next = next.saturating_add(1);
|
||||
next - 1
|
||||
} else {
|
||||
(1..).find(|c| !used.contains(c)).unwrap_or(1)
|
||||
};
|
||||
a.tags[i].id = id;
|
||||
used.push(id);
|
||||
}
|
||||
});
|
||||
self.raise_next_id(next);
|
||||
}
|
||||
|
||||
/// A new tag id for object `id`, which none of its tags has: the next node id. `None` once the
|
||||
/// next node id has reached [`crate::limits::MAX_NEXT_ID`] (a file with ids at the top of the
|
||||
/// range), since an id from there would be outside the range [`Self::tidy_tags`] keeps and an
|
||||
/// id below it could be a deleted tag's.
|
||||
pub fn alloc_tag_id(&mut self, id: crate::NodeId) -> Option<u64> {
|
||||
let used: Vec<u64> =
|
||||
self.node(id).map(|n| n.extras().attrs.as_deref().map_or(Vec::new(), |a| a.tags.iter().map(|t| t.id).collect())).unwrap_or_default();
|
||||
for _ in 0..=used.len() {
|
||||
if self.peek_next_id() >= crate::limits::MAX_NEXT_ID {
|
||||
return None;
|
||||
}
|
||||
let tag = self.alloc_id().0;
|
||||
if !used.contains(&tag) {
|
||||
return Some(tag);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Calls `f` with the attributes of every object with tags in the art [`Self::tidy_tags`] reads.
|
||||
fn each_tagged(&mut self, f: &mut impl FnMut(&mut ObjectAttributes)) {
|
||||
let mut fix = |n: &mut Node| {
|
||||
if n.extras().attrs.as_deref().is_some_and(|a| !a.tags.is_empty()) {
|
||||
n.edit_attrs(&mut *f);
|
||||
}
|
||||
};
|
||||
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 {
|
||||
crate::placed_document::each_mut(std::sync::Arc::make_mut(root), &mut fix);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An attribute in another application's XML namespace: `plotter:pen="2"` with `xmlns:plotter=
|
||||
|
||||
@@ -131,6 +131,13 @@ impl Node {
|
||||
matches!(self.kind, NodeKind::Layer { template: true, .. })
|
||||
}
|
||||
|
||||
/// Whether a view that hides template layers (`templates`) or guides (`guides`) leaves this
|
||||
/// object out: a template layer while templates are hidden, or a path made into a guide while
|
||||
/// guides are hidden. The canvas draws ruler guides apart from the art.
|
||||
pub fn hidden_by_view(&self, templates: bool, guides: bool) -> bool {
|
||||
(templates && self.is_template()) || (guides && matches!(self.kind, NodeKind::Path { guide: true, .. }))
|
||||
}
|
||||
|
||||
/// The art objects of this container: its children, looking through sublayers, which are not
|
||||
/// objects (bottom first). With `editable`, only the visible, unlocked objects in visible,
|
||||
/// unlocked, non-template sublayers.
|
||||
@@ -360,17 +367,32 @@ impl Node {
|
||||
self.geometric(Some(symbols))
|
||||
}
|
||||
|
||||
/// Children that contribute to a container's editing bounds and selection highlights. A live trace retains a
|
||||
/// hidden bitmap for re-tracing/release; only source-image views measure that bitmap.
|
||||
/// Children that contribute to a container's editing bounds. A live trace retains a hidden bitmap for
|
||||
/// re-tracing/release; only source-image views measure that bitmap. Selection highlights outline
|
||||
/// [`Node::drawn_children`].
|
||||
pub fn editing_children(&self) -> &[Arc<Node>] {
|
||||
let children = self.children().map(Vec::as_slice).unwrap_or_default();
|
||||
let trace_source = self.extras().trace.is_some()
|
||||
&& !self.trace_view().shows_source()
|
||||
&& children.first().is_some_and(|n| !n.visible && matches!(n.kind, NodeKind::Image(_)));
|
||||
let trace_source = !self.trace_view().shows_source() && self.trace_source().is_some_and(|n| !n.visible);
|
||||
let skip = usize::from(self.extras().shaper.is_some() || trace_source);
|
||||
children.get(skip..).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The children a selection highlight outlines: [`Node::editing_children`] without the hidden
|
||||
/// members, which the canvas does not draw. An Image Trace object's hidden source image stays
|
||||
/// when the object's view shows it, and every path of a compound path stays, since the compound
|
||||
/// path draws all of them.
|
||||
pub fn drawn_children(&self) -> impl Iterator<Item = &Arc<Node>> {
|
||||
let members = !matches!(self.kind, NodeKind::Compound { .. });
|
||||
let source = self.trace_source().filter(|_| self.trace_view().shows_source());
|
||||
self.editing_children().iter().filter(move |c| !members || c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c)))
|
||||
}
|
||||
|
||||
/// The first child of an Image Trace object when it is an image: the bitmap the trace keeps.
|
||||
fn trace_source(&self) -> Option<&Arc<Node>> {
|
||||
self.extras().trace.as_ref()?;
|
||||
self.children()?.first().filter(|n| matches!(n.kind, NodeKind::Image(_)))
|
||||
}
|
||||
|
||||
/// The box of [`Node::geometric_bounds`], or of [`Node::geometric_bounds_with`] when `symbols`
|
||||
/// is given.
|
||||
pub(crate) fn geometric(&self, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
|
||||
|
||||
@@ -5,9 +5,10 @@
|
||||
//! stay attached and deleted objects leave nothing stale behind.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use vectorcraft_geom::{Homography, Rect};
|
||||
use vectorcraft_geom::{Homography, Point, Rect};
|
||||
|
||||
use crate::{Node, NodeKind};
|
||||
use crate::symbols::SYMBOL_SQUARE;
|
||||
use crate::{Node, NodeKind, SymbolBoxes};
|
||||
|
||||
/// The plane an object in perspective lies on.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
@@ -58,6 +59,33 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// The corners of the box a symbol instance or type is drawn in, on the page (top left, top
|
||||
/// right, bottom right, bottom left): an instance's art box (measured from `symbols`, or
|
||||
/// `SYMBOL_SQUARE` when it has none) placed by its transform, and type's flat bounds, both
|
||||
/// through the projection of type or an instance in perspective. Joined by straight lines,
|
||||
/// they outline the box as drawn. When the projection sends a corner to infinity the corners
|
||||
/// stay flat, as the flat box is kept for [`Node::geometric_bounds_with`]. `None` for other
|
||||
/// objects and for type without bounds.
|
||||
pub fn drawn_corners(&self, symbols: &SymbolBoxes) -> Option<[Point; 4]> {
|
||||
let flat = match &self.kind {
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
let art = symbols.art(symbol).map_or(SYMBOL_SQUARE, |a| a.geometric);
|
||||
[(art.x0, art.y0), (art.x1, art.y0), (art.x1, art.y1), (art.x0, art.y1)].map(|(x, y)| *xf * Point::new(x, y))
|
||||
}
|
||||
NodeKind::Text(t) => {
|
||||
let b = t.bounds()?;
|
||||
[(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| Point::new(x, y))
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let Some(h) = self.projection() else { return Some(flat) };
|
||||
let [a, b, c, d] = flat.map(|p| h.apply(p));
|
||||
Some(match (a, b, c, d) {
|
||||
(Some(a), Some(b), Some(c), Some(d)) => [a, b, c, d],
|
||||
_ => flat,
|
||||
})
|
||||
}
|
||||
|
||||
/// Keep a projection drawing the same picture moved by `a` (the flat art moves by `a` too). An
|
||||
/// invertible `a` that the projection cannot follow removes it, and the art is drawn flat.
|
||||
pub(crate) fn transform_projection(&mut self, a: vectorcraft_geom::Affine) {
|
||||
|
||||
@@ -7,6 +7,7 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, Vec2};
|
||||
use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, StrokeAlign, StrokeLayer};
|
||||
|
||||
mod area;
|
||||
mod attr_ranges;
|
||||
mod char_style;
|
||||
mod composite;
|
||||
mod file_fonts;
|
||||
@@ -18,6 +19,9 @@ mod tabs_lists;
|
||||
mod wrap;
|
||||
|
||||
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
|
||||
pub use attr_ranges::{
|
||||
AttrRangeError, CHAR_MITER_LIMIT, CHAR_ROTATION, CHAR_SCALE, CHAR_SPACING, FONT_SIZE, LEADING, MAX_BASELINE_SHIFT, MAX_PARA_DISTANCE,
|
||||
};
|
||||
use char_style::yes;
|
||||
pub use char_style::{
|
||||
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_DIACRITIC_POSITION, MAX_TSUME,
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
//! The ranges the character and paragraph style commands keep each numeric attribute to, checked
|
||||
//! in one place: the style commands check the attributes a call changes, and type a plug-in
|
||||
//! returns has every attribute checked.
|
||||
|
||||
use std::fmt;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use super::{CharStyle, JustificationOptions, ParaStyle, TabStop};
|
||||
|
||||
/// Font size ([`CharStyle::size`]), in points.
|
||||
pub const FONT_SIZE: RangeInclusive<f64> = 0.1..=1296.0;
|
||||
/// Leading ([`CharStyle::leading`]) other than Auto, in points.
|
||||
pub const LEADING: RangeInclusive<f64> = 0.1..=5000.0;
|
||||
/// Horizontal and vertical scale ([`CharStyle::h_scale`], [`CharStyle::v_scale`]), in percent.
|
||||
pub const CHAR_SCALE: RangeInclusive<f64> = 1.0..=10000.0;
|
||||
/// Tracking, kerning and the space before a line's first character ([`CharStyle::tracking`],
|
||||
/// [`CharStyle::kerning`], [`CharStyle::kerning_before`]), in 1/1000 em.
|
||||
pub const CHAR_SPACING: RangeInclusive<f64> = -1000.0..=10000.0;
|
||||
/// The largest baseline shift and Tate-chu-yoko Up/Down and Left/Right either way, in points.
|
||||
pub const MAX_BASELINE_SHIFT: f64 = 1296.0;
|
||||
/// Character rotation ([`CharStyle::rotation`]), in degrees.
|
||||
pub const CHAR_ROTATION: RangeInclusive<f64> = -360.0..=360.0;
|
||||
/// The miter limit of a character stroke ([`CharStyle::stroke_miter_limit`]).
|
||||
pub const CHAR_MITER_LIMIT: RangeInclusive<f64> = 1.0..=500.0;
|
||||
/// The largest paragraph indent, space before or after and Hyphenation Zone either way, in points.
|
||||
pub const MAX_PARA_DISTANCE: f64 = 1296.0;
|
||||
|
||||
/// An attribute outside the range the style commands keep it to.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct AttrRangeError {
|
||||
/// The attribute's JSON name, a nested field after a dot (`hyphenation.zone`).
|
||||
pub key: String,
|
||||
/// What is wrong, naming the attribute.
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl fmt::Display for AttrRangeError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for AttrRangeError {}
|
||||
|
||||
fn out(key: &str, message: String) -> AttrRangeError {
|
||||
AttrRangeError { key: key.to_string(), message }
|
||||
}
|
||||
|
||||
/// `value` within `lo..=hi`, or the error naming `key` (a value that is not a number is outside).
|
||||
fn within(key: &str, value: f64, lo: f64, hi: f64) -> Result<(), AttrRangeError> {
|
||||
if (lo..=hi).contains(&value) { Ok(()) } else { Err(out(key, format!("`{key}` must be from {lo} to {hi}"))) }
|
||||
}
|
||||
|
||||
impl CharStyle {
|
||||
/// Checks each numeric attribute `check` names, by its JSON key, against the range the
|
||||
/// character style commands keep it to: size, leading, scales, tracking, kerning, baseline
|
||||
/// shift, rotation, the character stroke's weight, miter limit and dashes, Small Caps, Insert
|
||||
/// Aki, Tsume, diacritic positions, the Tate-chu-yoko offsets, the Warichu settings and the
|
||||
/// variable font axes. The first attribute out of its range is the error.
|
||||
pub fn check_ranges(&self, check: impl Fn(&str) -> bool) -> Result<(), AttrRangeError> {
|
||||
for (key, value, range) in [("size", self.size, FONT_SIZE), ("h_scale", self.h_scale, CHAR_SCALE), ("v_scale", self.v_scale, CHAR_SCALE)] {
|
||||
if check(key) {
|
||||
within(key, value, *range.start(), *range.end())?;
|
||||
}
|
||||
}
|
||||
if check("leading") && self.leading.is_some_and(|value| !LEADING.contains(&value)) {
|
||||
let (lo, hi) = (LEADING.start(), LEADING.end());
|
||||
return Err(out("leading", format!("`leading` must be from {lo} to {hi}, or null for Auto")));
|
||||
}
|
||||
let shift = MAX_BASELINE_SHIFT;
|
||||
for (key, value) in [("baseline_shift", self.baseline_shift), ("tcyUpDown", self.tcy_up_down), ("tcyLeftRight", self.tcy_left_right)] {
|
||||
if check(key) {
|
||||
within(key, value, -shift, shift)?;
|
||||
}
|
||||
}
|
||||
let spacing = [("tracking", Some(self.tracking)), ("kerning", self.kerning), ("kerningBefore", Some(self.kerning_before))];
|
||||
for (key, value) in spacing {
|
||||
if check(key)
|
||||
&& let Some(value) = value
|
||||
{
|
||||
within(key, value, *CHAR_SPACING.start(), *CHAR_SPACING.end())?;
|
||||
}
|
||||
}
|
||||
if check("rotation") {
|
||||
within("rotation", self.rotation, *CHAR_ROTATION.start(), *CHAR_ROTATION.end())?;
|
||||
}
|
||||
for (key, value) in [("akiLeft", self.aki_left), ("akiRight", self.aki_right)] {
|
||||
if check(key) {
|
||||
within(key, value, 0.0, super::MAX_AKI)?;
|
||||
}
|
||||
}
|
||||
if check("tsume") {
|
||||
within("tsume", self.tsume, 0.0, super::MAX_TSUME)?;
|
||||
}
|
||||
let hi = super::MAX_DIACRITIC_POSITION;
|
||||
for (key, value) in [("diacriticHorizontal", self.diacritic_horizontal), ("diacriticVertical", self.diacritic_vertical)] {
|
||||
if check(key) {
|
||||
within(key, value, -hi, hi)?;
|
||||
}
|
||||
}
|
||||
let lines = super::WARICHU_LINES;
|
||||
if check("warichuLines") && !lines.contains(&self.warichu_lines) {
|
||||
return Err(out("warichuLines", format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end())));
|
||||
}
|
||||
let scale = super::WARICHU_SCALE;
|
||||
for (key, value, lo, hi) in
|
||||
[("warichuGap", self.warichu_gap, 0.0, super::MAX_WARICHU_GAP), ("warichuScale", self.warichu_scale, *scale.start(), *scale.end())]
|
||||
{
|
||||
if check(key) {
|
||||
within(key, value, lo, hi)?;
|
||||
}
|
||||
}
|
||||
if check("stroke_width") {
|
||||
within("stroke_width", self.stroke_width, 0.0, crate::MAX_COORD)?;
|
||||
}
|
||||
if check("stroke_miter_limit") {
|
||||
within("stroke_miter_limit", self.stroke_miter_limit, *CHAR_MITER_LIMIT.start(), *CHAR_MITER_LIMIT.end())?;
|
||||
}
|
||||
if check("stroke_dash")
|
||||
&& let Some(dash) = &self.stroke_dash
|
||||
{
|
||||
for value in &dash.pattern {
|
||||
within("stroke_dash.pattern", *value, 0.0, crate::MAX_COORD)?;
|
||||
}
|
||||
within("stroke_dash.offset", dash.offset, -crate::MAX_COORD, crate::MAX_COORD)?;
|
||||
}
|
||||
if check("small_caps")
|
||||
&& let Some(value) = self.small_caps
|
||||
{
|
||||
within("small_caps", value, 1.0, crate::setup::MAX_SMALL_CAPS)?;
|
||||
}
|
||||
if check("fontAxes")
|
||||
&& let Some((tag, _)) = self.font_axes.iter().find(|(_, v)| !v.is_finite())
|
||||
{
|
||||
return Err(out("fontAxes", format!("`fontAxes`: the setting of axis `{tag}` must be a number")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl ParaStyle {
|
||||
/// Checks each paragraph attribute `check` names, by its JSON key and for a nested option its
|
||||
/// field, against the range the paragraph style commands keep it to: the indents and the space
|
||||
/// before and after, each Hyphenation option, each Justification option in `justification`
|
||||
/// (the options as given, since reading a paragraph style brings them into range) with
|
||||
/// Minimum, Desired and Maximum in order, and the number of tab stops with the position and
|
||||
/// leader of each stop that is not in `kept_tabs`. The first attribute out of its range is the
|
||||
/// error.
|
||||
pub fn check_ranges(
|
||||
&self,
|
||||
justification: Option<&JustificationOptions>,
|
||||
kept_tabs: &[TabStop],
|
||||
check: impl Fn(&str, Option<&str>) -> bool,
|
||||
) -> Result<(), AttrRangeError> {
|
||||
for (key, value) in [
|
||||
("left_indent", self.left_indent),
|
||||
("right_indent", self.right_indent),
|
||||
("first_line_indent", self.first_line_indent),
|
||||
("space_before", self.space_before),
|
||||
("space_after", self.space_after),
|
||||
] {
|
||||
if check(key, None) {
|
||||
within(key, value, -MAX_PARA_DISTANCE, MAX_PARA_DISTANCE)?;
|
||||
}
|
||||
}
|
||||
let h = &self.hyphenation;
|
||||
for (field, value, lo, hi) in [
|
||||
("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0),
|
||||
("after_first", f64::from(h.after_first), 1.0, 15.0),
|
||||
("before_last", f64::from(h.before_last), 1.0, 15.0),
|
||||
("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0),
|
||||
("zone", h.zone, 0.0, MAX_PARA_DISTANCE),
|
||||
] {
|
||||
if check("hyphenation", Some(field)) {
|
||||
within(&format!("hyphenation.{field}"), value, lo, hi)?;
|
||||
}
|
||||
}
|
||||
if let Some(j) = justification {
|
||||
for (field, values, (lo, hi)) in [
|
||||
("word_spacing", j.word_spacing, JustificationOptions::WORD_SPACING),
|
||||
("letter_spacing", j.letter_spacing, JustificationOptions::LETTER_SPACING),
|
||||
("glyph_scaling", j.glyph_scaling, JustificationOptions::GLYPH_SCALING),
|
||||
] {
|
||||
if !check("justification", Some(field)) {
|
||||
continue;
|
||||
}
|
||||
let name = format!("justification.{field}");
|
||||
for value in values {
|
||||
within(&name, value, lo, hi)?;
|
||||
}
|
||||
if !(values[0] <= values[1] && values[1] <= values[2]) {
|
||||
return Err(out(&name, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")));
|
||||
}
|
||||
}
|
||||
if check("justification", Some("auto_leading")) {
|
||||
let (lo, hi) = JustificationOptions::AUTO_LEADING;
|
||||
within("justification.auto_leading", j.auto_leading, lo, hi)?;
|
||||
}
|
||||
}
|
||||
if check("tabs", None) {
|
||||
let max = TabStop::MAX_STOPS;
|
||||
if self.tabs.len() > max.max(kept_tabs.len()) {
|
||||
return Err(out("tabs", format!("at most {max} tab stops")));
|
||||
}
|
||||
for stop in self.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) {
|
||||
within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?;
|
||||
let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER);
|
||||
if stop.leader.chars().count() > max {
|
||||
return Err(out("tabs.leader", format!("{label} must be at most {max} characters")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -802,6 +802,45 @@ fn auto_alignment_saves_readable_by_older_builds() {
|
||||
assert_eq!(serde_json::from_str::<ParaStyle>(r#"{"justify":"Center"}"#).unwrap().justify, Justify::Center);
|
||||
}
|
||||
|
||||
/// The default character and paragraph styles are in range, and each number outside its range,
|
||||
/// one that is not a number included, is the error naming its attribute; an attribute the check
|
||||
/// is not asked about is not checked.
|
||||
#[test]
|
||||
fn style_ranges_name_the_attribute_out_of_range() {
|
||||
let all = |_: &str| true;
|
||||
assert_eq!(CharStyle::default().check_ranges(all), Ok(()));
|
||||
let key = |s: CharStyle| s.check_ranges(all).map_err(|e| e.key);
|
||||
let d = CharStyle::default();
|
||||
assert_eq!(key(CharStyle { baseline_shift: f64::NAN, ..d.clone() }), Err("baseline_shift".into()));
|
||||
assert_eq!(key(CharStyle { leading: Some(1e9), ..d.clone() }), Err("leading".into()));
|
||||
assert_eq!(key(CharStyle { v_scale: 0.0, ..d.clone() }), Err("v_scale".into()));
|
||||
assert_eq!(key(CharStyle { kerning: Some(f64::INFINITY), ..d.clone() }), Err("kerning".into()));
|
||||
assert_eq!(key(CharStyle { rotation: 720.0, ..d.clone() }), Err("rotation".into()));
|
||||
assert_eq!(key(CharStyle { warichu_lines: 9, ..d.clone() }), Err("warichuLines".into()));
|
||||
assert_eq!(key(CharStyle { stroke_miter_limit: 0.0, ..d.clone() }), Err("stroke_miter_limit".into()));
|
||||
assert_eq!(key(CharStyle { small_caps: Some(0.0), ..d.clone() }), Err("small_caps".into()));
|
||||
let axes = std::iter::once(("wght".to_string(), f64::NAN)).collect();
|
||||
assert_eq!(key(CharStyle { font_axes: axes, ..d.clone() }), Err("fontAxes".into()));
|
||||
let dash = Some(Dash { pattern: vec![2.0, -1.0], offset: 0.0, align_corners: false });
|
||||
assert_eq!(key(CharStyle { stroke_dash: dash, ..d.clone() }), Err("stroke_dash.pattern".into()));
|
||||
assert_eq!(CharStyle { size: 0.0, ..d.clone() }.check_ranges(|k| k != "size"), Ok(()));
|
||||
|
||||
let all = |_: &str, _: Option<&str>| true;
|
||||
let p = ParaStyle::default();
|
||||
assert_eq!(p.check_ranges(Some(&JustificationOptions::default()), &[], all), Ok(()));
|
||||
let key = |s: ParaStyle, j: Option<&JustificationOptions>| s.check_ranges(j, &[], all).map_err(|e| e.key);
|
||||
assert_eq!(key(ParaStyle { first_line_indent: f64::NAN, ..p.clone() }, None), Err("first_line_indent".into()));
|
||||
let stop = TabStop { position: 1.0, align: TabAlign::Left, leader: String::new(), align_on: '.' };
|
||||
assert_eq!(key(ParaStyle { tabs: vec![stop.clone(); TabStop::MAX_STOPS + 1], ..p.clone() }, None), Err("tabs".into()));
|
||||
let far = TabStop { position: -1.0, ..stop.clone() };
|
||||
assert_eq!(key(ParaStyle { tabs: vec![far.clone()], ..p.clone() }, None), Err("tabs.position".into()));
|
||||
assert_eq!(ParaStyle { tabs: vec![far.clone()], ..p.clone() }.check_ranges(None, &[far], all), Ok(()), "a kept stop");
|
||||
let hyphenation = HyphenationOptions { hyphen_limit: 99, ..HyphenationOptions::default() };
|
||||
assert_eq!(key(ParaStyle { hyphenation, ..p.clone() }, None), Err("hyphenation.hyphen_limit".into()));
|
||||
let reversed = JustificationOptions { word_spacing: [133.0, 100.0, 80.0], ..JustificationOptions::default() };
|
||||
assert_eq!(key(p.clone(), Some(&reversed)), Err("justification.word_spacing".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_fonts_draw_type_only_while_its_text_is_the_files() {
|
||||
use super::file_fonts::*;
|
||||
|
||||
@@ -326,21 +326,21 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"stylize.dropShadow",
|
||||
"Drop Shadow…",
|
||||
STYLIZE,
|
||||
"{mode: blend mode (\"multiply\"), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": use d = darkness / 100 on the source colors before document color conversion and blur; RGB channels become max(0, channel - d), CMYK keeps C/M/Y and sets K to min(1, K + d), and Gray sets its black component to min(1, K + d). The near-100% endpoint is gray black. Shadow opacity remains separate)",
|
||||
"{mode: blend mode (\"multiply\"; normal, darken, multiply, colorBurn, lighten, screen, colorDodge, overlay, softLight, hardLight, difference, exclusion, hue, saturation, color or luminosity, in any letter case), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": use d = darkness / 100 on the source colors before document color conversion and blur; RGB channels become max(0, channel - d), CMYK keeps C/M/Y and sets K to min(1, K + d), and Gray sets its black component to min(1, K + d). The near-100% endpoint is gray black. Shadow opacity remains separate)",
|
||||
json!({"mode": "multiply", "opacity": 75.0, "x": 7.0, "y": 7.0, "blur": 5.0, "shade": "color", "color": "#000000", "darkness": 100.0}),
|
||||
),
|
||||
r(
|
||||
"stylize.innerGlow",
|
||||
"Inner Glow…",
|
||||
STYLIZE,
|
||||
"{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}",
|
||||
"{mode: blend mode (\"screen\"; one of Drop Shadow's modes), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}",
|
||||
json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffffff", "source": "edge"}),
|
||||
),
|
||||
r(
|
||||
"stylize.outerGlow",
|
||||
"Outer Glow…",
|
||||
STYLIZE,
|
||||
"{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}",
|
||||
"{mode: blend mode (\"screen\"; one of Drop Shadow's modes), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}",
|
||||
json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffff00"}),
|
||||
),
|
||||
r("stylize.feather", "Feather…", STYLIZE, "{radius: pt (5)}", json!({"radius": 5.0})),
|
||||
@@ -875,6 +875,12 @@ pub(crate) fn catalog_index() -> &'static std::collections::HashMap<&'static str
|
||||
INDEX.get_or_init(|| effect_catalog().into_iter().map(|e| (e.id, e)).collect())
|
||||
}
|
||||
|
||||
/// The id and menu label of built-in effect `id`, as the catalog holds them (no plug-in
|
||||
/// effects).
|
||||
pub fn built_in_effect(id: &str) -> Option<(&'static str, &'static str)> {
|
||||
catalog_index().get(id).map(|e| (e.id, e.label))
|
||||
}
|
||||
|
||||
/// Catalogue entry for `id` (built-in, or an installed plug-in effect).
|
||||
pub fn effect_info(id: &str) -> Option<EffectInfo> {
|
||||
catalog_index().get(id).cloned().or_else(|| plugin_info(id))
|
||||
|
||||
@@ -82,11 +82,12 @@ pub use group::{
|
||||
pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset};
|
||||
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
|
||||
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
|
||||
pub use params::{blend_mode_id, parse_blend_mode, takes_blend_mode};
|
||||
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
|
||||
pub use placement::pinned_gradient_item;
|
||||
pub use raster::{
|
||||
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects,
|
||||
without_geometry,
|
||||
RASTERIZE, RasterFx, Rasterize, blend_mode, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps,
|
||||
staged_effects, without_geometry,
|
||||
};
|
||||
pub use reshape::{
|
||||
SYMBOL_ART_MAX_NODES, add_instance_row_effects_to_parts, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster,
|
||||
@@ -124,7 +125,9 @@ mod catalog;
|
||||
mod geometry;
|
||||
mod params;
|
||||
|
||||
pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range};
|
||||
pub use catalog::{
|
||||
EffectInfo, Lengths, WARP_STYLES, built_in_effect, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range,
|
||||
};
|
||||
pub(crate) use geometry::{Budget, apply_one};
|
||||
pub use geometry::{
|
||||
Carry, GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_bez_carrying, apply_geometry_carrying, apply_geometry_with,
|
||||
|
||||
@@ -1,6 +1,28 @@
|
||||
use vectorcraft_doc::color::BlendMode;
|
||||
|
||||
use super::catalog::{catalog_index, plugin_info};
|
||||
use super::{CROP_MARKS, Effect, Map, Node, PIXEL_EFFECTS, RASTERIZE, Value, is_adjustment, is_pathfinder, is_three_d, json, util};
|
||||
|
||||
/// Whether parameter `key` of effect `effect` is the blend mode the effect draws in.
|
||||
pub fn takes_blend_mode(effect: &str, key: &str) -> bool {
|
||||
key == "mode" && matches!(effect, "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow")
|
||||
}
|
||||
|
||||
/// Read a blend mode name as the effect renderer does. Case and punctuation do not change the mode.
|
||||
pub fn parse_blend_mode(s: &str) -> Option<BlendMode> {
|
||||
let name: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect();
|
||||
BlendMode::parse(&name)
|
||||
}
|
||||
|
||||
/// The name an effect stores for blend mode `mode`, such as `normal`, `multiply`, or `colorBurn`.
|
||||
pub fn blend_mode_id(mode: BlendMode) -> String {
|
||||
let mut name = format!("{mode:?}");
|
||||
if let Some(first) = name.get_mut(..1) {
|
||||
first.make_ascii_lowercase();
|
||||
}
|
||||
name
|
||||
}
|
||||
|
||||
/// Dialog defaults for `id` (`None` for unknown effects).
|
||||
pub fn default_params(id: &str) -> Option<Value> {
|
||||
match catalog_index().get(id) {
|
||||
|
||||
@@ -80,11 +80,28 @@ rustix = { workspace = true, features = ["std", "process"] }
|
||||
# (walkdir), so this adds no new crate.
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
same-file = "1.0.6"
|
||||
# Credential Manager, the system key store of grant_keys.rs on Windows (see keyring-core below).
|
||||
windows-native-keyring-store = "1.1"
|
||||
|
||||
# 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 }
|
||||
# The MAC that `grants.json` carries (grant_keys.rs) and the random key it is made with, which the
|
||||
# user's key store keeps: Keychain on macOS, Credential Manager on Windows, the Secret Service on
|
||||
# Linux. All MIT OR Apache-2.0.
|
||||
hmac = "0.12.1"
|
||||
sha2 = { version = "0.10", default-features = false }
|
||||
getrandom = "0.4"
|
||||
keyring-core = "1.1"
|
||||
|
||||
# The system key store of grant_keys.rs on each platform, connected through keyring-core: the same
|
||||
# store crates and features that keyring 4.2 uses. All MIT OR Apache-2.0.
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
apple-native-keyring-store = { version = "1.0.2", features = ["keychain"] }
|
||||
|
||||
[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))'.dependencies]
|
||||
zbus-secret-service-keyring-store = { version = "1.0.1", features = ["crypto-rust"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# JPEG XL files for the `.jxl` open and place tests.
|
||||
|
||||
@@ -102,6 +102,7 @@ pub mod swatchlib;
|
||||
pub(crate) mod symboledit;
|
||||
pub mod symbollib;
|
||||
pub(crate) mod tabs;
|
||||
pub(crate) mod tags;
|
||||
mod textedit;
|
||||
|
||||
pub use textedit::effective_kerning;
|
||||
@@ -376,6 +377,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(library::specs());
|
||||
v.extend(expand::specs());
|
||||
v.extend(attributes::specs());
|
||||
v.extend(tags::specs());
|
||||
v.extend(interactivity::specs());
|
||||
v.extend(spelling::specs());
|
||||
v.extend(svgfilter::specs());
|
||||
@@ -845,7 +847,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
|
||||
|
||||
pub(crate) use addons::{DecodedImages, refresh_color_masks};
|
||||
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
|
||||
pub use addons::{fold_source, print_hidden};
|
||||
pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
|
||||
/// Document Info's category titles, the Objects category's count labels, and how its image rows
|
||||
/// write a resolution and a number of bytes.
|
||||
pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number};
|
||||
@@ -924,6 +926,9 @@ pub use buildcmds::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYT
|
||||
/// An Image Trace made off the UI thread, and what it traced (#3098).
|
||||
pub use buildcmds::{TraceRun, Traced, image_trace_target};
|
||||
|
||||
/// Retype's search of the installed fonts, made off the UI thread.
|
||||
pub use retype::{RetypeFound, RetypeRun, RetypeSearch};
|
||||
|
||||
/// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them).
|
||||
pub(crate) use buildcmds::TracePresetChanges;
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ mod typetools;
|
||||
mod units;
|
||||
|
||||
pub(crate) use image::{DecodedImages, refresh_color_masks};
|
||||
pub use packaging::{fold_source, print_hidden};
|
||||
pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
|
||||
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
use super::CommandSpec;
|
||||
|
||||
@@ -173,7 +173,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, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches))
|
||||
s.edit_effect(id, |s| 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
|
||||
|
||||
@@ -2,13 +2,16 @@
|
||||
//! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line
|
||||
//! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each
|
||||
//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Check Fold
|
||||
//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Its submenu
|
||||
//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's.
|
||||
//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Set
|
||||
//! Fold Angle ([`angle`]) gives a fold line its own angle. Its submenu (Object › Plug-ins ›
|
||||
//! Packaging Tools) and its Fold Lines panel are the UI's.
|
||||
|
||||
mod angle;
|
||||
mod check;
|
||||
mod fold;
|
||||
mod roles;
|
||||
|
||||
pub use angle::{FoldAngles, selection_fold_angles, selection_fold_lines};
|
||||
pub use fold::{fold_source, print_hidden};
|
||||
pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
@@ -17,6 +20,7 @@ use super::super::CommandSpec;
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = roles::specs();
|
||||
v.extend(check::specs());
|
||||
v.extend(angle::specs());
|
||||
v.extend(fold::specs());
|
||||
v
|
||||
}
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
//! Set Fold Angle (`addon.packaging.setFoldAngle`): the angle each fold line folds at. A Crease,
|
||||
//! Partial Cut or Perforation line keeps its own angle in its data under [`KEY`], as a number of
|
||||
//! degrees from -180 to 180; without one it folds at its role's angle (90° for a Crease or a
|
||||
//! Perforation, -90° for a Partial Cut). A positive angle folds away from the printed side.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_three_d::fold::kept_angle;
|
||||
|
||||
use super::super::super::edit::refuse_symbol_part;
|
||||
use super::super::super::overprint::edit_counted;
|
||||
use super::super::super::pathops::number_given;
|
||||
use super::super::super::{CommandSpec, bad, cmd, switch_or};
|
||||
use super::check::kind;
|
||||
use super::roles::{Role, RoleTable, editable_members, role_targets, taken_roots};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// Object data key: a fold line's own fold angle, in degrees. Native save keeps it; SVG export
|
||||
/// leaves `vc-` keys out.
|
||||
pub(crate) const KEY: &str = "vc-fold-angle";
|
||||
|
||||
const SET_FOLD_ANGLE: &str = "addon.packaging.setFoldAngle";
|
||||
|
||||
/// The range a fold angle may take, in degrees.
|
||||
const RANGE: std::ops::RangeInclusive<f64> = -180.0..=180.0;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.packaging.setFoldAngle",
|
||||
"Set Fold Angle…",
|
||||
["Object", "Plug-ins", "Packaging Tools"],
|
||||
None,
|
||||
"{angle?: degrees -180..180, reset?: bool (false), ids?: [id…] (default: the selection)} give each Crease, Partial Cut and Perforation line among the objects (addon.packaging.roles; through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) its own fold angle, rounded to the millionth of a degree, or with reset: true take it away, so the line folds at its role's angle again: 90° for a Crease or a Perforation, -90° for a Partial Cut. A positive angle folds the panel away from the printed side, a negative one toward it; addon.packaging.fold and the Fold Preview window fold each hinge at the angle of the line with the most length in it. Cut lines and objects without a role are skipped and counted. Give exactly one of angle and reset: true. One undo step, none when nothing changes → {ids (the fold lines changed or kept), changed, skipped}",
|
||||
has_fold_line,
|
||||
set_fold_angle
|
||||
)]
|
||||
}
|
||||
|
||||
/// Why Set Fold Angle has nothing to change.
|
||||
const NO_FOLD_LINE: &str = "select a crease, partial cut or perforation line that is neither locked nor hidden";
|
||||
|
||||
/// The last answer of [`has_fold_line`], with what it was for.
|
||||
struct Answer {
|
||||
/// The document (a weak reference keeps another document from taking the same address).
|
||||
doc: Weak<Document>,
|
||||
revision: u64,
|
||||
/// The objects looked at: the selection, or the `ids` a command was given in its place.
|
||||
objects: Vec<NodeId>,
|
||||
found: bool,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Menus ask [`has_fold_line`] on every refresh, and its answer changes only with the
|
||||
/// document, its revision and the objects looked at.
|
||||
static LAST_ANSWER: std::cell::RefCell<Option<Answer>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// The selection holds a line that folds and that Set Fold Angle can change, or an id of no object.
|
||||
fn has_fold_line(s: &Session) -> std::result::Result<(), String> {
|
||||
refuse_symbol_part(s).map_err(|e| e.to_string())?;
|
||||
let st = s.doc().map_err(|e| e.to_string())?;
|
||||
let objects = &st.selection.objects;
|
||||
let kept = LAST_ANSWER.with_borrow(|last| match last {
|
||||
Some(a) if a.revision == st.revision && a.objects == *objects && Weak::ptr_eq(&a.doc, &Arc::downgrade(&st.doc)) => Some(a.found),
|
||||
_ => None,
|
||||
});
|
||||
let found = kept.unwrap_or_else(|| {
|
||||
// An id of no object (given as `ids`) is left to the command, which names it.
|
||||
let found = objects.iter().any(|id| st.doc.node(*id).is_none()) || any_fold_line(&st.doc, objects);
|
||||
LAST_ANSWER.set(Some(Answer { doc: Arc::downgrade(&st.doc), revision: st.revision, objects: objects.clone(), found }));
|
||||
found
|
||||
});
|
||||
if found { Ok(()) } else { Err(NO_FOLD_LINE.into()) }
|
||||
}
|
||||
|
||||
/// Whether the objects `roots` of `d` hold a line that folds and can be changed, looking through
|
||||
/// groups and clip groups as [`role_targets`] does and stopping at the first. As [`taken_roots`]
|
||||
/// takes them, an object inside another one given is left out (a crease in a selected layer counts
|
||||
/// no more than the layer does), a layer is left out, and a path of a compound path stands for the
|
||||
/// compound path, which holds its role, unless it is locked or hidden.
|
||||
fn any_fold_line(d: &Document, roots: &[NodeId]) -> bool {
|
||||
fn find(n: &Node, hit: &dyn Fn(&Node) -> bool) -> bool {
|
||||
match &n.kind {
|
||||
// A group's clipping path draws no stroke.
|
||||
NodeKind::Group { children, .. } => children.iter().any(|c| !matches!(c.kind, NodeKind::Path { clipping: true, .. }) && find(c, hit)),
|
||||
_ => hit(n),
|
||||
}
|
||||
}
|
||||
let table = RoleTable::of(d);
|
||||
let editable = d.editable();
|
||||
let hit = |n: &Node| table.role_of(n).is_some_and(folds) && editable(n.id);
|
||||
let given: HashSet<NodeId> = roots.iter().copied().collect();
|
||||
// Each object's place, from the document's lookup of ids.
|
||||
let outer = |id: NodeId| -> Option<NodeId> {
|
||||
let a = d.ancestry(id)?;
|
||||
let (_, up) = a.split_last()?;
|
||||
if up.iter().any(|p| given.contains(p)) {
|
||||
return None;
|
||||
}
|
||||
match up.last().copied().filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))) {
|
||||
// A locked or hidden path of a compound path is left out, as `editable_members` leaves it.
|
||||
Some(_) if !editable(id) => None,
|
||||
Some(compound) => Some(compound),
|
||||
None => Some(id),
|
||||
}
|
||||
};
|
||||
// An object given twice is looked through once.
|
||||
let mut seen = HashSet::new();
|
||||
roots
|
||||
.iter()
|
||||
.filter_map(|id| outer(*id))
|
||||
.filter(|id| seen.insert(*id))
|
||||
.filter_map(|id| d.node(id))
|
||||
.filter(|n| !n.is_layer())
|
||||
.any(|n| find(n, &hit))
|
||||
}
|
||||
|
||||
/// The text `n`'s data holds under [`KEY`], if any.
|
||||
fn stored(n: &Node) -> Option<&str> {
|
||||
n.extras().attrs.as_deref()?.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
/// `n`'s own fold angle: the number its data holds under [`KEY`], when it is a finite number from
|
||||
/// -180 to 180, to the millionth of a degree it folds at ([`kept_angle`]). Anything else reads as
|
||||
/// no angle of its own.
|
||||
pub(super) fn own_angle(n: &Node) -> Option<f64> {
|
||||
stored(n)?.trim().parse::<f64>().ok().filter(|a| a.is_finite() && RANGE.contains(a)).map(kept_angle)
|
||||
}
|
||||
|
||||
/// Whether a line with `role` folds: every role but Cut.
|
||||
pub(super) fn folds(role: Role) -> bool {
|
||||
kind(role).fold_angle().is_some()
|
||||
}
|
||||
|
||||
/// Writes `angle` (`None`: takes it away) into object `id`'s data → whether its data changed.
|
||||
fn store(d: &mut Document, id: NodeId, angle: Option<f64>) -> bool {
|
||||
// `+ 0.0` turns -0 into 0, so a line set to 0° reads "0".
|
||||
let text = angle.map(|a| format!("{}", a + 0.0));
|
||||
// Read first: taking the node to change it copies it, its geometry included. An angle stored
|
||||
// as other text for the same number ("45.0") is kept; a reset removes any stored text.
|
||||
let same = |n: &Node| match angle {
|
||||
Some(a) => own_angle(n) == Some(a),
|
||||
None => stored(n).is_none(),
|
||||
};
|
||||
if d.node(id).is_none_or(same) {
|
||||
return false;
|
||||
}
|
||||
let Some(n) = d.node_mut(id) else { return false };
|
||||
n.edit_attrs(|a| match text {
|
||||
Some(text) => match a.data.iter_mut().find(|(k, _)| k == KEY) {
|
||||
Some(e) => e.1 = text,
|
||||
None => a.data.push((KEY.into(), text)),
|
||||
},
|
||||
None => a.data.retain(|(k, _)| k != KEY),
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
fn set_fold_angle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let angle = number_given(p, "angle", SET_FOLD_ANGLE)?;
|
||||
let reset = switch_or(p, "reset", false, SET_FOLD_ANGLE)?;
|
||||
let angle = match (angle, reset) {
|
||||
(Some(_), true) => return Err(bad(SET_FOLD_ANGLE, "give `angle` or `reset: true`, not both")),
|
||||
(None, false) => return Err(bad(SET_FOLD_ANGLE, "missing `angle`")),
|
||||
(Some(a), false) if !RANGE.contains(&a) => return Err(bad(SET_FOLD_ANGLE, "`angle` must be from -180 to 180 degrees")),
|
||||
// Kept to the millionth of a degree, the angle the line folds at.
|
||||
(a, _) => a.map(kept_angle),
|
||||
};
|
||||
let (roots, named) = taken_roots(s, p, SET_FOLD_ANGLE)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let (targets, skipped) = role_targets(d, &roots, false);
|
||||
let mut skipped = skipped + named;
|
||||
let mut ids = folding(d, &RoleTable::of(d), &targets);
|
||||
{
|
||||
let editable = d.editable();
|
||||
ids.retain(|id| editable(*id));
|
||||
}
|
||||
skipped += targets.len() - ids.len();
|
||||
if ids.is_empty() {
|
||||
return Err(bad(SET_FOLD_ANGLE, NO_FOLD_LINE));
|
||||
}
|
||||
let label = if angle.is_some() { "Set Fold Angle" } else { "Reset Fold Angle" };
|
||||
let changed = edit_counted(s, label, |d| Ok(ids.iter().filter(|id| store(d, **id, angle)).count()))?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "changed": changed, "skipped": skipped }))
|
||||
}
|
||||
|
||||
/// The lines among `ids` of `d` that fold (Crease, Partial Cut, Perforation), in order.
|
||||
fn folding(d: &Document, table: &RoleTable, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
ids.iter().copied().filter(|id| d.node(*id).and_then(|n| table.role_of(n)).is_some_and(folds)).collect()
|
||||
}
|
||||
|
||||
/// What Set Fold Angle can change among the objects `roots` of `d` (through groups and clip
|
||||
/// groups, leaving out what is locked or hidden, as `addon.packaging.setFoldAngle` does).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct FoldAngles {
|
||||
/// How many lines that fold it can change.
|
||||
pub lines: usize,
|
||||
/// The angle they all fold at (their own or their role's); `None` when they differ or there
|
||||
/// are none.
|
||||
pub angle: Option<f64>,
|
||||
/// How many of them have an angle of their own.
|
||||
pub own: usize,
|
||||
/// How many of them hold text under [`KEY`], an angle or not: what `reset: true` takes away.
|
||||
pub stored: usize,
|
||||
}
|
||||
|
||||
/// The [`FoldAngles`] of the selected objects of the active document, as Set Fold Angle reads them
|
||||
/// with no `ids` (nothing, while it would refuse the selection).
|
||||
pub fn selection_fold_angles(s: &Session) -> FoldAngles {
|
||||
match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) {
|
||||
(Ok((roots, _)), Ok(st)) => fold_angles(&st.doc, &roots),
|
||||
_ => FoldAngles::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines Set Fold Angle changes among the selected objects of the active document, as it takes
|
||||
/// them with no `ids` (none, while it would refuse the selection). Given back as `ids`, they are the
|
||||
/// lines it changes.
|
||||
pub fn selection_fold_lines(s: &Session) -> Vec<NodeId> {
|
||||
match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) {
|
||||
(Ok((roots, _)), Ok(st)) => changeable(&st.doc, &roots).into_iter().map(|(n, _)| n.id).collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`FoldAngles`] of the outermost objects `roots` of `d`.
|
||||
pub(super) fn fold_angles(d: &Document, roots: &[NodeId]) -> FoldAngles {
|
||||
let mut f = FoldAngles::default();
|
||||
for (n, role) in changeable(d, roots) {
|
||||
f.add(n, role);
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
/// The lines that fold among the outermost objects `roots` of `d` that Set Fold Angle can change,
|
||||
/// with their roles, in order.
|
||||
fn changeable<'a>(d: &'a Document, roots: &[NodeId]) -> Vec<(&'a Node, Role)> {
|
||||
let table = RoleTable::of(d);
|
||||
let editable = d.editable();
|
||||
let targets = role_targets(d, &editable_members(d, roots.to_vec()).0, false).0;
|
||||
// The role first: whether an object can be edited can take its bounds to find out.
|
||||
targets
|
||||
.iter()
|
||||
.filter_map(|id| d.node(*id))
|
||||
.filter_map(|n| table.role_of(n).filter(|r| folds(*r)).filter(|_| editable(n.id)).map(|r| (n, r)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl FoldAngles {
|
||||
/// Counts line `n`, which has `role` and can be changed; a line that does not fold is left out.
|
||||
pub(super) fn add(&mut self, n: &Node, role: Role) {
|
||||
let Some(default) = kind(role).fold_angle() else { return };
|
||||
let own = own_angle(n);
|
||||
let a = own.unwrap_or(default);
|
||||
self.angle = if self.lines == 0 { Some(a) } else { self.angle.filter(|b| *b == a) };
|
||||
self.lines += 1;
|
||||
self.own += usize::from(own.is_some());
|
||||
self.stored += usize::from(stored(n).is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,409 @@
|
||||
//! Tests for Set Fold Angle: a fold line's own angle, where it is kept, and how the fold uses it.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{KEY, fold_angles, own_angle};
|
||||
use crate::*;
|
||||
|
||||
const SET: &str = "addon.packaging.setFoldAngle";
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn path(s: &mut Session, d: &str) -> u64 {
|
||||
s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
fn role(s: &mut Session, role: &str, ids: &[u64]) {
|
||||
s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap();
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn err(s: &mut Session, p: Value) -> String {
|
||||
s.execute(SET, &p).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
/// The text object `id`'s data holds under the fold angle key.
|
||||
fn stored(s: &Session, id: u64) -> Option<String> {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let n = d.node(NodeId(id)).unwrap();
|
||||
n.extras().attrs.as_deref().and_then(|a| a.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.clone()))
|
||||
}
|
||||
|
||||
/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side →
|
||||
/// (outline, creases: top, right, bottom, left).
|
||||
fn tray(s: &mut Session) -> (u64, Vec<u64>) {
|
||||
let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z");
|
||||
let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")];
|
||||
role(s, "cut", &[outline]);
|
||||
role(s, "crease", &creases);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
(outline, creases)
|
||||
}
|
||||
|
||||
/// Whether panel `p` of a fold is the tray's top wall (y 100 to 140): the middle of the bounds of
|
||||
/// its outline's points (absolute moves and lines only) is above the base.
|
||||
fn top_wall(p: &Value) -> bool {
|
||||
let d = p["outline"].as_str().unwrap();
|
||||
let n: Vec<f64> = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect();
|
||||
let ys = n.iter().skip(1).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t)));
|
||||
(ys.0 + ys.1) / 2.0 < 140.0
|
||||
}
|
||||
|
||||
fn vector(v: &Value) -> [f64; 3] {
|
||||
let a = v.as_array().unwrap();
|
||||
[a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_fold_angle_keeps_the_angle_on_the_line_and_reset_takes_it_away() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
let before = steps(&s);
|
||||
let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(0), &json!([creases[0]])), "{r}");
|
||||
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45"));
|
||||
assert_eq!(steps(&s), before + 1, "one undo step");
|
||||
// The same angle again changes nothing and records no undo step.
|
||||
let r = s.execute(SET, &json!({"angle": 45.0, "ids": [creases[0]]})).unwrap();
|
||||
assert_eq!(r["changed"].as_u64(), Some(0));
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
// An angle is kept to the millionth of a degree, so one closer to 45 than that is 45.
|
||||
let r = s.execute(SET, &json!({"angle": 45.00000001, "ids": [creases[0]]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before + 1), "{r}");
|
||||
s.execute(SET, &json!({"angle": 179.99999998, "ids": [creases[3]]})).unwrap();
|
||||
assert_eq!(stored(&s, creases[3]).as_deref(), Some("180"));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// A number as text, and the selection when ids is left out; -0 is kept as 0.
|
||||
s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap();
|
||||
let r = s.execute(SET, &json!({"angle": "-0"})).unwrap();
|
||||
assert_eq!(r["changed"].as_u64(), Some(2), "{r}");
|
||||
assert_eq!(stored(&s, creases[1]).as_deref(), Some("0"));
|
||||
let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0], creases[1], creases[3]]})).unwrap();
|
||||
assert_eq!(r["changed"].as_u64(), Some(2), "the line without an angle of its own is unchanged: {r}");
|
||||
assert_eq!((stored(&s, creases[0]), stored(&s, creases[1])), (None, None));
|
||||
// Nothing left to reset: no undo step.
|
||||
let at = steps(&s);
|
||||
let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), at));
|
||||
// Undo brings the angle back.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_angles_and_targets_are_refused() {
|
||||
let mut s = session();
|
||||
let (outline, creases) = tray(&mut s);
|
||||
let plain = path(&mut s, "M10 10 L50 50");
|
||||
let before = steps(&s);
|
||||
let ids = json!([creases[0]]);
|
||||
assert!(err(&mut s, json!({"ids": ids})).contains("missing `angle`"));
|
||||
assert!(err(&mut s, json!({"angle": 30, "reset": true, "ids": ids})).contains("not both"));
|
||||
assert!(err(&mut s, json!({"angle": 180.5, "ids": ids})).contains("from -180 to 180"));
|
||||
assert!(err(&mut s, json!({"angle": -181, "ids": ids})).contains("from -180 to 180"));
|
||||
assert!(err(&mut s, json!({"angle": "wide", "ids": ids})).contains("must be a number"));
|
||||
assert!(err(&mut s, json!({"angle": true, "ids": ids})).contains("must be a number"));
|
||||
assert!(err(&mut s, json!({"reset": "yes", "ids": ids})).contains("true or false"));
|
||||
// A cut line and a path without a role do not fold.
|
||||
assert!(err(&mut s, json!({"angle": 30, "ids": [outline, plain]})).contains("crease, partial cut or perforation"));
|
||||
// An id of no object is named as such, alone or beside a crease.
|
||||
assert!(err(&mut s, json!({"angle": 30, "ids": [999_999]})).contains("no such object id 999999"));
|
||||
assert!(err(&mut s, json!({"angle": 30, "ids": [creases[0], 999_999]})).contains("no such object id 999999"));
|
||||
assert_eq!(steps(&s), before, "no refusal records an undo step");
|
||||
// The ends of the range are allowed; cut lines and plain paths among fold lines are skipped.
|
||||
let r = s.execute(SET, &json!({"angle": -180, "ids": [creases[0], outline, plain]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(2), &json!([creases[0]])), "{r}");
|
||||
s.execute(SET, &json!({"angle": 180, "ids": [creases[0]]})).unwrap();
|
||||
assert_eq!(stored(&s, creases[0]).as_deref(), Some("180"));
|
||||
assert_eq!(stored(&s, outline), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_fold_angle_is_dimmed_without_a_line_it_can_change() {
|
||||
let mut s = session();
|
||||
let (outline, creases) = tray(&mut s);
|
||||
let enabled = |s: &Session| (find_command(SET).unwrap().enabled)(s).is_ok();
|
||||
assert!(!enabled(&s), "nothing selected");
|
||||
s.execute("select.set", &json!({"ids": [outline]})).unwrap();
|
||||
assert!(!enabled(&s), "a cut line does not fold");
|
||||
assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation"));
|
||||
s.execute("select.set", &json!({"ids": [creases[0]]})).unwrap();
|
||||
assert!(enabled(&s));
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(creases[0])]).lines, 0, "a locked crease can't be changed");
|
||||
// A group holding a crease is enough.
|
||||
s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
assert!(enabled(&s));
|
||||
// A layer selected with a crease in it: the crease is inside the layer, which is left out, as
|
||||
// Set Fold Angle itself leaves them out.
|
||||
let layer = s.doc().unwrap().doc.layer_of(NodeId(creases[3])).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [layer.0, creases[3]]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "both are selected");
|
||||
assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation"));
|
||||
assert!(!enabled(&s), "dimmed as the command refuses it");
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}");
|
||||
// With nothing selected the counts are the document's, but Set Fold Angle takes no line.
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
assert!(s.execute(SET, &json!({"angle": 30})).is_err());
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
assert_eq!(r["scope"].as_str(), Some("document"), "{r}");
|
||||
assert_eq!(r["roles"][1]["count"].as_u64(), Some(4), "{r}");
|
||||
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crease_named_in_ids_is_set_after_the_menu_found_none_in_the_selection() {
|
||||
let mut s = session();
|
||||
let (outline, creases) = tray(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [outline]})).unwrap();
|
||||
assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "a cut line does not fold");
|
||||
let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap();
|
||||
assert_eq!(r["changed"].as_u64(), Some(1), "{r}");
|
||||
assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "the selection is still the cut line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selection_s_fold_angles_count_a_crease_and_its_selected_group_once() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let group = s.doc().unwrap().selection.objects[0].0;
|
||||
s.execute("select.set", &json!({"ids": [group, creases[0]]})).unwrap();
|
||||
let f = crate::cmd::selection_fold_angles(&s);
|
||||
assert_eq!((f.lines, f.angle, f.own), (2, None, 1), "{f:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_locked_crease_is_skipped() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0], creases[1]]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1)), "{r}");
|
||||
assert_eq!(stored(&s, creases[1]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_locked_path_of_a_compound_crease_named_by_id_is_skipped() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
let (a, b) = (path(&mut s, "M300 300 L400 300"), path(&mut s, "M300 320 L400 320"));
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
role(&mut s, "crease", &[compound]);
|
||||
s.edit("Test", |d, _| {
|
||||
if let Some(n) = d.node_mut(NodeId(a)) {
|
||||
n.locked = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(err(&mut s, json!({"angle": 30, "ids": [a]})).contains("crease, partial cut or perforation"));
|
||||
// Named twice, it is skipped once.
|
||||
let r = s.execute(SET, &json!({"angle": 30, "ids": [a, a, creases[0]]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(1), &json!([creases[0]])), "{r}");
|
||||
assert_eq!(stored(&s, compound), None);
|
||||
assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(a)]).lines, 0);
|
||||
let r = s.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap();
|
||||
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}");
|
||||
// The same with the locked path selected.
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "dimmed");
|
||||
assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation"));
|
||||
assert_eq!(crate::cmd::selection_fold_angles(&s).lines, 0);
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}");
|
||||
assert_eq!(stored(&s, compound), None);
|
||||
// With its compound, given or selected, the locked path is part of the compound, not skipped.
|
||||
let r = s.execute(SET, &json!({"angle": 20, "ids": [compound, a]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}");
|
||||
s.execute("select.set", &json!({"ids": [compound, a]})).unwrap();
|
||||
let r = s.execute(SET, &json!({"angle": 25})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}");
|
||||
s.execute(SET, &json!({"reset": true, "ids": [compound]})).unwrap();
|
||||
// The compound named by id takes the angle; its other path, not locked, names it too.
|
||||
let r = s.execute(SET, &json!({"angle": 30, "ids": [b]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), &r["ids"]), (Some(1), &json!([compound])), "{r}");
|
||||
assert_eq!(stored(&s, compound).as_deref(), Some("30"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_angle_reads_as_none_of_its_own() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
let mut n = s.doc().unwrap().doc.node(NodeId(creases[0])).cloned().unwrap();
|
||||
for (text, want) in [("45", Some(45.0)), (" -30.5 ", Some(-30.5)), ("wide", None), ("NaN", None), ("inf", None), ("181", None), ("", None)] {
|
||||
n.edit_attrs(|a| {
|
||||
a.data.retain(|(k, _)| k != KEY);
|
||||
a.data.push((KEY.into(), text.into()));
|
||||
});
|
||||
assert_eq!(own_angle(&n), want, "{text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_angle_stored_as_other_text_for_the_same_number_is_unchanged() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
let id = NodeId(creases[0]);
|
||||
s.edit("Test", |d, _| {
|
||||
if let Some(n) = d.node_mut(id) {
|
||||
n.edit_attrs(|a| a.data.push((KEY.into(), "45.0".into())));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = steps(&s);
|
||||
let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before), "{r}");
|
||||
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45.0"));
|
||||
s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap();
|
||||
assert_eq!(stored(&s, creases[0]), None);
|
||||
// A reset also removes text that is not an angle.
|
||||
s.edit("Test", |d, _| {
|
||||
if let Some(n) = d.node_mut(id) {
|
||||
n.edit_attrs(|a| a.data.push((KEY.into(), "wide".into())));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), stored(&s, creases[0])), (Some(1), None), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_keeps_its_own_angle_through_a_role_change() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
|
||||
role(&mut s, "partialCut", &[creases[0]]);
|
||||
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap();
|
||||
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}");
|
||||
role(&mut s, "none", &[creases[0]]);
|
||||
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45"));
|
||||
role(&mut s, "crease", &[creases[0]]);
|
||||
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap();
|
||||
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_save_and_preserve_editing_keep_the_angle_and_svg_leaves_it_out() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
s.execute(SET, &json!({"angle": 120, "ids": [creases[0]]})).unwrap();
|
||||
let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap();
|
||||
let svg = svg["text"]
|
||||
.as_str()
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| String::from_utf8_lossy(&vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).into_owned());
|
||||
assert!(svg.contains("<svg"), "{svg}");
|
||||
assert!(!svg.contains("fold-angle"), "{svg}");
|
||||
// An SVG with Preserve Editing reopens as the document it carries, the angle with it.
|
||||
let editing = s.execute("document.serialize", &json!({"format": "svg", "preserveEditing": true})).unwrap();
|
||||
let editing = editing["text"].as_str().unwrap().to_string();
|
||||
let mut t = Session::new();
|
||||
t.execute("document.open", &json!({"name": "box.svg", "dataBase64": vectorcraft_format::base64_encode(editing.as_bytes())})).unwrap();
|
||||
assert_eq!(stored(&t, creases[0]).as_deref(), Some("120"));
|
||||
let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap();
|
||||
s.execute("document.open", &json!({"name": "box.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
|
||||
assert_eq!(stored(&s, creases[0]).as_deref(), Some("120"));
|
||||
let r = s.execute("addon.packaging.fold", &json!({})).unwrap();
|
||||
let angles: Vec<f64> = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect();
|
||||
assert!(angles.contains(&120.0), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tray_wall_with_its_own_angle_stands_at_that_angle() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
// The top wall (y 100 to 140) folds at 45°.
|
||||
s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
|
||||
let r = s.execute("addon.packaging.fold", &json!({})).unwrap();
|
||||
let base = r["base"].as_u64().unwrap() as usize;
|
||||
let mut angles: Vec<f64> = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect();
|
||||
angles.sort_by(f64::total_cmp);
|
||||
assert_eq!(angles, [45.0, 90.0, 90.0, 90.0]);
|
||||
for (i, p) in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base) {
|
||||
let z = vector(&p["frame"]["z"]);
|
||||
let top = top_wall(p);
|
||||
let tilt = if top { std::f64::consts::FRAC_1_SQRT_2 } else { 0.0 };
|
||||
assert!((z[2] - tilt).abs() < 1e-9, "panel {i}: {p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_negative_angle_folds_a_crease_toward_the_print() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
s.execute(SET, &json!({"angle": -90, "ids": [creases[0]]})).unwrap();
|
||||
let r = s.execute("addon.packaging.fold", &json!({})).unwrap();
|
||||
let base = r["base"].as_u64().unwrap() as usize;
|
||||
let mut up = 0;
|
||||
for p in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base).map(|(_, p)| p) {
|
||||
// The top wall folds toward the print, so its printed side faces back over the base
|
||||
// (toward -y in the y-up frame); the other walls stand square to the base as before.
|
||||
let top = top_wall(p);
|
||||
let z = vector(&p["frame"]["z"]);
|
||||
if top {
|
||||
assert!((z[1] + 1.0).abs() < 1e-9, "the top wall's print faces the base: {p}");
|
||||
up += 1;
|
||||
} else {
|
||||
assert!(z[2].abs() < 1e-9, "{p}");
|
||||
}
|
||||
}
|
||||
assert_eq!(up, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roles_reports_the_angle_the_selected_fold_lines_share() {
|
||||
let mut s = session();
|
||||
let (outline, creases) = tray(&mut s);
|
||||
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap();
|
||||
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(90.0), Some(0)), "the role's angle: {r}");
|
||||
s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap();
|
||||
assert_eq!((r["foldAngle"].clone(), r["ownAngles"].as_u64()), (Value::Null, Some(1)), "they differ: {r}");
|
||||
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], outline]})).unwrap();
|
||||
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(30.0), Some(1)), "a cut line has no angle: {r}");
|
||||
let r = s.execute("addon.packaging.roles", &json!({"ids": [outline]})).unwrap();
|
||||
assert!(r["foldAngle"].is_null(), "{r}");
|
||||
// A partial cut folds at -90° unless it has an angle of its own.
|
||||
role(&mut s, "partialCut", &[creases[2]]);
|
||||
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[2]]})).unwrap();
|
||||
assert_eq!((r["foldAngle"].as_f64(), r["foldLines"].as_u64()), (Some(-90.0), Some(1)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roles_leaves_locked_fold_lines_out_of_the_angle_as_set_fold_angle_does() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
s.execute(SET, &json!({"angle": 45, "ids": [creases[1]]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let group = s.doc().unwrap().selection.objects[0].0;
|
||||
s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({"ids": [group]})).unwrap();
|
||||
assert_eq!(r["roles"][1]["count"].as_u64(), Some(2), "both are counted: {r}");
|
||||
assert_eq!((r["foldLines"].as_u64(), r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(1), Some(90.0), Some(0)), "{r}");
|
||||
// So Reset has nothing to change, as the panel shows it.
|
||||
let r = s.execute(SET, &json!({"reset": true, "ids": [group]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(1)), "{r}");
|
||||
let (lines, angle, own) = {
|
||||
let f = fold_angles(&s.doc().unwrap().doc, &[NodeId(group)]);
|
||||
(f.lines, f.angle, f.own)
|
||||
};
|
||||
assert_eq!((lines, angle, own), (1, Some(90.0), 0));
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX
|
||||
|
||||
use super::super::super::pathops::length_given;
|
||||
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or};
|
||||
use super::angle::own_angle;
|
||||
use super::roles::{Role, RoleTable, can_carry, role_targets};
|
||||
use crate::{Result, Session};
|
||||
|
||||
@@ -92,7 +93,8 @@ fn on_non_printing_layer(d: &Document, id: NodeId) -> bool {
|
||||
d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| matches!(n.kind, NodeKind::Layer { printable: false, .. }))
|
||||
}
|
||||
|
||||
fn kind(role: Role) -> LineKind {
|
||||
/// The kind of fold line a line with `role` is.
|
||||
pub(super) fn kind(role: Role) -> LineKind {
|
||||
match role {
|
||||
Role::Cut => LineKind::Cut,
|
||||
Role::Crease => LineKind::Crease,
|
||||
@@ -155,7 +157,7 @@ fn lines_of(d: &Document, scope: &'static str, targets: Vec<NodeId>) -> Lines {
|
||||
non_printing.push(id.0);
|
||||
}
|
||||
segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum());
|
||||
lines.push(FoldLine { path, kind: kind(role), key: id.0 });
|
||||
lines.push(FoldLine { path, kind: kind(role), key: id.0, angle: own_angle(n) });
|
||||
}
|
||||
Lines { scope, lines, non_printing }
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fold",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
|
||||
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: the angle of the line with the most length in it, which is the line's own (addon.packaging.setFoldAngle; a positive angle folds away from the printed side) or else its role's, a Crease or a Perforation 90° away from the printed side and a Partial Cut 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true when the gap is within the larger of tolerance and 0.5% of the distance between the hinge's two ends. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
|
||||
has_doc,
|
||||
fold_command
|
||||
)]
|
||||
|
||||
@@ -10,6 +10,7 @@ use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::super::super::edit::{outermost, refuse_symbol_part, roots_of};
|
||||
use super::super::super::overprint::edit_counted;
|
||||
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
|
||||
use crate::{Result, Session};
|
||||
@@ -194,6 +195,41 @@ pub(super) fn can_carry(n: &Node) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects a command that changes roles or angles takes for params `p`: `ids` (the outermost of
|
||||
/// them), or else the selection (as `selected_roots` takes it), with a path of a compound path that
|
||||
/// is locked or hidden, or in a locked or hidden group or layer, or on a locked artboard, left out
|
||||
/// before it stands for its compound, and how many such paths were left out, each once.
|
||||
pub(super) fn taken_roots(s: &Session, p: &Value, command: &str) -> Result<(Vec<NodeId>, usize)> {
|
||||
if p.get("ids").is_some_and(|v| !v.is_null()) {
|
||||
let roots = checked_ids_or_selection(s, p, command)?;
|
||||
return Ok(editable_members(&s.doc()?.doc, roots));
|
||||
}
|
||||
refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
// An object inside another selected one is left out first, as it is from `ids`.
|
||||
let (kept, left) = editable_members(&st.doc, outermost(&st.doc, st.selection.in_paint_order(&st.doc)));
|
||||
Ok((roots_of(&st.doc, kept), left))
|
||||
}
|
||||
|
||||
/// `ids` less the paths of compound paths among them that are locked or hidden (or in a locked or
|
||||
/// hidden group or layer, or on a locked artboard), and how many different ones were left out.
|
||||
pub(super) fn editable_members(d: &Document, ids: Vec<NodeId>) -> (Vec<NodeId>, usize) {
|
||||
let ok = d.editable();
|
||||
let member = |id: NodeId| d.parent_of(id).is_some_and(|p| matches!(d.node(p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
|
||||
let mut left = std::collections::HashSet::new();
|
||||
let kept = ids
|
||||
.into_iter()
|
||||
.filter(|id| {
|
||||
let out = member(*id) && !ok(*id);
|
||||
if out {
|
||||
left.insert(*id);
|
||||
}
|
||||
!out
|
||||
})
|
||||
.collect();
|
||||
(kept, left.len())
|
||||
}
|
||||
|
||||
/// The objects under the outermost objects `roots` that can carry a role, through groups and clip
|
||||
/// groups, each once, and
|
||||
/// how many of `roots` and their members can't (text, images, symbol instances and other objects).
|
||||
@@ -257,7 +293,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make Fold Line",
|
||||
["Object", "Plug-ins", "Packaging Tools"],
|
||||
None,
|
||||
"{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}",
|
||||
"{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. A line keeps its own fold angle (addon.packaging.setFoldAngle) through a role change and through none. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}",
|
||||
has_selection,
|
||||
set_role
|
||||
),
|
||||
@@ -266,7 +302,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fold Lines",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out",
|
||||
"{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected), foldLines, foldAngle, ownAngles, storedAngles}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out. foldLines is how many of the Crease, Partial Cut and Perforation lines among them addon.packaging.setFoldAngle can change (those not locked or hidden; none while nothing is selected and ids is left out, or while the selection holds only a layer and objects in it), foldAngle the angle in degrees they all fold at (their own or their role's), null when they fold at different angles or there are none, ownAngles how many of them have an angle of their own, and storedAngles how many hold stored angle text, an angle or not, which setFoldAngle's reset: true removes",
|
||||
has_doc,
|
||||
roles
|
||||
),
|
||||
@@ -382,8 +418,9 @@ fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Pai
|
||||
fn set_role(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let role = role_param(p, SET_ROLE, true)?;
|
||||
let overprint = switch_or(p, "overprint", true, SET_ROLE)?;
|
||||
let roots = checked_ids_or_selection(s, p, SET_ROLE)?;
|
||||
let (roots, left) = taken_roots(s, p, SET_ROLE)?;
|
||||
let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true);
|
||||
let skipped = skipped + left;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role"));
|
||||
}
|
||||
@@ -403,19 +440,38 @@ fn set_role(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn roles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let given = p.get("ids").is_some_and(|v| !v.is_null());
|
||||
let roots = checked_ids_or_selection(s, p, ROLES)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// The objects Set Fold Angle takes: a locked or hidden path of a compound path does not stand
|
||||
// for its compound there. They are the objects the counts are of unless such a path was left
|
||||
// out, and only then are those found apart.
|
||||
let (taken, left) = taken_roots(s, p, ROLES)?;
|
||||
let (roots, angle_roots) = if left == 0 { (taken, vec![]) } else { (checked_ids_or_selection(s, p, ROLES)?, taken) };
|
||||
let st = s.doc()?;
|
||||
let d = &st.doc;
|
||||
let (scope, ids) = match (given, roots.is_empty()) {
|
||||
(true, _) => ("ids", role_targets(d, &roots, false).0),
|
||||
(false, false) => ("selection", role_targets(d, &roots, false).0),
|
||||
(false, true) => ("document", document_targets(d)),
|
||||
};
|
||||
let whole = scope == "document";
|
||||
// The lines Set Fold Angle can change are those of the objects it takes: with nothing selected,
|
||||
// or a selection that holds no such object (only a layer and what is in it), it takes none,
|
||||
// though the counts are the document's.
|
||||
let angles_of_all = given || !roots.is_empty();
|
||||
let table = RoleTable::of(d);
|
||||
let mut counts = [0usize; 4];
|
||||
for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) {
|
||||
let editable = d.editable();
|
||||
let mut angles = super::angle::FoldAngles::default();
|
||||
for n in ids.iter().filter_map(|id| d.node(*id)) {
|
||||
let Some(r) = table.role_of(n) else { continue };
|
||||
if let Some(c) = counts.get_mut(r.index()) {
|
||||
*c += 1;
|
||||
}
|
||||
if left == 0 && angles_of_all && super::angle::folds(r) && editable(n.id) {
|
||||
angles.add(n, r);
|
||||
}
|
||||
}
|
||||
if !whole && left > 0 {
|
||||
angles = super::angle::fold_angles(d, &angle_roots);
|
||||
}
|
||||
let rows: Vec<Value> = Role::ALL
|
||||
.into_iter()
|
||||
@@ -425,7 +481,10 @@ fn roles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count })
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() }))
|
||||
Ok(json!({
|
||||
"roles": rows, "scope": scope, "selected": roots.len(),
|
||||
"foldLines": angles.lines, "foldAngle": angles.angle, "ownAngles": angles.own, "storedAngles": angles.stored,
|
||||
}))
|
||||
}
|
||||
|
||||
fn set_role_swatch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -537,4 +537,20 @@ fn compound_paths_carry_a_role() {
|
||||
let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]}));
|
||||
assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1)));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]);
|
||||
// A locked member named by id is skipped, and its compound keeps its role.
|
||||
s.edit("Test", |d, _| {
|
||||
if let Some(n) = d.node_mut(a) {
|
||||
n.locked = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0]})).contains("neither locked nor hidden"));
|
||||
// The same with the locked path selected.
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut"})).contains("neither locked nor hidden"));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]);
|
||||
// Named twice, it is skipped once.
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, a.0, b.0]}));
|
||||
assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([c.0]), Some(1)), "{r}");
|
||||
}
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Parametric Shape",
|
||||
[],
|
||||
None,
|
||||
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}",
|
||||
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), with `center` the shape's center moves to it, otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}",
|
||||
has_doc,
|
||||
set
|
||||
),
|
||||
|
||||
@@ -1172,6 +1172,64 @@ fn the_tangent_circle_tool_keeps_its_first_segment_when_drawing_fails() {
|
||||
assert!(!shown(&mut s), "the first segment is forgotten once the circle is drawn");
|
||||
}
|
||||
|
||||
/// With Add Points to Existing Paths on, the Tangent Circle tool's circle and an anchor point where
|
||||
/// it touches each line are one undo step; the lines keep their shape, and one Undo takes all of it
|
||||
/// back.
|
||||
#[test]
|
||||
fn the_tangent_circle_tool_adds_points_where_the_circle_touches_in_one_step() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false);
|
||||
let b = line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false);
|
||||
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
|
||||
s.select_tool("tangentCircle", view).unwrap();
|
||||
s.set_tool_option("addPoints", &json!(true));
|
||||
let n = steps(&s);
|
||||
for (kind, x, y) in
|
||||
[(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)]
|
||||
{
|
||||
s.pointer(&PointerEvent::new(kind, x, y), view).unwrap();
|
||||
}
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
let points = |s: &Session, id| path(s, id).subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect::<Vec<_>>();
|
||||
let near = |got: Vec<(f64, f64)>, want: &[(f64, f64)]| {
|
||||
got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6)
|
||||
};
|
||||
assert!(near(points(&s, a), &[(100.0, 100.0), (150.0, 100.0), (300.0, 100.0)]), "{:?}", points(&s, a));
|
||||
assert!(near(points(&s, b), &[(100.0, 140.0), (150.0, 140.0), (300.0, 140.0)]), "{:?}", points(&s, b));
|
||||
let st = s.doc().unwrap();
|
||||
let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) };
|
||||
let r = st.doc.node(circle).and_then(|c| c.path_data()).and_then(|pd| pd.bounds()).unwrap();
|
||||
assert!((r.x0 - 130.0).abs() < 1e-6 && (r.y0 - 100.0).abs() < 1e-6 && (r.width() - 40.0).abs() < 1e-6, "{r:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((steps(&s), points(&s, a).len(), points(&s, b).len()), (n, 2, 2));
|
||||
assert!(s.doc().unwrap().doc.node(circle).is_none(), "the circle is gone too");
|
||||
}
|
||||
|
||||
/// In Draw Behind, the Tangent Circle tool's circle goes behind the object selected before the
|
||||
/// clicks, also when Add Points to Existing Paths adds anchors to lines that were not selected.
|
||||
#[test]
|
||||
fn the_tangent_circle_tool_adding_points_draws_behind_the_selection() {
|
||||
let mut s = session();
|
||||
line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false);
|
||||
line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false);
|
||||
let other = line(&mut s, &[(100.0, 400.0), (300.0, 400.0)], false);
|
||||
select(&mut s, &[other]);
|
||||
s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap();
|
||||
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
|
||||
s.select_tool("tangentCircle", view).unwrap();
|
||||
s.set_tool_option("addPoints", &json!(true));
|
||||
for (kind, x, y) in
|
||||
[(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)]
|
||||
{
|
||||
s.pointer(&PointerEvent::new(kind, x, y), view).unwrap();
|
||||
}
|
||||
let st = s.doc().unwrap();
|
||||
let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) };
|
||||
let at = |id| st.doc.position(id).map(|(parent, index, _)| (parent, index));
|
||||
let (Some((p, c)), Some((q, o))) = (at(circle), at(other)) else { panic!("not placed") };
|
||||
assert!(p == q && c + 1 == o, "the circle is right behind the selected line: {c} and {o}");
|
||||
}
|
||||
|
||||
fn ids(v: &Value) -> Vec<NodeId> {
|
||||
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ use vectorcraft_text::edit;
|
||||
use super::super::menucmds::whole_or;
|
||||
use super::super::object::choice;
|
||||
use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges};
|
||||
use super::super::typecmd::refresh_bounds;
|
||||
use super::super::typecmd::{refresh_bounds, refresh_with_given_leading};
|
||||
use super::super::typemenu::{bake_dynamic_text, text_ids};
|
||||
use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets};
|
||||
use crate::{EngineError, Result, Session};
|
||||
@@ -170,7 +170,11 @@ fn text_tweaker(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for (id, changes) in &plans {
|
||||
let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?;
|
||||
t.runs = tweak(std::mem::take(&mut t.runs), changes);
|
||||
refresh_bounds(t);
|
||||
// With Block on, the first changed character's leading goes to the frame's line gap.
|
||||
match changes.first().filter(|_| key == "leading") {
|
||||
Some(&(at, _)) => refresh_with_given_leading(t, at),
|
||||
None => refresh_bounds(t),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill Area",
|
||||
[],
|
||||
None,
|
||||
"{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too; a path a clipping mask clips bounds areas only where every mask around it shows it), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, only the paths of the listed objects that are in it), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}",
|
||||
"{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too; a path a clipping mask clips bounds areas only where every mask around it shows it), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, the paths of the listed objects that are in it, and all of its paths when a listed layer or group holds it or is it; other listed objects are ignored), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}",
|
||||
has_doc,
|
||||
sb_copy_region
|
||||
),
|
||||
|
||||
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Swatch Conflicts",
|
||||
[],
|
||||
None,
|
||||
"{profileMismatch?: as edit.paste} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours",
|
||||
"{profileMismatch?: as edit.paste, allArtboards?: false (true: for edit.pasteOnAllArtboards, which leaves the background colors of copied artboards behind)} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours",
|
||||
has_doc,
|
||||
conflicts
|
||||
),
|
||||
@@ -568,9 +568,12 @@ fn import_svg(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn conflicts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let hex = |w: &Swatch| w.paint.color().map(|c| c.to_hex());
|
||||
// The swatches as the paste brings them: converted from another profile when it converts.
|
||||
let profile = super::colormgmt::PasteProfile::param(p, "clipboard.conflicts")?;
|
||||
const CMD: &str = "clipboard.conflicts";
|
||||
let profile = super::colormgmt::PasteProfile::param(p, CMD)?;
|
||||
// Paste on All Artboards leaves the copied artboards, and so their backgrounds, behind.
|
||||
let all_artboards = super::switch_or(p, "allArtboards", false, CMD)?;
|
||||
let st = s.doc()?;
|
||||
let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, true);
|
||||
let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, !all_artboards);
|
||||
let list: Vec<Value> = converted
|
||||
.as_ref()
|
||||
.unwrap_or(&s.clipboard)
|
||||
|
||||
@@ -141,7 +141,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Contrast",
|
||||
[],
|
||||
None,
|
||||
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color`), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}",
|
||||
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}",
|
||||
always,
|
||||
contrast
|
||||
),
|
||||
@@ -1260,8 +1260,9 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re
|
||||
.transpose()
|
||||
};
|
||||
let drawing;
|
||||
// Selected objects that share a color but draw it differently have no one answer.
|
||||
if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) {
|
||||
// Selected objects that share a color but draw it differently have no one answer. While the
|
||||
// active tool paints with the proxy's color, the selection does not draw it.
|
||||
if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none() && !s.tool_paints(stroke)) {
|
||||
let item = s.appearance_item();
|
||||
// Every painted object inside a selected group counts, as the proxy's color comes from all,
|
||||
// except hidden ones and those inside a hidden group, which draw nothing. The first shown
|
||||
|
||||
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Color Settings…",
|
||||
["Edit"],
|
||||
Some("Cmd+Shift+K"),
|
||||
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\", askMismatchOpen?: bool, askMismatchPaste?: bool, askMissingOpen?: bool (all false by default)} set the working spaces, the color management policies and the Ask boxes → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, askMismatchOpen, askMismatchPaste, askMissingOpen, profiles: [{name, kind, builtin}]}. With askMismatchOpen or askMissingOpen on, the desktop app's File › Open asks what to do when the profile of a document's color mode is not the working space, or it has none (document.open takes the answer as profileChoice; it never asks); with askMismatchPaste on, Paste asks whether colors copied from a document with another profile keep their numbers or convert (edit.paste takes it as profileMismatch; see clipboard.profileMismatch). A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
|
||||
"{rgb?: profile, cmyk?: profile (built in: \"VectorCraft Generic CMYK (SWOP-like)\" (default), \"VectorCraft Coated CMYK (FOGRA51)\" and \"VectorCraft Uncoated CMYK (FOGRA52)\" (computed from Fogra's characterization data), \"Device CMYK (uncalibrated)\"), intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\", askMismatchOpen?: bool, askMismatchPaste?: bool, askMissingOpen?: bool (all false by default)} set the working spaces, the color management policies and the Ask boxes → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, askMismatchOpen, askMismatchPaste, askMissingOpen, profiles: [{name, kind, builtin}]}. With askMismatchOpen or askMissingOpen on, the desktop app's File › Open asks what to do when the profile of a document's color mode is not the working space, or it has none (document.open takes the answer as profileChoice; it never asks); with askMismatchPaste on, Paste asks whether colors copied from a document with another profile keep their numbers or convert (edit.paste takes it as profileMismatch; see clipboard.profileMismatch). A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
|
||||
always,
|
||||
color_settings
|
||||
),
|
||||
@@ -704,7 +704,7 @@ fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Co
|
||||
/// from. → a note for each profile, and whether `d` changed.
|
||||
pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec<String>, bool) {
|
||||
// Without a choice nothing can fail.
|
||||
apply_open_policies_choosing(d, None).unwrap_or_default()
|
||||
apply_open_policies_choosing(d, None, &cms::working_settings()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What opening a document can ask about its profile (Edit › Color Settings' Ask When Opening
|
||||
@@ -879,10 +879,14 @@ impl ProfileQuestion {
|
||||
/// mismatch choice takes the place of the policy of the document's color mode, and a missing
|
||||
/// choice tags the document after the policies ran. A choice for the other kind of question, or
|
||||
/// for a document with none, is not used. → as [`apply_open_policies`]; an error when the profile
|
||||
/// to assign is not a profile of that model.
|
||||
pub(crate) fn apply_open_policies_choosing(d: &mut vectorcraft_doc::Document, choice: Option<&ProfileChoice>) -> Result<(Vec<String>, bool)> {
|
||||
let working = cms::working_settings();
|
||||
let question = ProfileQuestion::of(d, &working);
|
||||
/// to assign is not a profile of that model. `working` is the settings snapshot the question is
|
||||
/// built from and the policies are read from.
|
||||
pub(crate) fn apply_open_policies_choosing(
|
||||
d: &mut vectorcraft_doc::Document,
|
||||
choice: Option<&ProfileChoice>,
|
||||
working: &ColorSettings,
|
||||
) -> Result<(Vec<String>, bool)> {
|
||||
let question = ProfileQuestion::of(d, working);
|
||||
let choice = choice.filter(|c| question.as_ref().is_some_and(|q| q.issue == c.issue()));
|
||||
// A mismatch answer stands in for the policy of the document's color mode.
|
||||
let chosen = |model: ColorMode, policy: Policy| -> (Policy, bool) {
|
||||
@@ -1596,3 +1600,22 @@ fn set_spot(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(json!({"name": name, "spot": spot}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The policies come from the settings snapshot the question was built from, not from the
|
||||
/// working settings as they are when the policies run.
|
||||
#[test]
|
||||
fn open_policies_use_the_snapshot_they_are_given() {
|
||||
let tagged = |d: &mut vectorcraft_doc::Document| d.color_profiles.rgb = Some(cms::canonical_name(cms::WIDE_GAMUT_RGB).to_string());
|
||||
let snapshot = ColorSettings { rgb_policy: Policy::Off, ..ColorSettings::default() };
|
||||
let mut d = vectorcraft_doc::Document::new(100.0, 100.0);
|
||||
tagged(&mut d);
|
||||
let (notes, changed) = apply_open_policies_choosing(&mut d, None, &snapshot).unwrap();
|
||||
assert!(changed, "the Off policy of the snapshot takes the profile off");
|
||||
assert_eq!(d.color_profiles.rgb, None);
|
||||
assert!(notes.iter().any(|n| n.contains("policy is")), "{notes:?}");
|
||||
}
|
||||
}
|
||||
@@ -82,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Curvature Circle",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?=0, segment, t: 0..1, convex?=false} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn",
|
||||
"{id, subpath?=0, segment, t: 0..1, convex?=false, constantRadius?=true, anchors?: \"standard\"|\"touch\" (default standard: a live ellipse with four anchors at 0°, 90°, 180° and 270°; touch: a path with an anchor where the circle touches the path and one every 90° from there)} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; with constantRadius, a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle, and with constantRadius false the cubic's own curvature at `t`; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn",
|
||||
has_doc,
|
||||
curvature_circle
|
||||
),
|
||||
@@ -548,7 +548,8 @@ fn selected_anchor_points(s: &Session) -> Result<Option<Vec<Point>>> {
|
||||
}
|
||||
|
||||
/// A live ellipse that touches a path at a point with the path's curvature there
|
||||
/// ([`curvature::curvature_circle_on`]). One undo step, named as an Ellipse tool drag is.
|
||||
/// ([`curvature::curvature_circle_on_with`]); with `anchors: "touch"`, a plain path with an anchor
|
||||
/// at the point it touches and one every 90° from there ([`shapes::circle_with_anchors_at`]). One undo step, named as an Ellipse tool drag is.
|
||||
fn curvature_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shape.curvatureCircle";
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
@@ -559,6 +560,13 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "`t` must be from 0 to 1"));
|
||||
}
|
||||
let convex = switch_or(p, "convex", false, C)?;
|
||||
let arcs = switch_or(p, "constantRadius", true, C)?;
|
||||
let key = "anchors";
|
||||
let at_touch = match p.get(key).map(Value::as_str) {
|
||||
None | Some(Some("standard")) => false,
|
||||
Some(Some("touch")) => true,
|
||||
Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, touch"))),
|
||||
};
|
||||
let found = {
|
||||
let st = s.doc()?;
|
||||
let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
@@ -570,7 +578,7 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if seg >= sp.segment_count() {
|
||||
return Err(bad(C, "no such segment"));
|
||||
}
|
||||
curvature::curvature_circle_on(sp, seg, t, convex)
|
||||
curvature::curvature_circle_on_with(sp, seg, t, convex, arcs)
|
||||
};
|
||||
let circle = found.map_err(|e| match e {
|
||||
NoCircle::Straight => bad(C, "the path is straight there, so no circle matches its curvature"),
|
||||
@@ -579,12 +587,19 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
let (center, radius) = (circle.center, circle.radius);
|
||||
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
|
||||
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.abs() <= MAX_COORD) {
|
||||
let (path, live) = if at_touch {
|
||||
(shapes::circle_with_anchors_at(center, radius, &[circle.at]), None)
|
||||
} else {
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
|
||||
(live.to_path(), Some(live))
|
||||
};
|
||||
// The bounds of the path drawn: started where it touches, its cubics reach a little past the
|
||||
// circle.
|
||||
if path.bounds().is_none_or(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= MAX_COORD)) {
|
||||
return Err(bad(C, "the circle that matches the path there would reach past the canvas"));
|
||||
}
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
|
||||
// Not pixel-aligned: the circle stays on the path.
|
||||
let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?;
|
||||
let mut out = add_art_unaligned(s, "Ellipse", path_kind(path, live))?;
|
||||
out["cx"] = json!(center.x);
|
||||
out["cy"] = json!(center.y);
|
||||
out["radius"] = json!(radius);
|
||||
|
||||
@@ -809,6 +809,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let selection = shared_selection(selection, st.history.redo.last());
|
||||
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
|
||||
turned.named = e.named;
|
||||
turned.effect = e.effect;
|
||||
let paints = e.color_mode_paints.clone();
|
||||
turned.color_mode_paints = e.color_mode_paints;
|
||||
turned.recost_paints();
|
||||
@@ -845,6 +846,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let selection = shared_selection(selection, st.history.undo.last());
|
||||
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
|
||||
turned.named = e.named;
|
||||
turned.effect = e.effect;
|
||||
let paints = e.color_mode_paints.clone();
|
||||
turned.color_mode_paints = e.color_mode_paints;
|
||||
turned.recost_paints();
|
||||
|
||||
@@ -453,12 +453,17 @@ pub fn pathfinder_effect_options(s: &Session) -> effects::PathfinderEffectOption
|
||||
}
|
||||
}
|
||||
|
||||
/// The effect an apply request names, including the older `id` parameter.
|
||||
pub(crate) fn requested_effect(p: &Value) -> Option<&str> {
|
||||
str_param(p, "effect").or_else(|| str_param(p, "id"))
|
||||
}
|
||||
|
||||
/// `effect.apply`: adds effect `effect` (or `id`) with `params`, its defaults filled in, to the
|
||||
/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one;
|
||||
/// a Pathfinder effect on loose objects groups them first. → `{ids, index, item}`.
|
||||
/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one.
|
||||
/// A Pathfinder effect on loose objects groups them first. → `{ids, index, item}`.
|
||||
pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "effect.apply";
|
||||
let id = str_param(p, "effect").or_else(|| str_param(p, "id")).ok_or_else(|| bad(C, "missing `effect` id"))?;
|
||||
let id = requested_effect(p).ok_or_else(|| bad(C, "missing `effect` id"))?;
|
||||
// An effect given as `id` names no objects: the targets are read with that `id` as null.
|
||||
let effect_as_id;
|
||||
let p = if str_param(p, "effect").is_none() {
|
||||
@@ -509,11 +514,13 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let label = effects::effect_info(id).map(|e| e.label.trim_end_matches('…').to_string()).unwrap_or_default();
|
||||
aligned(p, C)?;
|
||||
if let Some(loose) = loose_for_pathfinder(s, p, id)? {
|
||||
let gid = s.edit(&label, |d, sel| {
|
||||
let gid = super::object::group_nodes(d, &loose)?;
|
||||
d.node_mut(gid).ok_or(EngineError::NoNode(gid))?.appearance.effects.push(effect.clone());
|
||||
sel.set([gid]);
|
||||
Ok(gid)
|
||||
let gid = s.edit_effect(id, |s| {
|
||||
s.edit(&label, |d, sel| {
|
||||
let gid = super::object::group_nodes(d, &loose)?;
|
||||
d.node_mut(gid).ok_or(EngineError::NoNode(gid))?.appearance.effects.push(effect.clone());
|
||||
sel.set([gid]);
|
||||
Ok(gid)
|
||||
})
|
||||
})?;
|
||||
return Ok(json!({ "ids": [gid.0], "index": 0, "item": null, "grouped": true }));
|
||||
}
|
||||
@@ -544,9 +551,11 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| {
|
||||
fx.push(effect.clone());
|
||||
true
|
||||
let ids = s.edit_effect(id, |s| {
|
||||
edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| {
|
||||
fx.push(effect.clone());
|
||||
true
|
||||
})
|
||||
})?;
|
||||
// The item the effect landed on in the object whose row the item is (the first selected object
|
||||
// for the active item, which applies where it fits), and the effect's index in that object.
|
||||
@@ -887,32 +896,37 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let ids = edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| {
|
||||
let Some(e) = fx.get_mut(index) else { return false };
|
||||
if let Some(id) = &warp_id {
|
||||
e.id.clone_from(id);
|
||||
}
|
||||
if let Some(to) = kind
|
||||
&& e.id != to
|
||||
{
|
||||
e.params = effects::three_d_params_as(&e.id, &e.params, to);
|
||||
e.id = to.to_string();
|
||||
}
|
||||
if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, ¶ms), &mut e.params) {
|
||||
if !cur.is_object() {
|
||||
*cur = effects::merged_params(&e.id, &Value::Null);
|
||||
// The effect edited, when every target has one at `index` and all are the same: a dialog's
|
||||
// preview names its step after it.
|
||||
let one = edited.first().filter(|e| edited.len() == targets.len() && edited.iter().all(|other| other == *e)).cloned().unwrap_or_default();
|
||||
let ids = s.edit_effect(&one, |s| {
|
||||
edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| {
|
||||
let Some(e) = fx.get_mut(index) else { return false };
|
||||
if let Some(id) = &warp_id {
|
||||
e.id.clone_from(id);
|
||||
}
|
||||
// Earlier parameters (a Perspective strength, a light by azimuth and elevation) take
|
||||
// their current form first, so the new values replace them and the rest is kept.
|
||||
*cur = effects::upgrade_params(&e.id, cur);
|
||||
if let Value::Object(m) = cur {
|
||||
m.extend(new);
|
||||
if let Some(to) = kind
|
||||
&& e.id != to
|
||||
{
|
||||
e.params = effects::three_d_params_as(&e.id, &e.params, to);
|
||||
e.id = to.to_string();
|
||||
}
|
||||
}
|
||||
if let Some(v) = visible {
|
||||
e.visible = v;
|
||||
}
|
||||
true
|
||||
if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, ¶ms), &mut e.params) {
|
||||
if !cur.is_object() {
|
||||
*cur = effects::merged_params(&e.id, &Value::Null);
|
||||
}
|
||||
// Earlier parameters (a Perspective strength, a light by azimuth and elevation) take
|
||||
// their current form first, so the new values replace them and the rest is kept.
|
||||
*cur = effects::upgrade_params(&e.id, cur);
|
||||
if let Value::Object(m) = cur {
|
||||
m.extend(new);
|
||||
}
|
||||
}
|
||||
if let Some(v) = visible {
|
||||
e.visible = v;
|
||||
}
|
||||
true
|
||||
})
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-b
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), d
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
|
||||
@@ -256,6 +256,11 @@ struct RasterOptions {
|
||||
dither: Option<String>,
|
||||
dither_amount: Option<u8>,
|
||||
transparency: Option<bool>,
|
||||
/// GIF and PNG-8 with `transparency`: none, diffusion, pattern or noise, read by
|
||||
/// [`RasterOptions::transparency_dither`] (other formats do not check it).
|
||||
transparency_dither: Option<Value>,
|
||||
/// The diffusion transparency dither's strength, 0–100, read as `transparency_dither` is.
|
||||
transparency_dither_amount: Option<Value>,
|
||||
matte: Option<Value>,
|
||||
lossless: Option<bool>,
|
||||
lzw: Option<bool>,
|
||||
@@ -295,6 +300,26 @@ impl RasterOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// GIF and PNG-8: `transparencyDither` (absent: none, which cuts at half opacity, not
|
||||
/// `Dither`'s own default) and `transparencyDitherAmount` (0–100, default 100), or an error.
|
||||
fn transparency_dither(&self) -> Result<(Dither, u8)> {
|
||||
const IDS: &str = "none, diffusion, pattern or noise";
|
||||
let method = match &self.transparency_dither {
|
||||
None | Some(Value::Null) => PaletteOptions::default().transparency_dither,
|
||||
Some(Value::String(s)) => parse(Some(s), Dither::from_id, "transparencyDither", IDS)?,
|
||||
Some(v) => return Err(bad(C, format!("transparencyDither must be {IDS}, not {v}"))),
|
||||
};
|
||||
let amount = match &self.transparency_dither_amount {
|
||||
None | Some(Value::Null) => 100,
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.filter(|n| *n <= 100)
|
||||
.and_then(|n| u8::try_from(n).ok())
|
||||
.ok_or_else(|| bad(C, format!("transparencyDitherAmount must be a whole number from 0 to 100, not {v}")))?,
|
||||
};
|
||||
Ok((method, amount))
|
||||
}
|
||||
|
||||
/// The pixel size each file is scaled to: `width`, else `height`; `None` when neither is set.
|
||||
fn pixel_size(&self) -> Result<Option<ScreenSize>> {
|
||||
let checked = |key: &str, n: f64| {
|
||||
@@ -1159,6 +1184,9 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
{
|
||||
return Err(bad(C, format!("quality {q}: WebP quality is 0–100")));
|
||||
}
|
||||
if matches!(format, RasterFormat::Gif | RasterFormat::Png8) {
|
||||
(settings.palette.transparency_dither, settings.palette.transparency_dither_amount) = o.transparency_dither()?;
|
||||
}
|
||||
check_options(format, &settings)?;
|
||||
// Use Artboards: one file per chosen artboard (default all); else the one chosen.
|
||||
let chosen = match use_artboards {
|
||||
|
||||
@@ -195,6 +195,20 @@ const TRANSPARENCY: FormatOption = FormatOption {
|
||||
description: "pixels under half opacity become one transparent entry (false: everything is blended over the matte)",
|
||||
};
|
||||
|
||||
const TRANSPARENCY_DITHER: FormatOption = FormatOption {
|
||||
name: "transparencyDither",
|
||||
ty: "string",
|
||||
default: "\"none\"",
|
||||
description: "with transparency, how partly transparent pixels are split between the transparent entry and their color: none (cut at half opacity), diffusion, pattern (8×8 ordered) or noise",
|
||||
};
|
||||
|
||||
const TRANSPARENCY_DITHER_AMOUNT: FormatOption = FormatOption {
|
||||
name: "transparencyDitherAmount",
|
||||
ty: "integer",
|
||||
default: "100",
|
||||
description: "the diffusion transparency dither's strength 0–100 (0 cuts at half opacity; more than 100 is refused)",
|
||||
};
|
||||
|
||||
const MATTE: FormatOption = FormatOption {
|
||||
name: "matte",
|
||||
ty: "string",
|
||||
@@ -235,6 +249,8 @@ const PALETTE_OPTIONS: &[FormatOption] = &[
|
||||
DITHER,
|
||||
DITHER_AMOUNT,
|
||||
TRANSPARENCY,
|
||||
TRANSPARENCY_DITHER,
|
||||
TRANSPARENCY_DITHER_AMOUNT,
|
||||
MATTE,
|
||||
];
|
||||
|
||||
|
||||
@@ -884,14 +884,16 @@ impl ReadFile {
|
||||
if self.rest.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
// One snapshot of the working settings serves the reply and the policies.
|
||||
let working = vectorcraft_color::cms::working_settings();
|
||||
// The question the answer was given to, for the reply's `profileChoice`.
|
||||
let question = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &vectorcraft_color::cms::working_settings());
|
||||
let question = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &working);
|
||||
let answered = match (&self.choice, &question) {
|
||||
(Some(c), Some(q)) if c.issue() == q.issue => Some(json!({ "issue": q.issue.id(), "model": q.to_json()["model"], "choice": c.id() })),
|
||||
_ => None,
|
||||
};
|
||||
// A failure leaves the file waiting, unchanged.
|
||||
let (notes, changed) = crate::cmd::colormgmt::apply_open_policies_choosing(&mut self.loaded.doc, self.choice.as_ref())?;
|
||||
let (notes, changed) = crate::cmd::colormgmt::apply_open_policies_choosing(&mut self.loaded.doc, self.choice.as_ref(), &working)?;
|
||||
let Some(rest) = self.rest.take() else { return Ok(()) };
|
||||
self.answered = answered;
|
||||
self.loaded.warnings.extend(notes);
|
||||
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export PDF",
|
||||
[],
|
||||
None,
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in
Line truncated
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in
Line truncated
|
||||
has_doc,
|
||||
export_pdf
|
||||
),
|
||||
|
||||
@@ -86,6 +86,80 @@ fn png8_and_gif_export_palettes() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The shares of opaque pixels in the left and right halves of a 40×30 image file.
|
||||
fn opaque_halves(file: &[u8]) -> [f64; 2] {
|
||||
let img = craft_image_codecs::decode(file).unwrap();
|
||||
assert_eq!(img.dimensions(), (40, 30));
|
||||
let alpha: Vec<u8> = img.to_rgba8().chunks(4).map(|p| p[3]).collect();
|
||||
[0, 20].map(|x0| (0..30).flat_map(|y| (x0..x0 + 20).map(move |x| y * 40 + x)).filter(|&i| alpha[i] == 255).count() as f64 / 600.0)
|
||||
}
|
||||
|
||||
/// GIF and PNG-8 exports take Save for Web's `transparencyDither` and `transparencyDitherAmount`.
|
||||
#[test]
|
||||
fn palette_exports_take_the_transparency_dither() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 40, "height": 30})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 25})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 20, "height": 30})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 75})).unwrap();
|
||||
for format in ["gif", "png8"] {
|
||||
let mut file = |extra: Value| {
|
||||
let p = merge(json!({"format": format, "background": "transparent", "antiAlias": "none"}), extra);
|
||||
b64(&s.execute("document.export", &p).unwrap())
|
||||
};
|
||||
// By default the pixels under half opacity are transparent and the others opaque.
|
||||
let none = file(json!({}));
|
||||
assert_eq!(opaque_halves(&none), [0.0, 1.0], "{format}");
|
||||
assert_eq!(file(json!({"transparencyDither": "none"})), none, "{format}");
|
||||
assert_eq!(file(json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 0})), none, "{format}");
|
||||
for method in ["diffusion", "pattern", "noise"] {
|
||||
let dithered = file(json!({"transparencyDither": method}));
|
||||
let [left, right] = opaque_halves(&dithered);
|
||||
assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}");
|
||||
assert_eq!(file(json!({"transparencyDither": method})), dithered, "{format} {method}: the same art gives the same file");
|
||||
// Without transparency the dither does nothing.
|
||||
let opaque = file(json!({"transparencyDither": method, "transparency": false}));
|
||||
assert_eq!(opaque, file(json!({"transparency": false})), "{format} {method}");
|
||||
}
|
||||
let weaker = opaque_halves(&file(json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 40})));
|
||||
assert!(weaker[0] < 0.25 && weaker[1] > 0.75, "{format}: {weaker:?}");
|
||||
// null is the same as leaving a key out.
|
||||
assert_eq!(file(json!({"transparencyDither": null, "transparencyDitherAmount": null})), none, "{format}");
|
||||
for bad in [
|
||||
json!({"transparencyDither": "spray"}),
|
||||
json!({"transparencyDither": 3}),
|
||||
json!({"transparencyDitherAmount": 101}),
|
||||
json!({"transparencyDitherAmount": -1}),
|
||||
json!({"transparencyDitherAmount": "50"}),
|
||||
json!({"transparencyDitherAmount": 50.5}),
|
||||
] {
|
||||
assert!(s.execute("document.export", &merge(json!({"format": format}), bad.clone())).is_err(), "{format} {bad}");
|
||||
}
|
||||
let e = s.execute("document.export", &json!({"format": format, "transparencyDitherAmount": 101})).unwrap_err().to_string();
|
||||
assert!(e.contains("transparencyDitherAmount must be a whole number from 0 to 100, not 101"), "{e}");
|
||||
let e = s.execute("document.export", &json!({"format": format, "transparencyDither": "spray"})).unwrap_err().to_string();
|
||||
assert!(e.contains("transparencyDither `spray`: none, diffusion, pattern or noise"), "{e}");
|
||||
let e = s.execute("document.export", &json!({"format": format, "transparencyDither": 3})).unwrap_err().to_string();
|
||||
assert!(e.contains("transparencyDither must be none, diffusion, pattern or noise, not 3"), "{e}");
|
||||
}
|
||||
// Formats without a palette do not read the keys: their values are not checked, and the
|
||||
// warnings name them.
|
||||
for format in ["png", "jpg", "tiff"] {
|
||||
for keys in [
|
||||
json!({"transparencyDither": "spray", "transparencyDitherAmount": 101}),
|
||||
json!({"transparencyDither": 3, "transparencyDitherAmount": "50"}),
|
||||
] {
|
||||
let r = s.execute("document.export", &merge(json!({"format": format}), keys.clone()));
|
||||
let w = r.unwrap_or_else(|e| panic!("{format} {keys}: {e}"))["warnings"].to_string();
|
||||
assert!(w.contains("`transparencyDither` was not used") && w.contains("`transparencyDitherAmount` was not used"), "{format}: {w}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn palette_formats_reach_export_as_and_screens() {
|
||||
let mut s = session();
|
||||
@@ -94,7 +168,9 @@ fn palette_formats_reach_export_as_and_screens() {
|
||||
let f = |id: &str| r["formats"].as_array().unwrap().iter().find(|f| f["id"] == id).unwrap().clone();
|
||||
assert_eq!((f("png8")["extensions"][0].as_str(), f("png8")["read"].as_bool()), (Some("png"), Some(false)));
|
||||
assert_eq!(f("gif")["write"], true);
|
||||
for k in ["colors", "reduction", "dither", "ditherAmount", "transparency", "matte", "interlaced"] {
|
||||
for k in
|
||||
["colors", "reduction", "dither", "ditherAmount", "transparency", "transparencyDither", "transparencyDitherAmount", "matte", "interlaced"]
|
||||
{
|
||||
assert!(f("gif")["options"].get(k).is_some() && f("png8")["options"].get(k).is_some(), "{k}");
|
||||
}
|
||||
assert_eq!(format_for_name("a.png").unwrap().id, "png");
|
||||
|
||||
@@ -87,10 +87,12 @@ fn select_stop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// front, the Appearance panel's active item and the tool the proxy in front shows the default
|
||||
/// paint for (the Live Paint Bucket, or the Shape Builder's Fill proxy). Selecting other art,
|
||||
/// picking a part of the instance, toggling the proxy, picking another item or choosing such a
|
||||
/// tool or leaving it leaves no stop selected.
|
||||
/// tool or leaving it leaves no stop selected. The Gradient panel keys its selected midpoint
|
||||
/// diamond by it as well ([`Session::gradient_owner`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct StopOwner {
|
||||
doc: Option<usize>,
|
||||
pub struct StopOwner {
|
||||
/// The active document's uid, which stays the same when its tab moves.
|
||||
doc: Option<u64>,
|
||||
object: Option<NodeId>,
|
||||
/// The object whose paint the active proxy shows: a Live Paint group without faces (or edges)
|
||||
/// first in the selection shows the next object's.
|
||||
@@ -106,7 +108,7 @@ impl StopOwner {
|
||||
pub(crate) fn of(s: &Session) -> Self {
|
||||
let st = s.active();
|
||||
Self {
|
||||
doc: s.active,
|
||||
doc: st.map(|d| d.uid),
|
||||
object: st.and_then(|d| d.selection.objects.first().copied()),
|
||||
source: s.proxy_source(!s.fill_active).map(|(n, _)| n.id),
|
||||
part: st.is_some_and(|d| d.selection.symbol_part.is_some()),
|
||||
@@ -140,6 +142,11 @@ impl Session {
|
||||
pub fn selected_stop(&self) -> Option<usize> {
|
||||
self.gradient_stop.filter(|(_, owner)| *owner == StopOwner::of(self)).map(|(i, _)| i)
|
||||
}
|
||||
|
||||
/// Whose gradient the active proxy shows now, as a selected stop keeps it ([`StopOwner`]).
|
||||
pub fn gradient_owner(&self) -> StopOwner {
|
||||
StopOwner::of(self)
|
||||
}
|
||||
}
|
||||
|
||||
type Parsed<T> = std::result::Result<T, String>;
|
||||
|
||||
@@ -305,7 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Shape Properties",
|
||||
[],
|
||||
None,
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
|
||||
has_selection,
|
||||
set_live_shape
|
||||
),
|
||||
|
||||
@@ -99,6 +99,12 @@ fn corners_param(p: &Value) -> Result<Option<BTreeSet<usize>>> {
|
||||
list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::<Result<_>>().map(Some)
|
||||
}
|
||||
|
||||
/// Whether `relativeRadii` applies to a path with live shape `live`: a live rectangle, a live
|
||||
/// polygon or a path with Live Corners. A plain path, an ellipse and a line stay as they are.
|
||||
fn takes_rounding(live: Option<&LiveShape>) -> bool {
|
||||
matches!(live, Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Path { .. }))
|
||||
}
|
||||
|
||||
/// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about
|
||||
/// its midpoint; a line whose ends meet has none to turn), or None when neither changes it.
|
||||
fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<LiveShape> {
|
||||
@@ -277,7 +283,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(l @ LiveShape::Rectangle { .. }) if rectangle_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => return false,
|
||||
_ => {}
|
||||
}
|
||||
if relative_radii.is_some_and(|on| live.as_deref().map(|l| l.radii_relative()) != Some(on)) {
|
||||
if relative_radii.is_some_and(|on| takes_rounding(live.as_deref()) && live.as_deref().is_some_and(LiveShape::radii_relative) != on) {
|
||||
return false;
|
||||
}
|
||||
if radius.is_none() && kind.is_none() {
|
||||
@@ -291,10 +297,17 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& picked.iter().all(|k| {
|
||||
*k < c.base.anchor_count()
|
||||
// A radius stored in document units can be larger than it draws; a relative
|
||||
// one is a fraction, so it is compared as drawn.
|
||||
// one is compared as the fraction `set_corners` would store for it, to a
|
||||
// precision of 1e-9 pt on a corner whose maximum is 1 pt or more.
|
||||
&& radius.is_none_or(|r| {
|
||||
let now = if c.radii_relative() { c.drawn_radius(*k) } else { c.radius(*k) };
|
||||
(now - r.max(0.0)).abs() < 1e-9
|
||||
let r = r.max(0.0);
|
||||
if c.radii_relative() {
|
||||
let max = c.corner(*k).map_or(0.0, |c| c.max_radius());
|
||||
let fraction = if max > 1e-12 { (r / max).clamp(0.0, 1.0) } else { 0.0 };
|
||||
(c.radius(*k) - fraction).abs() * max.max(1.0) < 1e-9
|
||||
} else {
|
||||
(c.radius(*k) - r).abs() < 1e-9
|
||||
}
|
||||
})
|
||||
&& kind.is_none_or(|kd| c.kind(*k) == kd)
|
||||
})
|
||||
|
||||
@@ -172,8 +172,9 @@ fn apply_transform_moving_guides(
|
||||
if c[..4] == [1.0, 0.0, 0.0, 1.0] {
|
||||
interpolate = Some(crate::cmd::path::interpolates_handles(s, p, label)?);
|
||||
}
|
||||
let mut ids = ids;
|
||||
if xf != Affine::IDENTITY {
|
||||
crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?;
|
||||
ids.extend(crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?);
|
||||
}
|
||||
ids
|
||||
} else if none || (!copy && xf == Affine::IDENTITY) {
|
||||
@@ -181,7 +182,7 @@ fn apply_transform_moving_guides(
|
||||
} else {
|
||||
let kept = if copy { preview_copies(s, &ids, with_guides, below)? } else { None };
|
||||
s.edit(label, |d, sel| {
|
||||
let targets = match &kept {
|
||||
let mut targets = match &kept {
|
||||
// The document becomes the snapshot with the kept copies, untransformed, and the
|
||||
// loop below transforms only the copies.
|
||||
Some(k) => {
|
||||
@@ -231,7 +232,9 @@ fn apply_transform_moving_guides(
|
||||
d.edit_ruler_guide(i, |g| *g = g.moved(delta));
|
||||
}
|
||||
} else if with_guides && !is_translation {
|
||||
d.transform_ruler_guides(sel, xf);
|
||||
// The guide paths are made already transformed, so they join the reply after the
|
||||
// loop above.
|
||||
targets.extend(d.transform_ruler_guides(sel, xf));
|
||||
}
|
||||
Ok(targets)
|
||||
})?
|
||||
|
||||
@@ -420,7 +420,7 @@ pub(crate) fn push_artboard_copy(d: &mut vectorcraft_doc::Document, src: &vector
|
||||
// ---------- text ----------
|
||||
|
||||
/// Largest indent or paragraph spacing (points; Illustrator's limit).
|
||||
const MAX_PARA: f64 = 1296.0;
|
||||
const MAX_PARA: f64 = vectorcraft_doc::text::MAX_PARA_DISTANCE;
|
||||
|
||||
/// `text.setFormat`'s `bullet` values and the bullets they pick.
|
||||
const BULLETS: [(&str, vectorcraft_doc::text::Bullet); 4] = [
|
||||
|
||||
@@ -34,7 +34,8 @@
|
||||
//! plays. A key a schema doesn't name passes there too, and the values of the parameters it names
|
||||
//! are still checked. Even there, an effect's `color` that the effect can't read and a Levels or Curves
|
||||
//! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams`
|
||||
//! themselves ([`check_effect_color`], [`check_effect_channel`]).
|
||||
//! themselves ([`check_effect_color`], [`check_effect_channel`]). A saved step may keep an unknown
|
||||
//! shadow or glow blend mode, which the effect draws as Normal.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::OnceLock;
|
||||
@@ -456,7 +457,8 @@ fn check_member_keys(id: &str, params: &Value) -> Result<()> {
|
||||
/// `params` of built-in effect `effect`, as command `id` was given them (#1592): only keys the
|
||||
/// effect takes (those of its dialog defaults and of its params description), each of the type
|
||||
/// the effect reads ([`check_effect_types`]), a `color` the effect can draw ([`check_effect_color`])
|
||||
/// and a Levels or Curves `channel` the effect has ([`check_effect_channel`]). Numbers out of range
|
||||
/// a Levels or Curves `channel` the effect has ([`check_effect_channel`]) and a Drop Shadow's or
|
||||
/// glow's `mode` that names a blend mode ([`check_effect_blend`]). Numbers out of range
|
||||
/// pass: the effect clamps them when it draws. An installed effect plug-in's are checked against its
|
||||
/// manifest, and an unknown effect is the command's to report.
|
||||
pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> {
|
||||
@@ -476,6 +478,7 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
|
||||
if let Some(key) = given.keys().find(|k| !keys.contains(&k.as_str())) {
|
||||
return Err(unknown(id, key, &keys));
|
||||
}
|
||||
check_effect_blend(id, effect, params)?;
|
||||
check_effect_types(id, effect, params)?;
|
||||
// An SVG filter's XML is one drawable <filter> element.
|
||||
if effect == vectorcraft_render::effects::SVG_FILTER
|
||||
@@ -661,6 +664,20 @@ pub(crate) fn check_effect_channel(id: &str, effect: &str, params: &Value) -> Re
|
||||
Err(bad(id, format!("`{key}` must be one of {}", vectorcraft_render::effects::CHANNELS.join(", "))))
|
||||
}
|
||||
|
||||
/// The `mode` in `params` of Drop Shadow, Inner Glow or Outer Glow (`effect`), as command `id` was
|
||||
/// given it: a parameter error naming the blend modes unless the effect reads it as one
|
||||
/// ([`vectorcraft_render::effects::parse_blend_mode`]); an older step with another value still replays in Normal.
|
||||
fn check_effect_blend(id: &str, effect: &str, params: &Value) -> Result<()> {
|
||||
use vectorcraft_render::effects;
|
||||
let key = "mode";
|
||||
let Some(v) = params.get(key) else { return Ok(()) };
|
||||
if !effects::takes_blend_mode(effect, key) || v.as_str().and_then(effects::parse_blend_mode).is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let modes: Vec<String> = vectorcraft_color::BlendMode::ALL.into_iter().map(effects::blend_mode_id).collect();
|
||||
Err(bad(id, format!("`{key}` must be one of {}", modes.join(", "))))
|
||||
}
|
||||
|
||||
/// The Blur Center (`centerX`, `centerY`) in `params` of Radial Blur (`effect`), as command `id`
|
||||
/// was given it: a parameter error unless each is a number from 0 to 1 (a share of the object's
|
||||
/// bounds). `effect.apply` and `effect.setParams` run this themselves before they edit, as they
|
||||
@@ -698,6 +715,7 @@ pub const UNCHECKED: &[&str] = &[
|
||||
"document.exportForScreens",
|
||||
"document.exportForWeb",
|
||||
"document.exportForWeb.preview",
|
||||
"document.exportForWeb.saveColorTable",
|
||||
"document.exportPdf",
|
||||
"document.find",
|
||||
"document.inspect",
|
||||
@@ -803,6 +821,7 @@ pub const UNCHECKED: &[&str] = &[
|
||||
"transparency.setOpacityMask",
|
||||
"transparency.unlinkOpacityMask",
|
||||
"type.pathOptions",
|
||||
"webExport.loadColorTable",
|
||||
"webExport.optimizeToFileSize",
|
||||
"webExport.presets.save",
|
||||
"webExport.settings",
|
||||
@@ -1067,7 +1086,7 @@ pub fn check_params(id: &str, params: &Value) -> Result<()> {
|
||||
fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> {
|
||||
let Some(spec) = find_command(id) else { return Ok(()) };
|
||||
if let ("effect.apply" | "appearance.addEffect", Some(effect), Some(given)) =
|
||||
(id, params.get("effect").or_else(|| params.get("id")).and_then(Value::as_str), params.get("params"))
|
||||
(id, super::effectcmd::requested_effect(params), params.get("params"))
|
||||
{
|
||||
check_effect_params(id, effect, given)?;
|
||||
}
|
||||
|
||||
@@ -330,18 +330,15 @@ pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Res
|
||||
|
||||
/// [`transform_selected`] on the active document's selection, as one undo step `label`. A
|
||||
/// transform other than a move also transforms the selected ruler guides
|
||||
/// ([`Document::transform_ruler_guides`]).
|
||||
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> {
|
||||
/// ([`Document::transform_ruler_guides`]). Returns the ids of the guide paths that adds.
|
||||
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<Vec<NodeId>> {
|
||||
let sel = s.doc()?.selection.clone();
|
||||
// As [`transform_selected`] tells a move apart, which moves the guides itself.
|
||||
let c = xf.as_coeffs();
|
||||
let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9;
|
||||
s.edit(label, |doc, live| {
|
||||
transform_selected(doc, &sel, xf, sc, interpolate)?;
|
||||
if !is_translation {
|
||||
doc.transform_ruler_guides(live, xf);
|
||||
}
|
||||
Ok(())
|
||||
Ok(if is_translation { vec![] } else { doc.transform_ruler_guides(live, xf) })
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+152
-34
@@ -42,18 +42,24 @@
|
||||
//!
|
||||
//! A filter whose manifest lists `inputs` (plug-in API level 2) is also given the selected type,
|
||||
//! images or symbol instances of those kinds, to read only: its output must return each of them
|
||||
//! unchanged ([`objects::decode_output_with`]).
|
||||
//! unchanged ([`objects::decode_output_with`]). At level 3 its manifest's `writes` lists the kinds
|
||||
//! among them it may change: type's runs and paragraph styles, an image's transform and opacity,
|
||||
//! an instance's symbol and transform, and each one's name ([`objects::decode_output_writing`]).
|
||||
//!
|
||||
//! A filter, or a live effect's command, whose manifest lists `context` (plug-in API level 3) is
|
||||
//! also given the parts of the active document it names in `_context.document`, whether or not
|
||||
//! anything is selected: the settings, artboards, layers and swatches, as plain values
|
||||
//! ([`context`]).
|
||||
//!
|
||||
//! A filter may be written in JavaScript ([`vectorcraft_plugins::js`]): `plugin.install {path}`
|
||||
//! takes its `.vcplugin` manifest and reads the `.js` file the manifest names beside it, and the
|
||||
//! plug-in store keeps the two as one module.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{Document, Effect, Node};
|
||||
use vectorcraft_doc::{Document, Effect, Node, NodeKind};
|
||||
use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode};
|
||||
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or};
|
||||
@@ -113,12 +119,19 @@ pub fn describe(p: &Plugin) -> Value {
|
||||
if !m.inputs.is_empty() {
|
||||
v["inputs"] = json!(m.inputs);
|
||||
}
|
||||
if !m.writes.is_empty() {
|
||||
v["writes"] = json!(m.writes);
|
||||
}
|
||||
if !m.context.is_empty() {
|
||||
v["context"] = json!(m.context);
|
||||
}
|
||||
if m.paint_output {
|
||||
v["paintOutput"] = json!(true);
|
||||
}
|
||||
if let Some(script) = p.script() {
|
||||
v["runtime"] = json!(m.runtime.name());
|
||||
v["script"] = json!(script);
|
||||
}
|
||||
if !m.command_allowlist.is_empty() {
|
||||
v["commandAllowlist"] = json!(m.command_allowlist);
|
||||
}
|
||||
@@ -377,7 +390,7 @@ impl FilterRun {
|
||||
fn finish(self, s: &mut Session, output: &[u8]) -> Result<Value> {
|
||||
let m = self.plugin.manifest();
|
||||
let may = m.permissions();
|
||||
let out = objects::decode_output_with(output, &self.input, &self.read_only).map_err(err)?;
|
||||
let out = objects::decode_output_writing(output, &self.input, &self.read_only, &m.write_kinds()).map_err(err)?;
|
||||
if out.document_data.is_some() && !may.contains(&Permission::State) {
|
||||
return Err(not_granted(&m.name, Permission::State));
|
||||
}
|
||||
@@ -393,18 +406,52 @@ impl FilterRun {
|
||||
if s.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
if !s.previewing && super::typing_in_progress(s) {
|
||||
// Typing whose text Real-time Drawing off left out of the document isn't in what the
|
||||
// plug-in was given, and the output would replace it ([`keep_unapplied_typing`] keeps it
|
||||
// before the run is prepared).
|
||||
if unapplied_typing(s) {
|
||||
return Err(err(vectorcraft_plugins::Error::Output(
|
||||
"typing in progress isn't in what the plug-in was given: nothing was changed".into(),
|
||||
)));
|
||||
}
|
||||
let data = out.document_data;
|
||||
// The output applied to `now`, with the checks that refuse it.
|
||||
let build = |now: &Document, objects: Vec<objects::OutObject>| -> Result<(Document, Vec<NodeId>)> {
|
||||
let mut d = now.clone();
|
||||
let before = (!may_write).then(|| d.layers.clone());
|
||||
let ids = objects::apply_output(&mut d, &inputs, objects, parent, &admit_effects).map_err(err)?;
|
||||
if before.is_some_and(|b| b != d.layers) {
|
||||
return Err(not_granted(&m.name, Permission::DocWrite));
|
||||
}
|
||||
// Type whose text the output changed is laid out again.
|
||||
let retyped: Vec<NodeId> = ids
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|&id| match (d.node(id).map(|n| &n.kind), now.node(id).map(|n| &n.kind)) {
|
||||
(Some(NodeKind::Text(new)), Some(NodeKind::Text(old))) => new.runs != old.runs || new.paras != old.paras || new.para != old.para,
|
||||
_ => false,
|
||||
})
|
||||
.collect();
|
||||
super::typecmd::refresh_bounds_of(&mut d, &retyped);
|
||||
if let Some(data) = data.clone() {
|
||||
d.set_plugin_data(&m.id, data);
|
||||
}
|
||||
Ok((d, ids))
|
||||
};
|
||||
// Typing in progress, its text already in the document, is kept as `s.edit` keeps it once
|
||||
// nothing can refuse the output, so a refused output leaves it in progress. Keeping it can
|
||||
// change the document, and the output is then applied to the document as kept.
|
||||
let typing = !s.previewing && super::typing_in_progress(s);
|
||||
let again = typing.then(|| out.objects.clone());
|
||||
let mut now = s.doc()?.doc.clone();
|
||||
let (mut d, mut ids) = build(&now, out.objects)?;
|
||||
if let Some(objects) = again {
|
||||
super::settle_interaction(s)?;
|
||||
}
|
||||
let now = s.doc()?.doc.clone();
|
||||
let mut d = (*now).clone();
|
||||
let before = (!may_write).then(|| d.layers.clone());
|
||||
let ids = objects::apply_output(&mut d, &inputs, out.objects, parent, &admit_effects).map_err(err)?;
|
||||
if before.is_some_and(|b| b != d.layers) {
|
||||
return Err(not_granted(&m.name, Permission::DocWrite));
|
||||
}
|
||||
if let Some(data) = out.document_data {
|
||||
d.set_plugin_data(&m.id, data);
|
||||
let kept = s.doc()?.doc.clone();
|
||||
if !Arc::ptr_eq(&kept, &now) {
|
||||
now = kept;
|
||||
(d, ids) = build(&now, objects)?;
|
||||
}
|
||||
}
|
||||
let selectable = |d: &Document| ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable)).collect::<Vec<_>>();
|
||||
if same_art(&d.layers, &now.layers) && d.plugin_data(&m.id) == now.plugin_data(&m.id) {
|
||||
@@ -447,6 +494,23 @@ fn not_granted(name: &str, permission: Permission) -> EngineError {
|
||||
err(vectorcraft_plugins::Error::Output(format!("“{name}” wasn't granted `{p}`, which its output needs: nothing was changed")))
|
||||
}
|
||||
|
||||
/// Is typing in progress whose text Real-time Drawing off left out of the document (not in a
|
||||
/// preview's run)? A run prepared now isn't given that text.
|
||||
pub fn unapplied_typing(s: &Session) -> bool {
|
||||
!s.previewing && super::typing_in_progress(s) && s.unapplied_interaction_preview().is_some()
|
||||
}
|
||||
|
||||
/// Keeps typing in progress whose text Real-time Drawing off left out of the document
|
||||
/// ([`super::settle_interaction`]) → whether there was any. A run prepared after it is given the
|
||||
/// typed text; one prepared before it is prepared again.
|
||||
pub fn keep_unapplied_typing(s: &mut Session) -> Result<bool> {
|
||||
if !unapplied_typing(s) {
|
||||
return Ok(false);
|
||||
}
|
||||
super::settle_interaction(s)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// `plugin.run`: runs filter `id` on `ids` (else the selected paths and compound paths) with its
|
||||
/// parameters and `_context` (what it keeps with the document included), and applies its output as
|
||||
/// one undo step ([`objects::apply_output`]; effect records as [`admit_effects`] admits them), with
|
||||
@@ -464,6 +528,8 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let r = if super::plugin_call::settle(s)? { FilterRun::prepare(s, p)? } else { r };
|
||||
return r.run_with_calls(s);
|
||||
}
|
||||
// Typing Real-time Drawing off left out of the document is kept first, so the plug-in is given it.
|
||||
let r = if keep_unapplied_typing(s)? { FilterRun::prepare(s, p)? } else { r };
|
||||
// Handed in for this very run (the app ran it in the background), it is what running the
|
||||
// plug-in again would return.
|
||||
let handed = handed.filter(|h| (h.serial, &h.input, &h.params) == (r.plugin.serial(), &r.input, &r.params));
|
||||
@@ -888,6 +954,13 @@ pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result<Value>
|
||||
};
|
||||
return r.run_with_calls(s).map_err(failed);
|
||||
}
|
||||
let r = match keep_unapplied_typing(s)? {
|
||||
true => {
|
||||
let (plugin, command) = command_of(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
|
||||
FilterRun::prepare_with(s, plugin, Some(command), id, p)?
|
||||
}
|
||||
false => r,
|
||||
};
|
||||
let output = r.run().map_err(&failed)?;
|
||||
r.finish(s, &output).map_err(failed)
|
||||
}
|
||||
@@ -944,8 +1017,9 @@ pub(crate) fn admit_effects_for(cmd: &str, fx: &[Effect], n: &Node) -> std::resu
|
||||
/// Largest base64 payload `plugin.install` accepts (the module limit, encoded).
|
||||
const MAX_DATA_CHARS: usize = (32 << 20) / 3 * 4 + 4;
|
||||
|
||||
/// The `.wasm` extension plug-in files have (File › Open installs them).
|
||||
pub const EXTS: &[&str] = &["wasm"];
|
||||
/// The extensions plug-in files have (File › Open installs them): a WebAssembly module, and a
|
||||
/// JavaScript plug-in's manifest.
|
||||
pub const EXTS: &[&str] = &["wasm", vectorcraft_plugins::js::PACKAGE_EXT];
|
||||
|
||||
/// The plug-in module command `c`'s params give, loaded and checked, and its bytes: `path` (a
|
||||
/// `.wasm` file) or `dataBase64` (the module, with `name` shown as its source).
|
||||
@@ -1325,12 +1399,23 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The plug-in in the `.wasm` file `path`, and its module.
|
||||
/// The plug-in in the `.wasm` file `path`, or in the `.vcplugin` manifest `path` and the `.js` file
|
||||
/// it names, and its module: for a JavaScript plug-in, the manifest with the script's text
|
||||
/// ([`registry::read_js_package`]). Under automation read roots the script must be inside them too.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn load_path(path: &str) -> Result<(Plugin, Vec<u8>)> {
|
||||
crate::file_access::check_read(path).map_err(EngineError::Other)?;
|
||||
let limits = vectorcraft_plugins::Limits::default();
|
||||
let bytes = crate::store::read_capped(std::path::Path::new(path), limits.max_module_bytes as u64).map_err(EngineError::Other)?;
|
||||
let file = std::path::Path::new(path);
|
||||
let bytes = if registry::is_js_package(file) {
|
||||
let allow = |script: &std::path::Path| match script.to_str() {
|
||||
Some(script) => crate::file_access::check_read(script),
|
||||
None => Err(format!("automation path rejected: {} isn't valid text", script.display())),
|
||||
};
|
||||
registry::read_js_package(file, &allow).map_err(err)?
|
||||
} else {
|
||||
crate::store::read_capped(file, limits.max_module_bytes as u64).map_err(EngineError::Other)?
|
||||
};
|
||||
Ok((Plugin::load(&bytes, limits).map_err(err)?.with_source(path), bytes))
|
||||
}
|
||||
|
||||
@@ -1809,18 +1894,49 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let installed = registry::get(id).is_some();
|
||||
// Settings and cache the store keeps for an id that isn't installed are deleted too.
|
||||
let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id);
|
||||
// Installed again, it asks again. A grant that can't be removed still approves the module, and
|
||||
// so may a grants file that can't be opened or read. One that is too large or doesn't hold a
|
||||
// list approves nothing and doesn't stop the removal.
|
||||
let forget = || s.store_grant_in(&turn, id, None) || !s.holds_plugin_grant(id);
|
||||
// Its settings and cache are moved aside and its grant removed before anything is deleted: when
|
||||
// either can't be done, the plug-in stays installed, as it was, and a second `plugin.remove`
|
||||
// tries again.
|
||||
// A module stored for an id that isn't installed (one no grant covers is skipped at startup)
|
||||
// counts as removed once its file is gone.
|
||||
let module = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.holds_stored_plugin(id);
|
||||
// An installed plug-in's stored module is deleted with its grant too, so that one that can't be
|
||||
// deleted leaves the plug-in installed. Without a plug-in folder it has none.
|
||||
let unstore = module || (installed && s.plugin_dir.is_some());
|
||||
// The grant the store keeps for an installed plug-in, which may differ from the one the session
|
||||
// holds (an update whose module couldn't be stored): written back when its module can't be
|
||||
// deleted, so that the stored module still loads at the next launch.
|
||||
let kept_grant = if installed { s.stored_plugin_grant(id) } else { None };
|
||||
let module_left = std::cell::Cell::new(false);
|
||||
let cant_delete = || format!("plugin.remove: can't delete {}", s.stored_plugin_file(id).unwrap_or_default());
|
||||
// Installed again, it asks again. A grant that can't be removed may still approve the module, and
|
||||
// so may a grants file that can't be opened or read, or a signed copy of the file put back when
|
||||
// the generation couldn't be raised (the key store can't be reached). Without a plug-in folder
|
||||
// nothing keeps a grant. The stored module is deleted next, while its settings and cache can
|
||||
// still be moved back.
|
||||
let forget = || {
|
||||
if !s.store_grant_in(&turn, id, None) && s.plugin_dir.is_some() {
|
||||
return false;
|
||||
}
|
||||
let deleted = !unstore || s.unstore_plugin(&turn, id);
|
||||
if !deleted
|
||||
&& let Some(grant) = kept_grant.clone()
|
||||
&& !s.store_grant_in(&turn, id, Some(grant))
|
||||
{
|
||||
log::warn!("plugin.remove: can't keep the grant of {id}, whose module stays: it asks again at the next launch");
|
||||
}
|
||||
module_left.set(!deleted);
|
||||
deleted
|
||||
};
|
||||
// Its settings and cache are moved aside, its grant removed and its stored module deleted before
|
||||
// anything else is deleted: when one of them can't be done, the settings and cache are moved back,
|
||||
// the plug-in stays installed, as it was, and a second `plugin.remove` tries again. An invalid id
|
||||
// names no grant and no module.
|
||||
let failed = if installed || stored {
|
||||
s.remove_plugin_storage(&turn, id, forget).err().map(|e| e.to_string())
|
||||
} else {
|
||||
} else if vectorcraft_plugins::manifest::valid_id(id) {
|
||||
(!forget()).then(|| crate::store::GRANT_NOT_REMOVED.to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let failed = failed.map(|e| if module_left.get() && e == crate::store::GRANT_NOT_REMOVED { cant_delete() } else { e });
|
||||
if let Some(e) = failed {
|
||||
if installed {
|
||||
s.attach_plugin_storage(&turn, id);
|
||||
@@ -1828,8 +1944,10 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Other(e));
|
||||
}
|
||||
registry::revoke(id);
|
||||
s.unstore_plugin(&turn, id);
|
||||
if !stored && (!installed || !registry::remove(id)) {
|
||||
if !s.unstore_plugin(&turn, id) && module {
|
||||
return Err(EngineError::Other(cant_delete()));
|
||||
}
|
||||
if !stored && !module && (!installed || !registry::remove(id)) {
|
||||
return Err(err(vectorcraft_plugins::Error::NotFound(id.into())));
|
||||
}
|
||||
Ok(json!({"removed": id}))
|
||||
@@ -1861,7 +1979,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Plug-ins",
|
||||
[],
|
||||
None,
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -1879,7 +1997,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step (an output that changes no object and no kept data records none and leaves the document unmodified); the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids, notice?, pluginName?} (notice: the text the output reports in its notice key once applied, escaped and cut at 200 characters; pluginName: the plug-in's name, with it)",
|
||||
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step (an output that changes no object and no kept data records none and leaves the document unmodified); the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given (an image may leave out opacity), or the run is refused and nothing changes. A filter at api 3 whose manifest lists some of those kinds in writes (with doc.write) may return an object of such a kind with only the fields it changes: name and transform (6 numbers within ±4,000,000 that don't flatten it), type's text.runs ({text, style, inline?} with the native character attributes; inline graphics stay as they were; at most 4,096 runs, 4,096 paragraphs and 256 KiB of text; every number of every run's style in the range charStyle.new takes, fills and strokes with only the keys their type reads, and a style of its own needs a font family) and text.paragraphs (one style per paragraph, also when given as they were next to changed runs, each number in the range paraStyle.new takes, a custom Kinsoku set only one of the document's by name), an image's opacity (0 to 1), an instance's symbolId (a symbol in the document); any other field changed, or a value out of range, refuses the run naming the object and the field, and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids, notice?, pluginName?} (notice: the text the output reports in its notice key once applied, escaped and cut at 200 characters; pluginName: the plug-in's name, with it)",
|
||||
has_doc,
|
||||
run
|
||||
),
|
||||
@@ -1888,7 +2006,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Install Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)",
|
||||
"{path: a .wasm file or a JavaScript plug-in's .vcplugin manifest (read with the .js file its script names) (desktop) | dataBase64: the module or a JavaScript plug-in as one JSON object (its manifest, with the script's text in source) (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count, and a grants.json without VectorCraft's MAC for that folder grants nothing; when the system key store can't be reached, the grant lasts for this session only; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)",
|
||||
always,
|
||||
install
|
||||
),
|
||||
@@ -1897,7 +2015,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Inspect Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)",
|
||||
"{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)",
|
||||
always,
|
||||
inspect
|
||||
),
|
||||
@@ -1906,7 +2024,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}",
|
||||
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, or its stored module can't be deleted, the command fails and the plug-in stays installed, as it does when the system key store can't be reached to make sure no earlier copy of grants.json grants it again; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it and the module stored for it that didn't load, and reports it removed; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}",
|
||||
always,
|
||||
remove
|
||||
),
|
||||
@@ -1924,7 +2042,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reload Plug-ins",
|
||||
["Object", "Plug-ins"],
|
||||
None,
|
||||
"{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm files past the first 1,000, not tried}",
|
||||
"{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm and *.vcplugin in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm and *.vcplugin files past the first 1,000, not tried}",
|
||||
always,
|
||||
reload
|
||||
),
|
||||
|
||||
@@ -43,6 +43,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.packaging.check",
|
||||
"addon.packaging.fold",
|
||||
"addon.packaging.roles",
|
||||
"addon.packaging.setFoldAngle",
|
||||
"addon.packaging.setRole",
|
||||
"addon.packaging.setRoleSwatch",
|
||||
"addon.pathtools.addPoints",
|
||||
@@ -403,6 +404,11 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"object.slice.release",
|
||||
"object.slice.select",
|
||||
"object.slice.setRect",
|
||||
"object.tag.add",
|
||||
"object.tag.remove",
|
||||
"object.tag.removeAll",
|
||||
"object.tag.set",
|
||||
"object.tags",
|
||||
"object.textWrap.make",
|
||||
"object.textWrap.options",
|
||||
"object.textWrap.release",
|
||||
|
||||
@@ -146,6 +146,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("showToolTips", "General", "Options", "Show Tool Tips", bool),
|
||||
p!("showToolCards", "General", "Options", "Show Tool Cards", bool),
|
||||
p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", bool),
|
||||
p!("runStartupScripts", "General", "Options", "Run Startup Scripts", bool),
|
||||
p!("antiAliasedArtwork", "General", "Options", "Anti-aliased Artwork", bool),
|
||||
p!("selectSameTintPercent", "General", "Options", "Select Same Tint %", bool),
|
||||
p!("showHomeScreen", "General", "Options", "Show The Home Screen When No Documents Are Open", bool),
|
||||
@@ -710,6 +711,12 @@ impl Prefs {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Take the categories `prefs.reset` reset since the last call, each once, with `None` for a
|
||||
/// reset of every category. A frontend resets the settings it keeps itself in them.
|
||||
pub fn take_prefs_resets(&mut self) -> Vec<Option<&'static str>> {
|
||||
std::mem::take(&mut self.prefs_resets)
|
||||
}
|
||||
|
||||
/// Replace the preferences and push the ones with engine-side consumers into open documents
|
||||
/// and the renderer (grid, history depth, render threads).
|
||||
pub fn apply_prefs(&mut self, mut p: Prefs) {
|
||||
@@ -817,7 +824,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
set
|
||||
),
|
||||
cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?} reset one category (or everything) to defaults", always, reset),
|
||||
cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?: string} reset one category (or everything, with category left out or null) to defaults; an unknown category or one that is not a string is an error", always, reset),
|
||||
cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference; under automation read roots a folder preference's value outside them is null", always, list),
|
||||
cmd!(
|
||||
query "prefs.export",
|
||||
@@ -1000,15 +1007,17 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn reset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cat = str_param(p, "category");
|
||||
if let Some(c) = cat
|
||||
&& !PREF_CATEGORIES.iter().any(|x| x.eq_ignore_ascii_case(c))
|
||||
{
|
||||
return Err(bad("prefs.reset", format!("unknown category `{c}`")));
|
||||
}
|
||||
let cat = text_param(p, "category", "prefs.reset")?;
|
||||
let known = |c: &str| {
|
||||
PREF_CATEGORIES.iter().copied().find(|x| x.eq_ignore_ascii_case(c)).ok_or_else(|| bad("prefs.reset", format!("unknown category `{c}`")))
|
||||
};
|
||||
let category = cat.map(known).transpose()?;
|
||||
let mut next = s.prefs.clone();
|
||||
next.reset(cat);
|
||||
s.apply_prefs(next);
|
||||
if !s.prefs_resets.contains(&category) {
|
||||
s.prefs_resets.push(category);
|
||||
}
|
||||
Ok(json!({ "prefs": shown_prefs(&s.prefs) }))
|
||||
}
|
||||
|
||||
|
||||
+190
-63
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Retype",
|
||||
["Type"],
|
||||
None,
|
||||
"{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05",
|
||||
"{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only), installed?: bool} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; shapes none of those fonts match are then compared in the same way (the tolerance and the splitting included) with the installed fonts not loaded yet, unless installed is false (true, omitted or null: compared): their files are read smallest first, one at a time, until each such shape matches the fonts read, leaving out files over 256 MiB and the files and faces past 2 GiB read or 500,000 glyphs drawn in all, and a font whose glyphs match such a shape, or complete the glyphs of a split one with the fonts found before it, is loaded; a plain shape (one contour of up to four straight edges, such as a rectangle) starts no such reading and matches only a font the other shapes found; a cancel stops between files; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are wh
Line truncated
|
||||
has_selected_path,
|
||||
retype
|
||||
)]
|
||||
@@ -56,6 +56,10 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
#[path = "retype_fonts.rs"]
|
||||
pub(super) mod fonts;
|
||||
#[path = "retype_installed.rs"]
|
||||
mod installed;
|
||||
|
||||
pub use installed::{RetypeFound, RetypeRun, RetypeSearch};
|
||||
|
||||
/// A shape to match: a path or compound path, in document space.
|
||||
struct Piece {
|
||||
@@ -141,7 +145,8 @@ fn type_can_paint(ap: &Appearance) -> bool {
|
||||
ap.is_basic() && ap.stroke().is_none_or(|s| s.start_arrow.is_none() && s.end_arrow.is_none() && s.profile.is_none() && s.brush.is_none())
|
||||
}
|
||||
|
||||
/// The faces to match against: the families in `fonts`, the document's fonts, then every loaded face.
|
||||
/// The faces to match against: the families in `fonts`, the document's fonts, the faces earlier
|
||||
/// searches of the installed fonts loaded ([`installed::found`]), then every other loaded face.
|
||||
fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec<Arc<vectorcraft_text::FontFace>> {
|
||||
let mut families: Vec<String> = fonts.iter().take(MAX_FONT_PARAMS).cloned().collect();
|
||||
d.walk(|n| {
|
||||
@@ -168,7 +173,8 @@ fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec<Arc<vecto
|
||||
}
|
||||
}
|
||||
}
|
||||
for face in db.loaded_faces() {
|
||||
// The faces earlier searches of the installed fonts found, then the other loaded faces.
|
||||
for face in installed::found(db).into_iter().chain(db.loaded_faces()) {
|
||||
if faces.len() >= cap {
|
||||
break;
|
||||
}
|
||||
@@ -1357,6 +1363,48 @@ fn new_line(pc: &Piece, cands: &[GlyphMatch], slack: f64) -> Option<Line> {
|
||||
})
|
||||
}
|
||||
|
||||
/// `type.retype`'s `fonts` param: the family names it lists.
|
||||
fn fonts_param(p: &Value) -> Result<Vec<String>> {
|
||||
const C: &str = "type.retype";
|
||||
match p.get("fonts") {
|
||||
None => Ok(vec![]),
|
||||
Some(Value::Array(a)) => {
|
||||
a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect()
|
||||
}
|
||||
Some(_) => Err(bad(C, "fonts must be a list of family names")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `type.retype`'s `tolerance` param: 0 (exact matches only) when omitted.
|
||||
fn tolerance_param(p: &Value) -> Result<f64> {
|
||||
const C: &str = "type.retype";
|
||||
match p.get("tolerance") {
|
||||
None => Ok(0.0),
|
||||
Some(v) => match v.as_f64() {
|
||||
Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => Ok(t),
|
||||
_ => Err(bad(C, "tolerance must be a number from 0 to 0.05")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The shapes of the selected objects, in paint order, and whether shapes past the limits were
|
||||
/// left out; an error when the selection holds none.
|
||||
fn selected_pieces(s: &Session) -> Result<(Vec<Piece>, bool)> {
|
||||
let roots = selected_roots(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let mut pieces = vec![];
|
||||
let (mut barrier, mut truncated) = (true, false);
|
||||
for r in &roots {
|
||||
if let Some(n) = d.node(*r) {
|
||||
collect(n, d.parent_of(*r), 0, &mut barrier, &mut truncated, &mut pieces);
|
||||
}
|
||||
}
|
||||
if pieces.is_empty() {
|
||||
return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into()));
|
||||
}
|
||||
Ok((pieces, truncated))
|
||||
}
|
||||
|
||||
/// The lines, by index, to drop so that no shape of several glyphs becomes type in part: each line
|
||||
/// is given by the shapes it sets, one per glyph, and `glyphs_of` says how many glyphs a shape
|
||||
/// is. A line setting a glyph of a shape not all of whose glyphs are set goes, and then so do the
|
||||
@@ -1675,26 +1723,70 @@ fn lookup_keys<'a>(
|
||||
(wanted, near_wanted)
|
||||
}
|
||||
|
||||
/// The candidates of `path` in `indexes`: the exact ones of every index (for a `part` of a split
|
||||
/// shape, either way round), or, when there are none and `near` is set, the near ones within
|
||||
/// `tolerance`. With `fill` (`Some(nonzero)`, for a shape with a visible fill), only glyphs that
|
||||
/// paint the area `path` paints under that rule are kept.
|
||||
fn candidates(indexes: &[&RetypeIndex], path: &BezPath, part: bool, near: bool, fill: Option<bool>, tolerance: f64) -> Vec<GlyphMatch> {
|
||||
let painted = |index: &RetypeIndex, ms: Vec<GlyphMatch>, tol: f64| -> Vec<GlyphMatch> {
|
||||
match fill {
|
||||
Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(),
|
||||
None => ms,
|
||||
}
|
||||
};
|
||||
let exact: Vec<GlyphMatch> =
|
||||
indexes.iter().flat_map(|ix| painted(ix, if part { ix.matches_either_way(path) } else { ix.all_matches(path) }, 0.0)).collect();
|
||||
if exact.is_empty() && near { indexes.iter().flat_map(|ix| painted(ix, ix.near_matches(path, tolerance), tolerance)).collect() } else { exact }
|
||||
}
|
||||
|
||||
/// The parts of the shape `path` ([`parts`]: the whole shape, or the glyphs of its contour
|
||||
/// `groups`), each with its [`candidates`] in `indexes`; empty when it matches nothing. `fill` is
|
||||
/// as [`candidates`] takes it, and `once` is set when the shape paints its overlaps once, as
|
||||
/// several objects would ([`paints_once`]).
|
||||
fn shape_parts(path: &BezPath, groups: &[BezPath], fill: Option<bool>, once: bool, indexes: &[&RetypeIndex], tolerance: f64) -> Vec<Vec<GlyphMatch>> {
|
||||
let find = |p: &BezPath, part: bool, near: bool| candidates(indexes, p, part, near, fill, tolerance);
|
||||
// Parts that all match exactly are checked at tolerance 0, in the near phase as in the exact
|
||||
// one; only a part that matches nearly brings the tolerance in. The glyphs of a split may
|
||||
// become separate objects: when the shape does not paint its overlaps as several objects
|
||||
// would (translucent, another blend, a gradient or pattern fill, a stroke), its parts must not
|
||||
// overlap, which the parts read by the even-odd rule against them all joined show.
|
||||
let together = |runs: &[BezPath], near: bool| {
|
||||
if fill.is_none() && once {
|
||||
return true;
|
||||
}
|
||||
let nearly = near && runs.iter().any(|r| find(r, true, false).is_empty());
|
||||
let tol = if nearly { tolerance } else { 0.0 };
|
||||
fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(path, runs, nz, tol))
|
||||
&& (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol))
|
||||
};
|
||||
parts(path, groups, &find, &together)
|
||||
}
|
||||
|
||||
/// Each of `pieces`' parts, as [`shape_parts`] finds them in `indexes`: none for a piece that
|
||||
/// keeps its outline or matches nothing. `groups` holds each piece's contour groups.
|
||||
fn match_pieces(pieces: &[Piece], groups: &[Vec<BezPath>], indexes: &[&RetypeIndex], tolerance: f64) -> Vec<Vec<Vec<GlyphMatch>>> {
|
||||
pieces
|
||||
.iter()
|
||||
.zip(groups)
|
||||
.map(|(pc, g)| {
|
||||
if pc.keeps_outline {
|
||||
return vec![];
|
||||
}
|
||||
shape_parts(&pc.path, g, pc.filled.then_some(pc.nonzero), paints_once(pc.opacity, pc.blend, &pc.appearance), indexes, tolerance)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "type.retype";
|
||||
let fonts: Vec<String> = match p.get("fonts") {
|
||||
None => vec![],
|
||||
Some(Value::Array(a)) => {
|
||||
a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect::<Result<_>>()?
|
||||
}
|
||||
Some(_) => return Err(bad(C, "fonts must be a list of family names")),
|
||||
};
|
||||
let tolerance = match p.get("tolerance") {
|
||||
None => 0.0,
|
||||
Some(v) => match v.as_f64() {
|
||||
Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => t,
|
||||
_ => return Err(bad(C, "tolerance must be a number from 0 to 0.05")),
|
||||
},
|
||||
};
|
||||
let fonts = fonts_param(p)?;
|
||||
let tolerance = tolerance_param(p)?;
|
||||
let search_installed = installed::wanted(C, p)?;
|
||||
let handed = installed::handed(s);
|
||||
let roots = selected_roots(s)?;
|
||||
let db = FontDb::global();
|
||||
let system_layout = s.doc()?.doc.setup.system_layout;
|
||||
let (lines, unmatched, truncated) = {
|
||||
let (lines, unmatched, truncated, installed) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let mut pieces = vec![];
|
||||
let mut truncated = false;
|
||||
@@ -1725,52 +1817,69 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (wanted, near_wanted) =
|
||||
lookup_keys(pieces.iter().zip(&groups).filter(|(pc, _)| !pc.keeps_outline).map(|(pc, g)| (&pc.path, g.as_slice())), tolerance);
|
||||
// Nothing to match (every shape stays an outline): no font is read.
|
||||
let index = if wanted.is_empty() && near_wanted.is_empty() {
|
||||
RetypeIndex::default()
|
||||
} else {
|
||||
RetypeIndex::build_near(db, candidate_faces(db, d, &fonts), &wanted, &near_wanted)
|
||||
let keyed = !(wanted.is_empty() && near_wanted.is_empty());
|
||||
let cands = if keyed { candidate_faces(db, d, &fonts) } else { vec![] };
|
||||
let mut compared: Vec<u32> = cands.iter().map(|f| f.id()).collect();
|
||||
let build = |faces: Vec<Arc<vectorcraft_text::FontFace>>| {
|
||||
if keyed { RetypeIndex::build_near(db, faces, &wanted, &near_wanted) } else { RetypeIndex::default() }
|
||||
};
|
||||
// Exact matches first; near ones, when allowed, only for a path with none.
|
||||
// With a visible fill, a glyph is kept only when it paints the area the shape paints under
|
||||
// the shape's fill rule (`fill` is `Some(nonzero)`).
|
||||
let find = |path: &BezPath, part: bool, near: bool, fill: Option<bool>| {
|
||||
let painted = |ms: Vec<GlyphMatch>, tol: f64| -> Vec<GlyphMatch> {
|
||||
match fill {
|
||||
Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(),
|
||||
None => ms,
|
||||
}
|
||||
};
|
||||
let exact = painted(if part { index.matches_either_way(path) } else { index.all_matches(path) }, 0.0);
|
||||
if exact.is_empty() && near { painted(index.near_matches(path, tolerance), tolerance) } else { exact }
|
||||
};
|
||||
// Each shape's parts (one, unless it holds several glyphs), each with its candidates.
|
||||
let found: Vec<Vec<Vec<GlyphMatch>>> = pieces
|
||||
.iter()
|
||||
.zip(&groups)
|
||||
.map(|(pc, g)| {
|
||||
if pc.keeps_outline {
|
||||
return vec![];
|
||||
}
|
||||
let fill = pc.filled.then_some(pc.nonzero);
|
||||
// Parts that all match exactly are checked at tolerance 0, in the near phase as in
|
||||
// the exact one; only a part that matches nearly brings the tolerance in.
|
||||
// The glyphs of a split may become separate objects: when the shape does not paint
|
||||
// its overlaps as several objects would (translucent, another blend, a gradient or
|
||||
// pattern fill, a stroke), its parts must not overlap, which the parts read by the
|
||||
// even-odd rule against them all joined show.
|
||||
let once = paints_once(pc.opacity, pc.blend, &pc.appearance);
|
||||
let together = |runs: &[BezPath], near: bool| {
|
||||
if fill.is_none() && once {
|
||||
return true;
|
||||
}
|
||||
let nearly = near && runs.iter().any(|r| find(r, true, false, fill).is_empty());
|
||||
let tol = if nearly { tolerance } else { 0.0 };
|
||||
fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, tol))
|
||||
&& (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol))
|
||||
let index = build(cands.clone());
|
||||
// Exact matches first; near ones, when allowed, only for a path with none. With a visible
|
||||
// fill, a glyph is kept only when it paints the area the shape paints under the shape's
|
||||
// fill rule. Each shape's parts (one, unless it holds several glyphs), each with its
|
||||
// candidates.
|
||||
let mut found = match_pieces(&pieces, &groups, &[&index], tolerance);
|
||||
// Shapes no face matched are compared with the other loaded faces, then with the installed
|
||||
// fonts not loaded yet; or with what a search made off the UI thread found for them.
|
||||
let left = left_shapes(&pieces, &groups, &found);
|
||||
// A split shape's glyphs may be spread over the candidates and the other faces. Near
|
||||
// matching spends an index's comparison budget, so with a tolerance the candidates are
|
||||
// indexed again for each search that has a split shape to look for.
|
||||
let again = |needed: bool| (needed && tolerance > 0.0).then(|| build(cands.clone()));
|
||||
let (more, installed) = match handed {
|
||||
Some(handed) => {
|
||||
let mut more = handed.faces.clone();
|
||||
compared.extend(handed.faces.iter().map(|f| f.id()));
|
||||
// The shapes still left are compared with the loaded faces the search did not
|
||||
// compare: none, unless a face was loaded after it looked.
|
||||
compared.extend(handed.scanned.iter().copied());
|
||||
let fresh = again(left.iter().any(|s| !s.groups.is_empty()));
|
||||
more.extend(installed::loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?.0);
|
||||
(more, handed)
|
||||
}
|
||||
None => {
|
||||
let fresh = again(left.iter().any(|s| !s.groups.is_empty()));
|
||||
let (mut more, done, kept) = installed::loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?;
|
||||
let left: Vec<installed::Sought> = left.into_iter().zip(done).filter(|(_, done)| !done).map(|(s, _)| s).collect();
|
||||
let installed = if search_installed {
|
||||
let fresh = again(left.iter().any(|s| !s.groups.is_empty()));
|
||||
let kept: Vec<RetypeIndex> = if tolerance > 0.0 { kept.iter().map(|ix| build(ix.faces().to_vec())).collect() } else { kept };
|
||||
let beside: Vec<&RetypeIndex> = std::iter::once(fresh.as_ref().unwrap_or(&index)).chain(&kept).collect();
|
||||
installed::search_beside(db, &left, &beside, tolerance, false)?
|
||||
} else {
|
||||
installed::Installed::default()
|
||||
};
|
||||
parts(&pc.path, g, &|p, part, near| find(p, part, near, fill), &together)
|
||||
})
|
||||
.collect();
|
||||
more.extend(installed.faces.iter().cloned());
|
||||
(more, installed)
|
||||
}
|
||||
};
|
||||
// The faces found join the candidates, the way the loaded ones are matched (near matches
|
||||
// and split shapes included), and every shape is matched again with them all, so a shape
|
||||
// that matched already can take the face its neighbors found.
|
||||
let mut extra: Vec<Arc<vectorcraft_text::FontFace>> = vec![];
|
||||
for f in more {
|
||||
if !cands.iter().chain(&extra).any(|k| k.id() == f.id()) {
|
||||
extra.push(f);
|
||||
}
|
||||
}
|
||||
if !extra.is_empty() {
|
||||
// Near matching spends an index's comparison budget, so with a tolerance the
|
||||
// candidates are indexed again for this pass.
|
||||
let first = if tolerance > 0.0 { build(cands) } else { index };
|
||||
let others: Vec<RetypeIndex> = extra.chunks(vectorcraft_text::retype::MAX_FACES).map(|g| build(g.to_vec())).collect();
|
||||
let all: Vec<&RetypeIndex> = std::iter::once(&first).chain(&others).collect();
|
||||
found = match_pieces(&pieces, &groups, &all, tolerance);
|
||||
}
|
||||
// The face most shapes match, so a glyph several fonts share is set in the same font as
|
||||
// the glyphs around it. Among faces that as many shapes match, the one whose glyphs fit
|
||||
// them closest in all (the least leftover distance summed over those shapes), so every
|
||||
@@ -1916,7 +2025,7 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room
|
||||
// for small blocks.
|
||||
let mut budget = lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add).saturating_mul(24).saturating_add(256);
|
||||
(blocks(lines, follows, system_layout, &mut budget), unmatched, truncated)
|
||||
(blocks(lines, follows, system_layout, &mut budget), unmatched, truncated, installed)
|
||||
};
|
||||
if lines.is_empty() {
|
||||
return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len())));
|
||||
@@ -2050,9 +2159,27 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.collect::<Vec<_>>(),
|
||||
"unmatched": unmatched.iter().map(|i| i.0).collect::<Vec<_>>(),
|
||||
"truncated": truncated,
|
||||
"installed": installed.json(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// The shapes of `pieces` that may become type and that `found` holds no part for, each with its
|
||||
/// contour groups from `groups`.
|
||||
fn left_shapes<'a>(pieces: &'a [Piece], groups: &'a [Vec<BezPath>], found: &[Vec<Vec<GlyphMatch>>]) -> Vec<installed::Sought<'a>> {
|
||||
pieces
|
||||
.iter()
|
||||
.zip(groups)
|
||||
.zip(found)
|
||||
.filter(|((pc, _), parts)| !pc.keeps_outline && parts.is_empty())
|
||||
.map(|((pc, g), _)| installed::Sought {
|
||||
path: &pc.path,
|
||||
groups: g,
|
||||
fill: pc.filled.then_some(pc.nonzero),
|
||||
once: paints_once(pc.opacity, pc.blend, &pc.appearance),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "retype_tests.rs"]
|
||||
mod tests;
|
||||
@@ -3,22 +3,25 @@
|
||||
//! (<https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html>,
|
||||
//! <https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html>).
|
||||
//! The panel lists ten fonts and five more on request. Each selected glyph shape is compared with
|
||||
//! the glyphs of up to 96 loaded fonts, those of the document's live type first, by the same
|
||||
//! matching as `type.retype` (exact matches only). Of two versions of one font, only the version its
|
||||
//! the glyphs of up to 96 loaded fonts, those of the document's live type first, and of the
|
||||
//! installed fonts not loaded yet (`retype_installed.rs`), by the same matching as `type.retype`
|
||||
//! (exact matches only). Of two versions of one font, only the version its
|
||||
//! family and style name gives is compared. The order is VectorCraft's own: a font ranks by how many
|
||||
//! of the shapes it matches, then by how closely, on average, and then by name. The query changes
|
||||
//! nothing.
|
||||
//! of the shapes it matches, then by how closely, on average, and then by name. The query does not
|
||||
//! change the document; the installed fonts that match are loaded.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::BezPath;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_text::FontDb;
|
||||
use vectorcraft_doc::Document;
|
||||
use vectorcraft_text::retype::{RetypeIndex, shape_key};
|
||||
use vectorcraft_text::{FontDb, FontFace};
|
||||
|
||||
use super::super::edit::selected_roots;
|
||||
use super::super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selected_path};
|
||||
use super::{candidate_faces, collect};
|
||||
use super::super::{CommandSpec, Result, Session, bad, cmd, has_selected_path};
|
||||
use super::installed::Installed;
|
||||
use super::{candidate_faces, selected_pieces};
|
||||
|
||||
pub(in crate::cmd) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
@@ -26,7 +29,7 @@ pub(in crate::cmd) fn specs() -> Vec<CommandSpec> {
|
||||
"Find Matching Fonts",
|
||||
[],
|
||||
None,
|
||||
"{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed; of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error",
|
||||
"{count?: 1..96 (default 10), installed?: bool} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed, and, unless installed is false (true, omitted or null: compared), with the installed fonts not loaded yet, within type.retype's limits on reading them (every file within them is read, and the fonts that match are loaded while the list holds fewer than 96 fonts, loaded ones included); of two versions of a font, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out), installed: {read, skipped} (as type.retype reports them)}; a count that is not a whole number from 1 to 96, or an installed that is not true, false or null, is an error",
|
||||
has_selected_path,
|
||||
retype_fonts
|
||||
)]
|
||||
@@ -38,7 +41,7 @@ pub(super) const DEFAULT_COUNT: usize = 10;
|
||||
pub(super) const MAX_COUNT: usize = vectorcraft_text::retype::MAX_FACES;
|
||||
|
||||
/// One font that matched some of the shapes.
|
||||
struct Ranked {
|
||||
pub(super) struct Ranked {
|
||||
face: Arc<vectorcraft_text::FontFace>,
|
||||
/// How many shapes it matched.
|
||||
matched: usize,
|
||||
@@ -49,62 +52,99 @@ struct Ranked {
|
||||
}
|
||||
|
||||
impl Ranked {
|
||||
/// The font.
|
||||
pub(super) fn face(&self) -> &Arc<FontFace> {
|
||||
&self.face
|
||||
}
|
||||
|
||||
fn mean(&self) -> f64 {
|
||||
self.residual / self.matched.max(1) as f64
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn retype_fonts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
retype_fonts_in(s, p, FontDb::global())
|
||||
}
|
||||
|
||||
/// [`retype_fonts`] with the fonts of `db`.
|
||||
fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
|
||||
const C: &str = "type.retypeFonts";
|
||||
let count = match p.get("count") {
|
||||
None | Some(Value::Null) => DEFAULT_COUNT,
|
||||
/// The `count` param: how many fonts to list.
|
||||
pub(super) fn count_param(p: &Value) -> Result<usize> {
|
||||
match p.get("count") {
|
||||
None | Some(Value::Null) => Ok(DEFAULT_COUNT),
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.and_then(|n| usize::try_from(n).ok())
|
||||
.filter(|n| (1..=MAX_COUNT).contains(n))
|
||||
.ok_or_else(|| bad(C, "`count` must be a whole number from 1 to 96"))?,
|
||||
};
|
||||
let roots = selected_roots(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let mut pieces = vec![];
|
||||
let (mut barrier, mut truncated) = (true, false);
|
||||
for r in &roots {
|
||||
if let Some(n) = d.node(*r) {
|
||||
collect(n, d.parent_of(*r), 0, &mut barrier, &mut truncated, &mut pieces);
|
||||
}
|
||||
.ok_or_else(|| bad("type.retypeFonts", "`count` must be a whole number from 1 to 96")),
|
||||
}
|
||||
if pieces.is_empty() {
|
||||
return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into()));
|
||||
}
|
||||
// Only glyphs with a selected shape's key (segments per contour) can match one.
|
||||
let wanted: BTreeSet<u64> = pieces.iter().filter_map(|pc| shape_key(&pc.path)).collect();
|
||||
// A font is chosen by its family and style, which set the version the name gives: of two
|
||||
// versions of one font, only that one is compared. The other versions do not take the places
|
||||
// of fonts loaded after them.
|
||||
let by_name = |f: &Arc<vectorcraft_text::FontFace>| db.face(&f.family, &f.style).is_some_and(|g| g.id() == f.id());
|
||||
let mut faces: Vec<_> = candidate_faces(db, d, &[]).into_iter().filter(by_name).collect();
|
||||
}
|
||||
|
||||
/// Is `f` the version of its font that its family and style name gives? A font is chosen by its
|
||||
/// family and style, which set that version: of two versions of one font, only that one is
|
||||
/// compared, and the other versions do not take the places of fonts loaded after them.
|
||||
fn by_name(db: &FontDb, f: &FontFace) -> bool {
|
||||
db.face(&f.family, &f.style).is_some_and(|g| g.id() == f.id())
|
||||
}
|
||||
|
||||
/// The loaded faces the list compares: those of the document's live type first, then the other
|
||||
/// loaded faces, each the version its name gives, at most [`MAX_COUNT`].
|
||||
pub(super) fn listed_faces(db: &FontDb, d: &Document) -> Vec<Arc<FontFace>> {
|
||||
let mut faces: Vec<_> = candidate_faces(db, d, &[]).into_iter().filter(|f| by_name(db, f)).collect();
|
||||
for f in db.loaded_faces() {
|
||||
if faces.len() >= vectorcraft_text::retype::MAX_FACES {
|
||||
if faces.len() >= MAX_COUNT {
|
||||
break;
|
||||
}
|
||||
if by_name(&f) && !faces.iter().any(|k| k.id() == f.id()) {
|
||||
if by_name(db, &f) && !faces.iter().any(|k| k.id() == f.id()) {
|
||||
faces.push(f);
|
||||
}
|
||||
}
|
||||
faces
|
||||
}
|
||||
|
||||
/// The fonts of `faces` whose glyphs match `shapes`, unranked, and with `search_installed` those of
|
||||
/// the installed fonts not loaded yet, for the places left of [`MAX_COUNT`] (loading the ones that
|
||||
/// match), with what that search read. With `handed` (what a search made off the UI thread found,
|
||||
/// [`super::installed::RetypeFound`]) its faces are ranked instead, and the installed fonts are not
|
||||
/// read again.
|
||||
pub(super) fn rank_fonts(
|
||||
db: &FontDb,
|
||||
faces: Vec<Arc<FontFace>>,
|
||||
shapes: &[&BezPath],
|
||||
search_installed: bool,
|
||||
handed: Option<Installed>,
|
||||
) -> Result<(Vec<Ranked>, Installed)> {
|
||||
// Only glyphs with a selected shape's key (segments per contour) can match one.
|
||||
let wanted: BTreeSet<u64> = shapes.iter().filter_map(|s| shape_key(s)).collect();
|
||||
// No shape has a key: no font is read.
|
||||
let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, faces, &wanted) };
|
||||
// A shape's paint does not change which glyph it is: shapes that would stay outlines count too.
|
||||
let mut ranked: Vec<Ranked> = vec![];
|
||||
for pc in &pieces {
|
||||
rank(&index, shapes, &mut ranked);
|
||||
// The installed fonts not loaded yet: those whose glyphs match a shape, of the version their
|
||||
// family and style name gives, up to 96 fonts listed in all. A font that matches only as
|
||||
// combining marks is not listed, so it takes no place.
|
||||
let room = MAX_COUNT.saturating_sub(ranked.iter().filter(|r| r.character).count());
|
||||
let found = if let Some(handed) = handed {
|
||||
handed
|
||||
} else if !search_installed {
|
||||
Installed::default()
|
||||
} else if room == 0 {
|
||||
// The list is full: the installed faces a search would compare count as skipped, none
|
||||
// when no shape would start one.
|
||||
let skipped = if super::installed::starts_search(shapes) { db.unloaded_installed_faces().len() } else { 0 };
|
||||
Installed { skipped, ..Default::default() }
|
||||
} else {
|
||||
super::installed::search_listed(db, shapes, room, &|f| by_name(db, f))?
|
||||
};
|
||||
// A face found earlier (handed in) may be loaded and ranked already: it counts once.
|
||||
let more: Vec<_> = found.faces.iter().filter(|f| !ranked.iter().any(|r| r.face.id() == f.id())).cloned().collect();
|
||||
if !more.is_empty() {
|
||||
rank(&RetypeIndex::build(db, more, &wanted), shapes, &mut ranked);
|
||||
}
|
||||
Ok((ranked, found))
|
||||
}
|
||||
|
||||
/// Adds to `ranked` the fonts of `index` that match `shapes`.
|
||||
fn rank(index: &RetypeIndex, shapes: &[&BezPath], ranked: &mut Vec<Ranked>) {
|
||||
for shape in shapes {
|
||||
// A shape can fit several glyphs or poses of one font: it counts once for the font, at its
|
||||
// closest fit.
|
||||
let mut best: Vec<(Arc<vectorcraft_text::FontFace>, f64, bool)> = vec![];
|
||||
for m in index.all_matches(&pc.path) {
|
||||
let mut best: Vec<(Arc<FontFace>, f64, bool)> = vec![];
|
||||
for m in index.all_matches(shape) {
|
||||
let character = !vectorcraft_text::retype::is_combining_mark(m.ch);
|
||||
match best.iter_mut().find(|(f, _, _)| f.id() == m.face.id()) {
|
||||
Some(b) => {
|
||||
@@ -125,6 +165,23 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn retype_fonts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
retype_fonts_in(s, p, FontDb::global())
|
||||
}
|
||||
|
||||
/// [`retype_fonts`] with the fonts of `db`.
|
||||
fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
|
||||
const C: &str = "type.retypeFonts";
|
||||
let count = count_param(p)?;
|
||||
let search_installed = super::installed::wanted(C, p)?;
|
||||
let handed = super::installed::handed(s);
|
||||
let (pieces, truncated) = selected_pieces(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// A shape's paint does not change which glyph it is: shapes that would stay outlines count too.
|
||||
let shapes: Vec<&BezPath> = pieces.iter().map(|pc| &pc.path).collect();
|
||||
let (mut ranked, found) = rank_fonts(db, listed_faces(db, d), &shapes, search_installed, handed)?;
|
||||
// A font whose glyphs match the shapes only as combining marks would retype none of them, as
|
||||
// type.retype starts no line with a mark: it is not listed.
|
||||
ranked.retain(|r| r.character);
|
||||
@@ -143,6 +200,7 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
|
||||
"shapes": pieces.len(),
|
||||
"more": more,
|
||||
"truncated": truncated,
|
||||
"installed": found.json(),
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -99,7 +99,7 @@ fn shapes_that_are_no_glyph_list_no_font() {
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
|
||||
let r = query(&mut s, json!({}), bundled());
|
||||
assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false}));
|
||||
assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false, "installed": {"read": 0, "skipped": 0}}));
|
||||
// Live type alone holds no shape to compare.
|
||||
let t = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "live"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [t]})).unwrap();
|
||||
@@ -113,7 +113,7 @@ fn a_font_that_matches_only_combining_marks_is_not_listed() {
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = query(&mut s, json!({}), bundled());
|
||||
assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false}));
|
||||
assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false, "installed": {"read": 0, "skipped": 0}}));
|
||||
// After a base, the mark counts with it.
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
@@ -161,6 +161,64 @@ fn of_two_versions_only_the_one_the_name_gives_is_listed() {
|
||||
assert_eq!(names(&r).iter().filter(|f| f.0 == FAMILY).count(), 1, "version 1 matches and is listed once: {r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_fonts_not_loaded_are_ranked_too_unless_left_out() {
|
||||
use vectorcraft_text::test_fonts::named_copy;
|
||||
let dir = vectorcraft_testkit::temp_dir("retype-fonts-installed");
|
||||
let file = dir.join("RetypeListed-Regular.ttf");
|
||||
std::fs::write(&file, named_copy(true, ("Retype Listed", "Regular", "Version 1.000", "RetypeListed-Regular")).unwrap()).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![dir]);
|
||||
let mut s = session();
|
||||
let inter = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Kgw", "size": 40, "font": "Inter", "style": "Regular"}));
|
||||
s.execute("select.set", &json!({"ids": [inter]})).unwrap();
|
||||
// Left out: the installed copy is not read, and stays unloaded.
|
||||
let r = query(&mut s, json!({"count": 96, "installed": false}), &db);
|
||||
assert!(!names(&r).iter().any(|f| f.0 == "Retype Listed"), "{r}");
|
||||
assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}");
|
||||
assert!(db.unloaded_installed_faces().iter().any(|f| f.family == "Retype Listed"));
|
||||
// Compared: the copy of Inter matches every shape, as Inter does, and is loaded.
|
||||
let r = query(&mut s, json!({"count": 96}), &db);
|
||||
let fonts = names(&r);
|
||||
assert!(fonts.contains(&("Retype Listed".to_string(), "Regular".to_string(), 3)), "{r}");
|
||||
assert!(fonts.contains(&("Inter".to_string(), "Regular".to_string(), 3)), "{r}");
|
||||
assert_eq!(r["installed"], json!({"read": 1, "skipped": 0}), "{r}");
|
||||
assert!(!db.unloaded_installed_faces().iter().any(|f| f.family == "Retype Listed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_fonts_fill_the_list_up_to_96_fonts_in_all() {
|
||||
use vectorcraft_text::test_fonts::named_copy;
|
||||
let copy = |family: &str| {
|
||||
let postscript = format!("{}-Regular", family.replace(' ', ""));
|
||||
(named_copy(false, (family, "Regular", "Version 1.000", &postscript)).unwrap(), postscript)
|
||||
};
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rg", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
// Loaded copies that match fill most of the list.
|
||||
let loaded = FontDb::with_font_dirs(vec![]);
|
||||
for i in 0..super::MAX_COUNT {
|
||||
loaded.add_font(copy(&format!("Fullcopy {i:02}")).0);
|
||||
}
|
||||
let listed = names(&query(&mut s, json!({"count": 96, "installed": false}), &loaded)).len();
|
||||
assert!(listed < super::MAX_COUNT, "{listed}");
|
||||
// Installed copies, two more than the places left.
|
||||
let dir = vectorcraft_testkit::temp_dir("retype-fonts-installed-full");
|
||||
for i in 0..super::MAX_COUNT - listed + 2 {
|
||||
let (data, postscript) = copy(&format!("Installed {i:02}"));
|
||||
std::fs::write(dir.join(format!("{postscript}.ttf")), data).unwrap();
|
||||
}
|
||||
let db = FontDb::with_font_dirs(vec![dir]);
|
||||
for i in 0..super::MAX_COUNT {
|
||||
db.add_font(copy(&format!("Fullcopy {i:02}")).0);
|
||||
}
|
||||
let r = query(&mut s, json!({"count": 96}), &db);
|
||||
assert_eq!(names(&r).len(), super::MAX_COUNT, "the installed copies fill the places left: {r}");
|
||||
assert_eq!(r["more"], json!(false), "no font past the list is found: {r}");
|
||||
assert_eq!(r["installed"]["skipped"], json!(2), "{r}");
|
||||
assert_eq!(db.unloaded_installed_faces().len(), 2, "the two past the list stay unloaded");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shapes_that_stay_outlines_still_name_their_font() {
|
||||
// A glyph with paint type cannot take (two fills) is not retyped, but it is still that font's glyph.
|
||||
|
||||
@@ -0,0 +1,773 @@
|
||||
//! Retype's installed fonts: the faces of installed fonts that nothing has loaded yet are
|
||||
//! candidates too, as the fonts on the device are among the sources Retype suggests fonts from
|
||||
//! (<https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html>).
|
||||
//! Each font file is read for the search and let go; a face whose glyphs match a shape is loaded
|
||||
//! as it was read, without the family's other files. Files are read smallest first, within a budget
|
||||
//! of bytes read and glyphs drawn, and the search stops between files when it is canceled. The app
|
||||
//! runs it off the UI thread ([`RetypeRun`]), with a Cancel. A face read is matched as a loaded one
|
||||
//! is: with Retype's tolerance, near matches count, and a compound path of several glyphs counts
|
||||
//! when every glyph it splits into matches, in one face or in several.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::BezPath;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, NodeId};
|
||||
use vectorcraft_text::retype::{MAX_FACES, NearKey, RetypeIndex, encoded_glyphs, is_plain, shape_key};
|
||||
use vectorcraft_text::{FontDb, FontFace};
|
||||
|
||||
use super::super::{EngineError, Result, Session, bad};
|
||||
|
||||
/// How much one search reads.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Limits {
|
||||
/// Font files (a suitcase font's resource fork) longer than this are not read.
|
||||
file: u64,
|
||||
/// The bytes of font files read, in all.
|
||||
read: u64,
|
||||
/// The glyphs of installed faces drawn, in all, to tell which can match a shape.
|
||||
glyphs: usize,
|
||||
/// The faces found: the faces after the last one found are not compared.
|
||||
faces: usize,
|
||||
}
|
||||
|
||||
const LIMITS: Limits = Limits { file: 256 << 20, read: 2 << 30, glyphs: 500_000, faces: MAX_FACES };
|
||||
|
||||
/// The `installed` param: whether to look in the installed fonts (default true).
|
||||
pub(super) fn wanted(cmd: &str, p: &Value) -> Result<bool> {
|
||||
match p.get("installed") {
|
||||
None | Some(Value::Null) => Ok(true),
|
||||
Some(Value::Bool(b)) => Ok(*b),
|
||||
Some(_) => Err(bad(cmd, "`installed` must be true, false or null")),
|
||||
}
|
||||
}
|
||||
|
||||
/// What a search of the installed fonts found and read.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Installed {
|
||||
/// The faces whose glyphs match a shape, loaded now, in the order they were read.
|
||||
pub(super) faces: Vec<Arc<FontFace>>,
|
||||
/// Faces read and compared.
|
||||
pub(super) read: usize,
|
||||
/// Faces left out by the limits ([`LIMITS`]).
|
||||
pub(super) skipped: usize,
|
||||
/// For a search made away from its command, the ids of the loaded faces it compared: the
|
||||
/// command does not compare them again.
|
||||
pub(super) scanned: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Installed {
|
||||
/// As a command's result reports it.
|
||||
pub(super) fn json(&self) -> Value {
|
||||
json!({"read": self.read, "skipped": self.skipped})
|
||||
}
|
||||
}
|
||||
|
||||
/// A shape to look for: its path, the contour groups it splits into when it may hold several
|
||||
/// glyphs (none for a shape matched whole only), its fill rule when it has a visible fill
|
||||
/// (`Some(nonzero)`) and whether it paints its overlaps once ([`super::paints_once`]), as
|
||||
/// `type.retype` reads them.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Sought<'a> {
|
||||
pub(super) path: &'a BezPath,
|
||||
pub(super) groups: &'a [BezPath],
|
||||
pub(super) fill: Option<bool>,
|
||||
pub(super) once: bool,
|
||||
}
|
||||
|
||||
impl<'a> Sought<'a> {
|
||||
/// `path` split into `groups`, with no paint check.
|
||||
pub(super) fn unpainted(path: &'a BezPath, groups: &'a [BezPath]) -> Self {
|
||||
Sought { path, groups, fill: None, once: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// `shapes`, each matched whole only.
|
||||
fn whole<'a>(shapes: &[&'a BezPath]) -> Vec<Sought<'a>> {
|
||||
shapes.iter().map(|path| Sought::unpainted(path, &[])).collect()
|
||||
}
|
||||
|
||||
/// The keys to look glyphs up by for `shapes`, at `tolerance` ([`super::lookup_keys`]).
|
||||
fn keys_of(shapes: &[Sought], tolerance: f64) -> (BTreeSet<u64>, Vec<NearKey>) {
|
||||
super::lookup_keys(shapes.iter().map(|s| (s.path, s.groups)), tolerance)
|
||||
}
|
||||
|
||||
/// Does a search look for `s`: is it not plain ([`is_plain`]: a rectangle, a triangle or a bar),
|
||||
/// with a key to look glyphs up by? A shape without one matches no face.
|
||||
fn starts(s: &Sought, tolerance: f64) -> bool {
|
||||
if is_plain(s.path) {
|
||||
return false;
|
||||
}
|
||||
let (keys, near) = keys_of(std::slice::from_ref(s), tolerance);
|
||||
!keys.is_empty() || !near.is_empty()
|
||||
}
|
||||
|
||||
/// Is `s` found in `indexes` at `tolerance`: does its whole shape match a glyph there, or does
|
||||
/// every glyph it splits into, painting the area `s` paints ([`super::shape_parts`])?
|
||||
fn found_in(indexes: &[&RetypeIndex], s: &Sought, tolerance: f64) -> bool {
|
||||
!super::shape_parts(s.path, s.groups, s.fill, s.once, indexes, tolerance).is_empty()
|
||||
}
|
||||
|
||||
/// [`search_for`] of `shapes` matched whole, exactly.
|
||||
#[cfg(test)]
|
||||
pub(super) fn search(db: &FontDb, shapes: &[&BezPath], every: bool) -> Result<Installed> {
|
||||
search_within(db, shapes, every, LIMITS, &|_| true)
|
||||
}
|
||||
|
||||
/// [`search_beside`] with no loaded faces.
|
||||
#[cfg(test)]
|
||||
pub(super) fn search_for(db: &FontDb, shapes: &[Sought], tolerance: f64, every: bool) -> Result<Installed> {
|
||||
search_beside(db, shapes, &[], tolerance, every)
|
||||
}
|
||||
|
||||
/// The installed faces nothing has loaded that `shapes` that are not plain ([`is_plain`]) are found
|
||||
/// in at `tolerance` ([`found_in`]), each loaded into `db` as it was read. With `every` false, a
|
||||
/// face is found when it matches such a shape, or completes the glyphs of a split one with the
|
||||
/// loaded faces of `loaded` (the indexes of faces the command compares too) and the faces found or
|
||||
/// read before it (a face read before whose glyphs it completes is found with it), and the search
|
||||
/// stops once each such shape is found; with it, every face within the limits ([`LIMITS`]) is
|
||||
/// compared, and found when it matches a shape on its own. No file is read when every shape is
|
||||
/// plain. At most [`MAX_FACES`] faces are found; the faces not compared past that count as skipped.
|
||||
/// The faces of `loaded` whose glyphs complete a split shape with a face found are among the faces
|
||||
/// found too, so the command compares them with it.
|
||||
pub(super) fn search_beside(db: &FontDb, shapes: &[Sought], loaded: &[&RetypeIndex], tolerance: f64, every: bool) -> Result<Installed> {
|
||||
search_sought(db, shapes, loaded, tolerance, every, LIMITS, &|_| true)
|
||||
}
|
||||
|
||||
/// [`search`] comparing every face within the limits, for a list of at most `faces` faces: a face
|
||||
/// found that `listed` turns down is loaded and not listed, and takes no place of the `faces`.
|
||||
pub(super) fn search_listed(db: &FontDb, shapes: &[&BezPath], faces: usize, listed: &dyn Fn(&FontFace) -> bool) -> Result<Installed> {
|
||||
search_sought(db, &whole(shapes), &[], 0.0, true, Limits { faces: faces.min(MAX_FACES), ..LIMITS }, listed)
|
||||
}
|
||||
|
||||
/// Would a search for `shapes`, matched whole and exactly, read any installed file: is one of them
|
||||
/// not plain, with a glyph's key ([`shape_key`])?
|
||||
pub(super) fn starts_search(shapes: &[&BezPath]) -> bool {
|
||||
shapes.iter().any(|s| !is_plain(s) && shape_key(s).is_some())
|
||||
}
|
||||
|
||||
/// [`loaded_rest_for`] of `shapes` matched whole, exactly: the faces only.
|
||||
#[cfg(test)]
|
||||
pub(super) fn loaded_rest(db: &FontDb, shapes: &[&BezPath], compared: &[u32]) -> Result<Vec<Arc<FontFace>>> {
|
||||
Ok(loaded_rest_for(db, &whole(shapes), &[], 0.0, compared)?.0)
|
||||
}
|
||||
|
||||
/// The loaded faces that are not among `compared` (those past the [`MAX_FACES`] a Retype compares
|
||||
/// first) that one of `shapes` that is not plain ([`is_plain`]) is found in at `tolerance`
|
||||
/// ([`found_in`]), indexed [`MAX_FACES`] at a time: the faces of the glyphs it matches. The glyphs of
|
||||
/// a split shape may be spread over those groups and the faces of `beside` (the indexes of faces
|
||||
/// among `compared`). With them, whether each shape was found, and the indexes of the latest
|
||||
/// groups that hold glyphs of the shapes while a split shape is not found (at most
|
||||
/// [`MAX_KEPT_GROUPS`]), for the search of the installed fonts. A cancel stops it between those
|
||||
/// groups.
|
||||
pub(super) fn loaded_rest_for(db: &FontDb, shapes: &[Sought], beside: &[&RetypeIndex], tolerance: f64, compared: &[u32]) -> Result<LoadedRest> {
|
||||
let mut done = vec![false; shapes.len()];
|
||||
let looked: Vec<(usize, &Sought)> = shapes.iter().enumerate().filter(|(_, s)| !is_plain(s.path)).collect();
|
||||
let (keys, near) = super::lookup_keys(looked.iter().map(|(_, s)| (s.path, s.groups)), tolerance);
|
||||
let mut out: Vec<Arc<FontFace>> = vec![];
|
||||
if keys.is_empty() && near.is_empty() {
|
||||
return Ok((out, done, vec![]));
|
||||
}
|
||||
let rest: Vec<Arc<FontFace>> = db.loaded_faces().into_iter().filter(|f| !compared.contains(&f.id())).collect();
|
||||
// The earlier groups' indexes that hold glyphs of the shapes, while a split shape is not found
|
||||
// yet: the latest [`MAX_KEPT_GROUPS`].
|
||||
let mut kept: Vec<RetypeIndex> = vec![];
|
||||
for group in rest.chunks(MAX_FACES) {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
let index = RetypeIndex::build_near(db, group.iter().cloned(), &keys, &near);
|
||||
let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&kept).chain(std::iter::once(&index)).collect();
|
||||
for (k, s) in &looked {
|
||||
// A split shape not found yet is matched with the faces before the group too (one pass,
|
||||
// as near matching spends an index's budget); any other shape with the group alone.
|
||||
let combined = !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true);
|
||||
let indexes: &[&RetypeIndex] = if combined { &with } else { &[&index] };
|
||||
let parts = super::shape_parts(s.path, s.groups, s.fill, s.once, indexes, tolerance);
|
||||
if parts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(d) = done.get_mut(*k) {
|
||||
*d = true;
|
||||
}
|
||||
for m in parts.into_iter().flatten() {
|
||||
if !compared.contains(&m.face.id()) && !out.iter().any(|f| f.id() == m.face.id()) {
|
||||
out.push(m.face);
|
||||
}
|
||||
}
|
||||
}
|
||||
let open = looked.iter().any(|(k, s)| !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true));
|
||||
if open && !index.is_empty() {
|
||||
// The latest groups are kept: the oldest goes when the cap is reached.
|
||||
if kept.len() >= MAX_KEPT_GROUPS {
|
||||
kept.remove(0);
|
||||
}
|
||||
kept.push(index);
|
||||
}
|
||||
}
|
||||
if !looked.iter().any(|(k, s)| !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true)) {
|
||||
kept.clear();
|
||||
}
|
||||
Ok((out, done, kept))
|
||||
}
|
||||
|
||||
/// What [`loaded_rest_for`] finds: the faces, whether each shape was found, and the indexes kept
|
||||
/// for the search of the installed fonts.
|
||||
type LoadedRest = (Vec<Arc<FontFace>>, Vec<bool>, Vec<RetypeIndex>);
|
||||
|
||||
/// Earlier groups of [`MAX_FACES`] loaded faces past the ones compared first that a group's faces
|
||||
/// complete a split shape's glyphs with, at most: the latest ones.
|
||||
const MAX_KEPT_GROUPS: usize = 4;
|
||||
|
||||
/// An installed font file: its path, its length and the (family, style) of the faces wanted from it.
|
||||
type File = (std::path::PathBuf, u64, Vec<(String, String)>);
|
||||
|
||||
/// [`search`] within `limits`, keeping in its faces only those `listed` accepts.
|
||||
#[cfg(test)]
|
||||
fn search_within(db: &FontDb, shapes: &[&BezPath], every: bool, limits: Limits, listed: &dyn Fn(&FontFace) -> bool) -> Result<Installed> {
|
||||
search_sought(db, &whole(shapes), &[], 0.0, every, limits, listed)
|
||||
}
|
||||
|
||||
/// [`search_beside`] within `limits`, keeping in its faces only those `listed` accepts.
|
||||
fn search_sought(
|
||||
db: &FontDb,
|
||||
shapes: &[Sought],
|
||||
beside: &[&RetypeIndex],
|
||||
tolerance: f64,
|
||||
every: bool,
|
||||
limits: Limits,
|
||||
listed: &dyn Fn(&FontFace) -> bool,
|
||||
) -> Result<Installed> {
|
||||
let mut out = Installed::default();
|
||||
// A shape without a glyph's key matches no face: the search does not wait for it.
|
||||
let shapes: Vec<Sought> = shapes.iter().copied().filter(|s| starts(s, tolerance)).collect();
|
||||
let (keys, near) = keys_of(&shapes, tolerance);
|
||||
if keys.is_empty() && near.is_empty() {
|
||||
return Ok(out);
|
||||
}
|
||||
let (keys, near) = (&keys, near.as_slice());
|
||||
// The indexes of the faces found, which the glyphs of a split shape may be spread over.
|
||||
let mut found: Vec<RetypeIndex> = vec![];
|
||||
// The faces read, not loaded, that hold glyphs of the shapes without completing one, with their
|
||||
// indexes: a later face may complete a split shape with them. The latest [`MAX_FACES`].
|
||||
let mut partial: Vec<(Arc<FontFace>, RetypeIndex)> = vec![];
|
||||
// The faces wanted from each file, smallest file first.
|
||||
let mut files: Vec<File> = vec![];
|
||||
let mut at: std::collections::HashMap<std::path::PathBuf, usize> = std::collections::HashMap::new();
|
||||
for f in db.unloaded_installed_faces() {
|
||||
match at.get(&f.path).and_then(|i| files.get_mut(*i)) {
|
||||
Some(file) => file.2.push((f.family, f.style)),
|
||||
None => {
|
||||
at.insert(f.path.clone(), files.len());
|
||||
files.push((f.path, f.len, vec![(f.family, f.style)]));
|
||||
}
|
||||
}
|
||||
}
|
||||
files.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0)));
|
||||
let mut matched = vec![false; shapes.len()];
|
||||
// Is a split shape not found yet: only then are faces kept in `partial`.
|
||||
let open = |matched: &[bool]| shapes.iter().zip(matched).any(|(s, m)| !*m && !s.groups.is_empty());
|
||||
let (mut bytes_left, mut glyphs_left) = (limits.read, limits.glyphs);
|
||||
let total = files.len() as u64;
|
||||
for (i, (path, len, styles)) in files.iter().enumerate() {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
vectorcraft_doc::cancel::progress(i as u64, total, "Retype: reading installed fonts");
|
||||
// A file too long for what is left, or read when no glyph is left to draw, is not read.
|
||||
if *len > limits.file || *len > bytes_left || glyphs_left == 0 {
|
||||
out.skipped += styles.len();
|
||||
continue;
|
||||
}
|
||||
// A file that grew since the scan is read only within what is left.
|
||||
let file = db.read_unloaded_file(path, limits.file.min(bytes_left));
|
||||
// The bytes read, those of a file that grew past the limits too.
|
||||
bytes_left = bytes_left.saturating_sub(file.bytes);
|
||||
if file.too_long {
|
||||
out.skipped += styles.len();
|
||||
continue;
|
||||
}
|
||||
let wanted = |f: &FontFace| styles.iter().any(|(family, style)| f.family.eq_ignore_ascii_case(family) && f.style.eq_ignore_ascii_case(style));
|
||||
let faces: Vec<Arc<FontFace>> = file.faces.into_iter().filter(|f| wanted(f)).collect();
|
||||
for (j, face) in faces.iter().enumerate() {
|
||||
if out.faces.len() >= limits.faces {
|
||||
// The faces not compared past the cap: the rest of this file's and the later files'.
|
||||
out.skipped += styles.len().saturating_sub(j) + files.iter().skip(i + 1).map(|f| f.2.len()).sum::<usize>();
|
||||
return Ok(out);
|
||||
}
|
||||
let n = encoded_glyphs(face);
|
||||
if n > glyphs_left {
|
||||
out.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
glyphs_left -= n;
|
||||
out.read += 1;
|
||||
let index = RetypeIndex::build_unloaded_near(db, face.clone(), keys, near);
|
||||
if index.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// With `every`, a face fits a shape it matches on its own; otherwise a shape not found
|
||||
// yet that it completes with the loaded faces of `beside`, the faces found before it and
|
||||
// the faces read before it that hold some of its glyphs (`partial`).
|
||||
let parts: Vec<&RetypeIndex> = partial.iter().map(|(_, ix)| ix).collect();
|
||||
let parts_with = |extra: &[&RetypeIndex], ix: &RetypeIndex, k: usize| -> Vec<Vec<super::GlyphMatch>> {
|
||||
let Some(s) = shapes.get(k) else { return vec![] };
|
||||
if every {
|
||||
return super::shape_parts(s.path, s.groups, s.fill, s.once, &[ix], tolerance);
|
||||
}
|
||||
if matched.get(k).copied().unwrap_or(true) {
|
||||
return vec![];
|
||||
}
|
||||
// A shape matched whole only takes one glyph: the faces read before it do not hold it.
|
||||
let extra = if s.groups.is_empty() { &[] } else { extra };
|
||||
let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&found).chain(extra.iter().copied()).chain(std::iter::once(ix)).collect();
|
||||
super::shape_parts(s.path, s.groups, s.fill, s.once, &with, tolerance)
|
||||
};
|
||||
let fit_with = |extra: &[&RetypeIndex], ix: &RetypeIndex, k: usize| !parts_with(extra, ix, k).is_empty();
|
||||
let fit = |ix: &RetypeIndex, k: usize| fit_with(&parts, ix, k);
|
||||
// Each shape it fits, with the glyphs it matches: one pass, as near matching spends an
|
||||
// index's budget.
|
||||
let first: Vec<(usize, Vec<Vec<super::GlyphMatch>>)> =
|
||||
(0..shapes.len()).map(|k| (k, parts_with(&parts, &index, k))).filter(|(_, p)| !p.is_empty()).collect();
|
||||
let fits: Vec<usize> = first.iter().map(|(k, _)| *k).collect();
|
||||
if fits.is_empty() {
|
||||
// The face holds glyphs of a shape without completing one: a later face may, while
|
||||
// a split shape is not found. The latest are kept: the oldest goes when the cap is
|
||||
// reached.
|
||||
if !every && open(&matched) {
|
||||
#[cfg(test)]
|
||||
KEPT_PARTIAL.with(|n| n.set(n.get() + 1));
|
||||
if partial.len() >= MAX_FACES {
|
||||
partial.remove(0);
|
||||
}
|
||||
partial.push((face.clone(), index));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let loaded = load(db, face);
|
||||
let same = loaded.id() == face.id();
|
||||
let (mut fits, index) = still_fit(db, face, &loaded, index, keys, near, fits, &fit);
|
||||
if fits.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// The faces read before whose glyphs the shapes it fits use, loaded with it: those
|
||||
// that leave room under the cap, or else only the shapes it fits without them. A face
|
||||
// loaded in place of the one read is matched again for them.
|
||||
let matches: Vec<Vec<super::GlyphMatch>> = if same {
|
||||
first.into_iter().flat_map(|(_, p)| p).collect()
|
||||
} else {
|
||||
fits.iter().flat_map(|k| parts_with(&parts, &index, *k)).collect()
|
||||
};
|
||||
let held: Vec<&Arc<FontFace>> = index.faces().iter().chain(found.iter().flat_map(|ix| ix.faces())).chain(&out.faces).collect();
|
||||
let (mut used, mut with_loaded) = companions(&matches, &held, beside, &partial);
|
||||
if out.faces.len() + used.len() + with_loaded.len() >= limits.faces {
|
||||
let alone: Vec<&RetypeIndex> = found.iter().chain(std::iter::once(&index)).collect();
|
||||
fits.retain(|k| shapes.get(*k).is_some_and(|s| found_in(&alone, s, tolerance)));
|
||||
used.clear();
|
||||
with_loaded.clear();
|
||||
if fits.is_empty() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let mut shadowed = false;
|
||||
let mut promoted: Vec<Arc<FontFace>> = vec![];
|
||||
for at in used.into_iter().rev() {
|
||||
let (read, ix) = partial.remove(at);
|
||||
let loaded = load(db, &read);
|
||||
let ix = if loaded.id() == read.id() {
|
||||
ix
|
||||
} else {
|
||||
shadowed = true;
|
||||
RetypeIndex::build_near(db, [loaded.clone()], keys, near)
|
||||
};
|
||||
promoted.insert(0, loaded);
|
||||
found.push(ix);
|
||||
}
|
||||
// A face loaded in place of one read may have other glyphs: the shapes are checked again.
|
||||
if shadowed {
|
||||
let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&found).chain(std::iter::once(&index)).collect();
|
||||
fits.retain(|k| shapes.get(*k).is_some_and(|s| found_in(&with, s, tolerance)));
|
||||
if fits.is_empty() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// The faces it completes shapes with, once the match holds.
|
||||
out.faces.extend(with_loaded);
|
||||
for loaded in promoted {
|
||||
if listed(&loaded) {
|
||||
remember(db, &loaded);
|
||||
if !out.faces.iter().any(|f| f.id() == loaded.id()) {
|
||||
out.faces.push(loaded);
|
||||
}
|
||||
}
|
||||
}
|
||||
// A face `listed` turns down (another version shadows it) is not compared ahead of others.
|
||||
if listed(&loaded) {
|
||||
remember(db, &loaded);
|
||||
if !out.faces.iter().any(|f| f.id() == loaded.id()) {
|
||||
out.faces.push(loaded);
|
||||
}
|
||||
}
|
||||
found.push(index);
|
||||
for k in fits {
|
||||
if let Some(m) = matched.get_mut(k) {
|
||||
*m = true;
|
||||
}
|
||||
}
|
||||
if !every && matched.iter().all(|m| *m) {
|
||||
return Ok(out);
|
||||
}
|
||||
// With every split shape found, the faces kept for them are dropped.
|
||||
if !open(&matched) {
|
||||
partial.clear();
|
||||
}
|
||||
}
|
||||
// The cap reached with the file's last face: the later files are not compared.
|
||||
if out.faces.len() >= limits.faces {
|
||||
out.skipped += files.iter().skip(i + 1).map(|f| f.2.len()).sum::<usize>();
|
||||
return Ok(out);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times a search on this thread kept a face it read in `partial`.
|
||||
static KEPT_PARTIAL: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// For each of `parts` (each part's candidates) that none of the faces of `held` has a glyph of,
|
||||
/// one face that does: a loaded face of `beside` (the command compares it with the face found),
|
||||
/// or else a face of `partial`, read before. The places in `partial` of those, in order, and the
|
||||
/// loaded faces.
|
||||
fn companions(
|
||||
parts: &[Vec<super::GlyphMatch>],
|
||||
held: &[&Arc<FontFace>],
|
||||
beside: &[&RetypeIndex],
|
||||
partial: &[(Arc<FontFace>, RetypeIndex)],
|
||||
) -> (Vec<usize>, Vec<Arc<FontFace>>) {
|
||||
let (mut used, mut loaded) = (BTreeSet::new(), Vec::<Arc<FontFace>>::new());
|
||||
for part in parts {
|
||||
let has = |f: &Arc<FontFace>| part.iter().any(|m| m.face.id() == f.id());
|
||||
let chosen = used.iter().filter_map(|at: &usize| partial.get(*at).map(|(f, _)| f));
|
||||
if held.iter().copied().chain(&loaded).chain(chosen).any(has) {
|
||||
continue;
|
||||
}
|
||||
let of_beside = part.iter().find(|m| beside.iter().any(|ix| ix.faces().iter().any(|f| f.id() == m.face.id())));
|
||||
if let Some(m) = of_beside {
|
||||
loaded.push(m.face.clone());
|
||||
} else if let Some(at) = part.iter().find_map(|m| partial.iter().position(|(f, _)| Arc::ptr_eq(f, &m.face))) {
|
||||
used.insert(at);
|
||||
}
|
||||
}
|
||||
(used.into_iter().collect(), loaded)
|
||||
}
|
||||
|
||||
/// The faces searches loaded from installed files, by database ([`FontDb::id`]) and face id, the
|
||||
/// latest first: at most [`MAX_FACES`].
|
||||
static FOUND: std::sync::Mutex<Vec<(u64, u32)>> = std::sync::Mutex::new(Vec::new());
|
||||
|
||||
/// Keep `face`, which a search loaded into `db`, among [`found`]'s faces.
|
||||
fn remember(db: &FontDb, face: &FontFace) {
|
||||
let mut kept = FOUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let at = (db.id(), face.id());
|
||||
kept.retain(|k| *k != at);
|
||||
kept.insert(0, at);
|
||||
kept.truncate(MAX_FACES);
|
||||
}
|
||||
|
||||
/// The faces of `db` that searches of the installed fonts found and loaded, the latest first. A
|
||||
/// later Retype compares them ahead of the other loaded faces.
|
||||
pub(super) fn found(db: &FontDb) -> Vec<Arc<FontFace>> {
|
||||
let kept = FOUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
|
||||
kept.into_iter().filter(|(d, _)| *d == db.id()).filter_map(|(_, id)| db.face_by_id(id)).collect()
|
||||
}
|
||||
|
||||
/// Of `fits` (the shapes `index`, the index of `read`, fits as `fit` tells), those that `loaded`,
|
||||
/// the face loading `read` gave, fits too, with the index they fit in: all of them and `index`
|
||||
/// when it is `read` itself. Another face of the same family, style and version, loaded from
|
||||
/// another file, may have other glyphs; it is indexed by `keys` and `near`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn still_fit(
|
||||
db: &FontDb,
|
||||
read: &FontFace,
|
||||
loaded: &Arc<FontFace>,
|
||||
index: RetypeIndex,
|
||||
keys: &BTreeSet<u64>,
|
||||
near: &[NearKey],
|
||||
fits: Vec<usize>,
|
||||
fit: &dyn Fn(&RetypeIndex, usize) -> bool,
|
||||
) -> (Vec<usize>, RetypeIndex) {
|
||||
if loaded.id() == read.id() {
|
||||
return (fits, index);
|
||||
}
|
||||
let index = RetypeIndex::build_near(db, [loaded.clone()], keys, near);
|
||||
let fits = fits.into_iter().filter(|k| fit(&index, *k)).collect();
|
||||
(fits, index)
|
||||
}
|
||||
|
||||
/// `face` (read from an installed file and not loaded) loaded into `db` as it was read
|
||||
/// ([`FontDb::load_read_face`]): neither its file nor the family's other files are read again.
|
||||
fn load(db: &FontDb, face: &Arc<FontFace>) -> Arc<FontFace> {
|
||||
db.load_read_face(face.clone())
|
||||
}
|
||||
|
||||
/// A search of the installed fonts made away from its command, so the app can run it off the UI
|
||||
/// thread with a Cancel. [`RetypeRun::prepare`] takes the selected shapes and the document from the
|
||||
/// session, checking the params as the command checks them; [`RetypeSearch::run`] picks the loaded
|
||||
/// faces to compare, compares them and searches the installed fonts on any thread, loading the
|
||||
/// faces that match; and
|
||||
/// [`RetypeFound::hand_in`] gives what it found to the command, which then runs with
|
||||
/// [`RetypeRun::params`] and compares those faces as its own search would, without reading the
|
||||
/// installed fonts again.
|
||||
pub struct RetypeRun {
|
||||
params: Value,
|
||||
/// The document ([`crate::DocState::uid`]), its content and the selection the search is for.
|
||||
doc: u64,
|
||||
content: Arc<Document>,
|
||||
selection: Vec<NodeId>,
|
||||
search: Arc<RetypeSearch>,
|
||||
}
|
||||
|
||||
/// What a [`RetypeRun`] compares and searches, without the session: it can be sent to another
|
||||
/// thread ([`RetypeRun::search`]).
|
||||
pub struct RetypeSearch {
|
||||
command: &'static str,
|
||||
/// The document it is for ([`crate::DocState::uid`]).
|
||||
doc: u64,
|
||||
/// The shapes to match, and the loaded faces they are compared with first.
|
||||
shapes: Vec<Shape>,
|
||||
faces: Faces,
|
||||
/// `type.retype`'s tolerance (0 for `type.retypeFonts`).
|
||||
tolerance: f64,
|
||||
}
|
||||
|
||||
/// The loaded faces a [`RetypeSearch`] compares first.
|
||||
enum Faces {
|
||||
/// These faces.
|
||||
#[cfg(test)]
|
||||
Given(Vec<Arc<FontFace>>),
|
||||
/// Those the command picks in `doc`: with `fonts` (`type.retype`'s `fonts` param), the faces of
|
||||
/// those families and of the document's live type ([`super::candidate_faces`]), and without, the
|
||||
/// faces `type.retypeFonts` lists ([`super::fonts::listed_faces`]). They are picked on the
|
||||
/// search's thread, since a family not loaded yet is read from its files.
|
||||
Of { doc: Arc<Document>, fonts: Option<Vec<String>> },
|
||||
}
|
||||
|
||||
impl Faces {
|
||||
fn get(&self, db: &FontDb) -> Vec<Arc<FontFace>> {
|
||||
match self {
|
||||
#[cfg(test)]
|
||||
Faces::Given(faces) => faces.clone(),
|
||||
Faces::Of { doc, fonts: Some(fonts) } => super::candidate_faces(db, doc, fonts),
|
||||
Faces::Of { doc, fonts: None } => super::fonts::listed_faces(db, doc),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A shape a [`RetypeSearch`] compares, as `type.retype` matches it ([`super::shape_parts`]): its
|
||||
/// path, its contour groups when it may hold several glyphs, its fill rule when it has a visible
|
||||
/// fill (`Some(nonzero)`), and whether it paints its overlaps once ([`super::paints_once`]).
|
||||
struct Shape {
|
||||
path: BezPath,
|
||||
groups: Vec<BezPath>,
|
||||
fill: Option<bool>,
|
||||
once: bool,
|
||||
}
|
||||
|
||||
impl Shape {
|
||||
/// `path`, matched whole, with no paint check.
|
||||
fn whole(path: BezPath) -> Self {
|
||||
Shape { path, groups: vec![], fill: None, once: true }
|
||||
}
|
||||
|
||||
fn sought(&self) -> Sought<'_> {
|
||||
Sought { path: &self.path, groups: &self.groups, fill: self.fill, once: self.once }
|
||||
}
|
||||
}
|
||||
|
||||
/// What a [`RetypeSearch`] found: for `type.retype`, the faces it compared first that match, the
|
||||
/// loaded faces past those that match ([`loaded_rest`]), the installed faces whose glyphs match,
|
||||
/// loaded, and the loaded faces it compared; and what it read of the installed fonts.
|
||||
pub struct RetypeFound {
|
||||
doc: u64,
|
||||
installed: Installed,
|
||||
}
|
||||
|
||||
impl RetypeFound {
|
||||
/// Hand it to the next `type.retype` or `type.retypeFonts`, which compares the faces found as
|
||||
/// its own search of the installed fonts would, in the document the search was made for. Any
|
||||
/// such command takes it; one in another document compares only what is loaded.
|
||||
pub fn hand_in(self, s: &mut Session) {
|
||||
s.retype_hand_off = Some(self);
|
||||
}
|
||||
|
||||
/// Drop what was handed in and no command took, as when the command failed before it took
|
||||
/// it: a later command searches for itself.
|
||||
pub fn drop_handed(s: &mut Session) {
|
||||
s.retype_hand_off = None;
|
||||
}
|
||||
|
||||
/// What it read, as the commands report it.
|
||||
pub fn json(&self) -> Value {
|
||||
self.installed.json()
|
||||
}
|
||||
}
|
||||
|
||||
/// What a search found for the active document of `s`, handed in for this command ([`RetypeFound`]).
|
||||
/// It is taken whatever the document, so it is used once.
|
||||
pub(super) fn handed(s: &mut Session) -> Option<Installed> {
|
||||
let found = s.retype_hand_off.take()?;
|
||||
let doc = s.doc().ok()?.uid;
|
||||
(found.doc == doc).then_some(found.installed)
|
||||
}
|
||||
|
||||
impl RetypeRun {
|
||||
/// The search `command` (`type.retype` or `type.retypeFonts`) with params `p` makes in the
|
||||
/// active document. None when it reads no installed font: `installed` is false, or no shape
|
||||
/// starts a search ([`starts`]: each is plain or has no glyph's key). An error where the command fails on its params or on the selection.
|
||||
/// The faces to compare are picked when the search runs.
|
||||
pub fn prepare(s: &Session, command: &str, p: &Value) -> Result<Option<RetypeRun>> {
|
||||
let (command, fonts, tolerance) = match command {
|
||||
"type.retype" => ("type.retype", Some(super::fonts_param(p)?), super::tolerance_param(p)?),
|
||||
"type.retypeFonts" => {
|
||||
super::fonts::count_param(p)?;
|
||||
("type.retypeFonts", None, 0.0)
|
||||
}
|
||||
other => return Err(EngineError::Other(format!("`{other}` doesn't search the installed fonts"))),
|
||||
};
|
||||
// The keys the command refuses (an unknown one) fail here too, before any search.
|
||||
s.check_params(command, p)?;
|
||||
if !wanted(command, p)? {
|
||||
return Ok(None);
|
||||
}
|
||||
let (pieces, _) = super::selected_pieces(s)?;
|
||||
let st = s.doc()?;
|
||||
// Retype compares the shapes that may become type, split as it splits them; the list
|
||||
// compares every shape whole.
|
||||
let shapes: Vec<Shape> = if fonts.is_some() {
|
||||
let mut budget = super::MAX_SPLIT_TOTAL_CONTOURS;
|
||||
pieces
|
||||
.into_iter()
|
||||
.filter(|pc| !pc.keeps_outline)
|
||||
.map(|pc| Shape {
|
||||
groups: super::split_groups(&pc.path, &mut budget),
|
||||
fill: pc.filled.then_some(pc.nonzero),
|
||||
once: super::paints_once(pc.opacity, pc.blend, &pc.appearance),
|
||||
path: pc.path,
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
pieces.into_iter().map(|pc| Shape::whole(pc.path)).collect()
|
||||
};
|
||||
if !shapes.iter().any(|s| starts(&s.sought(), tolerance)) {
|
||||
return Ok(None);
|
||||
}
|
||||
let faces = Faces::Of { doc: st.doc.clone(), fonts };
|
||||
Ok(Some(RetypeRun {
|
||||
params: p.clone(),
|
||||
doc: st.uid,
|
||||
content: st.doc.clone(),
|
||||
selection: st.selection.objects.clone(),
|
||||
search: Arc::new(RetypeSearch { command, doc: st.uid, shapes, faces, tolerance }),
|
||||
}))
|
||||
}
|
||||
|
||||
/// `type.retype` or `type.retypeFonts`.
|
||||
pub fn command(&self) -> &'static str {
|
||||
self.search.command
|
||||
}
|
||||
|
||||
/// What it compares and searches, for another thread.
|
||||
pub fn search(&self) -> Arc<RetypeSearch> {
|
||||
self.search.clone()
|
||||
}
|
||||
|
||||
/// The command's params: those it was prepared with.
|
||||
pub fn params(&self) -> &Value {
|
||||
&self.params
|
||||
}
|
||||
|
||||
/// Does it still apply: is the document it was prepared in active, with the same content and
|
||||
/// the same objects selected?
|
||||
pub fn current(&self, s: &Session) -> bool {
|
||||
s.doc().is_ok_and(|st| st.uid == self.doc && Arc::ptr_eq(&st.doc, &self.content) && st.selection.objects == self.selection)
|
||||
}
|
||||
|
||||
/// [`RetypeSearch::run`] with the fonts of `db`.
|
||||
#[cfg(test)]
|
||||
fn run_in(&self, db: &FontDb) -> Result<RetypeFound> {
|
||||
self.search.run_in(db)
|
||||
}
|
||||
}
|
||||
|
||||
impl RetypeSearch {
|
||||
/// Compare the shapes with the loaded faces, then search the installed fonts as the command
|
||||
/// would, loading the faces that match → what it found ([`EngineError::Cancelled`] when a
|
||||
/// cancel stopped it). It touches no document, so it can run on any thread.
|
||||
pub fn run(&self) -> Result<RetypeFound> {
|
||||
self.run_in(FontDb::global())
|
||||
}
|
||||
|
||||
/// [`RetypeSearch::run`] with the fonts of `db`.
|
||||
fn run_in(&self, db: &FontDb) -> Result<RetypeFound> {
|
||||
let picked = self.faces.get(db);
|
||||
let installed = if self.command == "type.retypeFonts" {
|
||||
let shapes: Vec<&BezPath> = self.shapes.iter().map(|s| &s.path).collect();
|
||||
let (ranked, mut found) = super::fonts::rank_fonts(db, picked, &shapes, true, None)?;
|
||||
// The loaded faces that match are handed in too, ahead of the installed ones found:
|
||||
// loading those can move a loaded face past the 96 the command lists.
|
||||
let mut faces: Vec<Arc<FontFace>> = ranked.iter().map(|r| r.face().clone()).collect();
|
||||
for f in std::mem::take(&mut found.faces) {
|
||||
if !faces.iter().any(|k| k.id() == f.id()) {
|
||||
faces.push(f);
|
||||
}
|
||||
}
|
||||
found.faces = faces;
|
||||
found
|
||||
} else {
|
||||
// The shapes are matched as the command matches them first.
|
||||
let tolerance = self.tolerance;
|
||||
let sought: Vec<Sought> = self.shapes.iter().map(Shape::sought).collect();
|
||||
let (keys, near) = keys_of(&sought, tolerance);
|
||||
let index = RetypeIndex::build_near(db, picked.iter().cloned(), &keys, &near);
|
||||
let parts: Vec<Vec<Vec<super::GlyphMatch>>> =
|
||||
self.shapes.iter().map(|s| super::shape_parts(&s.path, &s.groups, s.fill, s.once, &[&index], tolerance)).collect();
|
||||
let left: Vec<Sought> = sought.iter().zip(&parts).filter(|(_, p)| p.is_empty()).map(|(s, _)| *s).collect();
|
||||
// The first faces that match are handed in too: loading the faces found can move one
|
||||
// past the first 96 the command compares.
|
||||
let mut first: Vec<Arc<FontFace>> = vec![];
|
||||
for m in parts.into_iter().flatten().flatten() {
|
||||
if !first.iter().any(|f| f.id() == m.face.id()) {
|
||||
first.push(m.face);
|
||||
}
|
||||
}
|
||||
// The loaded faces past the ones compared first, then the installed fonts for what
|
||||
// none of them matches; the command takes both from what is handed in.
|
||||
let compared: Vec<u32> = picked.iter().map(|f| f.id()).collect();
|
||||
// Every face loaded now is compared, among the first ones or with the rest.
|
||||
let scanned: Vec<u32> = compared.iter().copied().chain(db.loaded_faces().iter().map(|f| f.id())).collect();
|
||||
// A split shape's glyphs may be spread over the faces compared first and the others.
|
||||
// Near matching spends an index's comparison budget, so with a tolerance the faces
|
||||
// compared first are indexed again for each search that has a split shape to look for.
|
||||
let again = |needed: bool| (needed && tolerance > 0.0).then(|| RetypeIndex::build_near(db, picked.iter().cloned(), &keys, &near));
|
||||
let fresh = again(left.iter().any(|s| !s.groups.is_empty()));
|
||||
let (rest, done, kept) = loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?;
|
||||
let left: Vec<Sought> = left.into_iter().zip(done).filter(|(_, done)| !done).map(|(s, _)| s).collect();
|
||||
let fresh = again(left.iter().any(|s| !s.groups.is_empty()));
|
||||
let kept: Vec<RetypeIndex> = if tolerance > 0.0 {
|
||||
kept.iter().map(|ix| RetypeIndex::build_near(db, ix.faces().iter().cloned(), &keys, &near)).collect()
|
||||
} else {
|
||||
kept
|
||||
};
|
||||
let beside: Vec<&RetypeIndex> = std::iter::once(fresh.as_ref().unwrap_or(&index)).chain(&kept).collect();
|
||||
let mut found = search_beside(db, &left, &beside, tolerance, false)?;
|
||||
found.faces.splice(0..0, first.into_iter().chain(rest));
|
||||
found.scanned = scanned;
|
||||
found
|
||||
};
|
||||
Ok(RetypeFound { doc: self.doc, installed })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "retype_installed_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,833 @@
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use kurbo::{Affine, BezPath, Shape};
|
||||
use serde_json::json;
|
||||
use vectorcraft_text::FontDb;
|
||||
use vectorcraft_text::retype::shape_key;
|
||||
|
||||
use super::{Limits, search, search_within};
|
||||
use crate::Session;
|
||||
|
||||
/// A database whose installed fonts are copies of the bundled Source Sans 3 Regular named
|
||||
/// `families`, one file each, in a folder of their own: they are installed and not loaded.
|
||||
/// Returns the database and the files.
|
||||
fn installed(tag: &str, families: &[&str]) -> (FontDb, Vec<PathBuf>) {
|
||||
let dir = vectorcraft_testkit::temp_dir(&format!("retype-installed-{tag}"));
|
||||
let mut files = vec![];
|
||||
for family in families {
|
||||
let postscript = format!("{}-Regular", family.replace(' ', ""));
|
||||
let data = vectorcraft_text::test_fonts::named_copy(false, (family, "Regular", "Version 1.000", &postscript)).unwrap();
|
||||
let path = dir.join(format!("{postscript}.ttf"));
|
||||
std::fs::write(&path, data).unwrap();
|
||||
files.push(path);
|
||||
}
|
||||
(FontDb::with_font_dirs(vec![dir]), files)
|
||||
}
|
||||
|
||||
/// The glyphs of `text` in the bundled Source Sans 3 Regular, as outlines at 30 pt.
|
||||
fn glyphs(db: &FontDb, text: &str) -> Vec<BezPath> {
|
||||
let face = db.face("Source Sans 3", "Regular").unwrap();
|
||||
text.chars()
|
||||
.enumerate()
|
||||
.map(|(i, c)| Affine::translate((40.0 + 30.0 * i as f64, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for(c)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn keys(shapes: &[BezPath]) -> BTreeSet<u64> {
|
||||
shapes.iter().filter_map(shape_key).collect()
|
||||
}
|
||||
|
||||
/// `paths` as a search compares them, each matched whole.
|
||||
fn whole(paths: Vec<BezPath>) -> Vec<super::Shape> {
|
||||
paths.into_iter().map(super::Shape::whole).collect()
|
||||
}
|
||||
|
||||
fn unloaded(db: &FontDb, family: &str) -> bool {
|
||||
db.unloaded_installed_faces().iter().any(|f| f.family == family)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_installed_face_whose_glyphs_match_is_found_and_loaded() {
|
||||
let (db, files) = installed("found", &["Retype Copy A"]);
|
||||
assert!(unloaded(&db, "Retype Copy A"));
|
||||
let shapes = glyphs(&db, "Rx");
|
||||
let refs: Vec<&BezPath> = shapes.iter().collect();
|
||||
let found = search(&db, &refs, false).unwrap();
|
||||
assert_eq!((found.read, found.skipped), (1, 0));
|
||||
let face = found.faces.first().expect("the installed copy matches");
|
||||
assert_eq!((face.family.as_str(), face.style.as_str()), ("Retype Copy A", "Regular"));
|
||||
assert_eq!(face.path(), Some(files[0].as_path()));
|
||||
// Loaded now, as it was read.
|
||||
assert!(db.loaded_faces().iter().any(|f| f.id() == face.id()));
|
||||
assert!(!unloaded(&db, "Retype Copy A"));
|
||||
assert_eq!(found.json(), json!({"read": 1, "skipped": 0}));
|
||||
// A later Retype compares it ahead of the other loaded faces, however many are loaded.
|
||||
assert_eq!(super::found(&db).first().map(|f| f.id()), Some(face.id()));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let candidates = super::super::candidate_faces(&db, &s.doc().unwrap().doc, &[]);
|
||||
assert_eq!(candidates.first().map(|f| f.id()), Some(face.id()));
|
||||
// Only this database's faces.
|
||||
assert!(super::found(&FontDb::with_font_dirs(vec![])).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_matching_face_loads_without_the_family_s_other_files() {
|
||||
let dir = vectorcraft_testkit::temp_dir("retype-installed-family");
|
||||
for style in ["Regular", "Bold"] {
|
||||
let data =
|
||||
vectorcraft_text::test_fonts::named_copy(false, ("Retype Copy N", style, "Version 1.000", &format!("RetypeCopyN-{style}"))).unwrap();
|
||||
std::fs::write(dir.join(format!("RetypeCopyN-{style}.ttf")), data).unwrap();
|
||||
}
|
||||
let db = FontDb::with_font_dirs(vec![dir]);
|
||||
let shapes = glyphs(&db, "Rx");
|
||||
let refs: Vec<&BezPath> = shapes.iter().collect();
|
||||
let found = search(&db, &refs, false).unwrap();
|
||||
assert_eq!((found.read, found.faces.len()), (1, 1));
|
||||
let style = found.faces[0].style.clone();
|
||||
let loaded: Vec<String> = db.loaded_faces().iter().filter(|f| f.family == "Retype Copy N").map(|f| f.style.clone()).collect();
|
||||
assert_eq!(loaded, std::slice::from_ref(&style), "only the face that matched is loaded");
|
||||
let left: Vec<String> = db.unloaded_installed_faces().into_iter().filter(|f| f.family == "Retype Copy N").map(|f| f.style).collect();
|
||||
assert_eq!(left.len(), 1);
|
||||
assert_ne!(left[0], style);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_loaded_face_of_the_same_names_counts_only_for_the_shapes_it_matches() {
|
||||
use vectorcraft_text::test_fonts::named_copy;
|
||||
let names = ("Retype Twin", "Regular", "Version 1.000", "RetypeTwin-Regular");
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
// Inter's glyphs, loaded under the names a file of Source Sans 3's glyphs has too.
|
||||
db.add_font(named_copy(true, names).unwrap());
|
||||
let dir = vectorcraft_testkit::temp_dir("retype-installed-twin");
|
||||
let path = dir.join("RetypeTwin-Regular.ttf");
|
||||
std::fs::write(&path, named_copy(false, names).unwrap()).unwrap();
|
||||
let read = db.read_unloaded_file(&path, u64::MAX).faces.into_iter().next().unwrap();
|
||||
let shapes = glyphs(&db, "Rx");
|
||||
let refs: Vec<&BezPath> = shapes.iter().collect();
|
||||
let keys = keys(&shapes);
|
||||
let loaded = super::load(&db, &read);
|
||||
assert_ne!(loaded.id(), read.id(), "the face loaded first is kept");
|
||||
let fit = |ix: &super::super::RetypeIndex, k: usize| !ix.matches(refs[k]).is_empty();
|
||||
let index = || super::super::RetypeIndex::build_unloaded(&db, read.clone(), &keys);
|
||||
let (fits, _) = super::still_fit(&db, &read, &loaded, index(), &keys, &[], vec![0, 1], &fit);
|
||||
assert!(fits.is_empty(), "Inter's R and x are not these");
|
||||
let (fits, _) = super::still_fit(&db, &read, &read, index(), &keys, &[], vec![0, 1], &fit);
|
||||
assert_eq!(fits, [0, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_installed_face_no_shape_matches_is_read_and_not_loaded() {
|
||||
let (db, _) = installed("none", &["Retype Copy B"]);
|
||||
let shapes = [kurbo::Circle::new((40.0, 40.0), 20.0).to_path(0.1)];
|
||||
let refs: Vec<&BezPath> = shapes.iter().collect();
|
||||
let found = search(&db, &refs, false).unwrap();
|
||||
assert_eq!((found.read, found.faces.len()), (1, 0));
|
||||
assert!(unloaded(&db, "Retype Copy B"), "a face that matches nothing stays unloaded");
|
||||
// No shape: no file is read.
|
||||
let none = search(&db, &[], false).unwrap();
|
||||
assert_eq!((none.read, none.skipped), (0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_shapes_alone_read_no_installed_font() {
|
||||
// A hyphen is a bar: many fonts have a glyph of its shape, so it tells no font apart.
|
||||
let (db, _) = installed("plain", &["Retype Copy L"]);
|
||||
let mut shapes = glyphs(&db, "-");
|
||||
shapes.push(kurbo::Rect::new(0.0, 0.0, 80.0, 40.0).to_path(0.1));
|
||||
assert!(shapes.iter().all(vectorcraft_text::retype::is_plain));
|
||||
let refs: Vec<&BezPath> = shapes.iter().collect();
|
||||
for every in [false, true] {
|
||||
let found = search(&db, &refs, every).unwrap();
|
||||
assert_eq!((found.read, found.skipped, found.faces.len()), (0, 0, 0));
|
||||
}
|
||||
assert!(unloaded(&db, "Retype Copy L"));
|
||||
// Beside a shape that is not plain, the search reads the file for that shape.
|
||||
shapes.extend(glyphs(&db, "q"));
|
||||
let refs: Vec<&BezPath> = shapes.iter().collect();
|
||||
assert_eq!(search(&db, &refs, false).unwrap().faces.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_without_a_glyph_s_key_does_not_keep_the_search_going() {
|
||||
let (db, _) = installed("keyless", &["Retype Copy Keyless A", "Retype Copy Keyless B"]);
|
||||
let mut shapes = glyphs(&db, "k");
|
||||
// More contours than any glyph's key counts: no face can match it.
|
||||
let mut dots = BezPath::new();
|
||||
for i in 0..49 {
|
||||
dots.extend(kurbo::Circle::new((10.0 * f64::from(i), 300.0), 3.0).path_elements(0.1));
|
||||
}
|
||||
assert!(shape_key(&dots).is_none() && !vectorcraft_text::retype::is_plain(&dots));
|
||||
shapes.push(dots);
|
||||
let refs: Vec<&BezPath> = shapes.iter().collect();
|
||||
let found = search(&db, &refs, false).unwrap();
|
||||
assert_eq!((found.read, found.faces.len()), (1, 1), "the second file is not read");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_search_stops_once_every_shape_matches_unless_every_face_is_wanted() {
|
||||
let (db, _) = installed("every", &["Retype Copy C", "Retype Copy D"]);
|
||||
let shapes = glyphs(&db, "ab");
|
||||
let refs: Vec<&BezPath> = shapes.iter().collect();
|
||||
let first = search(&db, &refs, false).unwrap();
|
||||
assert_eq!((first.read, first.faces.len()), (1, 1), "the second file is not read");
|
||||
let (db, _) = installed("every-all", &["Retype Copy E", "Retype Copy F"]);
|
||||
let all = search(&db, &refs, true).unwrap();
|
||||
assert_eq!((all.read, all.faces.len()), (2, 2));
|
||||
let mut families: Vec<&str> = all.faces.iter().map(|f| f.family.as_str()).collect();
|
||||
families.sort_unstable();
|
||||
assert_eq!(families, ["Retype Copy E", "Retype Copy F"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn faces_read_are_kept_for_split_shapes_only() {
|
||||
let (db, _) = installed("kept-whole", &["Retype Kept Whole A", "Retype Kept Whole B", "Retype Kept Whole C"]);
|
||||
// The k matches in the first file and the circle in none, so every file is read; the later
|
||||
// files hold the k's glyph without completing a shape. With every shape whole, none is kept.
|
||||
let mut shapes = glyphs(&db, "k");
|
||||
shapes.push(kurbo::Circle::new((300.0, 100.0), 7.3).to_path(0.1));
|
||||
assert!(shape_key(&shapes[1]).is_some(), "the circle has a key to look glyphs up by");
|
||||
let refs: Vec<&BezPath> = shapes.iter().collect();
|
||||
super::KEPT_PARTIAL.with(|n| n.set(0));
|
||||
let found = search(&db, &refs, false).unwrap();
|
||||
assert_eq!((found.read, found.faces.len()), (3, 1));
|
||||
assert_eq!(super::KEPT_PARTIAL.with(std::cell::Cell::get), 0, "no face read is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn faces_past_the_limits_are_skipped_and_counted() {
|
||||
let (db, files) = installed("limits", &["Retype Copy G", "Retype Copy H"]);
|
||||
let shapes = glyphs(&db, "k");
|
||||
let refs: Vec<&BezPath> = shapes.iter().collect();
|
||||
let len = files.iter().map(|f| std::fs::metadata(f).unwrap().len()).max().unwrap();
|
||||
// Files longer than the limit for one file.
|
||||
let open = Limits { file: u64::MAX, read: u64::MAX, glyphs: usize::MAX, faces: usize::MAX };
|
||||
let all = |_: &vectorcraft_text::FontFace| true;
|
||||
let small = search_within(&db, &refs, true, Limits { file: len / 2, ..open }, &all).unwrap();
|
||||
assert_eq!((small.read, small.skipped, small.faces.len()), (0, 2, 0));
|
||||
// Bytes for one file only.
|
||||
let one = search_within(&db, &refs, true, Limits { read: len + len / 2, ..open }, &all).unwrap();
|
||||
assert_eq!((one.read, one.skipped, one.faces.len()), (1, 1, 1));
|
||||
// Glyphs for no face.
|
||||
let (db, _) = installed("limits-glyphs", &["Retype Copy I"]);
|
||||
let few = search_within(&db, &refs, true, Limits { glyphs: 10, ..open }, &all).unwrap();
|
||||
assert_eq!((few.read, few.skipped, few.faces.len()), (0, 1, 0));
|
||||
assert!(unloaded(&db, "Retype Copy I"));
|
||||
// Faces found up to the cap: the faces after it are not compared, and count as skipped.
|
||||
let (db, _) = installed("limits-faces", &["Retype Copy O", "Retype Copy P", "Retype Copy Q"]);
|
||||
let capped = search_within(&db, &refs, true, Limits { faces: 1, ..open }, &all).unwrap();
|
||||
assert_eq!((capped.read, capped.skipped, capped.faces.len()), (1, 2, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_grows_past_the_limits_after_the_listing_is_skipped_and_its_bytes_count() {
|
||||
let (db, mut files) = installed("grown", &["Retype Copy Y", "Retype Copy Z"]);
|
||||
let shapes = glyphs(&db, "k");
|
||||
let refs: Vec<&BezPath> = shapes.iter().collect();
|
||||
// The order the search reads them in: smallest first.
|
||||
let len = |p: &PathBuf| std::fs::metadata(p).unwrap().len();
|
||||
files.sort_by(|a, b| len(a).cmp(&len(b)).then_with(|| a.cmp(b)));
|
||||
let (first, second) = (len(&files[0]), len(&files[1]));
|
||||
let grown = files[0].clone();
|
||||
// The first file grows past the limit for one file as its reading starts, after the listing.
|
||||
let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(move |done, _, _| {
|
||||
if done == 0 {
|
||||
let mut data = std::fs::read(&grown).unwrap();
|
||||
data.resize(data.len() + second as usize + 1, 0);
|
||||
std::fs::write(&grown, data).unwrap();
|
||||
}
|
||||
});
|
||||
// Bytes for both files as listed: the grown file's reading takes one more than the limit for
|
||||
// one file, which leaves too little for the second.
|
||||
let limits = Limits { file: second, read: first + second, glyphs: usize::MAX, faces: usize::MAX };
|
||||
let token = vectorcraft_doc::cancel::CancelToken::new();
|
||||
let all = |_: &vectorcraft_text::FontFace| true;
|
||||
let found = vectorcraft_doc::cancel::scope(&token, Some(sink), || search_within(&db, &refs, true, limits, &all)).unwrap();
|
||||
assert_eq!((found.read, found.skipped, found.faces.len()), (0, 2, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_glyph_budget_counts_the_glyphs_drawn() {
|
||||
let (db, files) = installed("glyph-budget", &["Retype Copy Budget"]);
|
||||
let shapes = glyphs(&db, "k");
|
||||
let refs: Vec<&BezPath> = shapes.iter().collect();
|
||||
let face = db.read_unloaded_file(&files[0], u64::MAX).faces.into_iter().next().unwrap();
|
||||
let mapped = face.mapped_chars().len();
|
||||
let drawn = vectorcraft_text::retype::encoded_glyphs(&face);
|
||||
assert!(drawn < mapped, "{drawn} of {mapped}");
|
||||
// A budget below the face's characters and at the glyphs drawn: the face is compared.
|
||||
let open = Limits { file: u64::MAX, read: u64::MAX, glyphs: drawn, faces: usize::MAX };
|
||||
let found = search_within(&db, &refs, true, open, &|_| true).unwrap();
|
||||
assert_eq!((found.read, found.skipped, found.faces.len()), (1, 0, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_away_from_the_list_hands_in_the_loaded_faces_that_match_with_the_installed_ones() {
|
||||
let (db, _) = installed("list-run", &["Retype Copy List"]);
|
||||
db.add_font(
|
||||
vectorcraft_text::test_fonts::named_copy(false, ("Retype Loaded List", "Regular", "Version 1.000", "RetypeLoadedList-Regular")).unwrap(),
|
||||
);
|
||||
let loaded: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Loaded List").collect();
|
||||
let search = super::RetypeSearch {
|
||||
command: "type.retypeFonts",
|
||||
doc: 1,
|
||||
shapes: whole(glyphs(&db, "Rx")),
|
||||
faces: super::Faces::Given(loaded.clone()),
|
||||
tolerance: 0.0,
|
||||
};
|
||||
let found = search.run_in(&db).unwrap();
|
||||
let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect();
|
||||
// The loaded face first, then the installed one, each once.
|
||||
assert_eq!(families, ["Retype Loaded List", "Retype Copy List"]);
|
||||
assert_eq!((found.installed.read, found.installed.skipped), (1, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn faces_a_list_turns_down_are_loaded_and_take_no_place() {
|
||||
let (db, _) = installed("listed", &["Retype Copy R", "Retype Copy S", "Retype Copy T"]);
|
||||
let shapes = glyphs(&db, "k");
|
||||
let refs: Vec<&BezPath> = shapes.iter().collect();
|
||||
// Two places, and the first face found is turned down: the next two are listed.
|
||||
let found = super::search_listed(&db, &refs, 2, &|f| f.family != "Retype Copy R").unwrap();
|
||||
let mut families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect();
|
||||
families.sort_unstable();
|
||||
assert_eq!(families, ["Retype Copy S", "Retype Copy T"]);
|
||||
assert_eq!((found.read, found.skipped), (3, 0));
|
||||
assert!(!unloaded(&db, "Retype Copy R"), "the face turned down was loaded");
|
||||
// Only the faces listed are compared ahead of the other loaded faces later.
|
||||
let ahead: Vec<String> = super::found(&db).iter().map(|f| f.family.clone()).collect();
|
||||
assert!(ahead.iter().any(|f| f == "Retype Copy S") && !ahead.iter().any(|f| f == "Retype Copy R"), "{ahead:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_stops_the_search_between_files() {
|
||||
let (db, _) = installed("cancel-between", &["Retype Copy U", "Retype Copy V", "Retype Copy W"]);
|
||||
let shapes = glyphs(&db, "k");
|
||||
let refs: Vec<&BezPath> = shapes.iter().collect();
|
||||
let token = vectorcraft_doc::cancel::CancelToken::new();
|
||||
let stop = token.clone();
|
||||
// The cancel comes as the second file starts: it is read, the third is not.
|
||||
let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(move |done, _, _| {
|
||||
if done == 1 {
|
||||
stop.cancel();
|
||||
}
|
||||
});
|
||||
let r = vectorcraft_doc::cancel::scope(&token, Some(sink), || search(&db, &refs, true));
|
||||
assert!(matches!(r, Err(crate::EngineError::Cancelled)));
|
||||
let left = ["Retype Copy U", "Retype Copy V", "Retype Copy W"].iter().filter(|f| unloaded(&db, f)).count();
|
||||
assert_eq!(left, 1, "two files were read and loaded, the third was not");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_away_from_the_command_loads_the_faces_it_finds() {
|
||||
let (db, _) = installed("run", &["Retype Copy X"]);
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let ids: Vec<u64> =
|
||||
glyphs(&db, "Wk").iter().map(|p| s.execute("path.create", &json!({"d": p.to_svg()})).unwrap()["id"].as_u64().unwrap()).collect();
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
// Off: nothing to run.
|
||||
for cmd in ["type.retype", "type.retypeFonts"] {
|
||||
assert!(super::RetypeRun::prepare(&s, cmd, &json!({"installed": false})).unwrap().is_none());
|
||||
}
|
||||
// The command's params are checked as it checks them.
|
||||
assert!(super::RetypeRun::prepare(&s, "type.retypeFonts", &json!({"count": 0})).is_err());
|
||||
assert!(super::RetypeRun::prepare(&s, "type.retype", &json!({"fonts": 1})).is_err());
|
||||
assert!(super::RetypeRun::prepare(&s, "type.text", &json!({})).is_err());
|
||||
// An unknown key fails before any search, as the command fails on it.
|
||||
for cmd in ["type.retype", "type.retypeFonts"] {
|
||||
let e = super::RetypeRun::prepare(&s, cmd, &json!({"typo": true})).err().map(|e| e.to_string()).unwrap_or_default();
|
||||
assert!(e.contains("typo"), "{cmd}: {e}");
|
||||
assert!(s.execute(cmd, &json!({"typo": true})).is_err());
|
||||
}
|
||||
// Retype: the loaded Source Sans 3 matches both shapes, so no installed file is read.
|
||||
let run = super::RetypeRun::prepare(&s, "type.retype", &json!({})).unwrap().unwrap();
|
||||
assert_eq!(run.command(), "type.retype");
|
||||
assert_eq!(run.params(), &json!({}));
|
||||
assert_eq!(run.run_in(&db).unwrap().json(), json!({"read": 0, "skipped": 0}));
|
||||
assert!(unloaded(&db, "Retype Copy X"));
|
||||
// The list compares every installed face: the copy is read and loaded.
|
||||
let run = super::RetypeRun::prepare(&s, "type.retypeFonts", &json!({"count": 5})).unwrap().unwrap();
|
||||
assert_eq!(run.params(), &json!({"count": 5}));
|
||||
assert!(run.current(&s));
|
||||
let found = run.run_in(&db).unwrap();
|
||||
assert_eq!(found.json(), json!({"read": 1, "skipped": 0}));
|
||||
// The loaded faces that match are handed in with it, ahead of it.
|
||||
let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect();
|
||||
assert_eq!(families.last(), Some(&"Retype Copy X"), "{families:?}");
|
||||
assert_eq!(families.iter().filter(|f| **f == "Retype Copy X").count(), 1, "{families:?}");
|
||||
assert!(families.contains(&"Source Sans 3"), "{families:?}");
|
||||
assert!(!unloaded(&db, "Retype Copy X"));
|
||||
// A change of selection or content: it no longer applies.
|
||||
s.execute("select.set", &json!({"ids": [ids[0]]})).unwrap();
|
||||
assert!(!run.current(&s));
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
assert!(run.current(&s));
|
||||
s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap();
|
||||
assert!(!run.current(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_shapes_alone_start_no_run_away_from_the_command() {
|
||||
// A rectangle and a bar are plain: the search reads no installed font for them, so the
|
||||
// command runs at once.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap();
|
||||
let bar = s.execute("shape.rectangle", &json!({"x": 10, "y": 100, "width": 4, "height": 60})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [rect, bar]})).unwrap();
|
||||
for (cmd, p) in [("type.retype", json!({})), ("type.retype", json!({"tolerance": 0.05})), ("type.retypeFonts", json!({}))] {
|
||||
assert!(super::RetypeRun::prepare(&s, cmd, &p).unwrap().is_none(), "{cmd} {p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_a_search_found_is_handed_to_the_next_command_in_its_document() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let uid = s.doc().unwrap().uid;
|
||||
let handed = |doc| super::RetypeFound { doc, installed: super::Installed { read: 7, skipped: 3, ..Default::default() } };
|
||||
// Taken instead of a search of the installed fonts, also with installed false.
|
||||
handed(uid).hand_in(&mut s);
|
||||
let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap();
|
||||
assert_eq!(r["installed"], json!({"read": 7, "skipped": 3}), "{r}");
|
||||
// Used once.
|
||||
let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap();
|
||||
assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}");
|
||||
// Another document's is dropped.
|
||||
handed(uid + 1).hand_in(&mut s);
|
||||
let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap();
|
||||
assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}");
|
||||
assert!(s.retype_hand_off.is_none(), "taken");
|
||||
// Retype takes it too, whether or not a loaded font matches the rectangle.
|
||||
handed(uid).hand_in(&mut s);
|
||||
let _ = s.execute("type.retype", &json!({"installed": false}));
|
||||
assert!(s.retype_hand_off.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_canceled_search_stops_before_reading_a_file() {
|
||||
let (db, _) = installed("cancel", &["Retype Copy J"]);
|
||||
let shapes = glyphs(&db, "z");
|
||||
let refs: Vec<&BezPath> = shapes.iter().collect();
|
||||
let token = vectorcraft_doc::cancel::CancelToken::new();
|
||||
token.cancel();
|
||||
let r = vectorcraft_doc::cancel::scope(&token, None, || search(&db, &refs, false));
|
||||
assert!(matches!(r, Err(crate::EngineError::Cancelled)));
|
||||
assert!(unloaded(&db, "Retype Copy J"), "nothing was loaded");
|
||||
}
|
||||
|
||||
/// The shapes of `text` set in Source Sans 3 and outlined, as `type.retype` collects them.
|
||||
fn pieces(text: &str) -> Vec<super::super::Piece> {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let id =
|
||||
s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 30, "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let group = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let node = d.node(vectorcraft_doc::NodeId(group)).unwrap();
|
||||
let (mut barrier, mut truncated, mut pieces) = (true, false, vec![]);
|
||||
super::super::collect(node, None, 0, &mut barrier, &mut truncated, &mut pieces);
|
||||
pieces
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retype_fills_the_shapes_no_loaded_font_matches_from_the_installed_fonts() {
|
||||
let (db, _) = installed("retype", &["Retype Copy K"]);
|
||||
let pieces = pieces("Wk-");
|
||||
assert_eq!(pieces.len(), 3);
|
||||
let groups = vec![vec![]; pieces.len()];
|
||||
// The first shape is taken as matched already: the others are looked for.
|
||||
let keep = super::super::RetypeIndex::build(&db, db.face("Source Sans 3", "Regular"), &keys(&[pieces[0].path.clone()]));
|
||||
let found = super::super::match_pieces(&pieces, &groups, &[&keep], 0.0);
|
||||
assert!(!found[0].is_empty() && found[1].is_empty() && found[2].is_empty());
|
||||
let left = super::super::left_shapes(&pieces, &groups, &found);
|
||||
assert_eq!(left.len(), 2);
|
||||
let installed = super::search_for(&db, &left, 0.0, false).unwrap();
|
||||
assert_eq!(installed.read, 1);
|
||||
// The faces found join the index, and every shape is matched again.
|
||||
let all_keys = keys(&pieces.iter().map(|pc| pc.path.clone()).collect::<Vec<_>>());
|
||||
let extra = super::super::RetypeIndex::build(&db, installed.faces.iter().cloned(), &all_keys);
|
||||
let found = super::super::match_pieces(&pieces, &groups, &[&keep, &extra], 0.0);
|
||||
let whole = |k: usize| found[k].first().expect("one part").clone();
|
||||
assert_eq!(whole(0).first().map(|m| m.face.family.as_str()), Some("Source Sans 3"), "a matched shape keeps its match");
|
||||
// and gets the face found too, so its line can be set in the face the others match.
|
||||
assert!(whole(0).iter().any(|m| m.face.family == "Retype Copy K" && m.ch == 'W'), "the W also matches the face found");
|
||||
let k = whole(1);
|
||||
let m = k.first().expect("the installed copy matches the k");
|
||||
assert_eq!((m.face.family.as_str(), m.ch), ("Retype Copy K", 'k'));
|
||||
assert!(db.loaded_faces().iter().any(|f| f.id() == m.face.id()), "the match is in a loaded face");
|
||||
// The hyphen, a plain shape, matches the font the k found.
|
||||
let hyphen = whole(2);
|
||||
let m = hyphen.first().expect("the installed copy matches the hyphen");
|
||||
assert_eq!((m.face.family.as_str(), m.ch), ("Retype Copy K", '-'));
|
||||
}
|
||||
|
||||
/// `path` flattened into lines `tol` from its curves, each contour started at its second point
|
||||
/// and run backwards: an outline built nothing like the font's.
|
||||
fn simplified(path: &BezPath, tol: f64) -> BezPath {
|
||||
let mut contours: Vec<Vec<kurbo::Point>> = vec![];
|
||||
kurbo::flatten(path.iter(), tol, |el| match el {
|
||||
kurbo::PathEl::MoveTo(q) => contours.push(vec![q]),
|
||||
kurbo::PathEl::LineTo(q) => contours.last_mut().unwrap().push(q),
|
||||
_ => {}
|
||||
});
|
||||
let mut out = BezPath::new();
|
||||
for mut c in contours {
|
||||
if c.len() > 1 && c.first() == c.last() {
|
||||
c.pop();
|
||||
}
|
||||
c.rotate_left(1);
|
||||
c.reverse();
|
||||
out.move_to(c[0]);
|
||||
for q in &c[1..] {
|
||||
out.line_to(*q);
|
||||
}
|
||||
out.close_path();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_installed_face_is_found_through_the_glyphs_of_a_split_shape_and_through_near_matches() {
|
||||
// A word outlined as one compound path: the whole shape is no glyph, and its glyphs are.
|
||||
let (db, _) = installed("split", &["Retype Copy Split"]);
|
||||
let mut word = BezPath::new();
|
||||
for g in glyphs(&db, "Wk") {
|
||||
word.extend(g.iter());
|
||||
}
|
||||
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
|
||||
let groups = super::super::split_groups(&word, &mut budget);
|
||||
assert_eq!(groups.len(), 2);
|
||||
let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap();
|
||||
assert_eq!(found.read, 1);
|
||||
let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect();
|
||||
assert_eq!(families, ["Retype Copy Split"], "the face the split's glyphs match is found");
|
||||
assert!(!unloaded(&db, "Retype Copy Split"));
|
||||
// A simplified outline: no installed glyph matches it exactly, and one does within a tolerance.
|
||||
let (db, _) = installed("near", &["Retype Copy Near"]);
|
||||
let r = simplified(&glyphs(&db, "R")[0], 0.05);
|
||||
let shape = [super::Sought::unpainted(&r, &[])];
|
||||
let exact = super::search_for(&db, &shape, 0.0, false).unwrap();
|
||||
assert_eq!((exact.read, exact.faces.len()), (1, 0));
|
||||
assert!(unloaded(&db, "Retype Copy Near"));
|
||||
let near = super::search_for(&db, &shape, 0.02, false).unwrap();
|
||||
let families: Vec<&str> = near.faces.iter().map(|f| f.family.as_str()).collect();
|
||||
assert_eq!(families, ["Retype Copy Near"], "the face the outline nearly matches is found");
|
||||
assert!(!unloaded(&db, "Retype Copy Near"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_shape_whose_glyphs_are_in_different_installed_faces_finds_them_all() {
|
||||
// A W of Source Sans 3 and a k of Inter, outlined as one compound path, with a copy of each
|
||||
// font installed: neither face holds both glyphs.
|
||||
let dir = vectorcraft_testkit::temp_dir("retype-installed-split-two");
|
||||
for (inter, family) in [(false, "Retype Mix S"), (true, "Retype Mix I")] {
|
||||
let postscript = format!("{}-Regular", family.replace(' ', ""));
|
||||
let data = vectorcraft_text::test_fonts::named_copy(inter, (family, "Regular", "Version 1.000", &postscript)).unwrap();
|
||||
std::fs::write(dir.join(format!("{postscript}.ttf")), data).unwrap();
|
||||
}
|
||||
let db = FontDb::with_font_dirs(vec![dir]);
|
||||
let mut word = BezPath::new();
|
||||
word.extend(glyphs(&db, "W")[0].iter());
|
||||
let inter = db.face("Inter", "Regular").unwrap();
|
||||
let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k'));
|
||||
word.extend(k.iter());
|
||||
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
|
||||
let groups = super::super::split_groups(&word, &mut budget);
|
||||
assert_eq!(groups.len(), 2);
|
||||
let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap();
|
||||
assert_eq!(found.read, 2);
|
||||
let mut families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect();
|
||||
families.sort_unstable();
|
||||
assert_eq!(families, ["Retype Mix I", "Retype Mix S"], "the faces of both glyphs are found");
|
||||
assert!(!unloaded(&db, "Retype Mix S") && !unloaded(&db, "Retype Mix I"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_shape_completes_with_the_loaded_faces_it_is_searched_beside() {
|
||||
// A W of Source Sans 3 and a k of Inter, outlined as one compound path. Source Sans 3 is the
|
||||
// loaded face compared first; the only other face is an installed copy of Inter.
|
||||
let dir = vectorcraft_testkit::temp_dir("retype-installed-beside");
|
||||
let data = vectorcraft_text::test_fonts::named_copy(true, ("Retype Beside I", "Regular", "Version 1.000", "RetypeBesideI-Regular")).unwrap();
|
||||
std::fs::write(dir.join("RetypeBesideI-Regular.ttf"), data).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![dir]);
|
||||
let mut word = BezPath::new();
|
||||
word.extend(glyphs(&db, "W")[0].iter());
|
||||
let inter = db.face("Inter", "Regular").unwrap();
|
||||
let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k'));
|
||||
word.extend(k.iter());
|
||||
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
|
||||
let groups = super::super::split_groups(&word, &mut budget);
|
||||
assert_eq!(groups.len(), 2);
|
||||
let shapes = [super::Sought::unpainted(&word, &groups)];
|
||||
let (keys, near) = super::keys_of(&shapes, 0.0);
|
||||
let first = super::super::RetypeIndex::build_near(&db, db.face("Source Sans 3", "Regular"), &keys, &near);
|
||||
let found = super::search_beside(&db, &shapes, &[&first], 0.0, false).unwrap();
|
||||
let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect();
|
||||
assert_eq!(families, ["Source Sans 3", "Retype Beside I"], "the installed face completes the loaded face's glyphs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_loaded_face_per_glyph_completes_a_split_shape_however_many_hold_it() {
|
||||
// A W of Source Sans 3 and a k of Inter in one compound path. More loaded copies of Source
|
||||
// Sans 3 than a search finds faces hold the W; an installed copy of Inter holds the k.
|
||||
let n = vectorcraft_text::retype::MAX_FACES + 4;
|
||||
let dir = vectorcraft_testkit::temp_dir("retype-installed-many");
|
||||
let data = vectorcraft_text::test_fonts::named_copy(true, ("Retype Many I", "Regular", "Version 1.000", "RetypeManyI-Regular")).unwrap();
|
||||
std::fs::write(dir.join("RetypeManyI-Regular.ttf"), data).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![dir]);
|
||||
for i in 0..n {
|
||||
let family = format!("Retype Many {i}");
|
||||
db.add_font(
|
||||
vectorcraft_text::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &format!("RetypeMany{i}-Regular"))).unwrap(),
|
||||
);
|
||||
}
|
||||
let mut word = BezPath::new();
|
||||
word.extend(glyphs(&db, "W")[0].iter());
|
||||
let inter = db.face("Inter", "Regular").unwrap();
|
||||
let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k'));
|
||||
word.extend(k.iter());
|
||||
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
|
||||
let groups = super::super::split_groups(&word, &mut budget);
|
||||
let shapes = [super::Sought::unpainted(&word, &groups)];
|
||||
let (keys, near) = super::keys_of(&shapes, 0.0);
|
||||
let copies: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Many ")).collect();
|
||||
assert_eq!(copies.len(), n);
|
||||
let indexes: Vec<super::super::RetypeIndex> = copies
|
||||
.chunks(vectorcraft_text::retype::MAX_FACES)
|
||||
.map(|g| super::super::RetypeIndex::build_near(&db, g.iter().cloned(), &keys, &near))
|
||||
.collect();
|
||||
let beside: Vec<&super::super::RetypeIndex> = indexes.iter().collect();
|
||||
let found = super::search_beside(&db, &shapes, &beside, 0.0, false).unwrap();
|
||||
let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect();
|
||||
assert_eq!(families.len(), 2, "{families:?}");
|
||||
assert_eq!(families.last(), Some(&"Retype Many I"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_shape_completes_with_loaded_faces_past_the_first_and_installed_ones() {
|
||||
// A W of Source Sans 3 and a k of Inter in one compound path. Past the faces compared first
|
||||
// (the bundled ones), a loaded copy of Inter holds the k and an installed copy of Source Sans 3
|
||||
// the W.
|
||||
let dir = vectorcraft_testkit::temp_dir("retype-installed-kept");
|
||||
let data = vectorcraft_text::test_fonts::named_copy(false, ("Retype Kept S", "Regular", "Version 1.000", "RetypeKeptS-Regular")).unwrap();
|
||||
std::fs::write(dir.join("RetypeKeptS-Regular.ttf"), data).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![dir]);
|
||||
let compared: Vec<u32> = db.loaded_faces().iter().map(|f| f.id()).collect();
|
||||
db.add_font(vectorcraft_text::test_fonts::named_copy(true, ("Retype Kept I", "Regular", "Version 1.000", "RetypeKeptI-Regular")).unwrap());
|
||||
let mut word = BezPath::new();
|
||||
word.extend(glyphs(&db, "W")[0].iter());
|
||||
let inter = db.face("Inter", "Regular").unwrap();
|
||||
let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k'));
|
||||
word.extend(k.iter());
|
||||
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
|
||||
let groups = super::super::split_groups(&word, &mut budget);
|
||||
assert_eq!(groups.len(), 2);
|
||||
let shapes = [super::Sought::unpainted(&word, &groups)];
|
||||
let (rest, done, kept) = super::loaded_rest_for(&db, &shapes, &[], 0.0, &compared).unwrap();
|
||||
assert!(rest.is_empty() && done == [false]);
|
||||
assert_eq!(kept.len(), 1, "the group with the k is kept for the installed fonts");
|
||||
let beside: Vec<&super::super::RetypeIndex> = kept.iter().collect();
|
||||
let found = super::search_beside(&db, &shapes, &beside, 0.0, false).unwrap();
|
||||
let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect();
|
||||
assert_eq!(families, ["Retype Kept I", "Retype Kept S"], "the loaded copy's k and the installed copy's W");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_installed_face_whose_glyphs_paint_otherwise_than_the_shape_is_not_found() {
|
||||
// Two o's moved onto each other in one compound path filled by the even-odd rule: the overlap
|
||||
// is unpainted, and two glyphs set side by side would paint it.
|
||||
let paths = |db: &FontDb| {
|
||||
let face = db.face("Source Sans 3", "Regular").unwrap();
|
||||
let o = Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for('o'));
|
||||
let mut word = BezPath::new();
|
||||
for x in [40.0, 49.0] {
|
||||
word.extend((Affine::translate((x, 100.0)) * o.clone()).iter());
|
||||
}
|
||||
word
|
||||
};
|
||||
let (db, _) = installed("paint", &["Retype Copy Paint"]);
|
||||
let word = paths(&db);
|
||||
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
|
||||
let groups = super::super::split_groups(&word, &mut budget);
|
||||
assert_eq!(groups.len(), 2);
|
||||
let even_odd = super::Sought { path: &word, groups: &groups, fill: Some(false), once: true };
|
||||
let found = super::search_for(&db, &[even_odd], 0.0, false).unwrap();
|
||||
assert_eq!((found.read, found.faces.len()), (1, 0), "the o's paint the overlap");
|
||||
assert!(unloaded(&db, "Retype Copy Paint"));
|
||||
// Without a fill to compare, the same glyphs are found.
|
||||
let (db, _) = installed("paint-none", &["Retype Copy Unpainted"]);
|
||||
let word = paths(&db);
|
||||
let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap();
|
||||
assert_eq!(found.faces.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retype_reads_no_installed_font_for_plain_shapes_alone() {
|
||||
let (db, _) = installed("retype-plain", &["Retype Copy M"]);
|
||||
let pieces = pieces("W-");
|
||||
let groups = vec![vec![]; pieces.len()];
|
||||
let keep = super::super::RetypeIndex::build(&db, db.face("Source Sans 3", "Regular"), &keys(&[pieces[0].path.clone()]));
|
||||
let found = super::super::match_pieces(&pieces, &groups, &[&keep], 0.0);
|
||||
let left = super::super::left_shapes(&pieces, &groups, &found);
|
||||
assert_eq!(left.len(), 1, "the hyphen is left");
|
||||
let installed = super::search_for(&db, &left, 0.0, false).unwrap();
|
||||
assert_eq!((installed.read, installed.faces.len()), (0, 0));
|
||||
assert!(unloaded(&db, "Retype Copy M"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_must_be_a_bool_or_null() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
for cmd in ["type.retype", "type.retypeFonts"] {
|
||||
for bad in [json!(1), json!("yes"), json!([])] {
|
||||
let e = s.execute(cmd, &json!({"installed": bad})).unwrap_err().to_string();
|
||||
assert!(e.contains("`installed` must be true, false or null"), "{cmd} {bad}: {e}");
|
||||
}
|
||||
}
|
||||
// false: no installed font is read, and the result says so.
|
||||
let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap();
|
||||
assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}");
|
||||
}
|
||||
|
||||
/// A database with no installed fonts and `n` copies of the bundled Source Sans 3 Regular loaded,
|
||||
/// named `{tag} 0` to `{tag} n-1`, after `inter` copies of Inter named `{tag} Inter 0` and on.
|
||||
fn loaded_copies(tag: &str, inter: usize, n: usize) -> FontDb {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let copies = (0..inter).map(|i| (true, format!("{tag} Inter {i}"))).chain((0..n).map(|i| (false, format!("{tag} {i}"))));
|
||||
for (inter, family) in copies {
|
||||
let postscript = format!("{}-Regular", family.replace(' ', ""));
|
||||
db.add_font(vectorcraft_text::test_fonts::named_copy(inter, (&family, "Regular", "Version 1.000", &postscript)).unwrap());
|
||||
}
|
||||
db
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loaded_faces_past_the_ones_compared_first_are_compared_too() {
|
||||
let n = vectorcraft_text::retype::MAX_FACES + 4;
|
||||
let db = loaded_copies("Retype Rest", 0, n);
|
||||
let shapes = glyphs(&db, "Rx");
|
||||
let refs: Vec<&BezPath> = shapes.iter().collect();
|
||||
// Every loaded face that matches, more than one index takes.
|
||||
let rest = super::loaded_rest(&db, &refs, &[]).unwrap();
|
||||
for i in 0..n {
|
||||
assert!(rest.iter().any(|f| f.family == format!("Retype Rest {i}")), "copy {i} of {}", rest.len());
|
||||
}
|
||||
// The faces compared already are left out.
|
||||
let last = format!("Retype Rest {}", n - 1);
|
||||
let compared: Vec<u32> = db.loaded_faces().iter().filter(|f| f.family != last).map(|f| f.id()).collect();
|
||||
let rest = super::loaded_rest(&db, &refs, &compared).unwrap();
|
||||
assert_eq!(rest.iter().map(|f| f.family.as_str()).collect::<Vec<_>>(), [last.as_str()]);
|
||||
// A plain shape alone compares none.
|
||||
let bar = [kurbo::Rect::new(0.0, 0.0, 80.0, 10.0).to_path(0.1)];
|
||||
assert!(super::loaded_rest(&db, &[&bar[0]], &[]).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_shape_completes_with_loaded_faces_past_the_ones_compared_first() {
|
||||
// A W of Source Sans 3 and a k of Inter in one compound path. Source Sans 3 and Inter are
|
||||
// compared first; past them, a loaded copy of Inter holds the k.
|
||||
let db = loaded_copies("Retype Rest Split", 1, 0);
|
||||
let mut word = BezPath::new();
|
||||
word.extend(glyphs(&db, "W")[0].iter());
|
||||
let inter = db.face("Inter", "Regular").unwrap();
|
||||
let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k'));
|
||||
word.extend(k.iter());
|
||||
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
|
||||
let groups = super::super::split_groups(&word, &mut budget);
|
||||
assert_eq!(groups.len(), 2);
|
||||
let shapes = [super::Sought::unpainted(&word, &groups)];
|
||||
let (keys, near) = super::keys_of(&shapes, 0.0);
|
||||
let source = db.face("Source Sans 3", "Regular").unwrap();
|
||||
let compared = [source.id(), inter.id()];
|
||||
let first = super::super::RetypeIndex::build_near(&db, [source], &keys, &near);
|
||||
let (rest, done, kept) = super::loaded_rest_for(&db, &shapes, &[&first], 0.0, &compared).unwrap();
|
||||
assert!(kept.is_empty(), "no split shape is left");
|
||||
let families: Vec<&str> = rest.iter().map(|f| f.family.as_str()).collect();
|
||||
assert_eq!(families, ["Retype Rest Split Inter 0"], "the copy completes the glyphs of the face compared first");
|
||||
assert_eq!(done, [true]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_past_the_glyph_budget_are_skipped_without_being_read() {
|
||||
let (db, mut files) = installed("budget-spent", &["Retype Copy E1", "Retype Copy E2"]);
|
||||
let shapes = glyphs(&db, "k");
|
||||
let refs: Vec<&BezPath> = shapes.iter().collect();
|
||||
// The order the search reads them in: smallest first.
|
||||
let len = |p: &PathBuf| std::fs::metadata(p).unwrap().len();
|
||||
files.sort_by(|a, b| len(a).cmp(&len(b)).then_with(|| a.cmp(b)));
|
||||
assert_eq!(db.unloaded_installed_faces().len(), 2);
|
||||
let face = db.read_unloaded_file(&files[0], u64::MAX).faces.into_iter().next().unwrap();
|
||||
let drawn = vectorcraft_text::retype::encoded_glyphs(&face);
|
||||
// The second file holds no font after the listing: had it been read, it would give no face
|
||||
// to skip.
|
||||
std::fs::write(&files[1], vec![0u8; len(&files[1]) as usize]).unwrap();
|
||||
let limits = Limits { file: u64::MAX, read: u64::MAX, glyphs: drawn, faces: usize::MAX };
|
||||
let found = search_within(&db, &refs, true, limits, &|_| true).unwrap();
|
||||
assert_eq!((found.read, found.skipped, found.faces.len()), (1, 1, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_away_from_the_command_hands_in_the_loaded_faces_past_the_ones_compared_first() {
|
||||
let db = loaded_copies("Retype Run Rest", vectorcraft_text::retype::MAX_FACES, 1);
|
||||
let shapes = glyphs(&db, "Rx");
|
||||
// The Inter copies are compared first: none matches, and the copy loaded after them does.
|
||||
let faces: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Run Rest Inter")).collect();
|
||||
assert_eq!(faces.len(), vectorcraft_text::retype::MAX_FACES);
|
||||
let search =
|
||||
super::RetypeSearch { command: "type.retype", doc: 1, shapes: whole(shapes.clone()), faces: super::Faces::Given(faces), tolerance: 0.0 };
|
||||
let found = search.run_in(&db).unwrap();
|
||||
assert!(found.installed.faces.iter().any(|f| f.family == "Retype Run Rest 0"), "the loaded copy is handed in");
|
||||
assert_eq!((found.installed.read, found.installed.skipped), (0, 0), "no installed file is read for it");
|
||||
// Every loaded face was compared: the command does not compare them again.
|
||||
assert!(db.loaded_faces().iter().all(|f| found.installed.scanned.contains(&f.id())));
|
||||
// A face compared first that matches is handed in too, as loading others may move it past
|
||||
// the faces the command compares first.
|
||||
let copy: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Run Rest 0").collect();
|
||||
let found = super::RetypeSearch { command: "type.retype", doc: 1, shapes: whole(shapes), faces: super::Faces::Given(copy), tolerance: 0.0 }
|
||||
.run_in(&db)
|
||||
.unwrap();
|
||||
assert_eq!(found.installed.faces.first().map(|f| f.family.as_str()), Some("Retype Run Rest 0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_list_counts_skipped_installed_faces_only_when_a_shape_would_start_a_search() {
|
||||
let (db, _) = installed("full-list", &["Retype Copy Full"]);
|
||||
for i in 0..super::super::fonts::MAX_COUNT {
|
||||
let family = format!("Retype Full {i}");
|
||||
let postscript = format!("RetypeFull{i}-Regular");
|
||||
db.add_font(vectorcraft_text::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &postscript)).unwrap());
|
||||
}
|
||||
let faces: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Full ")).collect();
|
||||
// A hyphen is plain: it fills the list and would start no search, so nothing is skipped.
|
||||
let hyphen = glyphs(&db, "-");
|
||||
let refs: Vec<&BezPath> = hyphen.iter().collect();
|
||||
let (ranked, found) = super::super::fonts::rank_fonts(&db, faces.clone(), &refs, true, None).unwrap();
|
||||
assert_eq!(ranked.len(), super::super::fonts::MAX_COUNT);
|
||||
assert_eq!((found.read, found.skipped), (0, 0));
|
||||
// A shape that is not plain would: the installed face counts as skipped.
|
||||
let shapes = glyphs(&db, "-q");
|
||||
let refs: Vec<&BezPath> = shapes.iter().collect();
|
||||
let (_, found) = super::super::fonts::rank_fonts(&db, faces, &refs, true, None).unwrap();
|
||||
assert_eq!((found.read, found.skipped), (0, 1));
|
||||
assert!(unloaded(&db, "Retype Copy Full"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_handed_in_and_not_taken_can_be_dropped() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let doc = s.doc().unwrap().uid;
|
||||
super::RetypeFound { doc, installed: super::Installed::default() }.hand_in(&mut s);
|
||||
assert!(s.retype_hand_off.is_some());
|
||||
super::RetypeFound::drop_handed(&mut s);
|
||||
assert!(s.retype_hand_off.is_none());
|
||||
}
|
||||
@@ -123,11 +123,13 @@ fn a_mark_in_one_font_starts_its_line_as_another_fonts_character() {
|
||||
#[test]
|
||||
fn a_combining_mark_starts_no_line() {
|
||||
// A combining mark on its own (a drawn dot, bar or ring is the same shape) stays an outline.
|
||||
// The calls that leave a shape an outline leave the installed fonts out, so what this machine
|
||||
// has installed does not change the result.
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let e = s.execute("type.retype", &json!({})).unwrap_err().to_string();
|
||||
let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string();
|
||||
assert!(e.contains("no selected shape matches"), "{e}");
|
||||
assert!(s.doc().unwrap().doc == before, "nothing changes");
|
||||
// A shape that is both a mark (tilde below) and a character (small tilde) starts its line as
|
||||
@@ -145,7 +147,7 @@ fn a_combining_mark_starts_no_line() {
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "\u{312}ab", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
|
||||
let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[0].id.0;
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["ab"]), "{r}");
|
||||
assert_eq!(r["unmatched"], json!([mark]));
|
||||
// After a base, the mark is retyped with it.
|
||||
@@ -160,7 +162,7 @@ fn a_combining_mark_starts_no_line() {
|
||||
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
|
||||
assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yz"]), &json!([mark])), "{r}");
|
||||
// A mark that is also another character (dot below, dot above) becomes that character there.
|
||||
let g = outlined(&mut s, json!({"x": 300, "y": 120, "text": "x\u{323}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
|
||||
@@ -183,7 +185,7 @@ fn a_combining_mark_starts_no_line() {
|
||||
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
|
||||
assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yzw"]), &json!([mark])), "{r}");
|
||||
assert_eq!(r["fonts"][1]["tracking"], json!(50.0), "{r}");
|
||||
// A one-contour glyph after a mark that stays an outline (a bar, then a dot) is alone, and
|
||||
@@ -193,7 +195,7 @@ fn a_combining_mark_starts_no_line() {
|
||||
pair.sort_unstable();
|
||||
let word = outlined(&mut s, json!({"x": 40, "y": 380, "text": "ab", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
|
||||
s.execute("select.set", &json!({"ids": [dot, word]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["ab"]), "{r}");
|
||||
let mut left: Vec<u64> = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
|
||||
left.sort_unstable();
|
||||
@@ -246,7 +248,8 @@ fn marks_first_after_a_split_leave_other_lines_their_tracking() {
|
||||
s.execute("select.set", &json!({"ids": moved})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [marks, tracked]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
// The installed fonts left out: what this machine has installed does not change the result.
|
||||
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
|
||||
let texts = r["texts"].as_array().unwrap();
|
||||
let at = texts.iter().position(|t| t == "yzw").unwrap_or_else(|| panic!("yzw in {r}"));
|
||||
assert_eq!(r["fonts"][at]["tracking"], json!(50.0), "{r}");
|
||||
@@ -374,7 +377,7 @@ fn an_open_path_along_a_glyph_is_not_a_glyph() {
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
assert!(s.execute("type.retype", &json!({})).is_err(), "nothing matches");
|
||||
assert!(s.execute("type.retype", &json!({"installed": false})).is_err(), "nothing matches");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -488,7 +491,8 @@ fn a_glyph_painted_beyond_what_type_takes_stays_an_outline() {
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
// The installed fonts left out: what this machine has installed does not change the result.
|
||||
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["B"]), "two fills: A stays an outline: {r}");
|
||||
assert_eq!(r["unmatched"], json!([a]));
|
||||
}
|
||||
@@ -551,7 +555,8 @@ fn a_drawn_dot_or_bar_beside_type_stays_art() {
|
||||
// A bar that is exactly a hyphen of the font, somewhere else: the worst case.
|
||||
let bar = outlined(&mut s, json!({"x": 200, "y": 300, "text": "-", "size": 50}));
|
||||
s.execute("select.set", &json!({"ids": [g, dot, bar]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
// The installed fonts left out: what this machine has installed does not change the result.
|
||||
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["AB"]), "{r}");
|
||||
let un = r["unmatched"].as_array().unwrap();
|
||||
assert!(un.contains(&json!(dot)) && un.len() == 2, "the dot and the bar stay art: {r}");
|
||||
@@ -754,7 +759,8 @@ fn simplified_outlines_retype_only_with_a_tolerance_and_report_their_score() {
|
||||
simplify_every_path(&mut s, 0.05);
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let e = s.execute("type.retype", &json!({})).unwrap_err().to_string();
|
||||
// The installed fonts left out: what this machine has installed does not change the result.
|
||||
let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string();
|
||||
assert!(e.contains("no selected shape matches"), "no exact match: {e}");
|
||||
for bad in [json!(-0.01), json!(0.06), json!("0.02"), json!(true), json!(null)] {
|
||||
let e = s.execute("type.retype", &json!({"tolerance": bad})).unwrap_err().to_string();
|
||||
@@ -825,8 +831,9 @@ fn two_overlapping_lone_glyphs_beside_art_stay_outlines() {
|
||||
let b = outlined(&mut s, json!({"x": 49, "y": 100, "text": "M", "size": 30}));
|
||||
let dot = s.execute("shape.ellipse", &json!({"x": 300, "y": 60, "width": 8, "height": 8})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b, dot]})).unwrap();
|
||||
// Nothing is left to retype: both stay outlines, as the lone bar beside art does.
|
||||
let e = s.execute("type.retype", &json!({})).unwrap_err();
|
||||
// Nothing is left to retype: both stay outlines, as the lone bar beside art does. The installed
|
||||
// fonts are left out, so what this machine has installed does not change the result.
|
||||
let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err();
|
||||
assert!(format!("{e:?}").contains("no selected shape matches"), "{e:?}");
|
||||
}
|
||||
|
||||
@@ -1363,7 +1370,8 @@ fn a_lone_period_in_a_compound_selected_alone_stays_an_outline() {
|
||||
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [c]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let e = match s.execute("type.retype", &json!({})) {
|
||||
// The installed fonts left out: what this machine has installed does not change the result.
|
||||
let e = match s.execute("type.retype", &json!({"installed": false})) {
|
||||
Ok(r) => panic!("the period became type: {r}"),
|
||||
Err(e) => e.to_string(),
|
||||
};
|
||||
@@ -1423,7 +1431,8 @@ fn a_compound_whose_parts_are_not_all_glyphs_stays_whole() {
|
||||
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [c]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let e = s.execute("type.retype", &json!({})).unwrap_err().to_string();
|
||||
// The installed fonts left out: what this machine has installed does not change the result.
|
||||
let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string();
|
||||
assert!(e.contains("(1 checked)"), "reported once: {e}");
|
||||
assert!(s.doc().unwrap().doc == before, "nothing changes");
|
||||
}
|
||||
@@ -1440,7 +1449,8 @@ fn glyphs_that_overlap_in_an_even_odd_compound_stay_an_outline() {
|
||||
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [c]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let e = match s.execute("type.retype", &json!({})) {
|
||||
// The installed fonts left out: what this machine has installed does not change the result.
|
||||
let e = match s.execute("type.retype", &json!({"installed": false})) {
|
||||
Ok(r) => panic!("the overlapping o's became type: {r}"),
|
||||
Err(e) => e.to_string(),
|
||||
};
|
||||
@@ -1481,7 +1491,8 @@ fn a_translucent_compound_whose_glyphs_overlap_stays_an_outline() {
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [c]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({}));
|
||||
// The installed fonts left out: what this machine has installed does not change the result.
|
||||
let r = s.execute("type.retype", &json!({"installed": false}));
|
||||
if opacity == 1.0 {
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r["texts"], json!(["i", "i"]), "opaque, the two lines become type: {r}");
|
||||
@@ -1502,8 +1513,9 @@ fn overlapping_exact_glyphs_stay_an_outline_when_near_matches_are_allowed() {
|
||||
s.execute("select.set", &json!({"ids": kids})).unwrap();
|
||||
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [c]})).unwrap();
|
||||
// The installed fonts left out: what this machine has installed does not change the result.
|
||||
for tolerance in [0.0, 0.05] {
|
||||
if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance})) {
|
||||
if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance, "installed": false})) {
|
||||
panic!("the overlapping o's became type at dx {dx}, tolerance {tolerance}: {r}");
|
||||
}
|
||||
}
|
||||
@@ -1564,7 +1576,8 @@ fn a_glyph_with_only_some_contours_turned_in_an_even_odd_compound_still_becomes_
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [c]})).unwrap();
|
||||
assert!(s.execute("type.retype", &json!({})).is_err(), "nonzero, contour {turned} turned paints the counter");
|
||||
// The installed fonts left out: what this machine has installed does not change the result.
|
||||
assert!(s.execute("type.retype", &json!({"installed": false})).is_err(), "nonzero, contour {turned} turned paints the counter");
|
||||
s.execute("path.setFillRule", &json!({"rule": "evenOdd", "ids": [c]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["do"]), "contour {turned} turned: {r}");
|
||||
@@ -1591,7 +1604,8 @@ fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() {
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [c, r]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let e = match s.execute("type.retype", &json!({})) {
|
||||
// The installed fonts left out: what this machine has installed does not change the result.
|
||||
let e = match s.execute("type.retype", &json!({"installed": false})) {
|
||||
Ok(r) => panic!("the A became type without its period: {r}"),
|
||||
Err(e) => e.to_string(),
|
||||
};
|
||||
|
||||
@@ -90,6 +90,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
list_installed
|
||||
),
|
||||
cmd!(
|
||||
query "script.startup.run",
|
||||
"Run Startup Scripts",
|
||||
[],
|
||||
None,
|
||||
"{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run; its source is read once and must compile before enabled startup scripts run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar, where the message of a startup script that fails or is stopped also stays; included files are read again when the chosen run starts; a preflight compilation failure clears the previous script report; each app queue pump processes at most one startup entry",
|
||||
always,
|
||||
startup_run
|
||||
),
|
||||
cmd!(
|
||||
query "script.grants",
|
||||
"List Script File Permissions",
|
||||
@@ -104,7 +113,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Revoke Script File Permissions",
|
||||
[],
|
||||
None,
|
||||
"{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as script.grants lists it, after its links are followed (a path outside the automation read roots is matched as given); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}",
|
||||
"{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as given, as script.grants lists it, or after its links are followed when no grant holds it as given (a path outside the automation read roots is matched as given only); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}",
|
||||
always,
|
||||
grants_revoke
|
||||
),
|
||||
@@ -149,6 +158,21 @@ const NOT_TEXT: &str = "the script is not UTF-8 text";
|
||||
pub const TOO_LARGE: &str = "the script is too large to run";
|
||||
|
||||
fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let request = prepare(s, p)?;
|
||||
run_prepared(s, request)
|
||||
}
|
||||
|
||||
fn run_prepared(s: &mut Session, request: script::Request) -> Result<Value> {
|
||||
let name = s.script_start(request)?;
|
||||
if s.script_frames {
|
||||
return Ok(json!({"running": true, "name": name}));
|
||||
}
|
||||
s.script_run_to_end()
|
||||
}
|
||||
|
||||
/// The run `script.run`'s parameters `p` ask for, with its file read and checked, or the error that
|
||||
/// keeps it from starting.
|
||||
fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
let optional_str = |key: &str| match p.get(key) {
|
||||
None => Ok(None),
|
||||
Some(Value::String(t)) => Ok(Some(t.as_str())),
|
||||
@@ -207,7 +231,7 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let name = given_name.map(str::to_string).or_else(|| path.map(super::fileio::file_name)).unwrap_or_else(|| "script".to_string());
|
||||
let locale = script::dollar::ui_locale(s.ui_language.as_deref().unwrap_or(&s.prefs.interface_language));
|
||||
let request = script::Request {
|
||||
Ok(script::Request {
|
||||
name,
|
||||
name_given: given_name.is_some(),
|
||||
file: path.map(str::to_string),
|
||||
@@ -217,12 +241,7 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fuel,
|
||||
locale,
|
||||
answers,
|
||||
};
|
||||
let name = s.script_start(request)?;
|
||||
if s.script_frames {
|
||||
return Ok(json!({"running": true, "name": name}));
|
||||
}
|
||||
s.script_run_to_end()
|
||||
})
|
||||
}
|
||||
|
||||
fn stop(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
@@ -342,6 +361,278 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// The error of a startup script that is no longer a `.jsx` file of the Startup Scripts folder, or
|
||||
/// cannot be read, when its turn comes.
|
||||
pub const STARTUP_UNREADABLE: &str = "the startup script could not be read";
|
||||
|
||||
impl Session {
|
||||
/// Have `script.startup.run` run the scripts of the folder `dir`. The folder is only read, and
|
||||
/// never made.
|
||||
pub fn attach_startup_scripts_dir(&mut self, dir: std::path::PathBuf) {
|
||||
self.startup_scripts_dir = Some(dir);
|
||||
}
|
||||
|
||||
/// The Startup Scripts folder ([`Session::attach_startup_scripts_dir`]); none on the web.
|
||||
pub fn startup_scripts_dir(&self) -> Option<&std::path::Path> {
|
||||
self.startup_scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
|
||||
}
|
||||
|
||||
/// Why `script.startup.run` runs nothing now: `off` (the `runStartupScripts` preference),
|
||||
/// `safeMode`, or `noFolder` (no Startup Scripts folder); `None` when it runs the folder.
|
||||
pub fn startup_skip(&self) -> Option<&'static str> {
|
||||
if !self.prefs.run_startup_scripts {
|
||||
Some("off")
|
||||
} else if vectorcraft_plugins::safe_mode::active() {
|
||||
Some("safeMode")
|
||||
} else if self.startup_scripts_dir().is_none() {
|
||||
Some("noFolder")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The startup script that ran has ended: the launch marker no longer names it.
|
||||
pub(crate) fn startup_ended(&mut self) {
|
||||
if let Some(token) = self.startup_loading.take() {
|
||||
vectorcraft_plugins::safe_mode::loaded(token);
|
||||
}
|
||||
}
|
||||
|
||||
/// The running script is a startup script (`script.startup.run`), not the script queued after
|
||||
/// them.
|
||||
pub fn startup_script_running(&self) -> bool {
|
||||
self.startup_loading.is_some()
|
||||
}
|
||||
|
||||
/// Begins a run of the startup script at `path`, read now and checked as `script.run` checks a
|
||||
/// file, with the launch marker naming it while it runs. → the run's name, or the error that kept
|
||||
/// it from starting, which the Script Console also shows.
|
||||
fn start_startup(&mut self, path: &std::path::Path, fuel: u64) -> std::result::Result<String, String> {
|
||||
let name = file_name_of(path);
|
||||
let text = self.startup_text(path);
|
||||
let (text, real) = match text {
|
||||
Ok(read) => read,
|
||||
Err(message) => {
|
||||
self.note_unread(&name, &message);
|
||||
return Err(message);
|
||||
}
|
||||
};
|
||||
let item = startup_item(path);
|
||||
self.startup_loading = Some(vectorcraft_plugins::safe_mode::loading(&item));
|
||||
let locale = script::dollar::ui_locale(self.ui_language.as_deref().unwrap_or(&self.prefs.interface_language));
|
||||
let request = script::Request {
|
||||
name: name.clone(),
|
||||
name_given: false,
|
||||
file: Some(path.to_string_lossy().into_owned()),
|
||||
checked_real: Some(real),
|
||||
source: text,
|
||||
args: serde_json::Map::new(),
|
||||
fuel,
|
||||
locale,
|
||||
answers: vec![],
|
||||
};
|
||||
let runs = self.script_runs;
|
||||
self.script_start(request).map_err(|e| {
|
||||
self.startup_ended();
|
||||
let message = e.to_string();
|
||||
// A run refused before it began, such as with an undo group open, has no console entry yet.
|
||||
if self.script_runs == runs {
|
||||
self.note_unread(&name, &message);
|
||||
}
|
||||
message
|
||||
})
|
||||
}
|
||||
|
||||
/// The text of the startup script at `path` and its real path, or the error that keeps it from
|
||||
/// running.
|
||||
fn startup_text(&self, path: &std::path::Path) -> std::result::Result<(String, std::path::PathBuf), String> {
|
||||
let unreadable = || STARTUP_UNREADABLE.to_string();
|
||||
let root = self.startup_scripts_dir().ok_or_else(unreadable)?;
|
||||
let mut real = std::fs::canonicalize(root).map_err(|_| unreadable())?;
|
||||
real.push(path.file_name().ok_or_else(unreadable)?);
|
||||
// One byte more than a script may have shows that the file is too large.
|
||||
let bytes = script::startup::read(root, path, script::MAX_SOURCE_BYTES + 1).ok_or_else(unreadable)?;
|
||||
if bytes.len() > script::MAX_SOURCE_BYTES {
|
||||
return Err(TOO_LARGE.to_string());
|
||||
}
|
||||
Ok((script_text(&bytes).map_err(|e| e.to_string())?, real))
|
||||
}
|
||||
|
||||
/// With no script running, starts the next run `script.startup.run` queued: the next startup
|
||||
/// script that starts, or the script queued after them. A run that cannot start is kept for
|
||||
/// [`Self::take_startup_failures`], and the next one starts on a later pump. → the reply of the script queued
|
||||
/// after them when it ran to its end at once.
|
||||
pub(crate) fn start_queued(&mut self) -> Option<Value> {
|
||||
// Held aside while a run starts, so that the queue does not count as a running script then.
|
||||
let mut queue = std::mem::take(&mut self.script_queue);
|
||||
// Each run starts in the file access scope of the request that queued it, which the run
|
||||
// keeps, and not in the scope of the frame that starts it.
|
||||
let scope = self.script_queue_scope.clone().unwrap_or_else(crate::file_access::ScopeHandle::capture);
|
||||
let mut reply = None;
|
||||
if self.script_key.is_none()
|
||||
&& let Some(next) = queue.pop_front()
|
||||
{
|
||||
match next {
|
||||
script::startup::Queued::Startup { path, fuel } => {
|
||||
if let Err(e) = scope.clone().run(|| self.start_startup(&path, fuel)) {
|
||||
self.startup_failures.push((file_name_of(&path), e));
|
||||
}
|
||||
}
|
||||
script::startup::Queued::Then(params) => {
|
||||
let prepared = self.script_queue_then.take();
|
||||
match scope.clone().run(|| match prepared {
|
||||
Some(request) => run_prepared(self, request),
|
||||
None => run(self, ¶ms),
|
||||
}) {
|
||||
Ok(_) if self.script_key.is_some() => {}
|
||||
Ok(v) => reply = Some(v),
|
||||
Err(e) => self.startup_failures.push((then_name(¶ms), e.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if queue.is_empty() {
|
||||
self.script_queue_scope = None;
|
||||
self.script_queue_then = None;
|
||||
}
|
||||
self.script_queue = queue;
|
||||
reply
|
||||
}
|
||||
|
||||
/// The runs `script.startup.run` queued that could not start since the last call, as (name,
|
||||
/// error), in order.
|
||||
pub fn take_startup_failures(&mut self) -> Vec<(String, String)> {
|
||||
std::mem::take(&mut self.startup_failures)
|
||||
}
|
||||
}
|
||||
|
||||
/// The file name of `path`, or the whole path when it has none.
|
||||
fn file_name_of(path: &std::path::Path) -> String {
|
||||
path.file_name().map_or_else(|| path.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
/// The name a failure of the script `params` (`script.run`'s) names it by: `name`, else the file
|
||||
/// name of `path`, else "script".
|
||||
fn then_name(params: &Value) -> String {
|
||||
let given = |key: &str| params.get(key).and_then(Value::as_str).filter(|v| !v.trim().is_empty());
|
||||
match (given("name"), given("path")) {
|
||||
(Some(name), _) => name.to_string(),
|
||||
(None, Some(path)) => file_name_of(std::path::Path::new(path)),
|
||||
(None, None) => "script".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The launch marker's entry for the startup script at `path`: its file and its file name.
|
||||
fn startup_item(path: &std::path::Path) -> vectorcraft_plugins::safe_mode::Item {
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned());
|
||||
vectorcraft_plugins::safe_mode::Item { id: None, file: Some(path.to_string_lossy().into_owned()), name }
|
||||
}
|
||||
|
||||
fn startup_run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "script.startup.run";
|
||||
let reason = match p.get("reason").and_then(Value::as_str) {
|
||||
Some(r @ ("launch" | "menu")) => r,
|
||||
_ => {
|
||||
let key = "reason";
|
||||
return Err(bad(C, format!("`{key}` must be one of {}", "launch, menu")));
|
||||
}
|
||||
};
|
||||
let then = match p.get("then") {
|
||||
None => None,
|
||||
Some(v @ Value::Object(_)) => Some(v.clone()),
|
||||
Some(_) => {
|
||||
let key = "then";
|
||||
return Err(bad(C, format!("`{key}` must be an object")));
|
||||
}
|
||||
};
|
||||
let fuel = match p.get("maxFuel") {
|
||||
None => script::DEFAULT_FUEL,
|
||||
Some(v) => v.as_u64().filter(|n| (1..=script::MAX_FUEL).contains(n)).ok_or_else(|| EngineError::BadParams {
|
||||
cmd: C.into(),
|
||||
msg: format!("`maxFuel` must be a whole number from 1 to {}", script::MAX_FUEL),
|
||||
})?,
|
||||
};
|
||||
if s.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
// A chosen script that cannot start ends the request before any startup script runs, and its
|
||||
// parameters are checked as `script.run` checks them.
|
||||
if let Some(then) = &then {
|
||||
super::params::check_params("script.run", then)?;
|
||||
}
|
||||
let root = match (s.startup_skip(), s.startup_scripts_dir()) {
|
||||
(None, Some(root)) => root.to_path_buf(),
|
||||
(why, _) => {
|
||||
let mut out = json!({"reason": reason, "skipped": true, "why": why.unwrap_or("noFolder")});
|
||||
if let Some(then) = then {
|
||||
out["then"] = run(s, &then)?;
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
};
|
||||
let prepared = then.as_ref().map(|params| prepare(s, params)).transpose()?;
|
||||
if let Some(request) = &prepared {
|
||||
let mut preflight = Session::new();
|
||||
if let Err(error) = preflight.script_start(request.clone()) {
|
||||
s.script_report = None;
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
let folder = root.to_string_lossy().into_owned();
|
||||
// The folder is the app's: a refusal names it as the request may see it.
|
||||
crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?;
|
||||
let listing = script::startup::list(&root);
|
||||
let name_of = |path: &std::path::Path| path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let (disabled, scripts): (Vec<_>, Vec<_>) =
|
||||
listing.scripts.into_iter().partition(|path| vectorcraft_plugins::safe_mode::skipped(&startup_item(path)));
|
||||
let disabled: Vec<String> = disabled.iter().map(|p| name_of(p)).collect();
|
||||
if s.script_frames {
|
||||
s.script_queue =
|
||||
scripts.into_iter().map(|path| script::startup::Queued::Startup { path, fuel }).chain(then.map(script::startup::Queued::Then)).collect();
|
||||
s.script_queue_scope = Some(crate::file_access::ScopeHandle::capture());
|
||||
s.script_queue_then = prepared;
|
||||
let queued = s.script_queue.len();
|
||||
s.startup_failures.clear();
|
||||
let then = s.start_queued();
|
||||
let failed: Vec<Value> = s.take_startup_failures().into_iter().map(|(name, error)| json!({"name": name, "error": error})).collect();
|
||||
let mut out = json!({
|
||||
"reason": reason,
|
||||
"skipped": false,
|
||||
"running": s.script_running(),
|
||||
"queued": queued,
|
||||
"failed": failed,
|
||||
"disabled": disabled,
|
||||
"truncated": listing.truncated,
|
||||
"unreadable": listing.unreadable,
|
||||
});
|
||||
if let Some(then) = then {
|
||||
out["then"] = then;
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
let (mut ran, mut failed) = (vec![], vec![]);
|
||||
for path in scripts {
|
||||
let name = name_of(&path);
|
||||
match s.start_startup(&path, fuel).map_err(EngineError::Other).and_then(|_| s.script_run_to_end()) {
|
||||
Ok(_) => ran.push(name),
|
||||
Err(e) => failed.push(json!({"name": name, "error": e.to_string()})),
|
||||
}
|
||||
}
|
||||
let mut out = json!({
|
||||
"reason": reason,
|
||||
"skipped": false,
|
||||
"ran": ran,
|
||||
"failed": failed,
|
||||
"disabled": disabled,
|
||||
"truncated": listing.truncated,
|
||||
"unreadable": listing.unreadable,
|
||||
});
|
||||
if let Some(request) = prepared {
|
||||
out["then"] = run_prepared(s, request)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The file name a reply names `path` by when the file is outside the automation read roots; `None`
|
||||
/// when a reply may name it whole.
|
||||
fn hidden_name(path: &str) -> Option<String> {
|
||||
@@ -384,16 +675,19 @@ fn grants(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
fn grants_revoke(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "script.grants.revoke";
|
||||
// A path is matched as given, or with its links followed when no grant holds it as given, so a
|
||||
// grant whose path a link has since taken the place of is still removed. A path the request may not read (outside the
|
||||
// automation read roots, a network path among them) is compared as written, without looking it up.
|
||||
let path_of = |key: &str| match p.get(key) {
|
||||
None => Ok(None),
|
||||
// A path the request may not read (outside the automation read roots, a network path among
|
||||
// them) is compared as written, without looking it up.
|
||||
Some(Value::String(t)) if !t.is_empty() => Ok(Some(
|
||||
crate::file_access::check_read(t)
|
||||
Some(Value::String(t)) if !t.is_empty() => {
|
||||
let real = crate::file_access::check_read(t)
|
||||
.ok()
|
||||
.and_then(|()| std::fs::canonicalize(t).ok())
|
||||
.map_or_else(|| t.clone(), |real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()),
|
||||
)),
|
||||
.map(|real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned())
|
||||
.filter(|real| real != t);
|
||||
Ok(Some([Some(t.clone()), real].into_iter().flatten().collect::<Vec<_>>()))
|
||||
}
|
||||
Some(_) => Err(bad(C, format!("`{key}` must be a path"))),
|
||||
};
|
||||
let (script_path, path) = (path_of("script")?, path_of("path")?);
|
||||
|
||||
@@ -497,6 +497,32 @@ impl Session {
|
||||
/// and with a target that has no stroke row, since `stroke.set` gives such a target a plain
|
||||
/// stroke.
|
||||
pub fn brushed_strokes_profiled(&self) -> Option<bool> {
|
||||
let st = self.active()?;
|
||||
let strokes: Vec<&StrokeLayer> = self.edited_strokes(false)?.into_iter().map(|s| s.filter(|s| s.brush.is_some())).collect::<Option<_>>()?;
|
||||
if strokes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// The library is read only when every stroke names a brush.
|
||||
let lib = vectorcraft_brush::library(&st.doc);
|
||||
strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some()))
|
||||
}
|
||||
|
||||
/// Does any of the strokes that `stroke.set` edits without `ids` or `item` have a width
|
||||
/// profile? The strokes are the ones [`Session::brushed_strokes_profiled`] reads, with or without
|
||||
/// a brush. Type without an active Appearance row is left out, since `stroke.set` gives its
|
||||
/// characters no profile. False with nothing selected, with an object inside a symbol instance
|
||||
/// selected, and with a target that has no stroke row, which a profile from `stroke.set` would
|
||||
/// give a plain stroke.
|
||||
pub fn edited_strokes_profiled(&self) -> bool {
|
||||
self.edited_strokes(true)
|
||||
.and_then(|strokes| strokes.into_iter().collect::<Option<Vec<_>>>())
|
||||
.is_some_and(|strokes| strokes.iter().any(|s| s.profile.is_some()))
|
||||
}
|
||||
|
||||
/// The strokes that `stroke.set` edits without `ids` or `item`, one for each target, `None` for
|
||||
/// a target without a stroke row (see [`Session::brushed_strokes_profiled`]). Type without an
|
||||
/// active Appearance row is skipped with `skip_type`, and makes the result `None` without it.
|
||||
fn edited_strokes(&self, skip_type: bool) -> Option<Vec<Option<&StrokeLayer>>> {
|
||||
const C: &str = "stroke.set";
|
||||
let st = self.active()?;
|
||||
if st.selected_symbol_part().is_some() {
|
||||
@@ -514,16 +540,14 @@ impl Session {
|
||||
let n = st.doc.node(*id)?;
|
||||
let row = each?.resolve(&n.appearance, false, C).ok()?;
|
||||
if row.is_none() && matches!(n.kind, NodeKind::Text(_)) {
|
||||
if skip_type {
|
||||
continue;
|
||||
}
|
||||
return None;
|
||||
}
|
||||
strokes.push(n.appearance.stroke_at(row).filter(|s| s.brush.is_some())?);
|
||||
strokes.push(n.appearance.stroke_at(row));
|
||||
}
|
||||
if strokes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// The library is read only when every stroke names a brush.
|
||||
let lib = vectorcraft_brush::library(&st.doc);
|
||||
strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some()))
|
||||
Some(strokes)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
//! An object's tags: name and value pairs scripts keep on page items (`object.tags`,
|
||||
//! `object.tag.add`, `object.tag.set`, `object.tag.remove`, `object.tag.removeAll`). The native file
|
||||
//! keeps them; other formats do not write them.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, MAX_TAG_TEXT, MAX_TAGS, Node, ObjectTag};
|
||||
|
||||
use super::{CommandSpec, NodeId, Result, Session, bad, cmd, has_doc, ids_param, targets, text_param, u64_req};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
query "object.tags",
|
||||
"Attributes",
|
||||
[],
|
||||
None,
|
||||
"{id} → {tags: [{tag, name, value}]} the object's tags in order; `tag` tells each apart from the others while its name and value change",
|
||||
has_doc,
|
||||
list
|
||||
),
|
||||
cmd!(
|
||||
"object.tag.add",
|
||||
"Attributes",
|
||||
[],
|
||||
None,
|
||||
"{id, name?: string, value?: string} adds a tag after the object's others (\"\" for a name or value left out), as one undo step; an object has at most 64 tags, each name and value at most 65,536 bytes → {tag}",
|
||||
has_doc,
|
||||
add
|
||||
),
|
||||
cmd!(
|
||||
"object.tag.set",
|
||||
"Attributes",
|
||||
[],
|
||||
None,
|
||||
"{id, tag, name?: string, value?: string} changes the tag's name or value, as one undo step; a value it already has changes nothing → {changed: bool}",
|
||||
has_doc,
|
||||
set
|
||||
),
|
||||
cmd!("object.tag.remove", "Attributes", [], None, "{id, tag} deletes the tag, as one undo step → {}", has_doc, remove),
|
||||
cmd!(
|
||||
"object.tag.removeAll",
|
||||
"Attributes",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?} deletes every tag of the objects in ids or the selection, as one undo step → {changed: objects}",
|
||||
has_doc,
|
||||
remove_all
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The page item `p`'s `id` names: an object of the document, not a layer or a ruler guide.
|
||||
fn object(s: &Session, p: &Value, c: &str) -> Result<NodeId> {
|
||||
let id = NodeId(u64_req(p, "id", c)?);
|
||||
let d = &s.doc()?.doc;
|
||||
match d.node(id) {
|
||||
Some(n) if is_page_item(n) => Ok(id),
|
||||
Some(_) => Err(bad(c, format!("object {} is a layer or a ruler guide, which has no tags", id.0))),
|
||||
None => Err(bad(c, format!("no object {}", id.0))),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_page_item(n: &Node) -> bool {
|
||||
!matches!(n.kind, vectorcraft_doc::NodeKind::Layer { .. }) && !n.is_ruler_guide()
|
||||
}
|
||||
|
||||
/// The tags of `n`.
|
||||
pub(crate) fn tags_of(n: &Node) -> &[ObjectTag] {
|
||||
n.extras().attrs.as_deref().map_or(&[], |a| a.tags.as_slice())
|
||||
}
|
||||
|
||||
/// The tag `p`'s `tag` names on object `id`: its index among the object's tags.
|
||||
fn tag_index(d: &Document, id: NodeId, p: &Value, c: &str) -> Result<usize> {
|
||||
let tag = u64_req(p, "tag", c)?;
|
||||
let n = d.node(id).ok_or_else(|| bad(c, format!("no object {}", id.0)))?;
|
||||
tags_of(n).iter().position(|t| t.id == tag).ok_or_else(|| bad(c, format!("object {} has no tag {tag}", id.0)))
|
||||
}
|
||||
|
||||
/// The text `p` gives for `key` (a tag's name or value), at most [`MAX_TAG_TEXT`] bytes. `None`
|
||||
/// when `p` leaves it out; a null is an error.
|
||||
fn tag_text<'a>(p: &'a Value, key: &str, c: &str) -> Result<Option<&'a str>> {
|
||||
if p.get(key).is_some_and(Value::is_null) {
|
||||
return Err(bad(c, format!("`{key}` must be a string")));
|
||||
}
|
||||
let t = text_param(p, key, c)?;
|
||||
if t.is_some_and(|t| t.len() > MAX_TAG_TEXT) {
|
||||
return Err(bad(c, format!("a tag's {key} is longer than 65,536 bytes")));
|
||||
}
|
||||
Ok(t)
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.tags";
|
||||
let id = object(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let tags = d.node(id).map(tags_of).unwrap_or_default();
|
||||
Ok(json!({"tags": tags.iter().map(|t| json!({"tag": t.id, "name": t.name, "value": t.value})).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.tag.add";
|
||||
let id = object(s, p, C)?;
|
||||
let name = tag_text(p, "name", C)?.unwrap_or_default().to_string();
|
||||
let value = tag_text(p, "value", C)?.unwrap_or_default().to_string();
|
||||
let count = s.doc()?.doc.node(id).map_or(0, |n| tags_of(n).len());
|
||||
if count >= MAX_TAGS {
|
||||
return Err(bad(C, format!("object {} has 64 tags, the most an object has", id.0)));
|
||||
}
|
||||
let tag = s.edit("Attributes", |d, _| {
|
||||
// A document-wide id: a tag deleted earlier in the run never shares it.
|
||||
let tag = d.alloc_tag_id(id).ok_or_else(|| bad(C, "the document has no tag ids left"))?;
|
||||
let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?;
|
||||
n.edit_attrs(|a| a.tags.push(ObjectTag { id: tag, name, value }));
|
||||
Ok(tag)
|
||||
})?;
|
||||
Ok(json!({"tag": tag}))
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.tag.set";
|
||||
let id = object(s, p, C)?;
|
||||
let name = tag_text(p, "name", C)?;
|
||||
let value = tag_text(p, "value", C)?;
|
||||
if name.is_none() && value.is_none() {
|
||||
return Err(bad(C, "give name or value"));
|
||||
}
|
||||
let at = tag_index(&s.doc()?.doc, id, p, C)?;
|
||||
let same = s
|
||||
.doc()?
|
||||
.doc
|
||||
.node(id)
|
||||
.and_then(|n| tags_of(n).get(at))
|
||||
.is_some_and(|t| name.is_none_or(|v| t.name == v) && value.is_none_or(|v| t.value == v));
|
||||
if same {
|
||||
return Ok(json!({"changed": false}));
|
||||
}
|
||||
s.edit("Attributes", |d, _| {
|
||||
let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?;
|
||||
n.edit_attrs(|a| {
|
||||
if let Some(t) = a.tags.get_mut(at) {
|
||||
if let Some(v) = name {
|
||||
v.clone_into(&mut t.name);
|
||||
}
|
||||
if let Some(v) = value {
|
||||
v.clone_into(&mut t.value);
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"changed": true}))
|
||||
}
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.tag.remove";
|
||||
let id = object(s, p, C)?;
|
||||
let at = tag_index(&s.doc()?.doc, id, p, C)?;
|
||||
s.edit("Attributes", |d, _| {
|
||||
let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?;
|
||||
let gone = n.edit_attrs(|a| (at < a.tags.len()).then(|| a.tags.remove(at).id));
|
||||
if let Some(t) = gone {
|
||||
d.raise_next_id(t.saturating_add(1));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({}))
|
||||
}
|
||||
|
||||
fn remove_all(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.tag.removeAll";
|
||||
ids_param(p, "ids", C)?;
|
||||
let ids = targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
for id in &ids {
|
||||
if d.node(*id).is_none() {
|
||||
return Err(bad(C, format!("no object {}", id.0)));
|
||||
}
|
||||
}
|
||||
let tagged: BTreeSet<NodeId> = ids.into_iter().filter(|id| d.node(*id).is_some_and(|n| !tags_of(n).is_empty())).collect();
|
||||
if !tagged.is_empty() {
|
||||
s.edit("Attributes", |d, _| {
|
||||
let mut last = 0;
|
||||
for id in &tagged {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
last = n.edit_attrs(|a| a.tags.drain(..).map(|t| t.id).fold(last, u64::max));
|
||||
}
|
||||
}
|
||||
d.raise_next_id(last.saturating_add(1));
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({"changed": tagged.len()}))
|
||||
}
|
||||
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character",
|
||||
[],
|
||||
None,
|
||||
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away, the glyph keeping its shape; 100 sets the ink edge to edge; a color glyph's ink is its color art or bitmap; a character without ink, such as a space, keeps its width; a ligature or a
Line truncated
|
||||
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\" (on area type with Dynamic Text (Block) on, a leading change sets the frame's line gap to the new leading less the size of the first character changed, within -1296..1296 pt, as text.setStyle), keepLineGap?: bool = false (as text.setStyle), tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each c
Line truncated
|
||||
has_doc,
|
||||
set_range_style
|
||||
),
|
||||
@@ -103,7 +103,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Step Type",
|
||||
[],
|
||||
None,
|
||||
"{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the space after the character before it, or at the start of a line (of the text, a paragraph, or after a forced line break) the space before the character after it (kerningBefore, as text.setRangeStyle), and nothing at an empty line's start; leading its paragraph), else every selected type object → {ids}",
|
||||
"{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the space after the character before it, or at the start of a line (of the text, a paragraph, or after a forced line break) the space before the character after it (kerningBefore, as text.setRangeStyle), and nothing at an empty line's start; leading its paragraph), else every selected type object. On area type with Dynamic Text (Block) on, a leading change sets the frame's line gap to the new leading less the size of the first character changed, within -1296..1296 pt, as text.setStyle → {ids}",
|
||||
has_doc,
|
||||
type_step
|
||||
),
|
||||
@@ -1213,6 +1213,7 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
},
|
||||
};
|
||||
let story = switch_or(p, "story", false, C)?;
|
||||
let keep_line_gap = switch_or(p, "keepLineGap", false, C)?;
|
||||
if story && ["start", "end"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
|
||||
return Err(bad(C, "`story` styles the whole story: give no `start` or `end`"));
|
||||
}
|
||||
@@ -1256,7 +1257,11 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let styled = if a == b { t.runs.clone() } else { unprotected_runs(&t.runs, a, b, &kept) };
|
||||
set.extend(styled.iter().flat_map(super::fonts::run_fonts));
|
||||
}
|
||||
refresh_bounds(t);
|
||||
// With Block on, the leading goes to the frame's line gap.
|
||||
match change.leading.filter(|_| !keep_line_gap).and_then(|l| super::typecmd::styled_start(t, a, b).map(|at| (at, l))) {
|
||||
Some((at, l)) => super::typecmd::refresh_with_leading(t, at, l),
|
||||
None => refresh_bounds(t),
|
||||
}
|
||||
n = if *f == id { t.runs.len() } else { n };
|
||||
}
|
||||
Ok(n)
|
||||
@@ -2077,7 +2082,11 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
edit::replace_range_styled(&mut t.runs, a, b, &runs);
|
||||
refresh_bounds(t);
|
||||
// With Block on, the step goes to the frame's line gap.
|
||||
match runs.first().filter(|_| matches!(step, Step::Leading)) {
|
||||
Some(first) => super::typecmd::refresh_with_leading(t, a, first.style.leading),
|
||||
None => refresh_bounds(t),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -157,13 +157,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"charStyle",
|
||||
"Character Styles",
|
||||
"Character",
|
||||
"; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt"
|
||||
"; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings"
|
||||
);
|
||||
v.push(spec(
|
||||
"charStyle.edit",
|
||||
"Edit Character Style",
|
||||
&[],
|
||||
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt",
|
||||
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings",
|
||||
|s, p| edit_style(s, p, Kind::Char),
|
||||
true,
|
||||
));
|
||||
@@ -500,13 +500,33 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Valu
|
||||
};
|
||||
each_text_mut(d, &mut |t| {
|
||||
let mut changed = false;
|
||||
// The first character whose leading the new definition changed.
|
||||
let mut leading_at = None;
|
||||
// Substitute the old definition only for leading generated by Block.
|
||||
let block = t.dynamic_text && matches!(t.kind, vectorcraft_doc::TextKind::Area { .. });
|
||||
let block_metrics = super::typecmd::block_fit_metrics(t).map(|(points, gap, _)| (gap / points, super::typecmd::BLOCK_SIZES.0 / points));
|
||||
let old_leading = old
|
||||
.get("leading")
|
||||
.filter(|_| block && old.get("leading") != new.get("leading"))
|
||||
.and_then(|v| serde_json::from_value::<Option<f64>>(v.clone()).ok());
|
||||
match kind {
|
||||
Kind::Char => {
|
||||
let mut off = 0;
|
||||
for r in &mut t.runs {
|
||||
if r.style.style_name == target {
|
||||
if let Some(l) = old_leading
|
||||
.filter(|_| block_metrics.is_some_and(|(gap, minimum)| r.style.leading == Some((r.style.size + gap).max(minimum))))
|
||||
{
|
||||
r.style.leading = l;
|
||||
}
|
||||
let was = r.style.leading;
|
||||
r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new, &base), new);
|
||||
changed = true;
|
||||
if r.style.leading != was && leading_at.is_none() {
|
||||
leading_at = Some(off);
|
||||
}
|
||||
}
|
||||
off += r.text.len();
|
||||
}
|
||||
}
|
||||
Kind::Para => {
|
||||
@@ -519,7 +539,11 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Valu
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
refresh_bounds(t);
|
||||
// With Block on, a leading the new definition gives goes to the frame's line gap.
|
||||
match leading_at {
|
||||
Some(at) => super::typecmd::refresh_with_given_leading(t, at),
|
||||
None => refresh_bounds(t),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
@@ -636,52 +660,7 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
}
|
||||
let mut st = with_attrs(&CharStyle::default(), m, &c)?;
|
||||
let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key);
|
||||
for (key, value, lo, hi) in
|
||||
[("size", st.size, 0.1, 1296.0), ("h_scale", st.h_scale, 1.0, 10000.0), ("v_scale", st.v_scale, 1.0, 10000.0)]
|
||||
{
|
||||
if changed(key) && !(lo..=hi).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
if changed("leading") && st.leading.is_some_and(|value| !(0.1..=5000.0).contains(&value)) {
|
||||
return Err(bad(&c, "`leading` must be from 0.1 to 5000, or null for Auto"));
|
||||
}
|
||||
let shift_max = 1296.0;
|
||||
for (key, value) in [("baseline_shift", st.baseline_shift), ("tcyUpDown", st.tcy_up_down), ("tcyLeftRight", st.tcy_left_right)] {
|
||||
if changed(key) && !(-shift_max..=shift_max).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {} to {shift_max}", -shift_max)));
|
||||
}
|
||||
}
|
||||
let (lo, hi) = (0.0, vectorcraft_doc::text::MAX_AKI);
|
||||
for (key, value) in [("akiLeft", st.aki_left), ("akiRight", st.aki_right)] {
|
||||
if changed(key) && !(lo..=hi).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
let (key, lo, hi) = ("tsume", 0.0, vectorcraft_doc::text::MAX_TSUME);
|
||||
if changed(key) && !(lo..=hi).contains(&st.tsume) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
let hi = vectorcraft_doc::text::MAX_DIACRITIC_POSITION;
|
||||
let lo = -hi;
|
||||
for (key, value) in [("diacriticHorizontal", st.diacritic_horizontal), ("diacriticVertical", st.diacritic_vertical)] {
|
||||
if changed(key) && !(lo..=hi).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
let lines = vectorcraft_doc::text::WARICHU_LINES;
|
||||
if changed("warichuLines") && !lines.contains(&st.warichu_lines) {
|
||||
return Err(bad(&c, format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end())));
|
||||
}
|
||||
let scale = vectorcraft_doc::text::WARICHU_SCALE;
|
||||
for (key, value, lo, hi) in [
|
||||
("warichuGap", st.warichu_gap, 0.0, vectorcraft_doc::text::MAX_WARICHU_GAP),
|
||||
("warichuScale", st.warichu_scale, *scale.start(), *scale.end()),
|
||||
] {
|
||||
if changed(key) && !(lo..=hi).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
st.check_ranges(changed).map_err(|e| bad(&c, e.message))?;
|
||||
// A language of the list, stored as its tag (as text.setFormat takes it).
|
||||
if let Some(l) = &st.language
|
||||
&& kept.and_then(|k| k.get("language")) != m.get("language")
|
||||
@@ -693,10 +672,6 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
style_paint(d, paint, key, &c)?;
|
||||
}
|
||||
}
|
||||
let (key, lo, hi) = ("stroke_width", 0.0, vectorcraft_doc::MAX_COORD);
|
||||
if changed(key) && !(lo..=hi).contains(&st.stroke_width) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
if changed("features") {
|
||||
style_features(&st.features, kept, &c)?;
|
||||
}
|
||||
@@ -753,85 +728,20 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
}
|
||||
}
|
||||
|
||||
/// The range of a paragraph style's indents, space before and space after, and Hyphenation Zone (pt),
|
||||
/// as `text.setFormat` keeps them.
|
||||
const PARA_DISTANCE: f64 = 1296.0;
|
||||
|
||||
/// Check the paragraph attributes of `st` (read from `attrs`) that differ from `kept` against the
|
||||
/// ranges `text.setFormat` keeps them to: the indents and the space before and after, each
|
||||
/// Hyphenation option, each Justification option (Minimum, Desired and Maximum in order, as
|
||||
/// `attrs` gives them), and the number of tab stops with the position and leader of each stop
|
||||
/// `kept` does not hold. A value `kept` has is not checked.
|
||||
/// ranges `text.setFormat` keeps them to ([`ParaStyle::check_ranges`]), the Justification options
|
||||
/// as `attrs` gives them. A value `kept` has is not checked.
|
||||
fn para_ranges(st: &ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>, c: &str) -> Result<()> {
|
||||
let within = |key: &str, value: f64, lo: f64, hi: f64| {
|
||||
if (lo..=hi).contains(&value) { Ok(()) } else { Err(bad(c, format!("`{key}` must be from {lo} to {hi}"))) }
|
||||
};
|
||||
let changed = |key: &str| attrs.contains_key(key) && kept.and_then(|k| k.get(key)) != attrs.get(key);
|
||||
let nested_changed = |key: &str, field: &str| {
|
||||
changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field))
|
||||
let check = |key: &str, field: Option<&str>| match field {
|
||||
None => changed(key),
|
||||
Some(field) => changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field)),
|
||||
};
|
||||
for (key, value) in [
|
||||
("left_indent", st.left_indent),
|
||||
("right_indent", st.right_indent),
|
||||
("first_line_indent", st.first_line_indent),
|
||||
("space_before", st.space_before),
|
||||
("space_after", st.space_after),
|
||||
] {
|
||||
if changed(key) {
|
||||
within(key, value, -PARA_DISTANCE, PARA_DISTANCE)?;
|
||||
}
|
||||
}
|
||||
let h = &st.hyphenation;
|
||||
for (field, value, lo, hi) in [
|
||||
("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0),
|
||||
("after_first", f64::from(h.after_first), 1.0, 15.0),
|
||||
("before_last", f64::from(h.before_last), 1.0, 15.0),
|
||||
("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0),
|
||||
("zone", h.zone, 0.0, PARA_DISTANCE),
|
||||
] {
|
||||
if nested_changed("hyphenation", field) {
|
||||
within(&format!("hyphenation.{field}"), value, lo, hi)?;
|
||||
}
|
||||
}
|
||||
// Read as given: a paragraph's attributes keep justification options in range as they load.
|
||||
if let Some(given) = attrs.get("justification").filter(|_| changed("justification")) {
|
||||
let j: vectorcraft_doc::JustificationOptions = serde_json::from_value(given.clone()).map_err(|e| bad(c, e.to_string()))?;
|
||||
for (field, values, (lo, hi)) in [
|
||||
("word_spacing", j.word_spacing, vectorcraft_doc::JustificationOptions::WORD_SPACING),
|
||||
("letter_spacing", j.letter_spacing, vectorcraft_doc::JustificationOptions::LETTER_SPACING),
|
||||
("glyph_scaling", j.glyph_scaling, vectorcraft_doc::JustificationOptions::GLYPH_SCALING),
|
||||
] {
|
||||
if !nested_changed("justification", field) {
|
||||
continue;
|
||||
}
|
||||
let name = format!("justification.{field}");
|
||||
for value in values {
|
||||
within(&name, value, lo, hi)?;
|
||||
}
|
||||
if !(values[0] <= values[1] && values[1] <= values[2]) {
|
||||
return Err(bad(c, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")));
|
||||
}
|
||||
}
|
||||
if nested_changed("justification", "auto_leading") {
|
||||
let (lo, hi) = vectorcraft_doc::JustificationOptions::AUTO_LEADING;
|
||||
within("justification.auto_leading", j.auto_leading, lo, hi)?;
|
||||
}
|
||||
}
|
||||
if changed("tabs") {
|
||||
let kept_tabs = kept_tab_stops(kept);
|
||||
let max = TabStop::MAX_STOPS;
|
||||
if st.tabs.len() > max.max(kept_tabs.len()) {
|
||||
return Err(bad(c, format!("at most {max} tab stops")));
|
||||
}
|
||||
for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) {
|
||||
within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?;
|
||||
let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER);
|
||||
if stop.leader.chars().count() > max {
|
||||
return Err(bad(c, format!("{label} must be at most {max} characters")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
let given = attrs.get("justification").filter(|_| changed("justification"));
|
||||
let justification: Option<vectorcraft_doc::JustificationOptions> =
|
||||
given.map(|g| serde_json::from_value(g.clone())).transpose().map_err(|e| bad(c, e.to_string()))?;
|
||||
st.check_ranges(justification.as_ref(), &kept_tab_stops(kept), check).map_err(|e| bad(c, e.message))
|
||||
}
|
||||
|
||||
/// The tab stops `kept` holds, each as it reads (a stop that does not read is left out).
|
||||
@@ -971,6 +881,8 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
let attrs = kind.attrs(d, &name).ok_or_else(|| bad(&c, format!("no style `{name}`")))?;
|
||||
let normal = kind.attrs(d, kind.normal()).unwrap_or_default();
|
||||
let clear = bool_or(p, "clearOverrides", false);
|
||||
// The style sets a leading, or clearing overrides gives the text Normal's.
|
||||
let sets_leading = kind == Kind::Char && (attrs.contains_key("leading") || (clear && normal.contains_key("leading")));
|
||||
let style_name = (name != kind.normal()).then(|| name.clone());
|
||||
// A Type tool range or whole text objects.
|
||||
let text_range = super::typecmd::TextRange::parse(p, &c)?;
|
||||
@@ -997,6 +909,8 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
s.edit_named("Apply {name}", &name, name == kind.normal(), |d, _| {
|
||||
for id in &ids {
|
||||
let Some(t) = text_mut(d, *id) else { continue };
|
||||
// The first character given the style's leading.
|
||||
let mut leading_at = None;
|
||||
match kind {
|
||||
Kind::Char => {
|
||||
let len = vectorcraft_text::edit::runs_len(&t.runs);
|
||||
@@ -1017,6 +931,7 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
if let Some(e) = err {
|
||||
return Err(e);
|
||||
}
|
||||
leading_at = sets_leading.then(|| super::typecmd::styled_start(t, a.min(b), a.max(b))).flatten();
|
||||
}
|
||||
Kind::Para => {
|
||||
let mut v = t.paragraph_styles();
|
||||
@@ -1030,7 +945,11 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
t.set_paragraph_styles(v);
|
||||
}
|
||||
}
|
||||
refresh_bounds(t);
|
||||
// With Block on, a leading the style sets goes to the frame's line gap.
|
||||
match leading_at {
|
||||
Some(at) => super::typecmd::refresh_with_given_leading(t, at),
|
||||
None => refresh_bounds(t),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -1204,17 +1123,22 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> {
|
||||
|
||||
/// The styles of `kind` in `src` that load, with their source names so that art in the file keeps
|
||||
/// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes,
|
||||
/// scales, leading, shifts, Insert Aki, Tsume, diacritic positions, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose
|
||||
/// scales, leading, tracking, kerning, shifts, rotation, Insert Aki, Tsume, diacritic positions, Warichu Settings, Small Caps,
|
||||
/// variable font axes or stroke weight, miter limit or dashes are out of the range `charStyle.new` takes ([`CharStyle::check_ranges`]), whose
|
||||
/// indents, spacing, Hyphenation or Justification options or tab stops are out of the range
|
||||
/// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in
|
||||
/// `src` of those skipped)
|
||||
fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
|
||||
const RANGED: [&str; 24] = [
|
||||
const RANGED: [&str; 32] = [
|
||||
"size",
|
||||
"h_scale",
|
||||
"v_scale",
|
||||
"leading",
|
||||
"tracking",
|
||||
"kerning",
|
||||
"kerningBefore",
|
||||
"baseline_shift",
|
||||
"rotation",
|
||||
"akiLeft",
|
||||
"akiRight",
|
||||
"tsume",
|
||||
@@ -1226,6 +1150,10 @@ fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
|
||||
"warichuGap",
|
||||
"warichuScale",
|
||||
"stroke_width",
|
||||
"stroke_miter_limit",
|
||||
"stroke_dash",
|
||||
"small_caps",
|
||||
"fontAxes",
|
||||
"left_indent",
|
||||
"right_indent",
|
||||
"first_line_indent",
|
||||
|
||||
@@ -401,6 +401,11 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
|
||||
json!({"tsume": 100.1}),
|
||||
json!({"diacriticHorizontal": -1000.1}),
|
||||
json!({"diacriticVertical": 1000.1}),
|
||||
json!({"tracking": -1000.1}),
|
||||
json!({"kerning": 10000.1}),
|
||||
json!({"rotation": 360.1}),
|
||||
json!({"stroke_miter_limit": 0.9}),
|
||||
json!({"small_caps": 200.1}),
|
||||
] {
|
||||
let key = attrs.as_object().unwrap().keys().next().unwrap();
|
||||
for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] {
|
||||
@@ -425,7 +430,9 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
|
||||
"tcyUpDown": 1296.0, "tcyLeftRight": -1296.0,
|
||||
"akiLeft": 0.0, "akiRight": 1000.0,
|
||||
"tsume": 100.0,
|
||||
"diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0
|
||||
"diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0,
|
||||
"tracking": 10000.0, "kerning": -1000.0, "rotation": -360.0,
|
||||
"stroke_miter_limit": 500.0, "small_caps": 200.0
|
||||
}}),
|
||||
)
|
||||
.unwrap();
|
||||
@@ -830,8 +837,8 @@ fn load_all_styles_loads_both_kinds_in_one_step() {
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
|
||||
/// A loaded character style whose size, scale, leading, shift, warichu Line Gap or stroke width is
|
||||
/// out of the range `charStyle.new` takes is skipped.
|
||||
/// A loaded character style whose size, scale, leading, shift, warichu Line Gap, stroke width or
|
||||
/// miter limit, tracking, kerning or rotation is out of the range `charStyle.new` takes is skipped.
|
||||
#[test]
|
||||
fn loaded_styles_out_of_range_are_skipped() {
|
||||
let (mut s, _) = session_with_text("Title");
|
||||
@@ -841,11 +848,17 @@ fn loaded_styles_out_of_range_are_skipped() {
|
||||
("Shifted", json!({"baseline_shift": 5000.0})),
|
||||
("Thick", json!({"stroke_width": -2.0})),
|
||||
("Gapped", json!({"warichuGap": 500.0})),
|
||||
("Spun", json!({"rotation": 720.0})),
|
||||
("Tracked", json!({"tracking": 50000.0})),
|
||||
("Kerned", json!({"kerning": -5000.0})),
|
||||
("Before", json!({"kerningBefore": 50000.0})),
|
||||
("Mitered", json!({"stroke_miter_limit": 0.5})),
|
||||
("Fine", json!({"size": 12.0, "h_scale": 50.0})),
|
||||
];
|
||||
let data = styles_file(&file, &[]);
|
||||
let r = s.execute("charStyle.load", &json!({"dataBase64": data, "name": "Other.vectorcraft"})).unwrap();
|
||||
assert_eq!(r, json!({"added": ["Fine"], "existing": [], "skipped": ["Huge", "Flat", "Shifted", "Thick", "Gapped"]}));
|
||||
let skipped = ["Huge", "Flat", "Shifted", "Thick", "Gapped", "Spun", "Tracked", "Kerned", "Before", "Mitered"];
|
||||
assert_eq!(r, json!({"added": ["Fine"], "existing": [], "skipped": skipped}));
|
||||
assert_eq!(listed(&mut s, "charStyle"), [NORMAL_CHAR, "Fine"]);
|
||||
}
|
||||
|
||||
|
||||
@@ -95,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Area Type Options…",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
|
||||
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error; a leading change on the text also sets lineGap, as type.dynamicText says) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
|
||||
has_selection,
|
||||
area_options
|
||||
),
|
||||
@@ -140,7 +140,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
|
||||
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", keepLineGap?: bool = false (true: Dynamic Text (Block) keeps the frame's line gap, as Reset Panel does), tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; on area type with Dynamic Text (Block) on, a leading change sets the frame's line gap (text.areaOptions lineGap) to the new leading less the size of the first character changed, within -1296..1296 pt, so every line spreads or tightens by the change, unless keepLineGap is true; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
|
||||
has_doc,
|
||||
set_style
|
||||
),
|
||||
@@ -335,6 +335,11 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) {
|
||||
// Edits that changed the paragraph count keep one paragraph style per paragraph.
|
||||
t.normalize_paras();
|
||||
block::block_fit(t);
|
||||
refresh_fitted(t);
|
||||
}
|
||||
|
||||
/// The part of [`refresh_bounds`] after Block has fitted the lines.
|
||||
fn refresh_fitted(t: &mut TextObject) {
|
||||
auto_height(t);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
t.cached_bounds = Some(lay.bounds);
|
||||
@@ -342,6 +347,36 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) {
|
||||
t.cached_ink = Some((lay.bounds, vectorcraft_render::effects::preview::laid_out_ink(&lay, t)));
|
||||
}
|
||||
|
||||
/// [`refresh_bounds`] after a change that set the leading of the character at `at` to `leading`
|
||||
/// (in text space; None: Auto): on area type with Block on the change goes to the frame's line gap
|
||||
/// ([`block::leading_to_line_gap`]), and the lines are fitted again only when the gap changed.
|
||||
pub(crate) fn refresh_with_leading(t: &mut TextObject, at: usize, leading: Option<f64>) {
|
||||
if block::leading_to_line_gap(t, at, leading) {
|
||||
refresh_fitted(t);
|
||||
} else {
|
||||
refresh_bounds(t);
|
||||
}
|
||||
}
|
||||
|
||||
/// The first character a style change over `a..b` of `t` reaches, with both ends on character
|
||||
/// boundaries as [`vectorcraft_text::edit::style_range`] sets them; None when the range styles no
|
||||
/// character (empty, or inside one character, in text that is not empty).
|
||||
pub(crate) fn styled_start(t: &TextObject, a: usize, b: usize) -> Option<usize> {
|
||||
let plain = t.plain_text();
|
||||
let (a, b) = (vectorcraft_text::edit::floor_char(&plain, a), vectorcraft_text::edit::floor_char(&plain, b));
|
||||
(a != b || plain.is_empty()).then_some(a.min(b))
|
||||
}
|
||||
|
||||
/// [`refresh_with_leading`] with the leading the character at `at` was just given (a character
|
||||
/// style, Text Tweaker).
|
||||
pub(crate) fn refresh_with_given_leading(t: &mut TextObject, at: usize) {
|
||||
if block::given_leading_to_line_gap(t, at) {
|
||||
refresh_fitted(t);
|
||||
} else {
|
||||
refresh_bounds(t);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`refresh_bounds`] for a document that is opening: the first frame takes the layout
|
||||
/// ([`vectorcraft_text::take_kept_layout`]) instead of laying the object out again.
|
||||
pub(crate) fn refresh_bounds_for_first_frame(t: &mut TextObject) {
|
||||
@@ -955,6 +990,7 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
return Err(bad(C, "nothing to change"));
|
||||
}
|
||||
let keep_line_gap = switch_or(p, "keepLineGap", false, C)?;
|
||||
let range = TextRange::parse(p, C)?;
|
||||
let ids = text_targets(s, p, C)?;
|
||||
let protect = s.prefs.missing_glyph_protection && (font.is_some() || style.is_some());
|
||||
@@ -1032,7 +1068,14 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let span = para_span(range, t);
|
||||
t.edit_paras(span, |pa| pa.justify = j);
|
||||
}
|
||||
refresh_bounds(t);
|
||||
// With Block on, the leading goes to the frame's line gap; an empty range styles nothing.
|
||||
let changed = leading.filter(|_| !keep_line_gap).and_then(|l| {
|
||||
range.map_or(Some(0), |r| Some(r.bytes(t)).filter(|(a, b)| a < b).and_then(|(a, b)| styled_start(t, a, b))).map(|at| (at, l))
|
||||
});
|
||||
match changed {
|
||||
Some((at, l)) => refresh_with_leading(t, at, l),
|
||||
None => refresh_bounds(t),
|
||||
}
|
||||
}
|
||||
// Graph labels keep a change made to all of their text through the graph being drawn again (sizes as given,
|
||||
// not in a scaled label's own units).
|
||||
@@ -1478,6 +1521,8 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
#[cfg(test)]
|
||||
mod area_tests;
|
||||
mod block;
|
||||
pub(super) use block::SIZES as BLOCK_SIZES;
|
||||
pub(super) use block::fit_metrics as block_fit_metrics;
|
||||
pub(crate) use block::needed_room;
|
||||
#[cfg(test)]
|
||||
mod block_tests;
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
//! typed is set to the frame's width by changing its font size, after every edit
|
||||
//! ([`super::refresh_bounds`]).
|
||||
|
||||
use vectorcraft_doc::{TextKind, TextObject, TextRun};
|
||||
use vectorcraft_doc::{CharStyle, TextKind, TextObject, TextRun};
|
||||
|
||||
/// The font size range a line's first character is fitted within, in document points (the
|
||||
/// Character panel's).
|
||||
const SIZES: (f64, f64) = (0.1, 1296.0);
|
||||
pub(crate) const SIZES: (f64, f64) = (0.1, 1296.0);
|
||||
|
||||
/// Most passes a refit runs to correct lines that still wrap after the first fit; each pass measures
|
||||
/// the lines and runs at most one more area layout.
|
||||
@@ -56,6 +56,19 @@ pub(crate) fn size_at(runs: &[TextRun], byte: usize) -> f64 {
|
||||
vectorcraft_text::edit::style_at(runs, byte).size
|
||||
}
|
||||
|
||||
/// The run that holds the character at `byte` (not the one before it), else the last run.
|
||||
fn run_at(runs: &[TextRun], byte: usize) -> Option<&TextRun> {
|
||||
let mut off = 0;
|
||||
for r in runs {
|
||||
let end = off + r.text.len();
|
||||
if (off..end).contains(&byte) {
|
||||
return Some(r);
|
||||
}
|
||||
off = end;
|
||||
}
|
||||
runs.last()
|
||||
}
|
||||
|
||||
/// The stored size of each line's first character, in one pass over the runs.
|
||||
fn first_sizes(runs: &[TextRun], lines: &[TypedLine]) -> Vec<f64> {
|
||||
let mut out = Vec::with_capacity(lines.len());
|
||||
@@ -122,6 +135,71 @@ pub(crate) fn needed_room(t: &TextObject) -> Option<(f64, usize, usize)> {
|
||||
.reduce(|a, b| if b.0 > a.0 { b } else { a })
|
||||
}
|
||||
|
||||
/// Whether every character's leading is the one Block gives it: its size plus the frame's line
|
||||
/// gap (in text space, at least the least size), as [`block_fit`] sets it.
|
||||
fn block_leadings(t: &TextObject, points: f64) -> bool {
|
||||
let gap = t.area.block_gaps().1 / points;
|
||||
let min_leading = SIZES.0 / points;
|
||||
t.runs.iter().all(|r| r.style.leading == Some((r.style.size + gap).max(min_leading)))
|
||||
}
|
||||
|
||||
/// A leading change on area type with Block on ([`TextObject::dynamic_text`]), called after the
|
||||
/// change is applied to the characters: Block sets each character's leading to its size plus the
|
||||
/// frame's line gap, so the change goes to the line gap instead. The lines are fitted, so the
|
||||
/// character at `at` has the size Block gives it (a size set by the same change included); the gap
|
||||
/// is then the leading `leading` gives that character (in text space; None: Auto) less its size, in
|
||||
/// document points and kept within [`vectorcraft_doc::AreaOptions::LINE_GAP`]. That moves the gap
|
||||
/// by the change to the character's leading, so every line spreads or tightens by the same amount.
|
||||
/// A new gap moves the lines, which in a shaped frame changes the room each one has and so the size
|
||||
/// Block gives the character, so the lines are fitted again and the gap worked out again from the
|
||||
/// new size, at most [`BLOCK_PASSES`] times. True when the lines are fitted for the final gap, so the
|
||||
/// caller lays the text out without fitting it again. Point type, type on a path and area type with
|
||||
/// Block off are left as they are.
|
||||
pub(crate) fn leading_to_line_gap(t: &mut TextObject, at: usize, leading: Option<f64>) -> bool {
|
||||
if !t.dynamic_text || !matches!(t.kind, TextKind::Area { .. }) {
|
||||
return false;
|
||||
}
|
||||
let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false };
|
||||
t.normalize_paras();
|
||||
let para = t.plain_text().get(..at).map_or(0, |s| s.bytes().filter(|&c| c == b'\n').count());
|
||||
for _ in 0..BLOCK_PASSES {
|
||||
block_fit(t);
|
||||
// A frame Block could not fit leaves the characters as they were.
|
||||
if !block_leadings(t, points) {
|
||||
return false;
|
||||
}
|
||||
let Some(run) = run_at(&t.runs, at) else { return true };
|
||||
let size = run.style.size;
|
||||
let new = match leading {
|
||||
Some(l) => l,
|
||||
None => {
|
||||
// Auto leading as the layout sets it: the paragraph's Auto Leading share of the em size
|
||||
// the font height reference gives the character. An inline graphic keeps its size.
|
||||
let em = if run.inline.is_some() { size } else { vectorcraft_text::FontDb::global().em_size(&run.style, t.vertical) };
|
||||
t.para_at(para).effective_leading(&CharStyle { size: em, leading: None, ..run.style.clone() })
|
||||
}
|
||||
};
|
||||
let gap = (new - size) * points;
|
||||
if !gap.is_finite() {
|
||||
return true;
|
||||
}
|
||||
let (lo, hi) = vectorcraft_doc::AreaOptions::LINE_GAP;
|
||||
let next = gap.clamp(lo, hi);
|
||||
if (next - t.area.line_gap).abs() <= 1e-9 {
|
||||
return true;
|
||||
}
|
||||
t.area.line_gap = next;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// [`leading_to_line_gap`] with the leading the character at `at` was just given (a character
|
||||
/// style, Text Tweaker), read before Block sets it again.
|
||||
pub(crate) fn given_leading_to_line_gap(t: &mut TextObject, at: usize) -> bool {
|
||||
let Some(leading) = run_at(&t.runs, at).map(|r| r.style.leading) else { return false };
|
||||
leading_to_line_gap(t, at, leading)
|
||||
}
|
||||
|
||||
/// The size a line set at `size` points and `width` wide takes to fill `avail`, its width growing
|
||||
/// by `slope` a point of size (`width / size` when the whole line follows its size): rounded down
|
||||
/// to tenths and kept within [`SIZES`]. A line that fits and would not fit a tenth larger keeps its
|
||||
@@ -140,6 +218,21 @@ fn tenths(points: f64) -> f64 {
|
||||
((points * 10.0 + 1e-6).floor() / 10.0).clamp(SIZES.0, SIZES.1)
|
||||
}
|
||||
|
||||
pub(crate) fn fit_metrics(t: &TextObject) -> Option<(f64, f64, f64)> {
|
||||
if !t.dynamic_text {
|
||||
return None;
|
||||
}
|
||||
let TextKind::Area { frame } = &t.kind else { return None };
|
||||
let (_, line_gap) = t.area.block_gaps();
|
||||
let b = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()))?;
|
||||
let points = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12)?;
|
||||
let a = &t.area;
|
||||
let (along, cells, gutter) = if t.vertical { (b.height(), a.rows, a.row_gutter.unwrap_or(a.gutter)) } else { (b.width(), a.columns, a.gutter) };
|
||||
let cells = cells.max(1) as f64;
|
||||
let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells;
|
||||
(cell.is_finite() && cell > 1e-9).then_some((points, line_gap, cell))
|
||||
}
|
||||
|
||||
/// Fit area type with Dynamic Text (Block) on: with the word gap as every paragraph's Desired word
|
||||
/// spacing ([`TextObject::layout_justification`]; the paragraphs keep their own values), each line
|
||||
/// as typed gets the size (its first character's, in steps of 0.1 pt within 0.1 to
|
||||
@@ -150,24 +243,9 @@ fn tenths(points: f64) -> f64 {
|
||||
/// has no size. A line that still wraps at its first fit is made smaller, in at most
|
||||
/// [`BLOCK_PASSES`] more passes. True when the text changed.
|
||||
pub(crate) fn block_fit(t: &mut TextObject) -> bool {
|
||||
if !t.dynamic_text {
|
||||
return false;
|
||||
}
|
||||
let TextKind::Area { frame } = &t.kind else { return false };
|
||||
let (_, line_gap) = t.area.block_gaps();
|
||||
let Some(b) = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) else { return false };
|
||||
let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false };
|
||||
let Some((points, line_gap, cell)) = fit_metrics(t) else { return false };
|
||||
let before = t.runs.clone();
|
||||
|
||||
// The room along a line in one cell of the frame, before indents.
|
||||
let a = &t.area;
|
||||
let (along, cells, gutter) = if t.vertical { (b.height(), a.rows, a.row_gutter.unwrap_or(a.gutter)) } else { (b.width(), a.columns, a.gutter) };
|
||||
let cells = cells.max(1) as f64;
|
||||
let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells;
|
||||
if !(cell.is_finite() && cell > 1e-9) {
|
||||
return t.runs != before;
|
||||
}
|
||||
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let text = t.plain_text();
|
||||
let lines = typed_lines(&text);
|
||||
|
||||
@@ -31,6 +31,29 @@ fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_a_character_style_keeps_manual_leading_when_block_has_no_room() {
|
||||
for command in ["charStyle.setAttrs", "charStyle.edit"] {
|
||||
for manual_leading in [42.0, 12.0] {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 50.0, 400.0, "Inset");
|
||||
s.execute("text.areaOptions", &json!({"inset": 30})).unwrap();
|
||||
s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"leading": 30}})).unwrap();
|
||||
s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap();
|
||||
s.execute("text.setStyle", &json!({"ids": [id], "leading": manual_leading})).unwrap();
|
||||
s.execute("type.dynamicText", &json!({"ids": [id], "on": true})).unwrap();
|
||||
assert_eq!(text(&s, id).runs[0].style.leading, Some(manual_leading));
|
||||
let params = if command == "charStyle.edit" {
|
||||
json!({"name": "Body", "to": "Body", "attrs": {"leading": 60}})
|
||||
} else {
|
||||
json!({"name": "Body", "attrs": {"leading": 60}})
|
||||
};
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
assert_eq!(text(&s, id).runs[0].style.leading, Some(manual_leading), "{command}: {manual_leading}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The size of the character at `byte`.
|
||||
fn size_at(t: &TextObject, byte: usize) -> f64 {
|
||||
super::block::size_at(&t.runs, byte)
|
||||
@@ -672,6 +695,109 @@ fn point_type_with_nothing_to_fit_is_left_as_it_is() {
|
||||
assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow);
|
||||
}
|
||||
|
||||
/// The distances between the baselines of `t`'s lines.
|
||||
fn baseline_steps(t: &TextObject) -> Vec<f64> {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
lay.lines.windows(2).map(|w| w[1].baseline - w[0].baseline).collect()
|
||||
}
|
||||
|
||||
/// Block owns each character's leading (its size plus the line gap): a leading change from
|
||||
/// `text.setStyle`, `text.setRangeStyle` or `type.step` on area type with Block on changes the
|
||||
/// line gap by the difference from the first character's leading, in one undo step, and sticks.
|
||||
#[test]
|
||||
fn a_leading_change_with_block_on_moves_the_line_gap() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, "BIG\na much longer second line\nmid one");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, id);
|
||||
let (first, second) = (t.runs[0].style.size, size_at(&t, 4));
|
||||
let steps = baseline_steps(&t);
|
||||
let n = undo_len(&s);
|
||||
|
||||
// The whole object: the first character's leading becomes the leading given.
|
||||
s.execute("text.setStyle", &json!({"ids": [id], "leading": first + 6.0})).unwrap();
|
||||
assert_eq!(undo_len(&s), n + 1, "one undo step");
|
||||
let t = text(&s, id);
|
||||
assert!((t.area.line_gap - 6.0).abs() < 1e-9, "line gap {}", t.area.line_gap);
|
||||
assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - r.style.size - 6.0).abs() < 1e-9)), "{:?}", t.runs);
|
||||
assert_block(&t);
|
||||
let wider = baseline_steps(&t);
|
||||
assert!(wider.iter().zip(&steps).all(|(w, s)| (w - s - 6.0).abs() < 1e-6), "every line spreads: {steps:?} -> {wider:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(text(&s, id).area.line_gap, 0.0);
|
||||
|
||||
// A range: measured from the leading of its first character.
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": second - 3.0})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!((t.area.line_gap + 3.0).abs() < 1e-9, "line gap {}", t.area.line_gap);
|
||||
assert!(baseline_steps(&t).iter().zip(&steps).all(|(w, s)| w < s), "every line tightens");
|
||||
|
||||
// Alt+Up/Down steps by the Size/Leading increment.
|
||||
let inc = s.prefs.type_size_increment;
|
||||
s.execute("type.step", &json!({"attribute": "leading", "by": 1, "id": id, "start": 0, "end": 3})).unwrap();
|
||||
assert!((text(&s, id).area.line_gap - (inc - 3.0)).abs() < 1e-9);
|
||||
|
||||
// Auto: the first character's Auto leading, 120% of its size.
|
||||
s.execute("text.setStyle", &json!({"ids": [id], "leading": "auto"})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!((t.area.line_gap - t.runs[0].style.size * 0.2).abs() < 1e-6, "line gap {}", t.area.line_gap);
|
||||
|
||||
// The leading the first character already has changes nothing.
|
||||
let n = undo_len(&s);
|
||||
let lead = text(&s, id).runs[0].style.leading.unwrap();
|
||||
s.execute("text.setStyle", &json!({"ids": [id], "leading": lead})).unwrap();
|
||||
assert_eq!(undo_len(&s), n, "no undo step");
|
||||
|
||||
// The gap stays within its range.
|
||||
s.execute("text.setStyle", &json!({"ids": [id], "leading": 5000})).unwrap();
|
||||
assert_eq!(text(&s, id).area.line_gap, vectorcraft_doc::AreaOptions::LINE_GAP.1);
|
||||
// From a gap that holds every leading at its least, the leading given still applies.
|
||||
s.execute("text.areaOptions", &json!({"lineGap": -1296})).unwrap();
|
||||
s.execute("text.setStyle", &json!({"ids": [id], "leading": 1})).unwrap();
|
||||
let lead = text(&s, id).runs[0].style.leading.unwrap();
|
||||
assert!((lead - 1.0).abs() < 1e-6, "leading {lead}");
|
||||
s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap();
|
||||
// A size set with the leading: the gap follows the size Block gives the first character, on an
|
||||
// empty line (whose size Block keeps) too.
|
||||
s.execute("text.setStyle", &json!({"ids": [id], "size": 20, "leading": 50})).unwrap();
|
||||
let lead = text(&s, id).runs[0].style.leading.unwrap();
|
||||
assert!((lead - 50.0).abs() < 1e-6, "leading {lead}");
|
||||
s.execute("text.setText", &json!({"text": "\nwords"})).unwrap();
|
||||
s.execute("text.setStyle", &json!({"ids": [id], "size": 20, "leading": 30})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert_eq!(size_at(&t, 0), 20.0, "the empty line keeps the size set");
|
||||
assert!((t.runs[0].style.leading.unwrap() - 30.0).abs() < 1e-6, "{:?}", t.runs[0].style);
|
||||
s.execute("text.setText", &json!({"text": "BIG\na much longer second line\nmid one"})).unwrap();
|
||||
s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap();
|
||||
|
||||
// Scaled type: the leading given and the line gap are in document points.
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
|
||||
let points = text(&s, id).style_scale().unwrap().points;
|
||||
s.execute("text.setStyle", &json!({"ids": [id], "leading": 150})).unwrap();
|
||||
let t = text(&s, id);
|
||||
let (size, lead) = (t.runs[0].style.size * points, t.runs[0].style.leading.unwrap() * points);
|
||||
assert!((lead - 150.0).abs() < 1e-6, "leading {lead}");
|
||||
assert!((t.area.line_gap - (150.0 - size)).abs() < 1e-6, "line gap {} for size {size}", t.area.line_gap);
|
||||
}
|
||||
|
||||
/// Without Block (point type, and area type with Block off) a leading change sets the
|
||||
/// characters' leading and leaves the line gap.
|
||||
#[test]
|
||||
fn a_leading_change_without_block_sets_the_leading() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, "one\ntwo");
|
||||
s.execute("text.areaOptions", &json!({"lineGap": 5})).unwrap();
|
||||
s.execute("text.setStyle", &json!({"ids": [id], "leading": 30})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert_eq!(t.area.line_gap, 5.0);
|
||||
assert!(t.runs.iter().all(|r| r.style.leading == Some(30.0)));
|
||||
let id = point(&mut s, "one\ntwo", json!({}));
|
||||
s.execute("type.step", &json!({"attribute": "leading", "by": 1, "id": id, "start": 0, "end": 3})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert_eq!(t.area.line_gap, 0.0);
|
||||
assert_eq!(t.runs[0].style.leading, Some(12.0 * 1.2 + s.prefs.type_size_increment));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_text_fits_in_a_bounded_number_of_layouts() {
|
||||
let mut s = session();
|
||||
@@ -698,3 +824,155 @@ fn long_text_fits_in_a_bounded_number_of_layouts() {
|
||||
let bound = 2 * (2 + 2 * super::block::BLOCK_PASSES as u64) + 8;
|
||||
assert!(used <= bound, "point type: {used} layouts");
|
||||
}
|
||||
|
||||
/// Area type with Block on, its lines at different sizes, and a line gap of 0.
|
||||
fn block_text(s: &mut Session) -> u64 {
|
||||
let id = area(s, 300.0, 400.0, "BIG\na much longer second line\nmid one");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
assert_eq!(text(s, id).area.line_gap, 0.0);
|
||||
id
|
||||
}
|
||||
|
||||
/// The leading of the one-byte character at `byte` (`style_at` reads the character before a run
|
||||
/// end, so it is asked for the end of the character).
|
||||
fn leading_at(t: &TextObject, byte: usize) -> Option<f64> {
|
||||
vectorcraft_text::edit::style_at(&t.runs, byte + 1).leading
|
||||
}
|
||||
|
||||
/// `text.setRangeStyle {leading}` on a range of Block text moves the line gap by the change to
|
||||
/// the leading of the range's first character, and the range keeps the leading given.
|
||||
#[test]
|
||||
fn a_range_leading_change_with_block_on_moves_the_line_gap() {
|
||||
let mut s = session();
|
||||
let id = block_text(&mut s);
|
||||
let second = vectorcraft_text::edit::style_at(&text(&s, id).runs, 5).size;
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": second + 5.0})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!((t.area.line_gap - 5.0).abs() < 1e-9, "line gap {}", t.area.line_gap);
|
||||
assert!(leading_at(&t, 4).is_some_and(|l| (l - second - 5.0).abs() < 1e-9), "{:?}", leading_at(&t, 4));
|
||||
assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - r.style.size - 5.0).abs() < 1e-9)), "every line spreads");
|
||||
// Reset Panel's form: the leading is set and Block keeps the line gap.
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": "auto", "keepLineGap": true})).unwrap();
|
||||
assert!((text(&s, id).area.line_gap - 5.0).abs() < 1e-9);
|
||||
s.execute("text.setStyle", &json!({"ids": [id], "leading": "auto", "keepLineGap": true})).unwrap();
|
||||
assert!((text(&s, id).area.line_gap - 5.0).abs() < 1e-9);
|
||||
assert!(s.execute("text.setStyle", &json!({"ids": [id], "leading": 30, "keepLineGap": 1})).is_err(), "keepLineGap takes a bool");
|
||||
}
|
||||
|
||||
/// A range inside one character styles nothing, so it leaves the line gap.
|
||||
#[test]
|
||||
fn a_leading_on_a_range_inside_one_character_leaves_the_line_gap() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, "\u{e9}t\u{e9}\nsecond line");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
s.execute("charStyle.new", &json!({"name": "Loose", "attrs": {"leading": 50}})).unwrap();
|
||||
let gap = text(&s, id).area.line_gap;
|
||||
let range = json!({"start": 0, "end": 1});
|
||||
let mut setstyle = json!({"ids": [id], "leading": 50});
|
||||
let mut setrange = json!({"id": id, "leading": 50});
|
||||
let mut apply = json!({"name": "Loose", "id": id});
|
||||
for p in [&mut setstyle, &mut setrange, &mut apply] {
|
||||
p.as_object_mut().unwrap().extend(range.as_object().unwrap().clone());
|
||||
}
|
||||
for (c, p) in [("text.setStyle", setstyle), ("text.setRangeStyle", setrange), ("charStyle.apply", apply)] {
|
||||
s.execute(c, &p).unwrap_or_else(|e| panic!("{c}: {e}"));
|
||||
assert_eq!(text(&s, id).area.line_gap, gap, "{c}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `type.step {attribute: "leading"}` (Alt+Up/Down) on Block text moves the line gap by the step.
|
||||
#[test]
|
||||
fn a_leading_step_with_block_on_moves_the_line_gap() {
|
||||
let mut s = session();
|
||||
let id = block_text(&mut s);
|
||||
let inc = s.prefs.type_size_increment;
|
||||
s.execute("type.step", &json!({"attribute": "leading", "by": -1, "id": id, "start": 0, "end": 3})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!((t.area.line_gap + inc).abs() < 1e-9, "line gap {}", t.area.line_gap);
|
||||
assert!(leading_at(&t, 0).is_some_and(|l| (l - t.runs[0].style.size + inc).abs() < 1e-9));
|
||||
}
|
||||
|
||||
/// A character style edited to set a leading while Block text uses it moves the line gap; a style
|
||||
/// without a leading leaves the gap.
|
||||
#[test]
|
||||
fn a_character_style_edited_to_a_leading_with_block_on_moves_the_line_gap() {
|
||||
let mut s = session();
|
||||
let id = block_text(&mut s);
|
||||
s.execute("charStyle.new", &json!({"name": "Plain", "attrs": {"tracking": 0}})).unwrap();
|
||||
s.execute("charStyle.apply", &json!({"name": "Plain", "id": id})).unwrap();
|
||||
assert_eq!(text(&s, id).area.line_gap, 0.0, "no leading in the style");
|
||||
s.execute("charStyle.edit", &json!({"name": "Plain", "to": "Plain", "attrs": {"tracking": 0, "leading": 60}})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!((t.area.line_gap - (60.0 - t.runs[0].style.size)).abs() < 1e-6, "edit: line gap {}", t.area.line_gap);
|
||||
assert!(leading_at(&t, 0).is_some_and(|l| (l - 60.0).abs() < 1e-6));
|
||||
assert_spread(&t);
|
||||
|
||||
// Once Block has given the characters other leadings than the style's (a new line gap here), a
|
||||
// new leading in the style still applies: Block's leadings are not overrides.
|
||||
s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap();
|
||||
let gap = text(&s, id).area.line_gap;
|
||||
s.execute("charStyle.edit", &json!({"name": "Plain", "to": "Plain", "attrs": {"tracking": 0, "leading": 70}})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!(t.area.line_gap != gap, "the line gap moved");
|
||||
assert!(leading_at(&t, 0).is_some_and(|l| (l - 70.0).abs() < 1e-6), "{:?}", leading_at(&t, 0));
|
||||
assert_spread(&t);
|
||||
}
|
||||
|
||||
/// Every character's leading is its size plus the frame's line gap (at least the least size), so
|
||||
/// every line spread or tightened by the same amount.
|
||||
fn assert_spread(t: &TextObject) {
|
||||
let gap = t.area.line_gap;
|
||||
let least = super::block::SIZES.0;
|
||||
assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - (r.style.size + gap).max(least)).abs() < 1e-6)), "{:?}", t.runs);
|
||||
}
|
||||
|
||||
/// A character style that sets a leading, applied to Block text, moves the line gap.
|
||||
#[test]
|
||||
fn a_character_style_leading_applied_with_block_on_moves_the_line_gap() {
|
||||
let mut s = session();
|
||||
let id = block_text(&mut s);
|
||||
s.execute("charStyle.new", &json!({"name": "Loose", "attrs": {"leading": 50}})).unwrap();
|
||||
s.execute("charStyle.apply", &json!({"name": "Loose", "id": id})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!((t.area.line_gap - (50.0 - t.runs[0].style.size)).abs() < 1e-6, "apply: line gap {}", t.area.line_gap);
|
||||
assert!(leading_at(&t, 0).is_some_and(|l| (l - 50.0).abs() < 1e-6));
|
||||
assert_spread(&t);
|
||||
|
||||
// Clearing overrides gives the text the leading of the Normal style.
|
||||
s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": {"leading": 44}})).unwrap();
|
||||
s.execute("charStyle.new", &json!({"name": "Plain", "attrs": {"tracking": 0}})).unwrap();
|
||||
s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap();
|
||||
s.execute("charStyle.apply", &json!({"name": "Plain", "id": id, "clearOverrides": true})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!(leading_at(&t, 0).is_some_and(|l| (l - 44.0).abs() < 1e-6), "clear: {:?}", leading_at(&t, 0));
|
||||
assert!((t.area.line_gap - (44.0 - t.runs[0].style.size)).abs() < 1e-6, "clear: line gap {}", t.area.line_gap);
|
||||
assert_spread(&t);
|
||||
}
|
||||
|
||||
/// Text Tweaker's leading ramp on Block text moves the line gap to its first character's value;
|
||||
/// Block then gives every other character its size plus that gap.
|
||||
#[test]
|
||||
fn a_text_tweaker_leading_with_block_on_moves_the_line_gap() {
|
||||
let mut s = session();
|
||||
let id = block_text(&mut s);
|
||||
s.execute("addon.type.textTweaker", &json!({"attribute": "leading", "from": 40, "to": 45, "ids": [id]})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!((t.area.line_gap - (40.0 - t.runs[0].style.size)).abs() < 1e-6, "line gap {}", t.area.line_gap);
|
||||
assert!(leading_at(&t, 0).is_some_and(|l| (l - 40.0).abs() < 1e-6));
|
||||
assert_spread(&t);
|
||||
}
|
||||
|
||||
/// The Eyedropper copies a whole character style, so the leading it copies onto Block text is not
|
||||
/// a leading change: the line gap stays, and Block gives every character its size plus the gap.
|
||||
#[test]
|
||||
fn an_eyedropper_copy_onto_block_text_keeps_the_line_gap() {
|
||||
let mut s = session();
|
||||
let source = point(&mut s, "source", json!({}));
|
||||
s.execute("text.setStyle", &json!({"ids": [source], "leading": 33})).unwrap();
|
||||
let id = block_text(&mut s);
|
||||
let gap = text(&s, id).area.line_gap;
|
||||
s.execute("appearance.copyFrom", &json!({"source": source, "ids": [id]})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert_eq!(t.area.line_gap, gap);
|
||||
assert_spread(&t);
|
||||
}
|
||||
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Dynamic Text",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type, or turn it on for point type (on omitted: the opposite of the first object's setting, point type counting as off, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap, and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection, and no point type it turns into area type, is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Turning it on turns point type into area type with Block on, with the default Area Type Options but the gaps (options kept from an earlier frame do not carry over): the frame is as wide (along the lines) as the widest line as typed with its paragraph's indents, so that line keeps its size and sits where it was (by its own alignment), the other lines are set to that width (when negative indents take more than that line's width, the frame is as wide as the line, and Block makes it larger), and the frame then grows in depth (down, or to the left for vertical type) to hold every fitted line, around any Text Wrap objects above it; the gaps apply to it as to area type. Point type with no line to fit (empty, or only spaces and breaks) is left as it is, and so is point type when it is turned off; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}",
|
||||
"{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type, or turn it on for point type (on omitted: the opposite of the first object's setting, point type counting as off, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap (a leading change on the text, from text.setStyle, text.setRangeStyle, type.step, a character style or Text Tweaker, sets lineGap to the new leading less the size of the first character changed), and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection, and no point type it turns into area type, is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Turning it on turns point type into area type with Block on, with the default Area Type Options but the gaps (options kept from an earlier frame do not carry over): the frame is as wide (along the lines) as the widest line as typed with its paragraph's indents, so that line keeps its size and sits where it was (by its own alignment), the other lines are set to that width (when negative indents take more than that line's width, the frame is as wide as the line, and Block makes it larger), and the frame then grows in depth (down, or to the left for vertical type) to hold every fitted line, around any Text Wrap objects above it; the gaps apply to it as to area type. Point type with no line to fit (empty, or only spaces and breaks) is left as it is, and so is point type when it is turned off; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}",
|
||||
has_dynamic_type,
|
||||
dynamic_text
|
||||
),
|
||||
|
||||
@@ -23,7 +23,10 @@ use vectorcraft_doc::{DataSet, DataValue, Document, NodeId, NodeKind, Selection,
|
||||
use super::edit::selected_roots;
|
||||
use super::fileio::{absolute_path, read_file_head, write_file};
|
||||
use super::textedit::set_story_text;
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selection, links, str_param};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_or_selection, checked_ids_param, cmd, has_doc, has_selection, links,
|
||||
str_param,
|
||||
};
|
||||
|
||||
mod csv;
|
||||
mod library;
|
||||
@@ -435,7 +438,8 @@ fn bind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn unbind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "variable.unbind";
|
||||
let ids = checked_ids_or_selection(s, p, C)?;
|
||||
// Explicit bindings can include both a group and its children; retain every supplied ID.
|
||||
let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { checked_ids_or_selection(s, p, C)? };
|
||||
let name = defined_variable(s, p, C)?;
|
||||
let n = edit_variables(s, "Unbind Variable", |vars| {
|
||||
let mut n = 0;
|
||||
|
||||
@@ -21,7 +21,7 @@ use vectorcraft_render::encode::quantize::{self, Dither, Indexed, PaletteOptions
|
||||
use vectorcraft_render::encode::web::{self, ColorSort};
|
||||
use vectorcraft_render::encode::{gif, jpeg, png};
|
||||
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_or, has_doc, str_param, unique_name_from};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_or, has_doc, str_param, text_param, unique_name_from};
|
||||
|
||||
const C: &str = "document.exportForWeb";
|
||||
|
||||
@@ -45,6 +45,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
preview
|
||||
),
|
||||
cmd!(
|
||||
"document.exportForWeb.saveColorTable",
|
||||
"Save Color Table",
|
||||
[],
|
||||
None,
|
||||
"{path?: the .act file (.act is added to a name without an extension), …the settings of document.exportForWeb (preset?, format?: gif|png8…), slice?: n (1-based, from slice.list, among the slices `slices` names; default the whole image, whatever `slices` is)} write the GIF or PNG-8 color table the preview shows as a color table file: 772 bytes, the colors as written (red, green, blue) in file order, zero bytes up to 256 colors, then the number of colors and the transparent entry's index (65535 for none), two bytes each, most significant byte first → {path, colors (how many), transparentIndex (null for none), bytes, warnings}; no path → {dataBase64, colors, transparentIndex, bytes, warnings}. An empty path, jpg and png24 are an error; the document and the settings do not change",
|
||||
has_doc,
|
||||
save_color_table
|
||||
),
|
||||
cmd!(
|
||||
query "webExport.loadColorTable",
|
||||
"Load Color Table",
|
||||
[],
|
||||
None,
|
||||
"{path | dataBase64: a color table file (.act: 768 bytes of 256 colors, or 772 bytes with the number of colors used, 1–256, and the transparent entry's index), …the settings of document.exportForWeb (preset?, format?: gif|png8…)} the settings with the table loaded: its colors other than the transparent entry become colorTable.customPalette, colors becomes the number of colors it uses (at least 2), the table's other edits (locked, transparent, deleted, shifted, webShift and sort) are cleared and webSnap becomes 0 →{colors: [\"#rrggbb\"…] (the colors it uses, in file order), transparentIndex (null for none; an index past the colors used names none), settings}. Give exactly one of path and dataBase64; another file size, a count of 0 or above 256, jpg and png24 are errors; nothing is remembered",
|
||||
always,
|
||||
load_color_table
|
||||
),
|
||||
cmd!(
|
||||
query "webExport.optimizeToFileSize",
|
||||
"Optimize to File Size",
|
||||
@@ -1253,24 +1271,7 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !(kbps.is_finite() && kbps > 0.0) {
|
||||
return Err(bad(P, format!("kbps must be a positive number, not {kbps}")));
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let doc = &st.doc;
|
||||
let failed = vectorcraft_render::decode_failures();
|
||||
let r = render(doc, &settings).map_err(|e| bad(P, e))?;
|
||||
let warnings = undecoded(failed);
|
||||
let areas = doc.slice_layout();
|
||||
let selected = super::slices::selected_slices(doc, &st.selection);
|
||||
let cells = cells(&areas, &selected, &settings, &r).map_err(|e| bad(P, e))?;
|
||||
let images = cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).count().max(1);
|
||||
let o = match p.get("slice").and_then(Value::as_u64) {
|
||||
Some(n) => {
|
||||
let c = cells.iter().find(|c| c.area.number as u64 == n).ok_or_else(|| bad(P, format!("no slice {n} in the image (see slice.list)")))?;
|
||||
let [x0, y0, x1, y1] = c.px;
|
||||
optimize(doc, &crop(&r, c.px), x1 - x0, y1 - y0, &settings)
|
||||
}
|
||||
None => optimize(doc, &r.rgba, r.width, r.height, &settings),
|
||||
}
|
||||
.map_err(|e| bad(P, e))?;
|
||||
let Shown { o, images, warnings } = shown(s, &settings, p, P, true)?;
|
||||
let mut out = json!({
|
||||
"format": settings.format.id(), "width": o.width, "height": o.height, "bytes": o.bytes.len(),
|
||||
"seconds": download_seconds(o.bytes.len(), kbps), "kbps": kbps, "slices": images, "warnings": warnings,
|
||||
@@ -1294,6 +1295,195 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The file Save writes with some settings, as the preview shows it.
|
||||
struct Shown {
|
||||
o: Optimized,
|
||||
/// The images an export writes (0 when they were not counted).
|
||||
images: usize,
|
||||
/// The export's warnings.
|
||||
warnings: Vec<&'static str>,
|
||||
}
|
||||
|
||||
/// What Save writes with `settings` for the whole image, or for the slice `p.slice` names (1-based,
|
||||
/// from `slice.list`), for the command `cmd`. A `slice` that is not a whole number from 1 up is an
|
||||
/// error. With `count_images` false and no `slice`, the slices are not looked up: `images` is 0,
|
||||
/// and selected slices with none selected are not an error.
|
||||
fn shown(s: &mut Session, settings: &WebSettings, p: &Value, cmd: &str, count_images: bool) -> Result<Shown> {
|
||||
let slice = match p.get("slice") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(v.as_u64().filter(|n| *n >= 1).ok_or_else(|| bad(cmd, "`slice` is a slice number from `slice.list`"))?),
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let doc = &st.doc;
|
||||
let failed = vectorcraft_render::decode_failures();
|
||||
let r = render(doc, settings).map_err(|e| bad(cmd, e))?;
|
||||
let warnings = undecoded(failed);
|
||||
let areas = doc.slice_layout();
|
||||
let cells = if count_images || slice.is_some() {
|
||||
let selected = super::slices::selected_slices(doc, &st.selection);
|
||||
cells(&areas, &selected, settings, &r).map_err(|e| bad(cmd, e))?
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
let images = if count_images {
|
||||
cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).count().max(1)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let o = match slice {
|
||||
Some(n) => {
|
||||
let c =
|
||||
cells.iter().find(|c| c.area.number as u64 == n).ok_or_else(|| bad(cmd, format!("no slice {n} in the image (see slice.list)")))?;
|
||||
let [x0, y0, x1, y1] = c.px;
|
||||
optimize(doc, &crop(&r, c.px), x1 - x0, y1 - y0, settings)
|
||||
}
|
||||
None => optimize(doc, &r.rgba, r.width, r.height, settings),
|
||||
}
|
||||
.map_err(|e| bad(cmd, e))?;
|
||||
Ok(Shown { o, images, warnings })
|
||||
}
|
||||
|
||||
// ---------- color table files ----------
|
||||
|
||||
/// The extension of a color table file.
|
||||
pub const COLOR_TABLE_EXT: &str = "act";
|
||||
/// The size of a color table file with its color count and transparent entry: 256 RGB triples
|
||||
/// (768 bytes), then the two numbers, each two bytes, most significant byte first.
|
||||
pub const ACT_LEN: usize = 772;
|
||||
/// The size of a color table file of 256 RGB triples alone.
|
||||
const ACT_COLORS_LEN: usize = 768;
|
||||
/// The transparent entry of a color table file that has none.
|
||||
const ACT_NO_TRANSPARENT: u16 = 0xFFFF;
|
||||
|
||||
/// The error for bytes that are not a color table file.
|
||||
const NOT_A_TABLE: &str = "not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors";
|
||||
|
||||
/// A color table file (`.act`) of `colors`, a palette format's color table in file order: each
|
||||
/// color as written, red, green and blue, one byte each; zero bytes up to 256 colors; the number
|
||||
/// of colors and the index of the transparent entry (`0xFFFF` for none), two bytes each, most
|
||||
/// significant byte first. Colors past the 256th are left out.
|
||||
pub fn act_bytes(colors: &[TableColor]) -> Vec<u8> {
|
||||
let colors = &colors[..colors.len().min(256)];
|
||||
let mut out = vec![0u8; ACT_LEN];
|
||||
for (slot, c) in out.as_chunks_mut::<3>().0.iter_mut().zip(colors) {
|
||||
*slot = c.color;
|
||||
}
|
||||
// At most 256 colors: both numbers fit in two bytes.
|
||||
let count = colors.len() as u16;
|
||||
let transparent = colors.iter().position(|c| c.transparent).map_or(ACT_NO_TRANSPARENT, |i| i as u16);
|
||||
out[ACT_COLORS_LEN..ACT_COLORS_LEN + 2].copy_from_slice(&count.to_be_bytes());
|
||||
out[ACT_COLORS_LEN + 2..].copy_from_slice(&transparent.to_be_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// The colors of a color table file and its transparent entry.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ActTable {
|
||||
/// The colors the file uses, in its order.
|
||||
pub colors: Vec<[u8; 3]>,
|
||||
/// The index of the transparent entry, when the file names one of `colors`.
|
||||
pub transparent: Option<usize>,
|
||||
}
|
||||
|
||||
/// Read a color table file: 768 bytes are 256 colors; 772 bytes add the number of colors used
|
||||
/// (1 to 256) and the transparent entry's index. A transparent index past the colors used names
|
||||
/// no entry. Any other size, or a count of 0 or above 256, is an error.
|
||||
pub fn read_act(bytes: &[u8]) -> std::result::Result<ActTable, String> {
|
||||
let (count, transparent) = match bytes.len() {
|
||||
ACT_COLORS_LEN => (256, None),
|
||||
ACT_LEN => {
|
||||
let at = |i: usize| usize::from(u16::from_be_bytes([bytes[i], bytes[i + 1]]));
|
||||
(at(ACT_COLORS_LEN), Some(at(ACT_COLORS_LEN + 2)))
|
||||
}
|
||||
_ => return Err(NOT_A_TABLE.into()),
|
||||
};
|
||||
if !(1..=256).contains(&count) {
|
||||
return Err(NOT_A_TABLE.into());
|
||||
}
|
||||
let colors: Vec<[u8; 3]> = bytes[..count * 3].as_chunks::<3>().0.to_vec();
|
||||
Ok(ActTable { colors, transparent: transparent.filter(|i| *i < count) })
|
||||
}
|
||||
|
||||
/// `settings` with the color table `t` loaded: its colors other than the transparent entry become
|
||||
/// the fixed palette (`colorTable.customPalette`), and `colors` becomes the number of colors the
|
||||
/// file uses (at least 2). The table's other edits (locked, transparent, deleted, shifted and
|
||||
/// web-shifted colors, and its sort) are cleared and Web Snap is set to 0, so every loaded color is
|
||||
/// written as it is, in the file's order. A table whose only color is its transparent entry loads
|
||||
/// that color.
|
||||
pub fn with_table(settings: &WebSettings, t: &ActTable) -> WebSettings {
|
||||
let mut s = settings.clone();
|
||||
let mut palette: Vec<String> = t.colors.iter().enumerate().filter(|(i, _)| Some(*i) != t.transparent).map(|(_, c)| hex(*c)).collect();
|
||||
if palette.is_empty() {
|
||||
palette = t.colors.iter().map(|c| hex(*c)).collect();
|
||||
}
|
||||
s.colors = (t.colors.len() as u16).clamp(2, 256);
|
||||
s.web_snap = 0;
|
||||
s.color_table = ColorTable { custom_palette: palette, ..ColorTable::default() };
|
||||
s
|
||||
}
|
||||
|
||||
/// `cmd`'s error for a format without a color table.
|
||||
fn no_table(cmd: &str, f: WebFormat) -> super::EngineError {
|
||||
let format = f.id();
|
||||
bad(cmd, format!("`{format}` has no color table: use gif or png8"))
|
||||
}
|
||||
|
||||
fn save_color_table(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const P: &str = "document.exportForWeb.saveColorTable";
|
||||
let settings = s.web_settings(p).map_err(|e| bad(P, e))?;
|
||||
if !settings.format.palette() {
|
||||
return Err(no_table(P, settings.format));
|
||||
}
|
||||
let path = text_param(p, "path", P)?;
|
||||
if path.is_some_and(|p| p.trim().is_empty()) {
|
||||
return Err(bad(P, "`path` is empty: give a file path, or leave it out for `dataBase64`"));
|
||||
}
|
||||
let path = path.map(|p| if std::path::Path::new(p).extension().is_none() { format!("{p}.{COLOR_TABLE_EXT}") } else { p.to_string() });
|
||||
let Shown { o, warnings, .. } = shown(s, &settings, p, P, false)?;
|
||||
let bytes = act_bytes(&o.colors);
|
||||
let mut out = json!({
|
||||
"colors": o.colors.len().min(256),
|
||||
"transparentIndex": o.colors.iter().position(|c| c.transparent),
|
||||
"bytes": bytes.len(),
|
||||
"warnings": warnings,
|
||||
});
|
||||
match path {
|
||||
Some(path) => {
|
||||
super::fileio::write_file(&path, &bytes)?;
|
||||
out["path"] = json!(path);
|
||||
}
|
||||
None => out["dataBase64"] = json!(vectorcraft_format::base64_encode(&bytes)),
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn load_color_table(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const L: &str = "webExport.loadColorTable";
|
||||
let settings = s.web_settings(p).map_err(|e| bad(L, e))?;
|
||||
if !settings.format.palette() {
|
||||
return Err(no_table(L, settings.format));
|
||||
}
|
||||
// One byte more than a color table shows a file that is too long.
|
||||
let bytes = match (text_param(p, "path", L)?, text_param(p, "dataBase64", L)?) {
|
||||
(Some(path), None) => super::fileio::read_file_head(path, ACT_LEN + 1)?,
|
||||
(None, Some(b64)) => {
|
||||
// Text past the base64 of the longest table makes the file too long.
|
||||
if b64.bytes().filter(|b| !b.is_ascii_whitespace()).count() > ACT_LEN.div_ceil(3) * 4 {
|
||||
return Err(bad(L, NOT_A_TABLE));
|
||||
}
|
||||
super::scripts::decode_head(b64, ACT_LEN + 1).ok_or_else(|| bad(L, "bad dataBase64"))?
|
||||
}
|
||||
_ => return Err(bad(L, "give exactly one of `path` and `dataBase64`")),
|
||||
};
|
||||
let t = read_act(&bytes).map_err(|e| bad(L, e))?;
|
||||
let loaded = with_table(&settings, &t);
|
||||
Ok(json!({
|
||||
"colors": t.colors.iter().map(|c| hex(*c)).collect::<Vec<_>>(),
|
||||
"transparentIndex": t.transparent,
|
||||
"settings": loaded.to_json(),
|
||||
}))
|
||||
}
|
||||
|
||||
// ---------- Optimize to File Size ----------
|
||||
|
||||
/// The most trial settings `webExport.optimizeToFileSize` encodes. Each trial encodes every image
|
||||
|
||||
@@ -53,6 +53,9 @@ pub struct DocState {
|
||||
pub interaction: Option<Interaction>,
|
||||
/// Edits made while this is open are one undo step (a scrubbed numeric field).
|
||||
pub undo_group: Option<UndoGroup>,
|
||||
/// The built-in effect the edit in progress applies ([`crate::Session::edit_effect`]): the
|
||||
/// undo step it records keeps it ([`DocState::push_undo`]).
|
||||
pub(crate) effect_step: Option<&'static str>,
|
||||
/// For Object → Transform → Transform Again (⌘D): what the last transformation was. A
|
||||
/// transform command keeps the `copy`, `typeAreas` and `patterns` it used, and `strokes` and
|
||||
/// `corners` when it scales; a drag keeps the params of its last preview with the values that
|
||||
@@ -410,6 +413,7 @@ impl DocState {
|
||||
symbol_edit_return: Default::default(),
|
||||
interaction: None,
|
||||
undo_group: None,
|
||||
effect_step: None,
|
||||
last_transform: None,
|
||||
last_selection_cmd: None,
|
||||
recalled_selection: RecalledSelection::default(),
|
||||
@@ -593,7 +597,9 @@ impl DocState {
|
||||
Some(l) if l.selection == it.selection => l.selection.clone(),
|
||||
_ => it.selection,
|
||||
};
|
||||
let effect = std::mem::replace(&mut self.effect_step, it.effect);
|
||||
self.push_undo(it.label, it.doc, selection);
|
||||
self.effect_step = effect;
|
||||
if let Some(paints) = it.color_mode_paints
|
||||
&& let Some(e) = self.history.undo.last_mut()
|
||||
{
|
||||
@@ -609,8 +615,10 @@ impl DocState {
|
||||
}
|
||||
/// Record an undo step: `doc` and `selection` as they were before an edit (the document now is
|
||||
/// the one after it). In an undo group only the group's first edit records one: the edits
|
||||
/// after it extend that step.
|
||||
/// after it extend that step. A new step named after the effect in [`DocState::effect_step`]
|
||||
/// keeps that effect ([`HistoryEntry::effect`]); a step an undo group names keeps none.
|
||||
pub(crate) fn push_undo(&mut self, mut label: String, doc: Arc<Document>, selection: Arc<Selection>) {
|
||||
let mut effect = self.effect_step;
|
||||
if let Some(g) = &mut self.undo_group {
|
||||
let recorded = |first: &Arc<Document>| self.history.undo.last().is_some_and(|l| Arc::ptr_eq(&l.doc, first));
|
||||
if g.first.as_ref().is_some_and(recorded) {
|
||||
@@ -621,9 +629,11 @@ impl DocState {
|
||||
g.first = Some(doc.clone());
|
||||
if let Some(l) = &g.label {
|
||||
label = l.clone();
|
||||
effect = None;
|
||||
}
|
||||
}
|
||||
let e = HistoryEntry::kept(label, doc, selection, &self.doc);
|
||||
let mut e = HistoryEntry::kept(label, doc, selection, &self.doc);
|
||||
e.effect = effect.filter(|id| crate::history::effect_step_label(id) == Some(e.label.as_str()));
|
||||
self.history.undo.push(e);
|
||||
self.history.clear_redo();
|
||||
self.history.trim();
|
||||
|
||||
@@ -25,6 +25,9 @@ pub struct HistoryEntry {
|
||||
next: usize,
|
||||
/// The template and name `label` was made from ([`Session::edit_named`]).
|
||||
pub(crate) named: Option<NamedStep>,
|
||||
/// The built-in effect the step applied or edited, when the step is named after it
|
||||
/// ([`Session::edit_effect`]).
|
||||
pub(crate) effect: Option<&'static str>,
|
||||
/// A number no other step takes ([`History::step`]).
|
||||
serial: u64,
|
||||
/// Original and changed new-art paints, only for steps that change them: a document color mode
|
||||
@@ -49,6 +52,7 @@ impl Clone for HistoryEntry {
|
||||
next_bytes: self.next_bytes,
|
||||
next: self.next,
|
||||
named: self.named.clone(),
|
||||
effect: self.effect,
|
||||
serial: self.serial,
|
||||
color_mode_paints: self.color_mode_paints.clone(),
|
||||
color_mode_bytes: self.color_mode_bytes,
|
||||
@@ -63,6 +67,12 @@ fn next_serial() -> u64 {
|
||||
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The name of the undo step that applies or edits built-in effect `id`: its menu label without
|
||||
/// the ellipsis. `None` for an id no built-in effect has.
|
||||
pub(crate) fn effect_step_label(id: &str) -> Option<&'static str> {
|
||||
vectorcraft_render::effects::built_in_effect(id).map(|(_, label)| label.trim_end_matches('…'))
|
||||
}
|
||||
|
||||
/// A step name made by filling the `{name}` placeholder of a template with a name
|
||||
/// ([`Session::edit_named`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -95,6 +105,7 @@ impl HistoryEntry {
|
||||
next_bytes,
|
||||
next: std::ptr::from_ref(next) as usize,
|
||||
named: None,
|
||||
effect: None,
|
||||
serial: next_serial(),
|
||||
color_mode_paints: None,
|
||||
color_mode_bytes: 0,
|
||||
@@ -109,6 +120,13 @@ impl HistoryEntry {
|
||||
self.named.as_ref().filter(|n| n.label() == self.label)
|
||||
}
|
||||
|
||||
/// The id of the built-in effect the step applied or edited, while the step's label is still
|
||||
/// the effect's name: `None` for any other step, and for one whose label was changed since it
|
||||
/// was recorded.
|
||||
pub fn effect(&self) -> Option<&'static str> {
|
||||
self.effect.filter(|id| effect_step_label(id) == Some(self.label.as_str()))
|
||||
}
|
||||
|
||||
/// The step that undoing (redoing) the step `costs` came from makes: it keeps `doc`, the
|
||||
/// document before the undo, whose next state is now `now` (that step's document). Its figures
|
||||
/// are that step's the other way round when `doc` is still the document they were taken
|
||||
@@ -128,6 +146,7 @@ impl HistoryEntry {
|
||||
next_bytes: costs.bytes,
|
||||
next: Arc::as_ptr(now) as usize,
|
||||
named: None,
|
||||
effect: None,
|
||||
serial: next_serial(),
|
||||
color_mode_paints: None,
|
||||
color_mode_bytes: 0,
|
||||
@@ -248,7 +267,7 @@ impl History {
|
||||
|
||||
/// The document at row `row` of the History panel, `now` being the document now: the rows before
|
||||
/// it are the undo steps, oldest first, and the rows after it the redo steps, nearest first.
|
||||
pub(crate) fn state<'a>(&'a self, now: &'a Arc<Document>, row: usize) -> Option<&'a Arc<Document>> {
|
||||
pub fn state<'a>(&'a self, now: &'a Arc<Document>, row: usize) -> Option<&'a Arc<Document>> {
|
||||
let current = self.undo.len();
|
||||
match row.cmp(¤t) {
|
||||
std::cmp::Ordering::Less => self.undo.get(row).map(|e| &e.doc),
|
||||
|
||||
@@ -4,6 +4,9 @@ use super::{Affine, Arc, Document, NodeId, Selection, Value};
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Interaction {
|
||||
pub label: String,
|
||||
/// The built-in effect the last preview applied or edited ([`crate::Session::edit_effect`]):
|
||||
/// the step the interaction records keeps it when `label` is the effect's name.
|
||||
pub(crate) effect: Option<&'static str>,
|
||||
pub doc: Arc<Document>,
|
||||
/// The selection the previews start from (shared, so a preview frame copies nothing).
|
||||
pub selection: Arc<Selection>,
|
||||
|
||||
@@ -30,6 +30,7 @@ pub use cmd::clipboard::{Clipboard, SourceLayer};
|
||||
pub use cmd::create::constrain_click;
|
||||
pub use cmd::distortcmds::{perspective_click, width_point_pair};
|
||||
pub use cmd::flare::flare_settings;
|
||||
pub use cmd::gradient::StopOwner;
|
||||
pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject};
|
||||
pub use cmd::params::{check_keys, check_params};
|
||||
pub use cmd::pathops::auto_simplify_level;
|
||||
@@ -136,6 +137,8 @@ pub struct Session {
|
||||
/// Set when a command that draws a shape was journaled outside saved steps
|
||||
/// ([`Session::take_shape_drawn`]).
|
||||
shape_drawn: bool,
|
||||
/// The categories `prefs.reset` reset, `None` for every one ([`Session::take_prefs_resets`]).
|
||||
prefs_resets: Vec<Option<&'static str>>,
|
||||
/// Set when the active tool panicked (see [`guard`]); reported by the next tool event.
|
||||
tool_panic: Option<EngineError>,
|
||||
/// How many times switching or closing documents, or replacing the active one, has started the
|
||||
@@ -216,6 +219,9 @@ pub struct Session {
|
||||
/// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder
|
||||
/// ([`Session::attach_scripts_dir`]).
|
||||
scripts_dir: Option<std::path::PathBuf>,
|
||||
/// The Startup Scripts folder, whose scripts `script.startup.run` runs; `None`: no folder
|
||||
/// ([`Session::attach_startup_scripts_dir`]).
|
||||
startup_scripts_dir: Option<std::path::PathBuf>,
|
||||
/// The folder of File Info's metadata templates; `None`: no folder
|
||||
/// ([`Session::attach_metadata_templates_dir`]).
|
||||
metadata_templates_dir: Option<std::path::PathBuf>,
|
||||
@@ -308,6 +314,9 @@ pub struct Session {
|
||||
/// What a [`cmd::TraceRun`] traced, until the next `imageTrace.make` or
|
||||
/// `imageTrace.makeAndExpand` takes it ([`cmd::Traced::hand_in`]).
|
||||
pub(crate) trace_hand_off: Option<cmd::Traced>,
|
||||
/// The installed fonts a [`cmd::RetypeSearch`] found, until the next `type.retype` or
|
||||
/// `type.retypeFonts` takes it ([`cmd::RetypeFound::hand_in`]).
|
||||
pub(crate) retype_hand_off: Option<cmd::RetypeFound>,
|
||||
/// Whether a click or drag of the place cursor asks the frontend to place its file
|
||||
/// ([`UiRequest::Place`]) instead of running `file.place`: the desktop app sets it to read the
|
||||
/// file off the UI thread. False: the file is placed at once.
|
||||
@@ -336,6 +345,19 @@ pub struct Session {
|
||||
/// `script.run` starts the job and returns, and the frontend advances it once per frame
|
||||
/// ([`Session::script_pump`]). Off, `script.run` advances it to its end.
|
||||
pub script_frames: bool,
|
||||
/// The runs `script.startup.run` queued in the app, each started when the run before it ends
|
||||
/// ([`Session::script_pump`]).
|
||||
pub(crate) script_queue: std::collections::VecDeque<script::startup::Queued>,
|
||||
/// The file access scope of the request that queued [`Self::script_queue`], in which each queued
|
||||
/// run starts and is read.
|
||||
pub(crate) script_queue_scope: Option<file_access::ScopeHandle>,
|
||||
pub(crate) script_queue_then: Option<script::Request>,
|
||||
/// While a startup script runs: the launch marker's entry naming it
|
||||
/// ([`vectorcraft_plugins::safe_mode::loading`]).
|
||||
pub(crate) startup_loading: Option<vectorcraft_plugins::safe_mode::Loading>,
|
||||
/// The queued runs that could not start, as (name, error), until the frontend takes them
|
||||
/// ([`Session::take_startup_failures`]).
|
||||
pub(crate) startup_failures: Vec<(String, String)>,
|
||||
/// Each open document's highest next id a run has seen, by [`DocState::uid`].
|
||||
pub(crate) script_high_water: std::collections::HashMap<u64, u64>,
|
||||
/// While a slice of a script runs in this session.
|
||||
|
||||
@@ -71,6 +71,10 @@ pub struct Prefs {
|
||||
pub show_tool_cards: bool,
|
||||
/// Other Script… warns before it runs a chosen script.
|
||||
pub show_external_script_warning: bool,
|
||||
/// General › Run Startup Scripts: the `.jsx` files of the Startup Scripts folder run when the
|
||||
/// app starts and before each script chosen from File › Scripts (`script.startup.run`). Off by
|
||||
/// default.
|
||||
pub run_startup_scripts: bool,
|
||||
pub anti_aliased_artwork: bool,
|
||||
pub select_same_tint_percent: bool,
|
||||
pub show_home_screen: bool,
|
||||
@@ -496,6 +500,7 @@ impl Default for Prefs {
|
||||
show_tool_tips: true,
|
||||
show_tool_cards: false,
|
||||
show_external_script_warning: true,
|
||||
run_startup_scripts: false,
|
||||
anti_aliased_artwork: true,
|
||||
select_same_tint_percent: false,
|
||||
show_home_screen: true,
|
||||
|
||||
@@ -66,6 +66,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem
|
||||
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size};
|
||||
use crate::{DocState, Document, NodeId, NodeKind, Session};
|
||||
|
||||
mod tags;
|
||||
|
||||
/// The error for a member read or called with no document open.
|
||||
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
|
||||
/// The error for an object that was deleted, or that came from an earlier run.
|
||||
@@ -772,6 +774,62 @@ fn app_is_open(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Bool(open))
|
||||
}
|
||||
|
||||
/// The menu command strings `app.executeMenuCommand` takes, each with the command it runs. The
|
||||
/// strings are the ones
|
||||
/// <https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510>
|
||||
/// lists, and `Fit Artboard to artwork bounds` is the one
|
||||
/// <https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee> gives for Object ›
|
||||
/// Artboards › Fit to Artwork Bounds.
|
||||
const MENU_COMMANDS: &[(&str, &str)] = &[
|
||||
("selectall", "select.all"),
|
||||
("deselectall", "select.none"),
|
||||
("group", "object.group"),
|
||||
("ungroup", "object.ungroup"),
|
||||
("makeMask", "object.clippingMask.make"),
|
||||
("releaseMask", "object.clippingMask.release"),
|
||||
("compoundPath", "object.compoundPath.make"),
|
||||
("noCompoundPath", "object.compoundPath.release"),
|
||||
("Fit Artboard to artwork bounds", "artboard.fitToArt"),
|
||||
];
|
||||
|
||||
/// `app.executeMenuCommand(name)`: runs the command of the menu item `name` names
|
||||
/// ([`MENU_COMMANDS`]) on the active document, as
|
||||
/// <https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts> describes the method. A
|
||||
/// name it does not list throws an error that names it. A menu item that is not available, with
|
||||
/// no document open or nothing selected that it acts on, does nothing, as a dimmed menu item does
|
||||
/// (VectorCraft's own rule). A menu item the menus show as available runs its command, and an error
|
||||
/// that command returns throws. `Fit Artboard to artwork bounds` fits the active artboard, and does
|
||||
/// nothing when that artboard is locked or has no art, as the canvas's right-click menu dims
|
||||
/// the item then ([`DocState::any_art_to_fit`]).
|
||||
fn app_menu_command(h: &Host, a: &[Data]) -> Answer {
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("executeMenuCommand needs a menu command, as a string".into())) };
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the menu command is too long".into()));
|
||||
}
|
||||
let Some(&(_, id)) = MENU_COMMANDS.iter().find(|(n, _)| n == name) else {
|
||||
return Err(HostError::Error(format!("executeMenuCommand: unknown menu command \"{name}\"")));
|
||||
};
|
||||
let params = {
|
||||
let s = h.session.borrow();
|
||||
let Some(spec) = crate::find_command(id) else { return Err(HostError::Abort(format!("executeMenuCommand: no command {id}"))) };
|
||||
if (spec.enabled)(&s).is_err() {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
match (id, s.active()) {
|
||||
("artboard.fitToArt", Some(st)) => {
|
||||
let index = active_artboard(st);
|
||||
if !st.any_art_to_fit(&[index]) {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
json!({"index": index})
|
||||
}
|
||||
_ => json!({}),
|
||||
}
|
||||
};
|
||||
command(h, id, ¶ms)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- Documents ----
|
||||
|
||||
fn docs_length(h: &Host, _: &[Data]) -> Answer {
|
||||
@@ -1297,12 +1355,13 @@ fn selection_of(h: &Host, uid: u64) -> Answer {
|
||||
/// `[]`. Every one must be an object of that document that can be selected.
|
||||
fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId>, HostError> {
|
||||
let list: Vec<&Data> = match v {
|
||||
Data::Null | Data::Undefined => Vec::new(),
|
||||
Data::Null => Vec::new(),
|
||||
Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))),
|
||||
Data::Array(a) => a.iter().collect(),
|
||||
d => vec![d],
|
||||
};
|
||||
let mut ids: Vec<NodeId> = Vec::with_capacity(list.len());
|
||||
let mut seen: HashSet<NodeId> = HashSet::with_capacity(list.len());
|
||||
// The document is read once for every object: nothing changes it while the list is checked.
|
||||
let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked()));
|
||||
let locks = d.locked_artboards();
|
||||
@@ -1317,7 +1376,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId
|
||||
let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item"));
|
||||
return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0)));
|
||||
}
|
||||
if !ids.contains(&item.id) {
|
||||
if seen.insert(item.id) {
|
||||
ids.push(item.id);
|
||||
}
|
||||
}
|
||||
@@ -1378,6 +1437,11 @@ fn items_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text("PageItems"))
|
||||
}
|
||||
|
||||
fn items_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
items_doc(h, a)?;
|
||||
Ok(text("[PageItems]"))
|
||||
}
|
||||
|
||||
fn items_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(doc_ref(h, doc.uid))
|
||||
@@ -1537,16 +1601,23 @@ fn item_set_note(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// Refuses a change to the item's appearance, place, stacking order or size while a layer it is in
|
||||
/// is hidden or locked. Its name and note may still change.
|
||||
fn refuse_in_closed_layer(h: &Host, item: Item) -> std::result::Result<(), HostError> {
|
||||
/// Refuses appearance, place, stacking order and size changes in hidden or locked layers and on
|
||||
/// locked artboards. Names and notes may still change.
|
||||
fn refuse_protected_edit(h: &Host, item: Item) -> std::result::Result<(), HostError> {
|
||||
let refused = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let closed = |i: &NodeId| d.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. }) && (!n.visible || n.locked));
|
||||
d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)).then(|| d.node(item.id).and_then(typename).unwrap_or("page item"))
|
||||
let why = if d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)) {
|
||||
Some("a layer it is in is hidden or locked")
|
||||
} else if on_locked_artboard(h, st, item.id) {
|
||||
Some("it is on a locked artboard")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
why.map(|why| (d.node(item.id).and_then(typename).unwrap_or("page item"), why))
|
||||
});
|
||||
match refused {
|
||||
Some(name) => Err(HostError::Error(format!("Cannot edit {name} {}: a layer it is in is hidden or locked", item.id.0))),
|
||||
Some((name, why)) => Err(HostError::Error(format!("Cannot edit {name} {}: {why}", item.id.0))),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -1557,7 +1628,7 @@ fn item_hidden(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
fn item_set_hidden(h: &Host, a: &[Data]) -> Answer {
|
||||
let hidden = boolean(arg(a, 1), "hidden")?;
|
||||
refuse_in_closed_layer(h, this_item(h, a)?)?;
|
||||
refuse_protected_edit(h, this_item(h, a)?)?;
|
||||
set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden}))
|
||||
}
|
||||
|
||||
@@ -1567,7 +1638,7 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
fn item_set_locked(h: &Host, a: &[Data]) -> Answer {
|
||||
let locked = boolean(arg(a, 1), "locked")?;
|
||||
refuse_in_closed_layer(h, this_item(h, a)?)?;
|
||||
refuse_protected_edit(h, this_item(h, a)?)?;
|
||||
set_props(h, a, |n| n.locked == locked, json!({"locked": locked}))
|
||||
}
|
||||
|
||||
@@ -1595,7 +1666,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
(now, keeps_other)
|
||||
});
|
||||
if now.is_none() || keeps_other {
|
||||
refuse_in_closed_layer(h, item)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
}
|
||||
set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)}))
|
||||
}
|
||||
@@ -1679,7 +1750,8 @@ fn item_height(h: &Host, a: &[Data]) -> Answer {
|
||||
/// stays).
|
||||
fn move_to(h: &Host, a: &[Data], x: Option<f64>, y: Option<f64>) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
refuse_in_closed_layer(h, item)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
|
||||
let c = h.dom.coords.get();
|
||||
let now = f.to_script(c, Point::new(r.x0, r.y0));
|
||||
@@ -1716,7 +1788,8 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer {
|
||||
return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points")));
|
||||
}
|
||||
let item = this_item(h, a)?;
|
||||
refuse_in_closed_layer(h, item)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
|
||||
let now = if width { r.width() } else { r.height() };
|
||||
if now <= 0.0 {
|
||||
@@ -1962,7 +2035,8 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// `zOrder(method)`: one of the four Object › Arrange commands for the item. A path inside a
|
||||
/// compound path is refused, and so is an object in a hidden or locked layer.
|
||||
/// compound path is refused. The item must be selectable and outside hidden or locked layers and
|
||||
/// locked artboards.
|
||||
fn item_z_order(h: &Host, a: &[Data]) -> Answer {
|
||||
let id = match arg(a, 1) {
|
||||
Data::String(s) if s == "ZOrderMethod.BRINGTOFRONT" => "object.arrange.bringToFront",
|
||||
@@ -1975,7 +2049,8 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
|
||||
if in_compound(h, item) {
|
||||
return Err(HostError::Error(COMPOUND_MEMBER_ORDER.into()));
|
||||
}
|
||||
refuse_in_closed_layer(h, item)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
let (before, after) = with_doc(h, item.doc, |_, st| {
|
||||
let at = st.doc.position(item.id);
|
||||
let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0);
|
||||
@@ -2085,6 +2160,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
("selection", property(l, app_selection, app_set_selection)),
|
||||
("coordinateSystem", property(l, app_coords, app_set_coords)),
|
||||
("getIsFileOpen", method(l, app_is_open)),
|
||||
("executeMenuCommand", method(l, app_menu_command)),
|
||||
("toString", class_text("Application")),
|
||||
]);
|
||||
application.push(later(l, "Application", "beep"));
|
||||
@@ -2137,6 +2213,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
.into_iter()
|
||||
.map(|m| later(l, "Document", m)),
|
||||
);
|
||||
document.push(("tags".into(), get(l, tags::doc_tags)));
|
||||
classes.push(class("Document", None, document, None));
|
||||
classes.push(class(
|
||||
"PageItems",
|
||||
@@ -2148,7 +2225,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
("index", method(l, items_index)),
|
||||
("getByName", method(l, items_by_name)),
|
||||
("removeAll", method(l, items_remove_all)),
|
||||
("toString", class_text("PageItems")),
|
||||
("toString", method(l, items_to_string)),
|
||||
]),
|
||||
Some(function(l, items_at)),
|
||||
));
|
||||
@@ -2157,6 +2234,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
("parent", get(l, item_parent)),
|
||||
("name", property(l, item_name, item_set_name)),
|
||||
("note", property(l, item_note, item_set_note)),
|
||||
("tags", get(l, tags::item_tags)),
|
||||
("hidden", property(l, item_hidden, item_set_hidden)),
|
||||
("locked", property(l, item_locked, item_set_locked)),
|
||||
("selected", property(l, item_selected, item_set_selected)),
|
||||
@@ -2185,7 +2263,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
"layer",
|
||||
"pixelAligned",
|
||||
"sliced",
|
||||
"tags",
|
||||
"uRL",
|
||||
"uuid",
|
||||
"visibilityVariable",
|
||||
@@ -2209,6 +2286,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name)), ("toString", method(l, layer_to_string))]),
|
||||
None,
|
||||
));
|
||||
classes.extend(tags::classes(l));
|
||||
realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])?;
|
||||
// The application's members a script may name without `app.`, assigned as `app.<member>` is.
|
||||
realm.define_host_globals(vec![
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
//! `PageItem.tags`, `Document.tags` and the `Tag` objects in them, as the help pages
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Tags/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Tag/> describe them: name and value pairs on a
|
||||
//! page item, which the native file keeps. Each change runs one of the `object.tag.*` commands.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - A `Tags` collection is live: it lists the tags in their order on the object, counted from 0.
|
||||
//! `Document.tags` lists the tags of every page item, in the order `pageItems` lists the items,
|
||||
//! and cannot add a tag, since a tag belongs to a page item.
|
||||
//! - `add()` gives a tag with an empty name and value. Names may be empty or repeated, and
|
||||
//! `getByName` gives the first tag with the name.
|
||||
//! - `name` and `value` are strings of at most 65,536 bytes, and an object has at most 64 tags.
|
||||
//! - A tag that was deleted, or whose page item was, throws an error on every member.
|
||||
|
||||
use std::ops::ControlFlow;
|
||||
|
||||
use vectorcraft_doc::{MAX_TAG_TEXT, ObjectTag};
|
||||
|
||||
use super::{
|
||||
Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_DOCUMENT, STALE_ITEM, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, get,
|
||||
handle_of, id_of, id_parts, item_of, item_ref, method, named, num, on_doc, page_items, property, text, typename, whole, with_doc,
|
||||
};
|
||||
use crate::NodeId;
|
||||
use serde_json::json;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref};
|
||||
|
||||
/// The error for a tag that was deleted, or that came from an earlier run.
|
||||
pub const STALE_TAG: &str = "Stale tag";
|
||||
/// The error of `Document.tags.add()`.
|
||||
pub const NO_OWNER: &str = "A tag is added to a page item's tags, not to the document's";
|
||||
|
||||
/// What a `Tags` collection lists the tags of.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Owner {
|
||||
Item(Item),
|
||||
Doc(Doc),
|
||||
}
|
||||
|
||||
/// The owner of the `Tags` collection `d` names.
|
||||
fn owner_of(h: &Host, d: &Data) -> std::result::Result<Owner, HostError> {
|
||||
let Some(handle) = handle_of(d, "Tags") else { return Err(HostError::Type("this is not a Tags collection".into())) };
|
||||
match handle.as_slice() {
|
||||
[run, uid] => find_doc(h, *run, *uid).map(Owner::Doc).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into())),
|
||||
[run, uid, high, low] => Ok(Owner::Item(resolve_item(h, *run, *uid, *high, *low)?)),
|
||||
_ => Err(HostError::Type("this is not a Tags collection".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The page item a handle's run, document uid and id (as [`id_parts`] gave it) name, which must
|
||||
/// still be in its document.
|
||||
fn resolve_item(h: &Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result<Item, HostError> {
|
||||
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let alive = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| typename(n).is_some()));
|
||||
if !alive {
|
||||
return Err(HostError::Error(STALE_ITEM.into()));
|
||||
}
|
||||
Ok(Item { doc, id })
|
||||
}
|
||||
|
||||
/// Calls `f` with each tag `owner` lists, in order, and the page item it is on, until `f` breaks.
|
||||
/// The tags are borrowed from the document, not copied. `Document.tags` charges the run by the
|
||||
/// number of page items read.
|
||||
fn each(h: &Host, owner: Owner, mut f: impl FnMut(NodeId, &ObjectTag) -> ControlFlow<()>) -> std::result::Result<(), HostError> {
|
||||
match owner {
|
||||
Owner::Item(item) => with_doc(h, item.doc, |_, st| {
|
||||
if let Some(n) = st.doc.node(item.id) {
|
||||
for t in crate::cmd::tags::tags_of(n) {
|
||||
if f(item.id, t).is_break() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}),
|
||||
Owner::Doc(doc) => with_doc(h, doc, |_, st| {
|
||||
let ids = page_items(h, st);
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
for id in ids.iter() {
|
||||
if let Some(n) = st.doc.node(*id) {
|
||||
for t in crate::cmd::tags::tags_of(n) {
|
||||
if f(*id, t).is_break() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first tag `owner` lists for which `pick` holds: its page item and its id.
|
||||
fn find(h: &Host, owner: Owner, mut pick: impl FnMut(&ObjectTag) -> bool) -> std::result::Result<Option<(NodeId, u64)>, HostError> {
|
||||
let mut found = None;
|
||||
each(h, owner, |id, t| {
|
||||
if pick(t) {
|
||||
found = Some((id, t.id));
|
||||
return ControlFlow::Break(());
|
||||
}
|
||||
ControlFlow::Continue(())
|
||||
})?;
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
fn doc_of_owner(owner: Owner) -> Doc {
|
||||
match owner {
|
||||
Owner::Item(i) => i.doc,
|
||||
Owner::Doc(d) => d,
|
||||
}
|
||||
}
|
||||
|
||||
fn tag_ref(h: &Host, doc: Doc, id: NodeId, tag: u64) -> Data {
|
||||
let [high, low] = id_parts(id);
|
||||
let [tag_high, tag_low] = id_parts(NodeId(tag));
|
||||
host_ref("Tag", &[float(h.run), float(doc.uid), high, low, tag_high, tag_low])
|
||||
}
|
||||
|
||||
/// `PageItem.tags`.
|
||||
pub(super) fn item_tags(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = item_of(h, arg(a, 0))?;
|
||||
let [high, low] = id_parts(item.id);
|
||||
Ok(host_ref("Tags", &[float(h.run), float(item.doc.uid), high, low]))
|
||||
}
|
||||
|
||||
/// `Document.tags`.
|
||||
pub(super) fn doc_tags(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = doc_of(h, arg(a, 0), "Document")?;
|
||||
Ok(host_ref("Tags", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
// ---- Tags ----
|
||||
|
||||
fn tags_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let owner = owner_of(h, arg(a, 0))?;
|
||||
let mut count = 0u64;
|
||||
each(h, owner, |_, _| {
|
||||
count += 1;
|
||||
ControlFlow::Continue(())
|
||||
})?;
|
||||
Ok(num(float(count)))
|
||||
}
|
||||
|
||||
fn tags_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
match owner_of(h, arg(a, 0))? {
|
||||
Owner::Item(item) => Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, item.id))),
|
||||
Owner::Doc(doc) => Ok(doc_ref(h, doc.uid)),
|
||||
}
|
||||
}
|
||||
|
||||
fn tags_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let owner = owner_of(h, arg(a, 0))?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
|
||||
let mut left = i;
|
||||
let found = find(h, owner, |_| {
|
||||
let here = left == 0;
|
||||
left = left.wrapping_sub(1);
|
||||
here
|
||||
})?;
|
||||
Ok(found.map_or(Data::Undefined, |(id, tag)| tag_ref(h, doc_of_owner(owner), id, tag)))
|
||||
}
|
||||
|
||||
fn tags_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let owner = owner_of(h, arg(a, 0))?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
let found = find(h, owner, |t| t.name == *name)?;
|
||||
found.map(|(id, tag)| tag_ref(h, doc_of_owner(owner), id, tag)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
}
|
||||
|
||||
fn tags_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => tags_by_name(h, a),
|
||||
Data::Number(_) => match tags_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `tags.add()`: a new tag with an empty name and value after the item's other tags.
|
||||
fn tags_add(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = match owner_of(h, arg(a, 0))? {
|
||||
Owner::Item(item) => item,
|
||||
Owner::Doc(_) => return Err(HostError::Error(NO_OWNER.into())),
|
||||
};
|
||||
edit_item(h, item, "object.tag.add", &json!({"id": item.id.0}))?;
|
||||
// The new tag is the item's last. Its id is read from the document, since the command's answer
|
||||
// gives it as a number, which is exact only up to 2^53.
|
||||
let tag = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(|n| crate::cmd::tags::tags_of(n).last().map(|t| t.id)));
|
||||
let tag = tag.ok_or_else(|| HostError::Error("the tag was not added".into()))?;
|
||||
Ok(tag_ref(h, item.doc, item.id, tag))
|
||||
}
|
||||
|
||||
/// `tags.removeAll()`: deletes every tag in the collection, in one command.
|
||||
fn tags_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let owner = owner_of(h, arg(a, 0))?;
|
||||
let mut ids: Vec<u64> = Vec::new();
|
||||
each(h, owner, |id, _| {
|
||||
if ids.last() != Some(&id.0) {
|
||||
ids.push(id.0);
|
||||
}
|
||||
ControlFlow::Continue(())
|
||||
})?;
|
||||
if !ids.is_empty() {
|
||||
let doc = doc_of_owner(owner);
|
||||
on_doc(h, doc.uid, true, |h| command(h, "object.tag.removeAll", &json!({"ids": ids})))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- Tag ----
|
||||
|
||||
/// A tag: its page item and its id there.
|
||||
#[derive(Clone, Copy)]
|
||||
struct TagRef {
|
||||
item: Item,
|
||||
tag: u64,
|
||||
}
|
||||
|
||||
/// The tag `d` names, which must still be on its page item.
|
||||
fn tag_of(h: &Host, d: &Data) -> std::result::Result<(TagRef, ObjectTag), HostError> {
|
||||
let Some(handle) = handle_of(d, "Tag") else { return Err(HostError::Type("this is not a Tag".into())) };
|
||||
let [run, uid, high, low, tag_high, tag_low] = handle.as_slice() else { return Err(HostError::Type("this is not a Tag".into())) };
|
||||
let item = resolve_item(h, *run, *uid, *high, *low)?;
|
||||
let tag = id_of(*tag_high, *tag_low).ok_or_else(|| HostError::Error(STALE_TAG.into()))?.0;
|
||||
let found = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(|n| crate::cmd::tags::tags_of(n).iter().find(|t| t.id == tag).cloned()));
|
||||
let t = found.ok_or_else(|| HostError::Error(STALE_TAG.into()))?;
|
||||
Ok((TagRef { item, tag }, t))
|
||||
}
|
||||
|
||||
fn tag_name(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text(tag_of(h, arg(a, 0))?.1.name))
|
||||
}
|
||||
|
||||
fn tag_value(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text(tag_of(h, arg(a, 0))?.1.value))
|
||||
}
|
||||
|
||||
/// Sets the tag's `key` (`name` or `value`) to the string the script gives, with no command when
|
||||
/// it already has it.
|
||||
fn set_text(h: &Host, a: &[Data], key: &str) -> Answer {
|
||||
let Data::String(v) = arg(a, 1) else { return Err(HostError::Type(format!("{key} must be a string"))) };
|
||||
if v.len() > MAX_TAG_TEXT {
|
||||
return Err(HostError::Range(format!("a tag's {key} is longer than 65,536 bytes")));
|
||||
}
|
||||
let (t, now) = tag_of(h, arg(a, 0))?;
|
||||
let same = if key == "name" { now.name == *v } else { now.value == *v };
|
||||
if !same {
|
||||
edit_item(h, t.item, "object.tag.set", &json!({"id": t.item.id.0, "tag": t.tag, key: v}))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn tag_set_name(h: &Host, a: &[Data]) -> Answer {
|
||||
set_text(h, a, "name")
|
||||
}
|
||||
|
||||
fn tag_set_value(h: &Host, a: &[Data]) -> Answer {
|
||||
set_text(h, a, "value")
|
||||
}
|
||||
|
||||
fn tag_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let (t, _) = tag_of(h, arg(a, 0))?;
|
||||
Ok(with_doc(h, t.item.doc, |_, st| item_ref(h, st, t.item.id)))
|
||||
}
|
||||
|
||||
fn tag_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let (t, _) = tag_of(h, arg(a, 0))?;
|
||||
edit_item(h, t.item, "object.tag.remove", &json!({"id": t.item.id.0, "tag": t.tag}))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `Tags.typename`, which throws like every other member once the collection's owner is gone.
|
||||
fn tags_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
owner_of(h, arg(a, 0))?;
|
||||
Ok(text("Tags"))
|
||||
}
|
||||
|
||||
/// `Tag.typename`, which throws like every other member once the tag is gone.
|
||||
fn tag_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
tag_of(h, arg(a, 0))?;
|
||||
Ok(text("Tag"))
|
||||
}
|
||||
|
||||
/// The `Tags` and `Tag` classes.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let tags: Vec<(String, HostMember)> = named(vec![
|
||||
("typename", get(l, tags_typename)),
|
||||
("length", get(l, tags_length)),
|
||||
("parent", get(l, tags_parent)),
|
||||
("index", method(l, tags_index)),
|
||||
("getByName", method(l, tags_by_name)),
|
||||
("add", method(l, tags_add)),
|
||||
("removeAll", method(l, tags_remove_all)),
|
||||
]);
|
||||
let tag = named(vec![
|
||||
("typename", get(l, tag_typename)),
|
||||
("name", property(l, tag_name, tag_set_name)),
|
||||
("value", property(l, tag_value, tag_set_value)),
|
||||
("parent", get(l, tag_parent)),
|
||||
("remove", method(l, tag_remove)),
|
||||
]);
|
||||
vec![class("Tags", None, tags, Some(super::function(l, tags_at))), class("Tag", None, tag, None)]
|
||||
}
|
||||
@@ -1080,14 +1080,28 @@ pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result<Vec<serde_json::
|
||||
|
||||
/// Removes from the grants file beside `data_dir` the grants of the script `script` and of the path
|
||||
/// `path`, of both when both are given and of every grant when neither is (`script.grants.revoke`).
|
||||
/// → how many were removed.
|
||||
pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&str>, path: Option<&str>) -> std::io::Result<usize> {
|
||||
/// The spellings of each are tried in order, the script's first, and the first pair that some grant
|
||||
/// holds is the one removed, so a grant kept under the spellings given first is removed without the
|
||||
/// grants of later ones. → how many were removed.
|
||||
pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&[String]>, path: Option<&[String]>) -> std::io::Result<usize> {
|
||||
let store = data_dir.with_file_name(GRANTS_FILE);
|
||||
let _lock = lock_store(&store)?;
|
||||
let grants = try_read_store(&store)?;
|
||||
let before = grants.len();
|
||||
let kept: Vec<serde_json::Value> =
|
||||
grants.into_iter().filter(|g| !(script.is_none_or(|s| g["script"] == *s) && path.is_none_or(|p| g["path"] == *p))).collect();
|
||||
// `None` matches any value; `Some(name)` only that name.
|
||||
fn spellings(names: Option<&[String]>) -> Vec<Option<&str>> {
|
||||
match names {
|
||||
None => vec![None],
|
||||
Some(names) => names.iter().map(|n| Some(n.as_str())).collect(),
|
||||
}
|
||||
}
|
||||
let matches = |g: &serde_json::Value, (script, path): (Option<&str>, Option<&str>)| {
|
||||
script.is_none_or(|s| g["script"] == s) && path.is_none_or(|p| g["path"] == p)
|
||||
};
|
||||
let pairs = spellings(script).into_iter().flat_map(|s| spellings(path).into_iter().map(move |p| (s, p)));
|
||||
let pair = pairs.into_iter().find(|&pair| grants.iter().any(|g| matches(g, pair)));
|
||||
let Some(pair) = pair else { return Ok(0) };
|
||||
let kept: Vec<serde_json::Value> = grants.into_iter().filter(|g| !matches(g, pair)).collect();
|
||||
let removed = before - kept.len();
|
||||
if removed > 0 {
|
||||
write_store(&store, kept)?;
|
||||
|
||||
@@ -237,7 +237,7 @@ fn hidden(entry: &std::fs::DirEntry) -> bool {
|
||||
|
||||
/// Does Windows mark the file or folder of `m` hidden or system?
|
||||
#[cfg(windows)]
|
||||
fn hidden_meta(m: &std::fs::Metadata) -> bool {
|
||||
pub(super) fn hidden_meta(m: &std::fs::Metadata) -> bool {
|
||||
use std::os::windows::fs::MetadataExt as _;
|
||||
const HIDDEN_OR_SYSTEM: u32 = 0x2 | 0x4;
|
||||
m.file_attributes() & HIDDEN_OR_SYSTEM != 0
|
||||
@@ -245,13 +245,13 @@ fn hidden_meta(m: &std::fs::Metadata) -> bool {
|
||||
|
||||
/// Elsewhere a hidden file is one whose name starts with a dot, which the listing leaves out by name.
|
||||
#[cfg(not(windows))]
|
||||
fn hidden_meta(_: &std::fs::Metadata) -> bool {
|
||||
pub(super) fn hidden_meta(_: &std::fs::Metadata) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Is `path` a folder (`folder`) or a file, and not a link? With `shown`, also not one Windows
|
||||
/// marks hidden or system, which a listing leaves out.
|
||||
fn plain(path: &Path, folder: bool, shown: bool) -> bool {
|
||||
pub(super) fn plain(path: &Path, folder: bool, shown: bool) -> bool {
|
||||
std::fs::symlink_metadata(path)
|
||||
.is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m)))
|
||||
}
|
||||
|
||||
Loaded 100 of 484 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user