Merge remote-tracking branch 'origin/main' into review-5560

# Conflicts:
#	docs/target-app-parity.md
This commit is contained in:
MarekSpodBiedry committed 2026-11-10 18:36:27 +01:00
commit 90a8912027
1007 files changed
+157695 -7693

No files matched your search

+7
View File
@@ -1,2 +1,9 @@
[alias]
xtask = "run --package xtask --"
# WebAssembly SIMD for the web build: without it vello_cpu's SIMD layer (fearless_simd) runs its
# scalar fallback on wasm32 and the canvas renders about 2.4x slower (#2786). The web build then
# needs Chrome/Edge 91+, Firefox 89+ or Safari 16.4+. A RUSTFLAGS environment variable replaces
# these flags.
[target.wasm32-unknown-unknown]
rustflags = ["-C", "target-feature=+simd128"]
+8 -1
View File
@@ -20,6 +20,12 @@ concurrency:
cancel-in-progress: false
jobs:
# Regenerates contributors/contributors.json for the release commit; every build bundles it.
credits:
permissions:
contents: read
pull-requests: read
uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main
git-sources:
name: Git dependencies come from storytold
runs-on: ubuntu-latest
@@ -60,7 +66,7 @@ jobs:
PY
release:
needs: git-sources
needs: [git-sources, credits]
permissions:
contents: write
packages: write
@@ -72,6 +78,7 @@ jobs:
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
web-craft-fonts: true
version: ${{ inputs.version }}
contributors-artifact: ${{ needs.credits.outputs.artifact-name }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
+12
View File
@@ -368,6 +368,18 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `crates/engine/tests/fixtures/jpeg2000/checker.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `3de9c2bb5b8aaec241d939b795002a68eb3d50e41d51c43368000804ad3de057` |
| `crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `76fa51ab8ccbc2534098b26b8e7fe16dd886e2b6298ba52d06a6b1bde9b61d9e` |
| `crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `1b1aeed8975d3cdc832da6ecf5855852d07d0c490105121e61a8aefb31af009b` |
| `crates/engine/tests/fixtures/heif/quadrants.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 32 red, green, blue and white quadrants encoded with libheif's `heif-enc` 1.23.2 (x265); SHA-256 `122d14963fe899daa736cd216902cf4fc8f2192b3a0ba81f94004adcd71a0ff5` |
| `crates/engine/tests/fixtures/heif/quadrants-alpha.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the quadrants with a transparent right half, encoded with `heif-enc` 1.23.2; SHA-256 `55b5a537401ead742714c3a1bc526559ec8c1ba97cdb7f43ac63f4037167475b` |
| `crates/engine/tests/fixtures/heif/quadrants-10bit.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the quadrants at 10 bits, encoded with `heif-enc` 1.23.2; SHA-256 `11014848c6a838e5799d87e034eff1b06b816712ed70ba451bd582d72741774f` |
| `crates/engine/tests/fixtures/heif/quadrants-grid.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 128 × 128 quadrants as a 2 × 2 grid of 64 × 64 tiles, encoded with `heif-enc` 1.23.2; SHA-256 `5802f8715110954eb9c58d4bdcc10d1200426a48cf726f1b88dfb60da825ba7a` |
| `crates/engine/tests/fixtures/heif/quadrants-300ppi.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the quadrants with EXIF resolution tags of 300 ppi, encoded with `heif-enc` 1.23.2; SHA-256 `6a344a6de04fc5fceaee46b6e0028b12478c90bdcb6f6f14ed8c86a44cb203d7` |
| `crates/engine/tests/fixtures/heif/wide-rotated.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 16 red and blue halves stored with a quarter-turn rotation, encoded with `heif-enc` 1.23.2; SHA-256 `e3a2c3a9beb4066c13d6deb8e1311805c6aac485fde8784f1ee317dd95b89973` |
| `crates/engine/tests/fixtures/heif/wide-rotated-300x150.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the rotated halves with EXIF resolution tags of 300 ppi across and 150 ppi down, encoded with `heif-enc` 1.23.2; SHA-256 `79ad7945cd2c1ea9d3e70ac9b93d9a162fd8ce37541a0f3de44e12f04745921d` |
| `crates/engine/tests/fixtures/heif/tones.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 32 quadrants of four mid tones, encoded with `heif-enc` 1.23.2; SHA-256 `29ed7d75fbfbc4c298eb2da3a6b62625a150cd6bfe5b7ff1d847437501b1b4b1` |
| `crates/engine/tests/fixtures/heif/tones-p3-nclx.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the tones labeled Display P3 in an `nclx` color box, encoded with `heif-enc` 1.23.2; SHA-256 `baeb32ffa58ac1ac29a00c9e388b9281f4acb4695c4681e4933d0ad061447101` |
| `crates/engine/tests/fixtures/heif/tones-p3-icc.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the tones with VectorCraft's own Display P3 ICC profile (`vectorcraft_color::cms::icc_bytes`), encoded with `heif-enc` 1.23.2; SHA-256 `472e1a123b9515926a8985a04c3f680387e8c410dbf8f7ff0cfb8cb99c89e93b` |
| `crates/engine/tests/fixtures/heif/tones-p3-icc-only.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the tones with VectorCraft's own Display P3 ICC profile as their only color box, encoded with `heif-enc` 1.23.2; SHA-256 `2654fdd21e56641107db20b3f4d0a66a86420ac040d42ddf55e20f7e789d5c55` |
| `crates/engine/tests/fixtures/heif/quadrants-grid16.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 32 quadrants as a 2 × 2 grid of 16 × 16 tiles, each cropped from a 64 × 64 picture, encoded with `heif-enc` 1.23.2; SHA-256 `bd114ee66cdac10142729dc9dddfa1cd96993a5cefa54c2f25b65496652f007f` |
## Assets embedded by the PDF backend
Generated
+285 -23
View File
@@ -975,12 +975,12 @@ source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1036,9 +1036,20 @@ dependencies = [
]
[[package]]
name = "craft-ui"
name = "craft-proof"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
dependencies = [
"log",
"miniz_oxide 0.9.1",
"toml",
"unicode-normalization",
]
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1059,7 +1070,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"chrono",
"dunce",
@@ -1442,7 +1453,7 @@ dependencies = [
"itertools",
"log",
"profiling",
"resvg",
"resvg 0.45.1",
]
[[package]]
@@ -2286,6 +2297,15 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "heic-rs"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8883c3bfa6b4ff19a40e52a6dc051c5612cbe21bf408fc6d4875e8dfd777cb66"
dependencies = [
"rayon",
]
[[package]]
name = "hermit-abi"
version = "0.5.3"
@@ -2835,6 +2855,182 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "jxl-bitstream"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b480e752277e29eb4054f69546887a9b84656fe78c08f54ba5850ced98a378fe"
dependencies = [
"tracing",
]
[[package]]
name = "jxl-coding"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd972bcd125e776f1eb241ac50e39f956095a1c2770c64736c968f8946bd9a3c"
dependencies = [
"jxl-bitstream",
"tracing",
]
[[package]]
name = "jxl-color"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f316b1358c1711755b3ee8e8cb5c4a1dad12e796233088a7a513440782de80b2"
dependencies = [
"jxl-bitstream",
"jxl-coding",
"jxl-grid",
"jxl-image",
"jxl-oxide-common",
"jxl-threadpool",
"tracing",
]
[[package]]
name = "jxl-frame"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d967c6fd669c7c01060b5022d8835fa82fd46b06ffc98b549f17600a097c2b3"
dependencies = [
"jxl-bitstream",
"jxl-coding",
"jxl-grid",
"jxl-image",
"jxl-modular",
"jxl-oxide-common",
"jxl-threadpool",
"jxl-vardct",
"tracing",
]
[[package]]
name = "jxl-grid"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01671307879a033bfa52e6e8784b941aca770b3f3a7d33830b455b6844f793fb"
dependencies = [
"tracing",
]
[[package]]
name = "jxl-image"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5f752d62577c702a94dbbce4045caf08cb58639e8a4d56464b40ecf33ffe565"
dependencies = [
"jxl-bitstream",
"jxl-grid",
"jxl-oxide-common",
"tracing",
]
[[package]]
name = "jxl-jbr"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e35d032bcec660647828527ff42c6f5776d2fd44b8357f9f6d9ac6dc07218e46"
dependencies = [
"brotli-decompressor",
"jxl-bitstream",
"jxl-frame",
"jxl-grid",
"jxl-image",
"jxl-modular",
"jxl-oxide-common",
"jxl-threadpool",
"jxl-vardct",
"tracing",
]
[[package]]
name = "jxl-modular"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a2f045b24c738dd91d482be385512b512721ae08a671bd4b27bf1c47f215235"
dependencies = [
"jxl-bitstream",
"jxl-coding",
"jxl-grid",
"jxl-oxide-common",
"jxl-threadpool",
"tracing",
]
[[package]]
name = "jxl-oxide"
version = "0.12.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d36c662923f47586880211f3bc7c0d83fb3a9b410d278c7bde93450748abeef3"
dependencies = [
"brotli-decompressor",
"jxl-bitstream",
"jxl-color",
"jxl-frame",
"jxl-grid",
"jxl-image",
"jxl-jbr",
"jxl-oxide-common",
"jxl-render",
"jxl-threadpool",
"tracing",
]
[[package]]
name = "jxl-oxide-common"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b62394c5021b3a9e7e0dbb2d639d555d019090c9946c39f6d3b09d390db4157b"
dependencies = [
"jxl-bitstream",
]
[[package]]
name = "jxl-render"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d34386bfdb6a19b5a30cc9beb4d475d537422c31ae8c39bb69640fcce3fcaf19"
dependencies = [
"bytemuck",
"jxl-bitstream",
"jxl-coding",
"jxl-color",
"jxl-frame",
"jxl-grid",
"jxl-image",
"jxl-modular",
"jxl-oxide-common",
"jxl-threadpool",
"jxl-vardct",
"tracing",
]
[[package]]
name = "jxl-threadpool"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25f15eb830aa77a7f21148d72e153562a26bfe570139bd4922eab1908dd499d3"
dependencies = [
"tracing",
]
[[package]]
name = "jxl-vardct"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce72a18c6d3a47172ab6c479be2bdb56f22066b5d7092663f03b4490820b4511"
dependencies = [
"jxl-bitstream",
"jxl-coding",
"jxl-grid",
"jxl-modular",
"jxl-oxide-common",
"jxl-threadpool",
"tracing",
]
[[package]]
name = "keyboard-types"
version = "0.8.3"
@@ -2978,8 +3174,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a25df1b0c5432893f41bba817150e323703ee5f6d974f3a6808ac7fd7f046d18"
source = "git+https://github.com/storytold/craft-libs?rev=481f66d287b2a06845f3667a19daf35f0fe958ed#481f66d287b2a06845f3667a19daf35f0fe958ed"
dependencies = [
"arrayvec",
"kurbo 0.13.1",
@@ -4430,11 +4625,29 @@ dependencies = [
"pico-args",
"rgb",
"svgtypes 0.15.3",
"tiny-skia",
"tiny-skia 0.11.4",
"usvg 0.45.1",
"zune-jpeg 0.4.21",
]
[[package]]
name = "resvg"
version = "0.48.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd"
dependencies = [
"bytemuck",
"gif 0.14.2",
"image-webp",
"log",
"pico-args",
"rgb",
"svgtypes 0.16.1",
"tiny-skia 0.12.0",
"usvg 0.48.1",
"zune-jpeg 0.5.15",
]
[[package]]
name = "rfd"
version = "0.17.2"
@@ -4719,7 +4932,7 @@ checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec"
dependencies = [
"log",
"smithay-client-toolkit 0.19.2",
"tiny-skia",
"tiny-skia 0.11.4",
]
[[package]]
@@ -5585,6 +5798,21 @@ dependencies = [
"tiny-skia-path 0.11.4",
]
[[package]]
name = "tiny-skia"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea"
dependencies = [
"arrayref",
"arrayvec",
"bytemuck",
"cfg-if",
"log",
"png 0.18.1",
"tiny-skia-path 0.12.0",
]
[[package]]
name = "tiny-skia-path"
version = "0.11.4"
@@ -6139,6 +6367,13 @@ dependencies = [
"ruzstd",
]
[[package]]
name = "vectorcraft-apischema"
version = "0.21.0"
dependencies = [
"serde_json",
]
[[package]]
name = "vectorcraft-brush"
version = "0.21.0"
@@ -6227,7 +6462,9 @@ version = "0.21.0"
dependencies = [
"image",
"kurbo 0.13.1",
"resvg 0.48.1",
"serde_json",
"svgtypes 0.16.1",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-geom",
@@ -6244,20 +6481,28 @@ dependencies = [
"cfb",
"chrono",
"craft-docpath",
"craft-proof",
"crc32fast",
"flate2",
"hayro-jpeg2000",
"heic-rs",
"image",
"jxl-color",
"jxl-grid",
"jxl-oxide",
"kurbo 0.13.1",
"log",
"proptest",
"rayon",
"roxmltree 0.21.2",
"rustix 1.1.6",
"ruzstd",
"serde",
"serde_json",
"skrifa 0.47.0",
"thiserror 2.0.21",
"vectorcraft-affinity",
"vectorcraft-apischema",
"vectorcraft-brush",
"vectorcraft-cad",
"vectorcraft-color",
@@ -6265,6 +6510,7 @@ dependencies = [
"vectorcraft-eps",
"vectorcraft-format",
"vectorcraft-geom",
"vectorcraft-js",
"vectorcraft-metafile",
"vectorcraft-pathops",
"vectorcraft-pdf",
@@ -6277,12 +6523,16 @@ dependencies = [
"vectorcraft-tools",
"vectorcraft-trace",
"wat",
"zune-core 0.5.3",
"zune-jpegxl",
]
[[package]]
name = "vectorcraft-eps"
version = "0.21.0"
dependencies = [
"craft-pdf",
"encoding_rs",
"fax",
"flate2",
"hayro-ccitt",
@@ -6291,6 +6541,7 @@ dependencies = [
"memchr",
"ruzstd",
"serde_json",
"skrifa 0.47.0",
"vectorcraft-brush",
"vectorcraft-color",
"vectorcraft-doc",
@@ -6332,6 +6583,15 @@ dependencies = [
"vectorcraft-testkit",
]
[[package]]
name = "vectorcraft-js"
version = "0.21.0"
dependencies = [
"chrono",
"proptest",
"unicode-general-category",
]
[[package]]
name = "vectorcraft-mcp"
version = "0.21.0"
@@ -6392,6 +6652,8 @@ dependencies = [
"kurbo 0.13.1",
"log",
"md-5",
"objc2-core-foundation",
"objc2-core-graphics",
"roxmltree 0.21.2",
"serde",
"serde_json",
@@ -6413,8 +6675,12 @@ dependencies = [
name = "vectorcraft-plugins"
version = "0.21.0"
dependencies = [
"craft-vectorcraft-format",
"image",
"log",
"serde",
"serde_json",
"sha2",
"thiserror 2.0.21",
"vectorcraft-color",
"vectorcraft-doc",
@@ -6469,7 +6735,7 @@ dependencies = [
"image",
"kurbo 0.13.1",
"proptest",
"resvg",
"resvg 0.45.1",
"serde",
"serde_json",
"simplecss",
@@ -7981,7 +8247,6 @@ dependencies = [
"nix",
"typed-path",
"windows-sys 0.61.2",
"zopfli",
]
[[package]]
@@ -7996,18 +8261,6 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zopfli"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
[[package]]
name = "zune-core"
version = "0.4.12"
@@ -8038,6 +8291,15 @@ dependencies = [
"zune-core 0.5.3",
]
[[package]]
name = "zune-jpegxl"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4"
dependencies = [
"zune-core 0.5.3",
]
[[package]]
name = "zvariant"
version = "5.15.1"
+19 -2
View File
@@ -14,15 +14,16 @@ repository = "https://github.com/storytold/vectorcraft"
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["serde"] }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "bb8320f5fa5d20fa78a026d0de06fe4e2f08a099", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] }
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -53,6 +54,8 @@ vectorcraft-metafile = { path = "crates/metafile" }
vectorcraft-plugins = { path = "crates/plugins" }
vectorcraft-affinity = { path = "crates/affinity" }
vectorcraft-scriptcheck = { path = "crates/scriptcheck" }
vectorcraft-js = { path = "crates/js" }
vectorcraft-apischema = { path = "crates/apischema" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
@@ -98,12 +101,25 @@ ruzstd = { version = "0.9.1", default-features = false, features = ["std"] }
hayro-ccitt = "0.3"
# Substring search for the EPS reader's PostScript `search`.
memchr = "2"
# The WHATWG Encoding Standard's legacy encodings: names in legacy .ai files read in the code page
# the user picks (Mac OS Roman, Korean, Japanese, Chinese).
encoding_rs = "0.8.42"
jpeg-encoder = { version = "0.6", default-features = false, features = ["std"] }
gif = { version = "0.14", default-features = false, features = ["std", "raii_no_panic"] }
# CMYK image samples (vectorcraft-doc's cmyk module): the image crate's own TIFF and JPEG
# decoders, read directly (the image crate converts CMYK to RGB).
tiff = "0.11"
zune-jpeg = "0.5"
# JPEG XL decoder (pure Rust, MIT OR Apache-2.0): File › Open and Place read `.jxl` images. It is
# built without its default `rayon` feature and decodes on one thread.
jxl-oxide = { version = "0.12.6", default-features = false }
# jxl-oxide's color conversions, run on colors after their alpha is divided out.
jxl-color = "0.11.0"
# jxl-oxide's buffer allocation error, told apart from other decoding errors.
jxl-grid = "0.6.2"
# Tests: a lossless JPEG XL encoder (pure Rust, MIT OR Apache-2.0 OR Zlib) for the `.jxl` test files.
zune-jpegxl = { version = "0.5.2", default-features = false, features = ["std"] }
zune-core = "0.5"
# ui
egui = "0.37"
@@ -153,6 +169,7 @@ hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "9be9a637
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "481f66d287b2a06845f3667a19daf35f0fe958ed" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+6 -1
View File
@@ -20,10 +20,15 @@ list (author, source, license) is in ASSETS.md.
(Ubuntu Font Licence 1.0), Hack (MIT), Noto Emoji (SIL Open Font License 1.1) and emoji-icon-font
(MIT). Their license texts ship with that crate.
Rust dependencies (vello_cpu, kurbo, peniko, skrifa, harfrust, usvg, linesweeper, egui, eframe, …) are
Rust dependencies (vello_cpu, kurbo, peniko, skrifa, harfrust, usvg, egui, eframe, …) are
fetched through crates.io under their own permissive licenses (mostly MIT and/or Apache-2.0; also
BSD, ISC, Zlib, BSL-1.0 and Unicode-3.0).
linesweeper 0.5.0 (MIT OR Apache-2.0) is fetched from https://github.com/storytold/craft-libs at
revision 481f66d287b2a06845f3667a19daf35f0fe958ed. The copy in craft-libs' vendor/linesweeper is
the crates.io package with no file changed, and it keeps the package's LICENSE-MIT and
LICENSE-APACHE.
JPEG export uses the jpeg-encoder crate (MIT OR Apache-2.0, and the IJG License): this software is
based in part on the work of the Independent JPEG Group.
+3 -3
View File
@@ -237,7 +237,7 @@ and what's next; [`docs/target-app-parity.md`](docs/target-app-parity.md) the fu
(92.5% of menu items do something), feature depth is ~75%, and we estimate ~65% ready for real work for a mainstream illustrator (~62% across all tracked features): everyday
vector illustration is close to usable: drawing and path tools,
Pathfinder and Shape Builder, paint, gradients, appearance and transparency, type with styles, threading and Hebrew/Arabic bidirectional layout, and
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out and PSD/PSB in as their merged image, Print, Package).
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out and PSD/PSB in as their merged image, JPEG XL in, Print, Package).
Affinity documents (`.af` from Affinity 3, `.afdesign`, `.afpub` and, by their content, `.afphoto` from Affinity 1 and 2) open
and place natively: layers, groups, artboards and pages, curves and shapes, fills, gradients and strokes, clipping
and masks, text with each paragraph's indents, spacing and leading, tables (as text frames and lines), master
@@ -253,7 +253,7 @@ The scores are self-assessed from our code against public documentation;
[target-app-parity.md](docs/target-app-parity.md#how-this-was-measured-2026-10-10) explains how far to trust them.
**What's missing:**
- reliable exchange of .ai files (layer structure in real files; the editing copy a save writes leaves out live effects and writes symbols and live objects as their art);
- reliable exchange of .ai files (layer structure in real files; the editing copy a save writes keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), leaves out other objects' effects other than geometry effects, and writes live objects as their art);
- an interaction-fidelity pass covering every tool's modifiers and small behaviours;
- 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials);
- filter thumbnails and a preview area inside the Effect Gallery (the gallery itself and all 57 Photoshop-style raster filters, approximated, are in);
@@ -317,7 +317,7 @@ Installers and executables are code-signed.
| Build | File | Notes |
|---|---|---|
| Static site | `vectorcraft-web-<ver>.zip` | Runs in a modern browser; host it on any static server |
| Static site | `vectorcraft-web-<ver>.zip` | Runs in a browser with WebAssembly SIMD (Chrome/Edge 91, Firefox 89, Safari 16.4 or newer), see `packaging/web/README.md`; host it on any static server |
## The Crafting Apps
+18 -18
View File
@@ -1,20 +1,8 @@
# VectorCraft Roadmap
- Contour add-on (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged.
- Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged.
- Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged.
- PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document.
- PDF.W1: PDF export and print composition use the shared optional writer for configuration, metadata, font preparation and guarded finalization; drawing and output policy remain app-owned.
- UI.5: Shared docking adds tab reordering, docking into other groups, dock splits and resizable floating panel groups. Panel positions and return locations persist with workspaces; the native icon rail and Tools panel remain available.
- UI.4: Dock and floating-panel headers use shared accessible tabs with bounded overflow. Widget-state theme application uses `craft-ui`; all four palettes, font stacks and preferences remain app-owned.
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs
on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON
@@ -24,7 +12,7 @@ and the work list in [`docs/gaps.md`](docs/gaps.md).
**Why alpha:** the core workflows exist end to end (drawing and path editing, Pathfinder, paint and appearance,
type, SVG/PDF/EPS, print, export) and feature depth is ~75%, but a professional can't yet switch: Illustrator's
own `.ai` files open with a wrong layer structure in real cases and are saved back with an editing copy that
leaves out live effects and writes symbols and live objects as their art, the interaction details have never been checked side by side, and some machines fail to start the
keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), and writes live objects as their art, the interaction details have never been checked side by side, and some machines fail to start the
app. Beta needs those closed (the beta list in [gaps.md](docs/gaps.md)). It passes the core-workflow
gate: all six core workflows (path drawing and editing, paint and style, type, layers/artboards/export, print
production, file exchange) work end to end on macOS with save and reopen, and only the last is partial, without
@@ -81,11 +69,11 @@ The dimension hours overlap (feature rows hold some UI, format and AI work), so
| Strokes, brushes, width profiles | 88% | 8–15 |
| Appearance, transparency, graphic styles, masks | 97% | 1–2 |
| Live vector effects | 85% | 4–8 |
| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 85% | 1–2 |
| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 88% | — |
| 3D and Materials | ~25% | 30–55 |
| Type core — [type-parity.md](docs/type-parity.md) | 80% | 14–19 |
| Type advanced (CJK, spelling, Touch Type) | 50% | 20–28 |
| Symbols, blends, envelopes, Repeat, perspective | 87% | 5–9 |
| Symbols, blends, envelopes, Repeat, perspective | 88% | 4–7 |
| Image Trace, graphs, image tools | 75% | 5–8 |
| Layers, artboards, document setup | 78% | 5–8 |
| View & navigation | 70% | 9–14 |
@@ -129,11 +117,11 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
2. **`.ai` files from real users** (G9): layer structure, guides, speed: 10–20 h.
3. **Launch and stability on real machines** (G10): 20–35 h.
4. **Core-tool correctness** (G11: Shape Builder regions, Asset Export borders): 8–15 h.
5. **Raster effects** (G2) alongside: the Effect Gallery's filter thumbnails and in-dialog preview area (the gallery and every Photoshop-style filter are in), 1–2 h.
6. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3).
5. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3). The Effect Gallery's filter thumbnails and in-dialog preview are in (G2).
## Progress log
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
@@ -223,6 +211,14 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| Date | Change | Summary |
|---|---|---|
| 2026-11-10 | minor | Tidy-up, no content change: the unheaded change bullets at the top of the file and a revision row inside the headline-numbers table move to this table under their commit dates. Scores and estimates unchanged. |
| 2026-11-10 | minor | Raster effects: Effect Gallery thumbnails and an in-dialog preview (an original drawing through each filter). Features-table Raster effects 85% → 88%, hours 1–2 → none. Headline numbers unchanged, so the progress log is unchanged. |
| 2026-11-05 | minor | Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged. |
| 2026-11-04 | minor | Contour add-on (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged. |
| 2026-11-03 | minor | Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged. |
| 2026-11-03 | minor | UI: Window → Help Bar toggles the tool-help strip separately from the status bar and saves visibility with workspaces. Scores and estimates unchanged. |
| 2026-11-03 | minor | Docked Tools stays between left-side panels and the canvas; redocking accepts canvas and window edges. Requested layout choice; scores and estimates unchanged. |
| 2026-11-02 | minor | Selection QoL: saved marquee modes, screen drag direction with a 3 px dead zone, and translated mode/E feedback (#5313); VectorCraft addition, scores and estimates unchanged. |
| 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged |
| 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. |
| 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. |
@@ -258,10 +254,14 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| 2026-10-13 | minor | Bounded synthetic control input (#1709): counts and queued events validated before mutation; control-channel bursts yield between frames. Scores and hours unchanged. |
| 2026-10-14 | minor | Progress log row for the merges of 2026-10-14 (#1641–#1808 as listed there) and Image Trace's #1647 and #1657; the 2026-10-13 row now says that a guide's position in the Transform panel (#1659) is not established by the documentation found and is kept as a convenience pending the owner's decision; headline numbers unchanged. |
| 2026-10-13 | minor | Control transport deadlines (#1726): idle and partial clients and blocked replies release connection slots; parity scores and estimates unchanged. |
| 2026-10-13 | minor | PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document. |
| 2026-10-13 | minor | PDF.W1: PDF export and print composition use the shared optional writer for configuration, metadata, font preparation and guarded finalization; drawing and output policy remain app-owned. |
| 2026-10-10 | minor | Method changed, no new evidence: full ready for real work is the additive weighted sum, ~62%; hours per audience; beta ~13 points away |
| 2026-10-10 | minor | Added the essentials-user readiness score (~75%) |
| 2026-10-10 | minor | Ready for real work re-examined against the issue tracker and user feedback: 50% → 55% (full), 65% mainstream added; see target-app-parity.md |
| 2026-10-10 | minor | Applied the core-workflow gate (docs/roadmap.md › Alpha gate): passes, stage stays alpha |
| 2026-10-10 | major | Re-measured against Illustrator 2026 (30.x) from code counts, 71 open issues and public docs; stage set to alpha; moved the parity estimate, honest assessment and "Shipped so far" to `docs/target-app-parity.md`, the gap list to `docs/gaps.md`, milestones to `docs/roadmap.md`, the `.ai` scope to `docs/file-format-parity.md` |
| 2026-10-10 | minor | UI.5: Shared docking adds tab reordering, docking into other groups, dock splits and resizable floating panel groups. Panel positions and return locations persist with workspaces; the native icon rail and Tools panel remain available. |
| 2026-10-10 | minor | UI.4: Dock and floating-panel headers use shared accessible tabs with bounded overflow. Widget-state theme application uses `craft-ui`; all four palettes, font stacks and preferences remain app-owned. |
| 2026-10-05 | major | Honest assessment by dimension and the prioritized gap list |
| 2026-10-02 | major | First 22-area weighted parity estimate |
+1 -1
View File
@@ -16,7 +16,7 @@ workspace = true
[dependencies]
vectorcraft-color = { workspace = true }
vectorcraft-doc = { workspace = true }
vectorcraft-engine = { workspace = true, features = ["bundled-fonts"] }
vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] }
vectorcraft-format = { workspace = true }
vectorcraft-geom = { workspace = true }
vectorcraft-svg = { workspace = true }
+100 -19
View File
@@ -1,10 +1,11 @@
//! `vectorcraft-cli`: VectorCraft from the command line.
//!
//! ```text
//! vectorcraft-cli --safe-mode SUBCOMMAND ...
//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300]
//! vectorcraft-cli commands
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
//! vectorcraft-cli info FILE
//! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5]
//! vectorcraft-cli perf [--paths 50000] [--deep]
@@ -72,7 +73,12 @@ const USAGE: &str = "\
vectorcraft-cli — VectorCraft automation
USAGE:
vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
vectorcraft-cli --safe-mode SUBCOMMAND ...
Run any subcommand without plug-ins: none loads or runs, and plug-in commands report that
Safe Mode is on. Plug-ins stay installed. `--safe-mode mcp` serves a headless session and
does not take --connect.
vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants]
Run the MCP server on stdio. Default: connect to a running app at 127.0.0.1:7979
(vectorcraft --control 7979), falling back to a headless in-process session.
--automation-read-root / --automation-write-root confine the files the agent's commands read
@@ -80,8 +86,18 @@ USAGE:
DIR, links followed; each may be given more than once, a path inside any of its folders being
allowed, and a kind left out grants none of its access. They imply --headless: a running app
enforces its own (vectorcraft --control PORT --automation-read-root DIR …).
--allow-plugin-grants lets plugin.install's grant and allowHeavy take effect in this session,
so whoever sends the commands can give a plug-in the permissions it lists, and a heavy budget,
with nobody approving them. Without it they are refused, and a plug-in that lists permissions
installs only when its hash is already recorded in grants.json, by a person's approval in the
desktop app or by a grant accepted under this flag. A grant accepted under this flag stays
recorded and counts as approved in later sessions. It implies --headless. It can't be used
with --automation-read-root or --automation-write-root: a server confined to folders has no
plug-in store, so it reads no grants.json, and a plug-in that lists permissions or asks for a
heavy budget does not install there. With VECTORCRAFT_NO_PREFS set there is no store either,
and a grant accepted under this flag lasts for that session only.
vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] [--ppi N]
vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] [--ppi N] [--allow-plugin-grants]
Headless batch: open FILE (any readable format) or start a new document, run commands in
order, export each FILE in the format its extension picks (see Writable formats; a .ait FILE
is a template, written as file.saveAsTemplate writes it). Raster exports use the document's
@@ -91,11 +107,13 @@ USAGE:
--cmd and --export steps: a JSON array of {\"command\": ID, \"params\": {...}} (or \"id\" for
\"command\"), or one such object per line (JSON Lines), at most 64 MiB and 100000 steps.
Errors name the step, counting from 0 as \"$N\" references do.
--allow-plugin-grants lets plugin.install's grant and allowHeavy take effect in this run, as
for mcp.
vectorcraft-cli commands
Print the command catalogue as JSON.
vectorcraft-cli convert IN OUT [--scale N] [--ppi N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
vectorcraft-cli convert IN OUT [--scale N] [--ppi N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
Open IN (any readable format) and export OUT in the format its extension picks (see Writable
formats). Raster resolution: --ppi, else 72 times --scale, else the document's raster effects
resolution; other formats leave them out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard
@@ -108,7 +126,10 @@ USAGE:
IN left things out (hidden text, art or layers it could not read; the notes say which) unless
--replace-lossy is given. --editing-data opens a .ai or an EPS with editing data from its editing copy
even where that draws differently from its PDF part or page (which can be older), as long as
it can be read. A PDF OUT omits the embedded native document unless --preserve-editing is
it can be read. --legacy-name-encoding reads the names in a .ai's or an EPS's editing data
that aren't UTF-8 (layers, objects, artboards, colors, gradients, patterns, graphic styles,
swatches, brushes, symbols, variables and data sets, and data sets' text values) in
windows-1252 (the default), macintosh, windows-949, shift_jis, gbk or big5. A PDF OUT omits the embedded native document unless --preserve-editing is
given (the app's Save As PDF still defaults to keeping it). With --preserve-editing, when the
attachment is written the result's warnings say so (it is left out, with its own warning, for
--artboard or a --range without every artboard).
@@ -128,12 +149,17 @@ USAGE:
Render FILE (any readable format) fitted to WxH (default 2880x1800) and print ms per frame
(warm), multithreaded and single-threaded.
vectorcraft-cli perf [--paths N] [--deep]
vectorcraft-cli perf [--paths N] [--deep] [--native-io [--artboards 1..4]]
Check the performance budgets (render, pan, hit test, save/load, SVG, Pathfinder, handle
and segment drags) on a synthetic N-path document (default 50000). Exits non-zero if a
budget is exceeded, unless the report says the machine is busy. --deep also times work with
no budget yet and prints memory use (the working set on Windows), with the peak so far on
Windows and Linux.
--native-io instead measures the application's native save/open commands (one warmup,
five samples, no disk I/O), including preview, PDF, compression and API base64 costs.
It reports the default and explicit PDF opt-out, with and without preview/compression;
--artboards repeats the same artwork
on 1 to 4 overlapping artboards. This mode allows at most 50000 paths.
";
/// The usage text plus the formats `document.open` reads and `document.export` writes.
@@ -175,12 +201,18 @@ fn main() -> ExitCode {
#[cfg(target_os = "macos")]
mac_fonts::install();
prefs_dir::install_fonts();
let args: Vec<String> = std::env::args().skip(1).collect();
let mut args: Vec<String> = std::env::args().skip(1).collect();
// Before any subcommand attaches the plug-in folder.
let safe_mode = args.first().is_some_and(|a| a == "--safe-mode");
if safe_mode {
args.remove(0);
vectorcraft_engine::cmd::plugin::start_in_safe_mode();
}
let r = match args.first().map(String::as_str) {
// `commands` and `info` take no options, so `--help` or `-h` anywhere after them prints the
// usage. The other subcommands check for it themselves.
Some("commands" | "info") if help_requested(&args[1..], &[]) => help(),
Some("mcp") => mcp(&args[1..]),
Some("mcp") => mcp(&args[1..], safe_mode),
Some("run") => run(&args[1..]),
Some("commands") => commands(),
Some("convert") => convert(&args[1..]),
@@ -204,21 +236,34 @@ fn main() -> ExitCode {
}
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
/// ICC profiles loaded and the plug-ins installed (#2168, #2174, #2541), in the folders next to the preferences that the desktop
/// app uses too. `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply as they do there.
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541) and the custom dictionary's words (#4936), in the folders
/// and files next to the preferences that the desktop app uses too. `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply
/// as they do there.
fn with_stores(mut h: Headless) -> Headless {
prefs_dir::attach_profile_store(&mut h.session);
prefs_dir::attach_plugin_store(&mut h.session);
prefs_dir::attach_pdf_preset_store(&mut h.session);
prefs_dir::attach_custom_dictionary(&mut h.session);
h
}
fn mcp(args: &[String]) -> Result<(), String> {
/// Makes `h`'s `plugin.install` accept `grant` and `allowHeavy` when `allow` (`--allow-plugin-grants`).
fn accepting_grants(mut h: Headless, allow: bool) -> Headless {
if allow {
h.session.allow_plugin_grants_from_requests();
}
h
}
/// `mcp`. With `--safe-mode` (`safe_mode`) it serves a headless session: a running app loads its own
/// plug-ins, so `--connect` is refused and the default does not connect.
fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
if help_requested(args, &["--connect", "--automation-read-root", "--automation-write-root"]) {
return help();
}
let mut connect: Option<String> = None;
let mut headless = false;
let mut allow_grants = false;
let (mut read_roots, mut write_roots): (Vec<String>, Vec<String>) = (vec![], vec![]);
let mut it = args.iter();
while let Some(a) = it.next() {
@@ -230,6 +275,7 @@ fn mcp(args: &[String]) -> Result<(), String> {
match flag {
"--connect" => connect = Some(it.next().cloned().ok_or("--connect needs an address")?),
"--headless" => headless = true,
"--allow-plugin-grants" => allow_grants = true,
"--automation-read-root" | "--automation-write-root" => {
let dir = inline.or_else(|| it.next().cloned()).ok_or_else(|| format!("{flag} needs a folder"))?;
if flag == "--automation-read-root" { read_roots.push(dir) } else { write_roots.push(dir) }
@@ -240,6 +286,15 @@ fn mcp(args: &[String]) -> Result<(), String> {
if headless && connect.is_some() {
return Err("use either --connect or --headless".into());
}
if allow_grants && connect.is_some() {
return Err("--allow-plugin-grants applies to the headless server; in a running app a person approves each plug-in".into());
}
if allow_grants && !(read_roots.is_empty() && write_roots.is_empty()) {
return Err("--allow-plugin-grants can't be used with --automation-read-root or --automation-write-root: a server confined to folders has no plug-in store to record a grant in".into());
}
if safe_mode && connect.is_some() {
return Err("--safe-mode runs a headless session without plug-ins; a running app loads its own: start it with `vectorcraft --safe-mode --control <port>`".into());
}
let read: Vec<&Path> = read_roots.iter().map(Path::new).collect();
let write: Vec<&Path> = write_roots.iter().map(Path::new).collect();
let roots = AutomationRoots::new(&read, &write)?;
@@ -251,9 +306,9 @@ fn mcp(args: &[String]) -> Result<(), String> {
// Every thread of this process, not only the server's: nothing reaches past the roots.
file_access::confine_process(roots.clone());
eprintln!("vectorcraft-cli: files confined: {}", roots.describe());
Box::new(Headless::with_document().with_automation_roots(Some(roots)))
} else if headless {
Box::new(with_stores(Headless::with_document()))
Box::new(accepting_grants(Headless::with_document().with_automation_roots(Some(roots)), allow_grants))
} else if headless || safe_mode || allow_grants {
Box::new(accepting_grants(with_stores(Headless::with_document()), allow_grants))
} else if let Some(addr) = connect {
// Explicit address: fail loudly if the app isn't there.
Box::new(Remote::connect(&addr).map_err(|e| format!("cannot connect to {addr}: {e}"))?)
@@ -280,8 +335,20 @@ fn commands() -> Result<(), String> {
}
fn convert(args: &[String]) -> Result<(), String> {
let valued =
["--scale", "-s", "--ppi", "--artboard", "-a", "--range", "-r", "--decimals", "--ai-version", "--hidden-objects", "--transparent-images"];
let valued = [
"--scale",
"-s",
"--ppi",
"--artboard",
"-a",
"--range",
"-r",
"--decimals",
"--ai-version",
"--hidden-objects",
"--transparent-images",
"--legacy-name-encoding",
];
if help_requested(args, &valued) {
return help();
}
@@ -290,6 +357,9 @@ fn convert(args: &[String]) -> Result<(), String> {
(None::<f64>, None::<u64>, None::<String>, false, false, false, false);
let mut ppi = None::<f64>;
let mut decimals = None::<u64>;
// The encoding of a legacy `.ai`'s names that aren't UTF-8, passed on as `document.open`'s
// `legacyNameEncoding`; the engine checks it.
let mut legacy_names = None::<String>;
// Legacy `.ai` options, passed on as the export's own (`aiVersion`, `hiddenObjects`,
// `transparentImages`); the engine checks their values.
let mut legacy: Vec<(&str, String)> = vec![];
@@ -312,6 +382,9 @@ fn convert(args: &[String]) -> Result<(), String> {
"--replace-lossy" => replace_lossy = true,
"--editing-data" => editing_data = true,
"--preserve-editing" => preserve_editing = true,
"--legacy-name-encoding" => {
legacy_names = Some(it.next().cloned().ok_or("--legacy-name-encoding needs an encoding such as windows-949")?);
}
"--ai-version" => legacy.push(("aiVersion", it.next().cloned().ok_or("--ai-version needs 7 or pdf")?)),
"--hidden-objects" => legacy.push(("hiddenObjects", it.next().cloned().ok_or("--hidden-objects needs layer, omit or visible")?)),
"--transparent-images" => legacy.push(("transparentImages", it.next().cloned().ok_or("--transparent-images needs flatten or omit")?)),
@@ -324,8 +397,14 @@ fn convert(args: &[String]) -> Result<(), String> {
return Err("a .ait template holds every artboard: --artboard and --range don't apply".into());
}
let mut h = Headless::new();
let opened = if editing_data {
let params = json!({"path": input, "editingData": "always"});
let opened = if editing_data || legacy_names.is_some() {
let mut params = json!({"path": input});
if editing_data {
params["editingData"] = json!("always");
}
if let Some(e) = &legacy_names {
params["legacyNameEncoding"] = json!(e);
}
h.call("engine.execute", json!({"command": "document.open", "params": params})).map_err(|e| format!("open {input}: {e}"))?
} else {
h.call("app.open", json!({"path": input})).map_err(|e| format!("open {input}: {e}"))?
@@ -512,6 +591,7 @@ fn run(args: &[String]) -> Result<(), String> {
let mut stdin_read = false;
let mut scale = None::<f64>;
let mut ppi = None::<f64>;
let mut allow_grants = false;
let mut it = args.iter();
while let Some(a) = it.next() {
let mut val = |what: &str| it.next().cloned().ok_or_else(|| format!("{a} needs {what}"));
@@ -546,6 +626,7 @@ fn run(args: &[String]) -> Result<(), String> {
steps.push(Step::Export(val("a file")?));
params_for = None;
}
"--allow-plugin-grants" => allow_grants = true,
"--scale" | "-s" => {
let raw = val("a number")?;
scale = Some(raw.parse::<f64>().map_err(|_| format!("--scale {raw}: not a number"))?);
@@ -563,7 +644,7 @@ fn run(args: &[String]) -> Result<(), String> {
}
}
let mut h = with_stores(Headless::new());
let mut h = accepting_grants(with_stores(Headless::new()), allow_grants);
let mut out = std::io::stdout().lock();
// A reader that stopped early (a closed pipe) isn't an error, and the batch goes on: its later
// steps (an export…) still run, unprinted.
+104 -2
View File
@@ -64,6 +64,61 @@ fn median_ms(runs: usize, mut f: impl FnMut()) -> f64 {
v.get(v.len() / 2).copied().unwrap_or(0.0)
}
/// Exercise the application's native save/open commands, including previews, PDF output,
/// compression and API base64 conversion. Session setup and validation are outside timing.
/// Five measured runs follow one warmup; no filesystem or GPU window is involved.
fn native_io(doc: &Document) -> Result<(), String> {
for (label, compatible, preview) in [
("default options", None, false),
("PDF disabled", Some(false), false),
("preview+gzip", None, true),
("preview+gzip, PDF disabled", Some(false), true),
] {
let mut session = vectorcraft_engine::Session::new();
session.add_document(doc.clone(), None);
let mut params = json!({"format":"vectorcraft","modified":null,"preview":preview,"compress":preview});
if let Some(value) = compatible {
params["pdfCompatible"] = json!(value);
}
let (mut saves, mut opens) = (Vec::new(), Vec::new());
let (mut size, mut has_pdf, mut compressed) = (0, false, false);
for run in 0..6 {
let start = Instant::now();
let saved = session.execute("file.saveAs", &params).map_err(|e| e.to_string())?;
let save_ms = start.elapsed().as_secs_f64() * 1000.0;
let data = saved["dataBase64"].as_str().ok_or("native save returned no dataBase64")?;
let bytes = vectorcraft_format::base64_decode(data).ok_or("native save returned invalid base64")?;
size = bytes.len();
has_pdf = vectorcraft_format::pdf_content(&bytes).is_some();
if compatible == Some(false) && has_pdf {
return Err("native save ignored the explicit PDF opt-out".into());
}
compressed = vectorcraft_format::is_compressed(&bytes);
if compressed != preview || vectorcraft_format::preview(&bytes).is_some() != preview {
return Err("native save did not apply the requested preview/compression options".into());
}
let args = json!({"name":"perf.vectorcraft","dataBase64":data});
let mut opened = vectorcraft_engine::Session::new();
let start = Instant::now();
opened.execute("document.open", &args).map_err(|e| e.to_string())?;
let open_ms = start.elapsed().as_secs_f64() * 1000.0;
if opened.doc().map_err(|e| e.to_string())?.doc.artboards.len() != doc.artboards.len() {
return Err("native round trip changed the artboard count".into());
}
if run > 0 {
saves.push(save_ms);
opens.push(open_ms);
}
}
saves.sort_by(f64::total_cmp);
opens.sort_by(f64::total_cmp);
let save = saves.get(2).copied().ok_or("no save measurements")?;
let open = opens.get(2).copied().ok_or("no open measurements")?;
outln!(" native {label}: save {save:.2} ms, open {open:.2} ms, {size} bytes, PDF {has_pdf}, compressed {compressed}");
}
Ok(())
}
/// 1-minute load average (macOS / Linux), if available.
#[cfg(not(windows))]
fn load_average() -> Option<f64> {
@@ -393,19 +448,36 @@ fn deep(n: usize) -> Result<(), String> {
}
pub fn run(args: &[String]) -> Result<(), String> {
if crate::help_requested(args, &["--paths"]) {
if crate::help_requested(args, &["--paths", "--artboards"]) {
return crate::help();
}
let mut n = 50_000usize;
let mut want_deep = false;
let mut want_native = false;
let mut artboards = None::<usize>;
let mut it = args.iter();
while let Some(a) = it.next() {
match a.as_str() {
"--deep" => want_deep = true,
"--native-io" => want_native = true,
"--artboards" => {
artboards =
Some(it.next().and_then(|v| v.parse().ok()).filter(|n| (1..=4).contains(n)).ok_or("--artboards needs a number from 1 to 4")?)
}
"--paths" => n = it.next().and_then(|v| v.parse().ok()).ok_or("--paths needs a number")?,
other => return Err(format!("unknown perf option `{other}`")),
}
}
if want_native && n > 50_000 {
return Err("--native-io allows at most 50000 paths".into());
}
if want_native && want_deep {
return Err("--native-io and --deep are separate measurement modes".into());
}
if artboards.is_some() && !want_native {
return Err("--artboards requires --native-io".into());
}
let artboards = artboards.unwrap_or(1);
let cores = std::thread::available_parallelism().map_or(1, |c| c.get());
// The figure is the 1-minute load average, or on Windows the cores busy over one second.
#[cfg(not(windows))]
@@ -418,8 +490,20 @@ pub fn run(args: &[String]) -> Result<(), String> {
outln!("WARNING: the machine is busy; wall-clock timings below are not trustworthy.");
}
let t = Instant::now();
let doc = synthetic(n)?;
let mut doc = synthetic(n)?;
outln!(" (built in {:.0} ms)", t.elapsed().as_secs_f64() * 1000.0);
if want_native {
let first = doc.artboards.first().cloned().ok_or("synthetic document has no artboard")?;
// Overlapping artboards intentionally repeat the same paths on every PDF page.
for index in 1..artboards {
let mut page = first.clone();
page.id = first.id.checked_add(index as u32).ok_or("artboard id overflow")?;
page.name = format!("Perf {}", index + 1);
doc.artboards.push(page);
}
outln!(" application native I/O: {artboards} overlapping artboard(s), one warmup + five samples; medians; no disk I/O");
return native_io(&doc);
}
let mut rows: Vec<(&str, f64, f64)> = vec![];
let opts = RenderOptions::default();
@@ -513,6 +597,24 @@ pub fn run(args: &[String]) -> Result<(), String> {
mod tests {
use super::*;
#[test]
fn native_io_exercises_the_application_save_and_open_commands() {
native_io(&synthetic(3).unwrap()).unwrap();
}
#[test]
fn native_io_rejects_conflicting_modes_and_excessive_workloads() {
for (args, expected) in [
(vec!["--native-io", "--deep"], "separate measurement modes"),
(vec!["--native-io", "--paths", "50001"], "at most 50000"),
(vec!["--native-io", "--artboards", "5"], "1 to 4"),
(vec!["--artboards", "1"], "requires --native-io"),
(vec!["--artboards", "2"], "requires --native-io"),
] {
assert!(run(&args.into_iter().map(str::to_owned).collect::<Vec<_>>()).unwrap_err().contains(expected));
}
}
#[test]
fn busy_share_leaves_out_idle_time() {
// In one second four processors log 40,000,000 ticks of 100 ns of kernel and user time,
+88 -1
View File
@@ -19,6 +19,77 @@ fn empty_dir(dir: std::path::PathBuf) -> std::path::PathBuf {
dir
}
/// `run` and `mcp --headless` refuse `plugin.install` with this param unless the process was started
/// with `--allow-plugin-grants`.
fn approval_param_needs_the_start_up_flag(key: &str, value: Value) {
let module = vectorcraft_format::base64_encode(include_bytes!("../../../../crates/plugins/tests/fixtures/desaturate.wasm"));
let steps = tmp(&format!("{key}.json"));
std::fs::write(&steps, json!([{"command": "plugin.install", "params": {"dataBase64": module, key: value}}]).to_string()).unwrap();
let config = empty_dir(std::env::temp_dir().join(format!("vectorcraft-cli-test-{key}-{}", std::process::id())));
let run = |extra: &[&str]| {
Command::new(BIN).env("VECTORCRAFT_CONFIG_DIR", &config).args(["run", "--commands", steps.to_str().unwrap()]).args(extra).output().unwrap()
};
let out = run(&[]);
assert!(!out.status.success());
let shown = String::from_utf8_lossy(&out.stderr).into_owned() + &String::from_utf8_lossy(&out.stdout);
assert!(shown.contains("--allow-plugin-grants"), "{shown}");
let out = run(&["--allow-plugin-grants"]);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let mcp_config = empty_dir(std::env::temp_dir().join(format!("vectorcraft-cli-test-mcp-{key}-{}", std::process::id())));
let mcp_install = |extra: &[&str]| -> Value {
let mut child = Command::new(BIN)
.env("VECTORCRAFT_CONFIG_DIR", &mcp_config)
.args(["mcp", "--headless"])
.args(extra)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
{
let mut stdin = child.stdin.take().unwrap();
let params = json!({"dataBase64": module, key: value});
for m in [
json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}),
json!({"jsonrpc":"2.0","method":"notifications/initialized"}),
json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"run_command","arguments":{"command":"plugin.install","params":params}}}),
] {
writeln!(stdin, "{m}").unwrap();
}
}
let out = child.wait_with_output().unwrap();
assert!(out.status.success());
let replies: Vec<Value> = String::from_utf8(out.stdout).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
replies.into_iter().find(|r| r["id"] == 2).unwrap()["result"].take()
};
let refused = mcp_install(&[]);
assert_eq!(refused["isError"], true, "without the flag: {refused}");
assert!(refused["content"][0]["text"].as_str().unwrap().contains("--allow-plugin-grants"), "{refused}");
let accepted = mcp_install(&["--allow-plugin-grants"]);
assert_eq!(accepted["isError"], false, "with the flag: {accepted}");
}
/// `run` and `mcp --headless` refuse `plugin.install`'s `grant` and `allowHeavy` unless the process was
/// started with `--allow-plugin-grants`, which `mcp` won't take with `--connect` or the automation roots.
#[test]
fn plugin_grants_need_the_start_up_flag() {
approval_param_needs_the_start_up_flag("grant", json!(["doc.read"]));
approval_param_needs_the_start_up_flag("allowHeavy", json!(true));
let out = Command::new(BIN).args(["mcp", "--allow-plugin-grants", "--connect", "127.0.0.1:1"]).output().unwrap();
assert!(!out.status.success());
assert!(String::from_utf8_lossy(&out.stderr).contains("--allow-plugin-grants applies to the headless server"));
let root = std::env::temp_dir();
for flag in ["--automation-read-root", "--automation-write-root"] {
let out = Command::new(BIN).args(["mcp", "--allow-plugin-grants", flag, root.to_str().unwrap()]).stdin(Stdio::null()).output().unwrap();
assert!(!out.status.success(), "{flag}");
assert!(String::from_utf8_lossy(&out.stderr).contains("--allow-plugin-grants can't be used with"), "{flag}");
}
let usage = Command::new(BIN).arg("help").output().unwrap();
assert!(String::from_utf8_lossy(&usage.stdout).contains("--allow-plugin-grants lets plugin.install's grant and allowHeavy take effect"));
}
#[test]
fn commands_prints_catalogue() {
let out = Command::new(BIN).arg("commands").output().unwrap();
@@ -283,6 +354,22 @@ fn mcp_headless_over_stdio() {
assert_eq!(replies[3]["result"]["content"][0]["type"], "image");
}
/// `--safe-mode mcp` serves a headless session without plug-ins: it refuses `--connect`, and by
/// default it does not connect to an app listening on the default address, which loads its own
/// plug-ins.
#[test]
fn safe_mode_mcp_does_not_connect_to_a_running_app() {
let out = Command::new(BIN).args(["--safe-mode", "mcp", "--connect", "127.0.0.1:9"]).env("VECTORCRAFT_NO_PREFS", "1").output().unwrap();
let err = String::from_utf8_lossy(&out.stderr);
assert!(!out.status.success() && err.contains("--safe-mode runs a headless session"), "{err}");
// Something listening on the default address, as a running app does; a running app or another
// program already holding it serves as well.
let _app = std::net::TcpListener::bind(vectorcraft_mcp::DEFAULT_ADDR);
let out = Command::new(BIN).args(["--safe-mode", "mcp"]).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap();
let err = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success() && err.contains("MCP server on stdio (headless)"), "{err}");
}
/// `mcp --automation-read-root` / `--automation-write-root` (#832): the flags are checked before the
/// server starts, and the process then reads and writes only inside its roots.
#[test]
@@ -510,7 +597,7 @@ fn exercise_mcp_core(
assert!(r["result"]["completion"]["values"].as_array().is_some_and(|v| v.contains(&json!("svg"))), "{r}");
mcp_send(stdin, json!({"jsonrpc":"2.0","id":5,"method":"resources/list","params":{}}));
assert!(mcp_recv(lines, notes, 5)["result"]["resources"].as_array().is_some_and(|v| v.len() == 3));
assert!(mcp_recv(lines, notes, 5)["result"]["resources"].as_array().is_some_and(|v| v.len() == 4));
mcp_send(stdin, json!({"jsonrpc":"2.0","id":6,"method":"resources/templates/list","params":{}}));
assert!(mcp_recv(lines, notes, 6)["result"]["resourceTemplates"].as_array().is_some_and(|v| v.len() >= 4));
+1
View File
@@ -5,3 +5,4 @@
mod cli;
mod fileio;
mod mcp_e2e;
mod script;
+39
View File
@@ -0,0 +1,39 @@
use std::process::Command;
use serde_json::{Value, json};
const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli");
/// `run` with `script.run` after `file.new`, with `params`.
fn run_script(params: &Value) -> std::process::Output {
Command::new(BIN).args(["run", "--cmd", "file.new", "--cmd", "script.run", "--params", &params.to_string()]).output().unwrap()
}
/// `run` runs a script headless: the reply holds the report, with what the script logged and the
/// documents it changed.
#[test]
fn run_gives_the_report_of_a_script() {
let source = "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); vc.log(vc.args.n * 2);";
let out = run_script(&json!({"source": source, "name": "double.js", "args": {"n": 21}}));
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let lines: Vec<Value> = String::from_utf8_lossy(&out.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(lines.len(), 2, "{lines:?}");
assert_eq!(lines[1]["command"], "script.run");
let report = &lines[1]["result"];
assert_eq!(report["ok"], true, "{report}");
assert_eq!(report["name"], "double.js");
assert_eq!(report["log"], json!([42]), "{report}");
assert_eq!(report["changed"].as_array().map(Vec::len), Some(1), "{report}");
}
/// A script that throws fails its step with the script's message, and the steps before it ran.
#[test]
fn run_fails_the_step_of_a_script_that_throws() {
let out = run_script(&json!({"source": "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); throw new Error('no margin given');"}));
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("step 1 (script.run)") && stderr.contains("no margin given"), "{stderr}");
let printed: Vec<Value> = String::from_utf8_lossy(&out.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(printed.len(), 1, "only file.new printed: {printed:?}");
assert_eq!(printed[0]["command"], "file.new");
}
+2 -2
View File
@@ -14,7 +14,7 @@ name = "vectorcraft-web"
path = "src/main.rs"
[dependencies]
vectorcraft-engine = { workspace = true, features = ["bundled-fonts"] }
vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] }
vectorcraft-ui-egui = { workspace = true }
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
@@ -26,7 +26,7 @@ log = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
rfd = { workspace = true }
rfd = { workspace = true, features = ["file-handle-inner"] }
wasm-bindgen = "0.2"
serde_json = { workspace = true }
wasm-bindgen-futures = "0.4"
+31 -2
View File
@@ -9,6 +9,9 @@ use vectorcraft_engine::Session;
use vectorcraft_engine::cmd::clipboard::{FILE_HEAD, Flavour, PASTE_ORDER, file_flavour, is_address};
use vectorcraft_engine::cmd::fileio;
use vectorcraft_engine::cmd::recovery::{self, Hold, RecoveryStore};
use vectorcraft_engine::cmd::scripts::RUN_EXTS;
use vectorcraft_engine::script::MAX_SOURCE_BYTES;
use vectorcraft_ui_egui::dialogs::script_run::ScriptInbox;
use vectorcraft_ui_egui::graphics::GraphicsLoss;
use vectorcraft_ui_egui::i18n;
use vectorcraft_ui_egui::place::{DropTarget, PlaceArrival, PlaceInbox};
@@ -47,6 +50,7 @@ struct Host {
runner: eframe::WebRunner,
inbox: Inbox,
place_inbox: PlaceInbox,
script_inbox: ScriptInbox,
drag: DragPos,
pasted: Rc<RefCell<Pasted>>,
/// Pen and finger input read from the page's Pointer Events (`crate::pencil`).
@@ -75,6 +79,7 @@ pub fn start() {
runner: eframe::WebRunner::new(),
inbox: Arc::default(),
place_inbox: Arc::default(),
script_inbox: Arc::default(),
drag: DragPos::default(),
pasted: Rc::default(),
pointers: SharedPointers::default(),
@@ -120,7 +125,8 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
}
host.pasted.borrow_mut().ctx = Some(ctx.clone());
let stylus = host.pointers.borrow().stylus();
let services = services(host.inbox.clone(), host.place_inbox.clone(), ctx.clone(), host.locks.clone(), stylus);
let services =
services(host.inbox.clone(), host.place_inbox.clone(), host.script_inbox.clone(), ctx.clone(), host.locks.clone(), stylus);
let app = match taken.borrow_mut().take() {
Some(mut app) => {
// The old services asked the old context for frames.
@@ -425,12 +431,35 @@ impl eframe::App for WebShell {
}
}
fn services(inbox: Inbox, place_inbox: PlaceInbox, ctx: egui::Context, locks: Option<WebLocks>, stylus: StylusFeed) -> Services {
fn services(
inbox: Inbox,
place_inbox: PlaceInbox,
script_inbox: ScriptInbox,
ctx: egui::Context,
locks: Option<WebLocks>,
stylus: StylusFeed,
) -> Services {
let open_inbox = inbox.clone();
let picked = place_inbox.clone();
let place_ctx = ctx.clone();
let screen_color = eye_dropper(ctx.clone());
let (script_picked, script_ctx) = (script_inbox.clone(), ctx.clone());
Services {
// File › Scripts › Other Script…: the picked file goes to the warning before it runs.
script_async: Some(Box::new(move || {
let inbox = script_picked.clone();
let ctx = script_ctx.clone();
wasm_bindgen_futures::spawn_local(async move {
let filter = vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", "Scripts");
let Some(file) = rfd::AsyncFileDialog::new().add_filter(filter, RUN_EXTS).pick_file().await else {
return;
};
let bytes = if file.inner().size() > MAX_SOURCE_BYTES as f64 { None } else { Some(file.read().await) };
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((file.file_name(), bytes));
ctx.request_repaint();
});
})),
script_inbox: Some(script_inbox),
// File → Place…: the picked files go to the Place dialog.
place_async: Some(Box::new(move || {
let inbox = picked.clone();
+2 -2
View File
@@ -15,7 +15,7 @@ wgpu = ["eframe/wgpu", "dep:winsafe"]
accessibility = ["eframe/accesskit"]
[dependencies]
vectorcraft-engine = { workspace = true, features = ["bundled-fonts"] }
vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] }
vectorcraft-ui-egui = { workspace = true }
vectorcraft-text = { workspace = true }
# Shared across the Craft suite: decides who draws the window frame per desktop (compositor vs app)
@@ -67,7 +67,7 @@ vectorcraft-render = { workspace = true }
# with default features off). Pinned exactly: review the diff before bumping.
muda = { version = "=0.21.2", default-features = false }
objc2 = "0.6"
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSButton", "NSColor", "NSColorSampler", "NSColorSpace", "NSControl", "NSMenu", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSampler", "NSColorSpace", "NSControl", "NSMenu", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] }
# Files opened from Finder and the Dock (src/open_documents.rs), pasted bitmaps (src/clipboard.rs) and the control channel's App Nap activity (src/control_server.rs); both already come with winit, muda and rfd.
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSGeometry", "NSNotification", "NSOperation", "NSProcessInfo", "NSString", "NSURL"] }
block2 = "0.6"
+43 -4
View File
@@ -8,6 +8,7 @@ use super::windows_stylus;
use super::{App, VectorcraftApp, file_access, window};
#[cfg(target_os = "macos")]
use super::{mac_menu, mac_window, open_documents};
use vectorcraft_ui_egui::dialogs::safe_mode;
/// The parts of [`App::raw_input_hook`] that every window needs, for the OS windows of floating
/// panels: a click or Escape that closes the macOS menu bar's open menu, and the pen barrel
@@ -91,12 +92,21 @@ impl eframe::App for App {
}
fn on_exit(&mut self) {
file_access::unconfined(|| save_prefs(&self.app));
// A ready update installs once the process has exited. The macOS exit below skips
// dropping the app, so the helper is started here.
self.app.start_pending_update();
#[cfg(target_os = "macos")]
super::mac_cursor::release();
end_before_teardown(self.frames);
}
}
impl App {
fn logic_frame(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
#[cfg(target_os = "macos")]
if self.winit_window.as_ref().is_some_and(|w| !w.has_focus() || w.is_visible() == Some(false) || w.is_minimized() == Some(true)) {
super::mac_cursor::release();
}
self.frames = ctx.cumulative_frame_nr();
if let Some(why) = self.graphics_loss.take() {
// eframe can't give a window a new device: the user saves and starts again.
@@ -113,18 +123,35 @@ impl App {
vectorcraft_ui_egui::background::wait_all(&mut self.app);
return;
}
// An app that stays in Safe Mode leaves later launches to start their own app with plug-ins.
#[cfg(not(target_os = "macos"))]
if safe_mode::staying_on(&self.app) {
single_instance::resign();
}
// Files from the Finder and the Dock (macOS) or from later launches (#4892) wait while a file
// dialog is open: what asked for it runs again on its document when it answers.
if !self.app.file_dialog_open() {
// dialog is open: what asked for it runs again on its document when it answers. They also
// wait for the choice about a stopped plug-in, so they open after the plug-ins it loads, as
// do the command line's files held back for it. Files later launches handed over before the
// choice ended in Safe Mode open in a new app with plug-ins.
if !self.app.file_dialog_open() && !safe_mode::choosing(&self.app) {
let held = std::mem::take(&mut self.held_files);
#[cfg(target_os = "macos")]
let files = open_documents::take();
#[cfg(not(target_os = "macos"))]
let files = single_instance::take();
let files = single_instance::take_for_frame(safe_mode::staying_on(&self.app), single_instance::launch_with_plug_ins);
if !files.is_empty() {
bring_window_forward(ctx);
}
open_files(&mut self.app, held);
open_files(&mut self.app, files);
}
let (now, zoom) = (ctx.input(|i| i.time), ctx.zoom_factor());
if let Some(w) = &self.winit_window
&& window::monitors_due(self.monitors_listed, now, zoom)
{
self.app.services.dock_monitors = window::dock_monitors(w, zoom);
self.monitors_listed = Some((now, zoom));
}
self.app.tick(ctx);
if self.pending_maximize {
if let Some(w) = &self.winit_window {
@@ -144,13 +171,15 @@ impl App {
/// On macOS with accessibility, end the process once the app has saved what it keeps on quitting,
/// before eframe tears the window down (#661). AccessKit then gives the window's content view back
/// its own class, which AppKit's Touch Bar support was observing it under, and AppKit aborts the
/// app as it quits on Macs with a Touch Bar. Nothing after the window is needed on a normal quit.
/// app as it quits on Macs with a Touch Bar. On a normal quit, only the launch marker is needed
/// after the window, so it is ended here as `main` ends it after the window on other platforms.
/// Not while the window is still starting up (`frames` below [`gpu::STARTUP_FRAMES`]): a graphics
/// failure then starts the app again on another adapter (#651).
#[allow(unused_variables)]
fn end_before_teardown(frames: u64) {
#[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))]
if frames >= gpu::STARTUP_FRAMES {
safe_mode::end_launch();
log::info!("quitting");
log::logger().flush();
std::process::exit(0);
@@ -165,6 +194,16 @@ pub(crate) fn bring_window_forward(ctx: &egui::Context) {
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
}
/// Open the command line's `files` now, or, while the choice about a stopped plug-in is up
/// ([`safe_mode::choosing`]), return them to open once it is made, with the plug-ins it loads.
pub(crate) fn open_or_hold(app: &mut VectorcraftApp, files: Vec<String>) -> Vec<String> {
if safe_mode::choosing(app) {
return files;
}
open_files(app, files);
Vec::new()
}
/// Open files handed to the app (command line, macOS Finder and Dock, later launches) as documents. A file that
/// can't be opened is reported to the user and on stderr; the others still open.
pub(crate) fn open_files(app: &mut VectorcraftApp, files: Vec<String>) {
+1 -1
View File
@@ -310,7 +310,7 @@ fn pci_ids(device_id: &str) -> Option<(u32, u32)> {
let field = |key: &str| {
device_id.split(['\\', '&']).find_map(|part| {
let (name, hex) = part.split_at_checked(key.len())?;
if name.eq_ignore_ascii_case(key) { u32::from_str_radix(hex, 16).ok() } else { None }
if name.eq_ignore_ascii_case(key) && hex.bytes().all(|b| b.is_ascii_hexdigit()) { u32::from_str_radix(hex, 16).ok() } else { None }
})
};
Some((field("VEN_")?, field("DEV_")?))
+7
View File
@@ -820,3 +820,10 @@ fn crashes_are_forgotten_in_another_version_or_under_another_preference() {
assert_eq!(record.crashed.len(), CRASHED_LIMIT);
assert_eq!(record.crashed.last().map(|c| c.key.as_str()), Some("Dx12:10de:0013"));
}
/// `u32::from_str_radix` accepts a leading `+`; a device id with one is not a PCI id.
#[test]
fn pci_ids_reject_a_sign_in_the_hex_digits() {
assert_eq!(pci_ids("PCI\\VEN_+10DE&DEV_2204"), None);
assert_eq!(pci_ids("PCI\\VEN_10DE&DEV_+2204"), None);
}
+5 -2
View File
@@ -298,13 +298,16 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti
// up its Format menu before the sheet begins (#866); rfd shows the others.
PickRequest::Save(pick) => match mac_save_format::begin(window, &pick) {
// The dialog thread blocks here until the sheet answers.
Some(picked) => Box::pin(async move { picked.recv().unwrap_or_default() }),
None => {
Ok(mac_save_format::Begin::Shown(picked)) => Box::pin(async move { picked.recv().unwrap_or_default() }),
Ok(mac_save_format::Begin::DeferToRfd) => {
// Nothing is added to the sheet once rfd has begun it: an accessory view set then
// made recent macOS versions dismiss the sheet at once (#1800).
let picked = dialog.save_file();
Box::pin(async move { picked.await.iter().map(path).collect() })
}
// AppKit returned nil for the panel. rfd uses the same `+savePanel` and would panic
// on that nil; treat the pick as cancelled instead (#5980).
Err(()) => Box::pin(async move { Vec::new() }),
},
PickRequest::Folder => {
let picked = dialog.pick_folder();
+241
View File
@@ -0,0 +1,241 @@
//! AppKit delivery of the UI's existing cursor artwork, independent of canvas presentation.
#![forbid(unsafe_code)]
// Interim #2292: remove when pinned winit correctly handles macOS cursor image and hotspot sizing.
use egui::{Context, FullOutput, Plugin, ViewportId};
use objc2::{AllocAnyThread, MainThreadMarker, rc::Retained};
use objc2_app_kit::{NSApplication, NSBitmapImageRep, NSCursor, NSImage, NSWindow};
use objc2_foundation::{NSData, NSPoint, NSSize};
use std::cell::RefCell;
use vectorcraft_ui_egui::cursors::native_request::{self, Bitmap, Key, Request};
const CAPACITY: usize = 128;
fn build(bitmap: &Bitmap) -> Option<Retained<NSCursor>> {
let one = &bitmap.representations[0];
let size = NSSize::new(f64::from(one.size[0]), f64::from(one.size[1]));
let image = NSImage::initWithSize(NSImage::alloc(), size);
for bitmap in &bitmap.representations {
let pixels = image::RgbaImage::from_raw(u32::from(bitmap.size[0]), u32::from(bitmap.size[1]), bitmap.rgba.to_vec())?;
let mut png = std::io::Cursor::new(Vec::new());
pixels.write_to(&mut png, image::ImageFormat::Png).ok()?;
let rep = NSBitmapImageRep::imageRepWithData(&NSData::with_bytes(png.get_ref()))?;
rep.setSize(size);
image.addRepresentation(&rep);
}
Some(NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, NSPoint::new(f64::from(one.hotspot[0]), f64::from(one.hotspot[1]))))
}
/// The ownership protocol also runs against a headless backend in tests.
trait Backend {
type Window: Clone + PartialEq;
type Cursor: Clone + PartialEq;
fn window(&self) -> Option<Self::Window>;
fn enabled(&self, window: &Self::Window) -> bool;
fn suspend(&mut self, window: &Self::Window);
fn restore(&mut self, window: &Self::Window);
fn build(&mut self, request: &Request) -> Option<Self::Cursor>;
fn current(&self) -> Option<Self::Cursor>;
fn set(&mut self, cursor: &Self::Cursor);
}
struct State<B: Backend> {
backend: B,
candidate: Option<B::Window>,
cache: Vec<(Key, Option<B::Cursor>)>,
// Retain the active object independently of cache eviction.
active: Option<(Key, B::Window, B::Cursor)>,
}
impl<B: Backend> State<B> {
fn new(backend: B) -> Self {
Self { backend, candidate: None, cache: Vec::new(), active: None }
}
fn begin(&mut self) {
self.candidate = self.backend.window();
}
fn release(&mut self) {
self.candidate = None;
if let Some((_, window, _)) = self.active.take() {
self.backend.restore(&window);
}
}
fn finish(&mut self, request: Option<Request>) {
let window = self.candidate.take().filter(|w| self.backend.window().as_ref() == Some(w));
let (Some(request), Some(window)) = (request, window) else {
self.release();
return;
};
if let Some((key, owned, cursor)) = &self.active
&& *key == request.key
&& *owned == window
{
if self.backend.current().as_ref() != Some(cursor) {
self.backend.set(cursor);
}
return;
}
self.release();
// Never take another component's suspension (a sheet or native tracking session).
if !self.backend.enabled(&window) {
return;
}
let cursor = if let Some((_, cursor)) = self.cache.iter().find(|(key, _)| *key == request.key) {
cursor.clone()
} else {
let cursor = self.backend.build(&request);
if self.cache.len() >= CAPACITY {
self.cache.clear();
}
self.cache.push((request.key, cursor.clone()));
cursor
};
if let Some(cursor) = cursor {
self.backend.suspend(&window);
self.backend.set(&cursor);
self.active = Some((request.key, window, cursor));
}
}
}
#[derive(Default)]
struct AppKit {
root: std::sync::Weak<winit::window::Window>,
}
impl Backend for AppKit {
type Window = Retained<NSWindow>;
type Cursor = Retained<NSCursor>;
fn window(&self) -> Option<Self::Window> {
let mtm = MainThreadMarker::new()?;
// Bind the candidate to the host's actual root window without converting raw pointers.
// A floating native panel may be key while egui still has stale root focus input.
let root = self.root.upgrade()?;
if !root.has_focus() || root.is_visible() == Some(false) || root.is_minimized() == Some(true) {
return None;
}
NSApplication::sharedApplication(mtm).keyWindow().filter(|w| w.isVisible() && w.isKeyWindow())
}
fn enabled(&self, window: &Self::Window) -> bool {
window.areCursorRectsEnabled()
}
fn suspend(&mut self, window: &Self::Window) {
window.disableCursorRects();
}
fn restore(&mut self, window: &Self::Window) {
window.enableCursorRects();
window.resetCursorRects();
// egui-winit may skip an unchanged fallback icon. Rebuild its stored rectangle anyway.
if let Some(view) = window.contentView() {
window.invalidateCursorRectsForView(&view);
}
}
fn build(&mut self, request: &Request) -> Option<Self::Cursor> {
build(&request.bitmap)
}
fn current(&self) -> Option<Self::Cursor> {
Some(NSCursor::currentCursor())
}
fn set(&mut self, cursor: &Self::Cursor) {
cursor.set();
}
}
thread_local! { static STATE: RefCell<State<AppKit>> = RefCell::new(State::new(AppKit::default())); }
fn with_state(f: impl FnOnce(&mut State<AppKit>)) {
// All production AppKit access, including restoration, stays on the main thread.
if MainThreadMarker::new().is_some() {
STATE.with(|state| {
if let Ok(mut state) = state.try_borrow_mut() {
f(&mut state);
}
});
}
}
/// Also called synchronously when native menu tracking begins and before process teardown.
pub(crate) fn release() {
with_state(State::release);
}
struct EndedPass {
viewport: ViewportId,
discarded: bool,
request: Option<Request>,
}
struct Delivery {
begin: fn(),
finish: fn(Option<Request>),
release: fn(),
tracking: fn() -> bool,
ended: Vec<EndedPass>,
}
impl Plugin for Delivery {
fn debug_name(&self) -> &'static str {
"macOS canvas cursor"
}
fn on_begin_pass(&mut self, ui: &mut egui::Ui) {
native_request::clear(ui.ctx());
// Floating panels must not acquire or release the main canvas's window.
if ui.ctx().viewport_id() == ViewportId::ROOT {
(self.begin)();
}
}
fn on_end_pass(&mut self, ui: &mut egui::Ui) {
// egui restores the parent viewport before output_hook. Capture this pass here so
// a floating panel's output cannot consume or release its parent's cursor.
self.ended.push(EndedPass { viewport: ui.ctx().viewport_id(), discarded: ui.ctx().will_discard(), request: native_request::take(ui.ctx()) });
}
fn input_hook(&mut self, _: &Context, input: &mut egui::RawInput) {
if input.viewport_id == ViewportId::ROOT
&& (!input.focused || input.viewports.get(&ViewportId::ROOT).is_some_and(|v| v.minimized == Some(true)))
{
(self.release)();
}
}
fn output_hook(&mut self, ctx: &Context, output: &mut FullOutput) {
let Some(ended) = self.ended.pop() else { return };
if ended.viewport != ViewportId::ROOT {
return;
}
if ended.discarded
|| (output.platform_output.requested_discard() && output.platform_output.num_completed_passes < ctx.options(|o| o.max_passes.get()))
{
return;
}
let request = ended.request.filter(|r| {
r.viewport == ended.viewport
&& r.pass.checked_add(1) == Some(ctx.cumulative_pass_nr_for(ended.viewport))
&& ctx.input(|i| i.focused && i.pointer.hover_pos().is_some())
&& output.platform_output.cursor_icon == r.fallback
&& output.platform_output.cursor_image.is_none()
&& !(self.tracking)()
});
// This is BEFORE egui-winit's platform output. In pinned winit, fallback changes update
// the view's stored cursor and invalidate rectangles. Our owned suspension is intended
// to keep that update from replacing the native cursor; native timing needs hand testing.
(self.finish)(request);
}
fn on_exit(&mut self, _: &Context) {
(self.release)();
}
}
pub(crate) fn install(ctx: &Context, window: Option<&std::sync::Arc<winit::window::Window>>) {
with_state(|state| state.backend.root = window.map(std::sync::Arc::downgrade).unwrap_or_default());
ctx.add_plugin(Delivery {
begin: || with_state(State::begin),
finish: |request| with_state(|state| state.finish(request)),
release,
tracking: super::mac_menu::is_tracking,
ended: Vec::new(),
});
}
#[cfg(test)]
mod tests;
+236
View File
@@ -0,0 +1,236 @@
use super::*;
use egui::{CursorIcon, RawInput};
use std::cell::Cell;
#[derive(Default)]
struct Fake {
window: Option<u8>,
suspended: Vec<u8>,
current: Option<Key>,
sets: usize,
builds: usize,
restores: Vec<u8>,
fail: bool,
}
impl Backend for Fake {
type Window = u8;
type Cursor = Key;
fn window(&self) -> Option<u8> {
self.window
}
fn enabled(&self, w: &u8) -> bool {
!self.suspended.contains(w)
}
fn suspend(&mut self, w: &u8) {
self.suspended.push(*w);
}
fn restore(&mut self, w: &u8) {
self.suspended.retain(|v| v != w);
self.restores.push(*w);
self.current = None;
}
fn build(&mut self, r: &Request) -> Option<Key> {
self.builds += 1;
(!self.fail).then_some(r.key)
}
fn current(&self) -> Option<Key> {
self.current
}
fn set(&mut self, cursor: &Key) {
self.current = Some(*cursor);
self.sets += 1;
}
}
fn fake_state() -> State<Fake> {
State::new(Fake { window: Some(1), ..Default::default() })
}
fn raw(id: ViewportId, focused: bool) -> RawInput {
let mut input = RawInput { viewport_id: id, focused, events: vec![egui::Event::PointerMoved(egui::pos2(10.0, 10.0))], ..Default::default() };
input.viewports.entry(id).or_default();
input
}
fn publish(ctx: &Context, scale: f32) {
let mut session = vectorcraft_engine::Session::new();
let cursor = session.cursor(Default::default(), Default::default(), Default::default());
let fallback = native_request::request(ctx, cursor, CursorIcon::Default, true, scale);
ctx.set_cursor_icon(fallback);
}
fn request(scale: f32) -> Request {
let ctx = Context::default();
let _ = headless(&ctx, raw(ViewportId::ROOT, true), |ui| publish(ui.ctx(), scale));
native_request::take(&ctx).unwrap()
}
fn deliver(state: &mut State<Fake>, request: Option<Request>) {
state.begin();
state.finish(request);
}
#[test]
fn mac_cursor_ownership_deduplicates_reasserts_and_restores() {
let req = request(1.0);
let mut state = fake_state();
deliver(&mut state, Some(req.clone()));
assert_eq!(state.backend.suspended, [1]);
assert_eq!((state.backend.builds, state.backend.sets), (1, 1));
deliver(&mut state, Some(req.clone()));
assert_eq!(state.backend.sets, 1);
// Simulate a platform fallback replacing the cursor after finalization. The next pass
// reasserts; this proves the protocol, not AppKit timing or absence of transient flicker.
state.backend.current = None;
deliver(&mut state, Some(req.clone()));
assert_eq!(state.backend.sets, 2);
deliver(&mut state, None);
assert_eq!(state.backend.restores, [1]);
deliver(&mut state, Some(req.clone()));
state.backend.window = None;
deliver(&mut state, Some(req.clone()));
assert!(state.active.is_none());
state.backend.window = Some(1);
deliver(&mut state, Some(req.clone()));
state.begin();
state.backend.window = Some(2);
state.finish(Some(req));
assert!(state.active.is_none(), "never acquire a different key window mid-pass");
assert_eq!(state.backend.restores, [1, 1, 1]);
}
#[test]
fn mac_cursor_respects_other_suspensions_failures_and_cache_eviction() {
let mut state = fake_state();
state.backend.suspended.push(1);
deliver(&mut state, Some(request(1.0)));
assert_eq!(state.backend.builds, 0);
state.release();
assert_eq!(state.backend.suspended, [1]);
assert!(state.backend.restores.is_empty());
state.backend.suspended.clear();
state.backend.fail = true;
for _ in 0..2 {
deliver(&mut state, Some(request(1.0)));
}
assert_eq!(state.backend.builds, 1, "cache failed constructions");
state.backend.fail = false;
for i in 1..140 {
deliver(&mut state, Some(request(1.0 + i as f32 / 1000.0)));
}
assert!(state.cache.len() <= CAPACITY);
let active = state.active.unwrap();
state.cache.clear();
assert_eq!(state.active, Some(active));
state.release();
assert!(state.backend.suspended.is_empty());
}
thread_local! {
static FAKE: RefCell<State<Fake>> = RefCell::new(fake_state());
static TRACKING: Cell<bool> = const { Cell::new(false) };
}
fn install_fake(ctx: &Context) {
ctx.add_plugin(Delivery {
begin: || FAKE.with(|s| s.borrow_mut().begin()),
finish: |r| FAKE.with(|s| s.borrow_mut().finish(r)),
release: || FAKE.with(|s| s.borrow_mut().release()),
tracking: || TRACKING.with(Cell::get),
ended: Vec::new(),
});
}
#[test]
fn mac_cursor_plugin_consumes_passes_and_releases_for_menu_focus_and_overrides() {
FAKE.with(|s| *s.borrow_mut() = fake_state());
TRACKING.with(|t| t.set(false));
let ctx = Context::default();
install_fake(&ctx);
install_fake(&ctx);
let root = ViewportId::ROOT;
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
FAKE.with(|s| assert_eq!(s.borrow().backend.sets, 1, "one installed plugin consumes the request"));
let _ = headless(&ctx, raw(ViewportId::from_hash_of("floating-panel"), true), |_| {});
FAKE.with(|s| assert!(s.borrow().active.is_some()));
let _ = headless(&ctx, raw(root, true), |_| {});
FAKE.with(|s| assert!(s.borrow().active.is_none(), "empty pass hands back even an unchanged Default icon"));
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
let _ = headless(&ctx, raw(root, true), |ui| {
publish(ui.ctx(), 1.0);
ui.ctx().set_cursor_icon(CursorIcon::Text);
});
FAKE.with(|s| assert!(s.borrow().active.is_none(), "changed-icon handback"));
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
// The notification calls release without waiting for another UI pass.
TRACKING.with(|t| t.set(true));
FAKE.with(|s| s.borrow_mut().release());
FAKE.with(|s| assert!(s.borrow().active.is_none()));
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
FAKE.with(|s| assert!(s.borrow().active.is_none()));
TRACKING.with(|t| t.set(false));
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
let _ = headless(&ctx, raw(root, false), |_| {});
FAKE.with(|s| assert!(s.borrow().active.is_none()));
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
FAKE.with(|s| assert!(s.borrow().active.is_some()));
}
#[test]
fn mac_cursor_discarded_pass_does_not_commit_and_installation_does_not_repaint() {
FAKE.with(|s| *s.borrow_mut() = fake_state());
TRACKING.with(|t| t.set(false));
let ctx = Context::default();
install_fake(&ctx);
let mut passes = 0;
let _ = headless(&ctx, raw(ViewportId::ROOT, true), |ui| {
passes += 1;
if passes == 1 {
publish(ui.ctx(), 1.0);
ui.ctx().request_discard("cursor regression");
}
});
assert_eq!(passes, 2);
FAKE.with(|s| assert_eq!(s.borrow().backend.sets, 0));
let idle = || {
let mut input = raw(ViewportId::ROOT, true);
input.events.clear();
input.time = Some(ctx.input(|i| i.time) + 0.1);
input
};
for _ in 0..3 {
let _ = headless(&ctx, idle(), |ui| publish(ui.ctx(), 1.0));
}
let out = headless(&ctx, idle(), |ui| publish(ui.ctx(), 1.0));
assert!(out.viewport_output[&ViewportId::ROOT].repaint_delay > std::time::Duration::ZERO);
}
#[test]
fn mac_cursor_appkit_representations_have_pixel_sizes_and_point_hotspots() {
// Only construct and inspect image/cursor objects: no NSApplication, window or cursor.set().
for scale in [0.75, 1.0, 1.25, 1.5, 2.0] {
let request = request(scale);
let cursor = build(&request.bitmap).unwrap();
let image = cursor.image();
let one = &request.bitmap.representations[0];
let size = NSSize::new(f64::from(one.size[0]), f64::from(one.size[1]));
assert_eq!(image.size(), size);
assert_eq!(cursor.hotSpot(), NSPoint::new(f64::from(one.hotspot[0]), f64::from(one.hotspot[1])));
let reps = image.representations();
assert_eq!(reps.len(), 2);
let mut dimensions: Vec<_> = reps
.iter()
.map(|rep| {
assert_eq!(rep.size(), size);
(rep.pixelsWide(), rep.pixelsHigh())
})
.collect();
dimensions.sort_unstable();
assert_eq!(
dimensions,
[
(isize::try_from(one.size[0]).unwrap(), isize::try_from(one.size[1]).unwrap()),
(isize::try_from(one.size[0]).unwrap() * 2, isize::try_from(one.size[1]).unwrap() * 2)
]
);
}
}
fn headless(ctx: &egui::Context, input: egui::RawInput, draw: impl FnMut(&mut egui::Ui)) -> egui::FullOutput {
let mut output = ctx.run_ui(input, draw);
output.textures_delta.clear();
output
}
+9 -1
View File
@@ -31,6 +31,10 @@ use vectorcraft_ui_egui::native_menu::{self, Backend, Event, MenuBar, MenuRole,
// asynchronous menu presentation). Keep the native tracking state separate from egui popups.
static TRACKING: AtomicBool = AtomicBool::new(false);
pub(crate) fn is_tracking() -> bool {
TRACKING.load(Ordering::Relaxed)
}
fn observe_tracking(ctx: &egui::Context) {
static INSTALL: Once = Once::new();
INSTALL.call_once(|| {
@@ -41,13 +45,17 @@ fn observe_tracking(ctx: &egui::Context) {
let repaint = ctx.clone();
let block = RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
TRACKING.store(tracking, Ordering::Relaxed);
if tracking {
super::mac_cursor::release();
}
// Apply any deferred menu updates as soon as the tracking session ends.
if !tracking {
repaint.request_repaint();
}
});
// SAFETY: these are AppKit's notification names. The notification center retains
// the observer and block for the application's lifetime; callbacks update an atomic and request repaint.
// the observer and block for the application's lifetime; callbacks update tracking, restore
// owned cursor rectangles and request repaint.
#[allow(unsafe_code)]
unsafe {
NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock(Some(name), None, None, &block);
+58 -11
View File
@@ -21,7 +21,7 @@ use std::sync::mpsc::{Receiver, channel};
use block2::RcBlock;
use objc2::rc::{Retained, Weak};
use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel};
use objc2::{ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel};
use objc2_app_kit::{NSModalResponse, NSModalResponseOK, NSPopUpButton, NSSavePanel, NSTextField, NSView};
use objc2_foundation::{NSArray, NSObjectProtocol, NSPoint, NSRect, NSSize, NSString, NSURL};
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
@@ -108,21 +108,42 @@ fn set_allowed_types(panel: &NSSavePanel, filters: &[Filter], selected: usize) {
panel.setAllowedFileTypes(Some(&NSArray::from_retained_slice(&types)));
}
/// Show the save panel for `pick` as a sheet on `window`, with a Format menu, and answer on the
/// receiver with the path picked (none when canceled). `None` when the request has fewer than two
/// named file types, or `window` has no AppKit window; nothing is shown then.
pub fn begin(window: &winit::window::Window, pick: &FilePick) -> Option<Receiver<Vec<String>>> {
let mtm = MainThreadMarker::new()?;
/// How [`begin`] decided to show a save sheet.
#[derive(Debug)]
pub enum Begin {
/// The Format-menu sheet is open; wait on the receiver for the path (empty when canceled).
Shown(Receiver<Vec<String>>),
/// Fewer than two named file types: the caller should show an rfd panel instead.
DeferToRfd,
}
/// Show the save panel for `pick` as a sheet on `window`, with a Format menu.
///
/// `Ok(Begin::Shown(…))` when the sheet is open. `Ok(Begin::DeferToRfd)` when the request has
/// fewer than two named file types (or no AppKit window yet) so rfd should show the panel.
/// `Err(())` when AppKit returned no panel: the caller must not call rfd, whose `+savePanel`
/// panics on the same nil (#5980).
pub fn begin(window: &winit::window::Window, pick: &FilePick) -> Result<Begin, ()> {
let Some(mtm) = MainThreadMarker::new() else {
return Ok(Begin::DeferToRfd);
};
let filters = menu_formats(&pick.filters);
if filters.is_empty() {
return None;
return Ok(Begin::DeferToRfd);
}
let RawWindowHandle::AppKit(handle) = window.window_handle().ok()?.as_raw() else { return None };
let Some(RawWindowHandle::AppKit(handle)) = window.window_handle().ok().map(|h| h.as_raw()) else {
return Ok(Begin::DeferToRfd);
};
// SAFETY: the handle's view is the window's content view, which AppKit keeps alive while the
// window is open, and winit hands out the handle only while it is.
let view = unsafe { handle.ns_view.cast::<NSView>().as_ref() };
let parent = view.window()?;
let panel = NSSavePanel::savePanel(mtm);
let Some(parent) = view.window() else {
return Ok(Begin::DeferToRfd);
};
let Some(panel) = new_panel(mtm) else {
log::error!("macOS save panel unavailable: AppKit returned nil for NSSavePanel (#5980)");
return Err(());
};
let selected = initial_format(&pick.name, &filters);
set_allowed_types(&panel, &filters, selected);
if let Some(folder) = &pick.folder {
@@ -145,7 +166,23 @@ pub fn begin(window: &winit::window::Window, pick: &FilePick) -> Option<Receiver
// The panel and its accessory are set up; AppKit keeps the handler (and the panel it holds)
// until the sheet closes.
panel.beginSheetModalForWindow_completionHandler(&parent, &handler);
Some(rx)
Ok(Begin::Shown(rx))
}
/// An `NSSavePanel` without panicking when AppKit returns nil (#5980).
///
/// Prefers `-[NSSavePanel init]` (Apple's current Swift API) over `+[NSSavePanel savePanel]`,
/// which objc2 turns into a panic on nil. Falls back to the class method, still as `Option`.
fn new_panel(mtm: MainThreadMarker) -> Option<Retained<NSSavePanel>> {
// SAFETY: designated initializer for a bare save panel; returns nil when AppKit refuses.
let panel: Option<Retained<NSSavePanel>> = unsafe { msg_send![NSSavePanel::alloc(mtm), init] };
if panel.is_some() {
return panel;
}
// SAFETY: class method; returns an autoreleased panel or nil. Typed as Option so nil is not a
// panic (unlike `NSSavePanel::savePanel`).
let panel: Option<Retained<NSSavePanel>> = unsafe { msg_send![NSSavePanel::class(), savePanel] };
panel
}
/// The "Format:" label and menu of `filters`, `selected` chosen, that rename `panel`'s file.
@@ -234,6 +271,16 @@ mod tests {
assert_eq!(allowed_types(&filters(), 9), ["vectorcraft", "svg", "pdf"]);
}
/// A nil AppKit panel must be `None`, not a panic. `NSSavePanel::savePanel` used to panic here
/// (#5980); `new_panel` types the same message send as `Option`.
#[test]
fn a_null_save_panel_pointer_is_none_not_a_panic() {
let null: *mut NSSavePanel = std::ptr::null_mut();
// SAFETY: retaining a null object pointer is defined to yield None.
let panel: Option<Retained<NSSavePanel>> = unsafe { Retained::retain(null) };
assert!(panel.is_none());
}
/// Each entry of the Save As menu gives a name the save command reads as that entry's format.
#[test]
fn each_menu_entry_names_a_file_the_save_command_writes_in_that_format() {
+115 -39
View File
@@ -1,7 +1,10 @@
//! VectorCraft desktop app.
//!
//! Usage: `vectorcraft [--control <port> [--automation-read-root <dir>]... [--automation-write-root <dir>]...]
//! [--in-window-menus] [--new-instance] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`)
//! [--in-window-menus] [--new-instance] [--safe-mode] [--] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`)
//!
//! Any other argument starting with '-' (not `-` alone) is an error; after `--`, every argument is
//! a file.
//!
//! Files given while VectorCraft already runs open in that window, unless `--new-instance` is given
//! (Windows and Linux; `single_instance`).
@@ -33,6 +36,8 @@ mod logging;
#[cfg(all(target_os = "macos", feature = "wgpu"))]
mod mac_color_space;
#[cfg(target_os = "macos")]
mod mac_cursor;
#[cfg(target_os = "macos")]
mod mac_fonts;
#[cfg(target_os = "macos")]
mod mac_menu;
@@ -65,6 +70,7 @@ mod xwayland;
use vectorcraft_engine::Session;
use vectorcraft_engine::cmd::fileio;
use vectorcraft_engine::file_access::{self, AutomationRoots};
use vectorcraft_ui_egui::dialogs::safe_mode;
use vectorcraft_ui_egui::graphics::GraphicsLoss;
use vectorcraft_ui_egui::picks::PickRequest;
use vectorcraft_ui_egui::{ClipboardProbeFactory, FilePick, Services, VectorcraftApp};
@@ -77,7 +83,7 @@ mod titlebar;
#[cfg(all(test, feature = "wgpu"))]
use app::bring_window_forward;
use app::native_input_hook;
use app::open_files;
use app::open_or_hold;
use host_services::services;
#[cfg(all(test, feature = "wgpu"))]
use prefs::{KEEP_UI_PREFS, decode_saved_prefs, keep_prefs_copy, prefs_bytes};
@@ -92,7 +98,9 @@ use titlebar::custom_titlebar_from;
use titlebar::opted_into_system_title_bar;
#[cfg(windows)]
use titlebar::set_taskbar_icon;
use titlebar::{custom_titlebar, native_options};
#[cfg(all(test, feature = "wgpu"))]
use titlebar::{app_draws_frame, opted_into_app_title_bar, start_frame, system_title_bar_applies};
use titlebar::{custom_titlebar, native_options, titlebar_from_env};
struct App {
app: VectorcraftApp,
@@ -111,6 +119,10 @@ struct App {
pending_maximize: bool,
/// Frames left to retry [`window::apply_pending_maximize`].
maximize_tries: u8,
/// The command line's files, held back until the choice about a stopped plug-in is made.
held_files: Vec<String>,
/// The time and UI zoom of the last monitor list ([`window::monitors_due`]).
monitors_listed: Option<(f64, f32)>,
}
/// `vectorcraft --help`. Headless work (convert, run, MCP) is `vectorcraft-cli`'s.
@@ -130,13 +142,89 @@ Options:
(or VECTORCRAFT_IN_WINDOW_MENUS=1)
--new-instance Open the files in a new window even when VectorCraft
already runs (Windows and Linux)
--safe-mode Start without plug-ins: none loads or runs until
VectorCraft starts normally (Help › Safe Mode); the
files open in a new window, as with --new-instance
--version Print the version and exit
-h, --help Print this help and exit
-- Treat every argument after it as a file
Any other argument starting with '-' is an error.
Without a window (converting, scripting, the MCP server), use vectorcraft-cli:
vectorcraft-cli --help
";
/// The command line's options other than the automation roots and the control port.
struct CommandLine {
files: Vec<String>,
in_window_menus: bool,
new_instance: bool,
/// `--safe-mode`: no plug-in loads or runs in this launch.
safe_mode: bool,
}
/// Reads the arguments after the program name. The automation roots and the control port go into
/// `roots_args` and `control`. `Err` is the exit code when the process ends here: `--version` and
/// `--help` print and succeed; a bad automation option or an unknown option prints an error and fails.
fn read_command_line(
mut args: impl Iterator<Item = String>,
control: &mut automation_args::ControlArg,
roots_args: &mut automation_args::AutomationArgs,
) -> Result<CommandLine, std::process::ExitCode> {
let mut files = Vec::new();
let mut in_window_menus = std::env::var_os("VECTORCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0");
let mut new_instance = false;
let mut safe_mode = false;
let mut unknown = None;
while let Some(a) = args.next() {
// After `--`, every argument is a file, even one whose name starts with '-'.
if a == "--" {
files.extend(args.by_ref());
break;
}
match roots_args.consume(&a, &mut args).and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) }) {
Ok(true) => continue,
Ok(false) => {}
Err(e) => {
eprintln!("vectorcraft: {e}");
return Err(std::process::ExitCode::FAILURE);
}
}
match a.as_str() {
"--in-window-menus" => in_window_menus = true,
"--new-instance" => new_instance = true,
"--safe-mode" => safe_mode = true,
"--version" => {
println!("vectorcraft {}", env!("CARGO_PKG_VERSION"));
return Err(std::process::ExitCode::SUCCESS);
}
// Before anything starts, like `--version`: from a terminal or an agent's shell the app
// used to open (or hang without a display) instead (#2110).
"--help" | "-h" => {
// Not `print!`, which panics when standard output is closed (`| head -0`):
// there is nothing left to tell then.
let _ = std::io::Write::write_all(&mut std::io::stdout(), USAGE.as_bytes());
return Err(std::process::ExitCode::SUCCESS);
}
// The process serial number older macOS versions pass to an app the Finder starts.
#[cfg(target_os = "macos")]
_ if a.starts_with("-psn_") => {}
// An option this version doesn't know (a typo such as `--safe-mod`) is an error, not a
// file to open. Reported after the loop, so a later `--help` or `--version` still wins.
_ if a.starts_with('-') && a != "-" => {
unknown.get_or_insert(a);
}
_ => files.push(a),
}
}
if let Some(a) = unknown {
eprintln!("vectorcraft: unknown option {a}; see vectorcraft --help, or put -- before a file whose name starts with '-'");
return Err(std::process::ExitCode::FAILURE);
}
Ok(CommandLine { files, in_window_menus, new_instance, safe_mode })
}
fn main() -> std::process::ExitCode {
// Windows: the update helper is a copy of this program started with `--finish-update`.
#[cfg(windows)]
@@ -152,37 +240,11 @@ fn main() -> std::process::ExitCode {
let root_env = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty()).map(std::path::PathBuf::from);
let mut roots_args =
automation_args::AutomationArgs::new(root_env("VECTORCRAFT_AUTOMATION_READ_ROOT"), root_env("VECTORCRAFT_AUTOMATION_WRITE_ROOT"));
let mut files = Vec::new();
let mut in_window_menus = std::env::var_os("VECTORCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0");
let mut new_instance = false;
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
match roots_args.consume(&a, &mut args).and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) }) {
Ok(true) => continue,
Ok(false) => {}
Err(e) => {
eprintln!("vectorcraft: {e}");
return std::process::ExitCode::FAILURE;
}
}
match a.as_str() {
"--in-window-menus" => in_window_menus = true,
"--new-instance" => new_instance = true,
"--version" => {
println!("vectorcraft {}", env!("CARGO_PKG_VERSION"));
return std::process::ExitCode::SUCCESS;
}
// Before anything starts, like `--version`: from a terminal or an agent's shell the app
// used to open (or hang without a display) instead (#2110).
"--help" | "-h" => {
// Not `print!`, which panics when standard output is closed (`| head -0`):
// there is nothing left to tell then.
let _ = std::io::Write::write_all(&mut std::io::stdout(), USAGE.as_bytes());
return std::process::ExitCode::SUCCESS;
}
_ => files.push(a),
}
}
let CommandLine { files, in_window_menus, new_instance, safe_mode: safe_mode_flag } =
match read_command_line(std::env::args().skip(1), &mut control, &mut roots_args) {
Ok(command_line) => command_line,
Err(code) => return code,
};
let automation_args::AutomationArgs { read_roots, write_roots, .. } = roots_args;
// After the arguments: `--control` and `--version` win over a bad environment value.
let control_port = match control.port {
@@ -200,10 +262,10 @@ fn main() -> std::process::ExitCode {
// Files opened from the file manager while VectorCraft runs open in its window (#4892). Before
// the log file is attached: a launch that hands its files over leaves the running app's log be.
#[cfg(not(target_os = "macos"))]
let instance = match single_instance::start(control_port.is_some(), new_instance, &files) {
match single_instance::start(control_port.is_some(), new_instance, safe_mode_flag, &files) {
single_instance::Start::Forwarded => return std::process::ExitCode::SUCCESS,
single_instance::Start::Running(primary) => primary,
};
single_instance::Start::Running(primary) => single_instance::hold(primary),
}
#[cfg(target_os = "macos")]
let _ = new_instance;
vectorcraft_ui_egui::i18n::detect_system_lang_in_background();
@@ -394,13 +456,20 @@ fn main() -> std::process::ExitCode {
let mut session = Session::new();
// The profiles loaded before come back before the preferences name any of them.
prefs_dir::attach_profile_store(&mut session);
// Before any plug-in loads: this launch's marker in the Launch folder next to the
// preferences (none for runs without preferences), and Safe Mode.
let launch_dir = prefs_path().filter(|_| prefs_enabled()).and_then(|p| Some(p.parent()?.join("Launch")));
let stopped = safe_mode::begin_launch(launch_dir.as_deref(), safe_mode_flag);
prefs_dir::attach_plugin_store(&mut session);
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
app.set_startup_update_check(true);
load_prefs(&mut app, saved);
safe_mode::after_start(&mut app, stopped);
// The saved PDF presets live in their own folder (also read by vectorcraft-cli),
// which takes over from the copy the preferences file used to hold.
prefs_dir::attach_pdf_preset_store(&mut app.session);
// The custom dictionary's words, kept in their own file next to the preferences.
prefs_dir::attach_custom_dictionary(&mut app.session);
// Fit the window to its monitor, or put it back where it was (still hidden).
let winit_window = cc.winit_window().cloned();
if let Some(w) = &winit_window {
@@ -464,7 +533,9 @@ fn main() -> std::process::ExitCode {
let (loss, ctx) = (graphics_loss.clone(), cc.egui_ctx.clone());
rs.device.set_device_lost_callback(move |reason, msg| loss.report(&ctx, format!("{reason:?}: {msg}")));
}
app.titlebar_from_env = titlebar_from_env();
app.custom_titlebar = custom_titlebar;
app.desktop_frame = !custom_titlebar;
if let Some(port) = control_port {
let rx = control_server::start(port, cc.egui_ctx.clone());
app = app.with_control(rx).with_automation_roots(roots.clone());
@@ -482,6 +553,7 @@ fn main() -> std::process::ExitCode {
if !in_window_menus {
app.services.native_menu = mac_menu::install(&cc.egui_ctx, &app);
}
mac_cursor::install(&cc.egui_ctx, winit_window.as_ref());
}
#[cfg(not(target_os = "macos"))]
{
@@ -489,7 +561,7 @@ fn main() -> std::process::ExitCode {
single_instance::set_ui(&cc.egui_ctx);
}
app.services.native_input_hook = native_input_hook(&app);
file_access::unconfined(|| open_files(&mut app, files));
let held_files = file_access::unconfined(|| open_or_hold(&mut app, files));
// The first frame is due from now (`gpu::watch_first_frame`).
#[cfg(feature = "wgpu")]
created.ready();
@@ -505,6 +577,8 @@ fn main() -> std::process::ExitCode {
winit_window,
pending_maximize,
maximize_tries: 8,
held_files,
monitors_listed: None,
}))
}),
)
@@ -512,7 +586,9 @@ fn main() -> std::process::ExitCode {
// The window is gone: later launches start their own app, including the one a graphics
// failure starts again below.
#[cfg(not(target_os = "macos"))]
drop(instance);
single_instance::resign();
// The process ends normally from here: this launch didn't stop while a plug-in was loading.
safe_mode::end_launch();
#[cfg(feature = "wgpu")]
let outcome = gpu::finish(outcome, &startup);
#[cfg(not(feature = "wgpu"))]
+26
View File
@@ -168,6 +168,11 @@ fn same_lasting(a: &serde_json::Value, b: &serde_json::Value) -> bool {
}
}
/// Fields that a read fills in from other fields when the file lacks them
/// (`vectorcraft_ui_egui::layout_migration`): `help_bar` follows `status_bar`. A save writes them
/// whenever the file lacks them, so the next read does not fill them in again from a changed field.
const DERIVED: &[&str] = &["help_bar"];
/// `on_disk` with what changed from `base` to `mine` put over it: each top-level field of the UI
/// state, and each engine preference (`engine_prefs`) on its own, so two windows that change
/// different settings keep both. A field both changed takes this window's value (it saves last).
@@ -219,6 +224,13 @@ fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: se
}
}
}
for key in DERIVED {
if !out.contains_key(*key)
&& let Some(v) = mine.get(*key)
{
out.insert((*key).to_string(), v.clone());
}
}
if use_mine {
match mine.get("action_set") {
Some(v) => {
@@ -383,6 +395,20 @@ mod tests {
assert!(!same_lasting(&base, &mine));
}
/// A file from before the Help Bar setting: the read shows the Help Bar with the status bar.
/// After the status bar is hidden and the Help Bar left showing, the save writes `help_bar`,
/// so the next read does not hide it with the status bar. A value on disk is kept.
#[test]
fn a_help_bar_setting_the_file_lacks_is_saved() {
let base = json!({"status_bar": true, "help_bar": true});
let mine = json!({"status_bar": false, "help_bar": true});
let on_disk = json!({"status_bar": true});
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"status_bar": false, "help_bar": true}));
// Another window saved its own Help Bar setting: it stays.
let on_disk = json!({"status_bar": true, "help_bar": false});
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"status_bar": false, "help_bar": false}));
}
/// One window deleted the first Actions set and saved; this one made the second set current.
/// The saved index follows that set to its place in the merged list.
#[test]
+8
View File
@@ -57,6 +57,14 @@ pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) {
}
}
/// Keep the custom dictionary (Edit › Spelling › Add, Edit Custom Dictionary) in the
/// `Custom Dictionary.txt` file next to the settings, one word per line, and take in its words.
pub fn attach_custom_dictionary(session: &mut vectorcraft_engine::Session) {
if let Some(path) = store_dir("Custom Dictionary.txt") {
session.attach_custom_dictionary(path);
}
}
#[cfg(test)]
mod tests {
use super::*;
+144 -5
View File
@@ -12,8 +12,12 @@
//! as its own app, which replaces a stale file. Nothing received is ever run.
//!
//! Runs that start many apps side by side (`--control`, `VECTORCRAFT_NO_PREFS`) neither forward
//! nor listen, and `--new-instance` opens a launch's files in an app of its own. macOS hands files
//! opened from Finder to the running app itself (`open_documents`), so this is off there.
//! nor listen, and neither does a `--safe-mode` launch, which opens its files in an app of its own
//! and leaves later launches to start theirs with plug-ins. `--new-instance` opens a launch's files
//! in an app of its own. An app that stays in Safe Mode after the choice about a stopped plug-in
//! stops listening ([`resign`]), and files later launches handed it before then open in a new app
//! with plug-ins ([`take_for_frame`]). macOS hands files opened from Finder to the running app itself
//! (`open_documents`), so this is off there.
use std::fs::{self, OpenOptions};
use std::hash::{BuildHasher as _, RandomState};
@@ -43,6 +47,8 @@ const CLIENT_TIMEOUT: Duration = Duration::from_secs(5);
/// Paths handed over by later launches that the UI hasn't opened yet.
static PENDING: Mutex<Vec<String>> = Mutex::new(Vec::new());
/// This app while it is the one later launches hand their files to ([`hold`]).
static HELD: Mutex<Option<Primary>> = Mutex::new(None);
/// The UI to wake when files arrive (unset until the window exists; the first frame opens them).
static UI: OnceLock<egui::Context> = OnceLock::new();
@@ -56,23 +62,46 @@ pub enum Start {
/// Hand `files` to the app already running, or become the app later launches hand theirs to.
/// `automation`: started with `--control`.
pub fn start(automation: bool, new_instance: bool, files: &[String]) -> Start {
pub fn start(automation: bool, new_instance: bool, safe_mode: bool, files: &[String]) -> Start {
if automation || !prefs_enabled() {
return Start::Running(None);
}
let Some(path) = prefs_path().and_then(|p| Some(p.parent()?.join(FILE_NAME))) else { return Start::Running(None) };
start_at(&path, new_instance, safe_mode, files)
}
/// [`start`] with the endpoint file `path`. A launch with `--new-instance` or `--safe-mode` keeps
/// its files and runs as its own app: a running app would open them with its plug-ins loaded. A
/// `--safe-mode` launch never becomes the app later launches hand their files to, which would open
/// them without plug-ins.
fn start_at(path: &Path, new_instance: bool, safe_mode: bool, files: &[String]) -> Start {
if safe_mode {
return Start::Running(None);
}
// With nothing to hand over, the same exchange only asks whether an app is running.
let send: &[String] = if new_instance { &[] } else { files };
match forward(&path, send) {
match forward(path, send) {
Ok(()) if send.is_empty() => Start::Running(None),
Ok(()) => Start::Forwarded,
Err(e) => {
log::debug!("no running VectorCraft to hand files to ({e})");
Start::Running(listen(&path, queue))
Start::Running(listen(path, queue))
}
}
}
/// Keep `primary` ([`start`]'s) until [`resign`].
pub fn hold(primary: Option<Primary>) {
*HELD.lock().unwrap_or_else(PoisonError::into_inner) = primary;
}
/// Later launches start their own app from now on: the endpoint file goes. The app calls it when
/// its window is gone, and when it stays in Safe Mode after the choice about a stopped plug-in.
pub fn resign() {
let primary = HELD.lock().unwrap_or_else(PoisonError::into_inner).take();
drop(primary);
}
/// Wake `ctx` when files arrive from later launches.
pub fn set_ui(ctx: &egui::Context) {
// Set once; a second call would hand over the same context.
@@ -84,6 +113,43 @@ pub fn take() -> Vec<String> {
std::mem::take(&mut *PENDING.lock().unwrap_or_else(PoisonError::into_inner))
}
/// The paths later launches handed over since the last call, to open in this app. An app that
/// stays in Safe Mode (`safe_mode`) resigns and hands them to a new app with plug-ins (`launch`,
/// [`launch_with_plug_ins`] in the app) instead: they arrived while it was the primary, before the
/// choice about a stopped plug-in ended in Safe Mode, or just before it resigned. When `launch`
/// fails (logged), they open here.
pub fn take_for_frame(safe_mode: bool, launch: impl FnOnce(&[String]) -> io::Result<()>) -> Vec<String> {
let files = take();
if !safe_mode {
return files;
}
// First, so the new app becomes the primary instead of handing the files back.
resign();
if files.is_empty() {
return files;
}
match launch(&files) {
Ok(()) => Vec::new(),
Err(e) => {
log::warn!("couldn't start VectorCraft with plug-ins for the files another launch opened: {e}");
files
}
}
}
/// Start this program again, with plug-ins, on `files`.
pub fn launch_with_plug_ins(files: &[String]) -> io::Result<()> {
app_with_plug_ins(&std::env::current_exe()?, files).spawn().map(drop)
}
/// The command [`launch_with_plug_ins`] runs: `exe -- files…`, so a file whose name starts with '-'
/// stays a file.
fn app_with_plug_ins(exe: &Path, files: &[String]) -> std::process::Command {
let mut command = std::process::Command::new(exe);
command.arg("--").args(files);
command
}
fn queue(files: Vec<String>) {
PENDING.lock().unwrap_or_else(PoisonError::into_inner).extend(files);
if let Some(ctx) = UI.get() {
@@ -263,6 +329,13 @@ mod tests {
use super::*;
/// Held by the tests that use the process-wide [`HELD`] and [`PENDING`], one at a time.
static GLOBALS: Mutex<()> = Mutex::new(());
fn globals() -> std::sync::MutexGuard<'static, ()> {
GLOBALS.lock().unwrap_or_else(PoisonError::into_inner)
}
struct TestDir(tempfile::TempDir);
impl std::ops::Deref for TestDir {
@@ -313,6 +386,72 @@ mod tests {
assert!(!path.exists(), "the endpoint file goes with the app");
}
#[test]
fn a_new_instance_or_safe_mode_launch_keeps_its_files() {
let (path, _dir, file) = folder("own");
let (primary, rx) = primary(&path);
for (new_instance, safe_mode) in [(true, false), (false, true)] {
let start = start_at(&path, new_instance, safe_mode, std::slice::from_ref(&file));
assert!(matches!(start, Start::Running(None)), "runs as its own app (new instance {new_instance}, Safe Mode {safe_mode})");
}
assert!(matches!(start_at(&path, false, false, std::slice::from_ref(&file)), Start::Forwarded));
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), std::slice::from_ref(&file));
assert!(rx.try_recv().is_err(), "only the plain launch handed its file over");
drop(primary);
}
#[test]
fn a_safe_mode_launch_leaves_later_launches_their_own_app() {
let _globals = globals();
let (path, _dir, file) = folder("safe-mode-alone");
// With no app running, a Safe Mode launch runs without listening.
assert!(matches!(start_at(&path, false, true, std::slice::from_ref(&file)), Start::Running(None)));
assert!(!path.exists(), "a Safe Mode launch records no endpoint");
// A plain launch after it starts its own app and takes later launches' files.
let Start::Running(Some(primary)) = start_at(&path, false, false, std::slice::from_ref(&file)) else {
panic!("the plain launch runs and listens")
};
assert!(path.exists());
// An app that stays in Safe Mode after the choice gives that up.
hold(Some(primary));
resign();
assert!(!path.exists(), "the endpoint file goes with resign");
}
#[test]
fn files_handed_to_an_app_staying_in_safe_mode_go_to_a_new_app_with_plug_ins() {
let _globals = globals();
// Nothing left over from a test that failed.
resign();
drop(take());
let (path, _dir, file) = folder("safe-mode-later");
let Start::Running(Some(primary)) = start_at(&path, false, false, &[]) else { panic!("the first launch listens") };
hold(Some(primary));
// A later launch handed its file over while the choice about a stopped plug-in was up.
queue(vec![file.clone()]);
let mut launched = Vec::new();
let here = take_for_frame(true, |files| {
launched = files.to_vec();
Ok(())
});
assert!(here.is_empty(), "nothing opens in the Safe Mode app");
assert_eq!(launched, std::slice::from_ref(&file), "a new app with plug-ins opens it");
assert!(!path.exists(), "the app resigned before starting the new one");
// When the new app can't start, the file opens here rather than being lost.
queue(vec![file.clone()]);
assert_eq!(take_for_frame(true, |_| Err(io::Error::other("no program"))), std::slice::from_ref(&file));
// An app with plug-ins opens what it is handed.
queue(vec![file.clone()]);
assert_eq!(take_for_frame(false, |_| panic!("no new app")), [file]);
}
#[test]
fn the_new_app_takes_every_name_as_a_file() {
let command = app_with_plug_ins(Path::new("vectorcraft"), &["-a.svg".to_owned(), "b.svg".to_owned()]);
let args: Vec<_> = command.get_args().collect();
assert_eq!(args, ["--", "-a.svg", "b.svg"]);
}
#[test]
fn a_wrong_token_garbage_and_oversized_messages_are_refused() {
let (path, _dir, file) = folder("refused");
+155
View File
@@ -36,6 +36,33 @@ fn shortcut_overrides_from_an_earlier_version_load() {
assert!(km.problems().iter().any(|p| format!("{p:?}") == r#"UnknownCommand { key: "test.unknown" }"#), "reported");
}
/// The command line's files wait for the choice about a stopped plug-in, so they open with the
/// plug-ins it loads; with no choice up they open at once.
#[test]
fn command_line_files_wait_for_the_choice_about_a_stopped_plug_in() {
let temp = tempfile::Builder::new().prefix("vectorcraft-held-files-").tempdir().unwrap();
let file = temp.path().join("a.svg");
std::fs::write(&file, r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>"#).unwrap();
let files = vec![file.to_string_lossy().into_owned()];
// The files the app reads to open them.
let read = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
let reads = read.clone();
let services = vectorcraft_ui_egui::Services {
read: Some(Box::new(move |p: &str| {
reads.borrow_mut().push(p.to_owned());
std::fs::read(p).map_err(|e| e.to_string())
})),
..Default::default()
};
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), services);
app.ui.stopped_plugin = Some(serde_json::json!({"id": "test.held", "name": "Held"}));
assert_eq!(open_or_hold(&mut app, files.clone()), files, "held while the choice is up");
assert!(read.borrow().is_empty(), "nothing opened before the choice");
app.ui.stopped_plugin = None;
assert!(open_or_hold(&mut app, files.clone()).is_empty());
assert_eq!(*read.borrow(), files, "opened with no choice up");
}
#[test]
fn opening_files_unminimizes_and_focuses_the_window() {
let ctx = egui::Context::default();
@@ -164,6 +191,134 @@ fn the_system_title_bar_preference_keeps_the_window_decorations() {
assert_eq!(super::native_options(true).viewport.decorations, Some(false));
}
/// Preferences › User Interface › VectorCraft Title Bar on Every Desktop gives the app frame where
/// the probe chose the desktop's (KDE, X11, a window opened through XWayland); without it the probe
/// decides, and `VECTORCRAFT_TITLEBAR` set to `app`, `system` or `desktop` takes precedence over
/// both.
#[test]
fn the_app_title_bar_preference_gives_the_app_frame_on_desktop_frames() {
assert!(!super::opted_into_app_title_bar(None), "no preferences: the default");
let off = ui_state_with_prefs(serde_json::json!({"appTitleBar": false}));
assert!(!super::opted_into_app_title_bar(Some(&off)));
let on = ui_state_with_prefs(serde_json::json!({"appTitleBar": true}));
assert!(super::opted_into_app_title_bar(Some(&on)));
// (probed_app, overridden, forced_to_x11): without the preference, then with it.
let cases = [
((false, None, false), false, true), // KDE, Sway, X11: the desktop frame
((true, None, false), true, true), // GNOME on Wayland: the app frame either way
((true, None, true), false, true), // GNOME, the window opened through XWayland
((false, Some(true), false), true, true), // VECTORCRAFT_TITLEBAR=app
((false, Some(true), true), true, true), // VECTORCRAFT_TITLEBAR=app, the window opened through XWayland
((true, Some(false), false), false, false), // VECTORCRAFT_TITLEBAR=desktop takes precedence over the preference
((false, Some(false), true), false, false),
];
for ((probed_app, overridden, forced_to_x11), without, with) in cases {
assert_eq!(super::app_draws_frame(probed_app, overridden, forced_to_x11, false), without, "{probed_app} {overridden:?} {forced_to_x11}");
assert_eq!(super::app_draws_frame(probed_app, overridden, forced_to_x11, true), with, "{probed_app} {overridden:?} {forced_to_x11}");
}
}
/// The frame a start uses: the preference turns the desktop frame the probe chose into the app frame
/// with the default window buttons, a probed app frame keeps its own buttons, and the desktop frame
/// stays where the app frame is not drawn. System Title Bar takes precedence over the preference.
#[test]
fn the_start_frame_applies_the_app_title_bar_preference() {
use craft_window::{Button, Frame, Layout};
let gnome = Layout { left: vec![Button::Close], right: vec![] };
let cases = [
// (probed, overridden, forced_to_x11, opted_into_app), expected
((Frame::Desktop, None, false, false), Frame::Desktop),
((Frame::Desktop, None, false, true), Frame::App(Layout::default())),
((Frame::Desktop, None, true, true), Frame::App(Layout::default())),
((Frame::App(gnome.clone()), None, false, false), Frame::App(gnome.clone())),
((Frame::App(gnome.clone()), None, true, false), Frame::Desktop),
((Frame::App(gnome.clone()), None, true, true), Frame::App(gnome.clone())),
((Frame::Desktop, Some(false), false, true), Frame::Desktop),
((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(gnome.clone())),
];
for ((probed, overridden, forced_to_x11, opted_into_app), expected) in cases {
let label = format!("{probed:?} {overridden:?} {forced_to_x11} {opted_into_app}");
assert_eq!(super::start_frame(probed, overridden, forced_to_x11, opted_into_app), expected, "{label}");
}
// With both preferences on, System Title Bar takes precedence: the desktop draws the frame.
let both = super::start_frame(Frame::Desktop, None, false, true);
assert!(!super::custom_titlebar_from(&both, true), "System Title Bar takes precedence over the app title bar preference");
}
/// `VECTORCRAFT_TITLEBAR` chooses the frame for the run it is set in, with System Title Bar off and
/// on. The saved preference still decides while the variable is unset.
#[test]
fn the_titlebar_variable_takes_precedence_over_system_title_bar() {
use craft_window::Frame;
assert!(super::system_title_bar_applies(true, false));
assert!(!super::system_title_bar_applies(true, true));
assert!(!super::system_title_bar_applies(false, false));
assert!(!super::system_title_bar_applies(false, true));
// VECTORCRAFT_TITLEBAR=app with System Title Bar on: VectorCraft draws its own title bar.
let frame = super::start_frame(Frame::Desktop, Some(true), false, false);
assert_eq!(super::custom_titlebar_from(&frame, super::system_title_bar_applies(true, true)), !cfg!(target_os = "macos"));
// VECTORCRAFT_TITLEBAR=desktop with System Title Bar off keeps the desktop's frame.
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
let frame = super::start_frame(Frame::App(craft_window::Layout::default()), Some(false), false, false);
assert!(!super::custom_titlebar_from(&frame, super::system_title_bar_applies(false, true)));
}
}
/// `VECTORCRAFT_TITLEBAR` read from the environment at startup, with System Title Bar off and on.
/// The variable is process-wide and read once, so each value runs in a separate test process.
#[test]
fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
const CHILD: &str = "VECTORCRAFT_TEST_TITLEBAR_CHILD";
if std::env::var_os(CHILD).is_none() {
for value in ["app", "system", "desktop", "unknown"] {
// Linux and the BSDs: hold `spawning` while the child starts, so it does not keep a
// copy of a GPU start test's locked start file (see `CHILD_SPAWN`).
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
let spawning = super::spawning();
let child = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "tests::the_titlebar_variable_decides_the_frame_before_the_window_opens", "--nocapture"])
.env(CHILD, "1")
.env("VECTORCRAFT_TITLEBAR", value)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn();
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
drop(spawning);
let output = child.unwrap().wait_with_output().unwrap();
assert!(
output.status.success(),
"VECTORCRAFT_TITLEBAR={value}\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
return;
}
let value = std::env::var("VECTORCRAFT_TITLEBAR").unwrap();
let not_read = cfg!(any(target_os = "macos", target_os = "windows"));
assert_eq!(super::titlebar_from_env(), !not_read && value != "unknown", "VECTORCRAFT_TITLEBAR={value}");
let off = ui_state_with_prefs(serde_json::json!({"systemTitleBar": false}));
let on = ui_state_with_prefs(serde_json::json!({"systemTitleBar": true}));
for (saved, opted_into_system) in [(None, false), (Some(&off), false), (Some(&on), true)] {
let custom = super::custom_titlebar(saved);
let expected = match value.as_str() {
_ if not_read => !cfg!(target_os = "macos") && !opted_into_system,
"app" => true,
"system" | "desktop" => false,
// Not a value the variable takes: System Title Bar decides when it is on. Otherwise the
// `craft-window` probe decides, the same with System Title Bar off as with no saved
// preferences.
_ if opted_into_system => false,
_ => super::custom_titlebar(None),
};
assert_eq!(custom, expected, "{value}, preference {opted_into_system}");
assert_eq!(super::native_options(custom).viewport.decorations, Some(!custom), "{value}, preference {opted_into_system}");
}
}
/// The file extensions the macOS bundle declares: its document types and its own exported type.
fn plist_extensions(plist: &str) -> Vec<&str> {
["<key>CFBundleTypeExtensions</key>", "<key>public.filename-extension</key>"]
+80 -19
View File
@@ -41,11 +41,66 @@ pub(crate) const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos");
/// Whether the user asked for the system title bar in Preferences › User Interface › System Title
/// Bar. Read from the saved preferences before the window opens; a missing or unreadable value is
/// `false` (the default). This preference forces the desktop/native frame back on.
/// `false` (the default). This preference forces the desktop/native frame back on unless
/// `VECTORCRAFT_TITLEBAR` is set to `app`, `system` or `desktop` ([`system_title_bar_applies`]).
pub(crate) fn opted_into_system_title_bar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
saved.map(|ui| ui.engine_prefs.get("systemTitleBar").and_then(serde_json::Value::as_bool).unwrap_or(false)).unwrap_or(false)
}
/// Whether the user asked for VectorCraft's own title bar in Preferences › User Interface ›
/// VectorCraft Title Bar on Every Desktop (Linux and the BSDs). Read like
/// [`opted_into_system_title_bar`]; a missing or unreadable value is `false` (the default).
pub(crate) fn opted_into_app_title_bar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
saved.map(|ui| ui.engine_prefs.get("appTitleBar").and_then(serde_json::Value::as_bool).unwrap_or(false)).unwrap_or(false)
}
/// Whether the app draws the frame on this start, before the System Title Bar preference is
/// applied ([`custom_titlebar_from`]). `probed_app` is the `craft-window` probe's answer and
/// `overridden` its `VECTORCRAFT_TITLEBAR` override. In order: the override decides when the
/// variable is set to `app`, `system` or `desktop`;VectorCraft Title Bar on Every Desktop (`opted_into_app`) gives the app frame; a window
/// that opens through XWayland (`forced_to_x11`) gets the desktop frame; otherwise the probe
/// decides.
pub(crate) fn app_draws_frame(probed_app: bool, overridden: Option<bool>, forced_to_x11: bool, opted_into_app: bool) -> bool {
match overridden {
Some(app) => app,
None => opted_into_app || (probed_app && !forced_to_x11),
}
}
/// The frame this start uses, before the System Title Bar preference is applied
/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. A probed
/// app frame keeps its window-button layout; an app frame the probe did not choose gets the default
/// layout, since `custom_titlebar_from` reads only which frame it is.
pub(crate) fn start_frame(probed: craft_window::Frame, overridden: Option<bool>, forced_to_x11: bool, opted_into_app: bool) -> craft_window::Frame {
let probed_app = matches!(probed, craft_window::Frame::App(_));
match (app_draws_frame(probed_app, overridden, forced_to_x11, opted_into_app), probed) {
(true, frame @ craft_window::Frame::App(_)) => frame,
(true, craft_window::Frame::Desktop) => craft_window::Frame::App(craft_window::Layout::default()),
(false, _) => craft_window::Frame::Desktop,
}
}
/// The `craft-window` probe's answer for this process (its override variable is
/// `VECTORCRAFT_TITLEBAR`). The probe runs once; on a Wayland session it opens a connection.
fn probed_choice() -> &'static craft_window::Choice {
static CHOICE: std::sync::OnceLock<craft_window::Choice> = std::sync::OnceLock::new();
CHOICE.get_or_init(|| craft_window::Choice::probe(craft_window::Prefix::new("VECTORCRAFT")))
}
/// Whether `VECTORCRAFT_TITLEBAR` chose this window's frame (Linux and the BSDs), so Preferences ›
/// User Interface › System Title Bar and VectorCraft Title Bar on Every Desktop do not apply while
/// it is set to `app`, `system` or `desktop`. Always `false` on macOS and Windows.
pub(crate) fn titlebar_from_env() -> bool {
cfg!(not(any(target_os = "macos", target_os = "windows"))) && probed_choice().overridden().is_some()
}
/// Whether System Title Bar decides this start: `opted_into_system` unless `VECTORCRAFT_TITLEBAR`
/// is set to `app`, `system` or `desktop` (`from_env`), which chooses the frame for the run it is
/// set in.
pub(crate) fn system_title_bar_applies(opted_into_system: bool, from_env: bool) -> bool {
opted_into_system && !from_env
}
/// Whether this start draws its own title bar, given the frame the shared `craft-window` crate
/// decided and the user's System Title Bar preference.
///
@@ -53,9 +108,10 @@ pub(crate) fn opted_into_system_title_bar(saved: Option<&vectorcraft_ui_egui::Ui
/// ([`craft_window::Frame::Desktop`]) on macOS, Windows, X11 and any Wayland compositor with
/// server-side decorations (KDE, Sway, Hyprland, COSMIC); the app draws it
/// ([`craft_window::Frame::App`]) only where the compositor leaves it to the app (GNOME's Mutter),
/// or when `VECTORCRAFT_TITLEBAR` overrides the probe. VectorCraft draws its own title bar exactly
/// or when `VECTORCRAFT_TITLEBAR` set to `app`, `system` or `desktop` overrides the probe. VectorCraft draws its own title bar exactly
/// when `craft-window` says the app owns the frame **and** the user has not opted into the system
/// title bar; the preference always forces the native frame back on.
/// title bar; the preference forces the native frame back on unless `VECTORCRAFT_TITLEBAR` is set
/// to one of those values ([`system_title_bar_applies`]).
///
/// macOS and Windows keep today's behavior and are decided by [`CUSTOM_TITLEBAR`] rather than the
/// probe: `craft-window` returns `Frame::Desktop` for both (the OS always draws a frame), but
@@ -77,29 +133,34 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
/// Whether this start draws its own title bar. Probes the shared `craft-window` crate once (its
/// override variable is `VECTORCRAFT_TITLEBAR`) and combines its decision with the saved System
/// Title Bar preference. Call once at startup, before [`native_options`].
/// Title Bar preference, which does not apply while the variable is set to `app`, `system` or
/// `desktop`. Call once at startup,
/// before [`native_options`].
///
/// On Linux, Preferences › Performance › Linux Display Server › X11 opens the window through
/// XWayland (below). A GNOME/Wayland probe would say `Frame::App` there, but the window really runs
/// on X11, whose window manager draws the frame — so when XWayland is being forced, keep the native
/// frame, the same as a real X11 session. An explicit `VECTORCRAFT_TITLEBAR` override still wins.
/// frame, the same as a real X11 session. A recognized `VECTORCRAFT_TITLEBAR` override still wins,
/// and so does VectorCraft Title Bar on Every Desktop ([`app_draws_frame`]).
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
let choice = craft_window::Choice::probe(craft_window::Prefix::new("VECTORCRAFT"));
let opted_into_system = opted_into_system_title_bar(saved);
let choice = probed_choice();
let opted_into_system = system_title_bar_applies(opted_into_system_title_bar(saved), titlebar_from_env());
// macOS and Windows never read VectorCraft Title Bar on Every Desktop (`custom_titlebar_from`
// ignores the frame there).
let opted_into_app = cfg!(not(any(target_os = "macos", target_os = "windows"))) && opted_into_app_title_bar(saved);
#[cfg(target_os = "linux")]
{
// When the window will actually open on X11 (XWayland) — the user asked for it *and* the X11
// libraries are present, the same two conditions the launch path checks below — that run is
// effectively X11, so keep the native frame. If the libraries are missing, startup stays on
// Wayland, so the probe's own decision (app-drawn on GNOME) must stand.
let forced_to_x11 = {
let pref = saved.and_then(|ui| ui.engine_prefs.get("linuxDisplayServer")).and_then(serde_json::Value::as_str);
// `overridden() == None` means the probe decided (no VECTORCRAFT_TITLEBAR). When the window
// will actually open on X11 (XWayland) — the user asked for it *and* the X11 libraries are
// present, the same two conditions the launch path checks below — that run is effectively
// X11, so keep the native frame. If the libraries are missing, startup stays on Wayland, so
// the probe's own decision (app-drawn on GNOME) must stand.
let forced_to_x11 = xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) && xwayland::x11_libraries_found();
if choice.overridden().is_none() && forced_to_x11 {
return custom_titlebar_from(&craft_window::Frame::Desktop, opted_into_system);
}
}
custom_titlebar_from(choice.frame(), opted_into_system)
xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) && xwayland::x11_libraries_found()
};
#[cfg(not(target_os = "linux"))]
let forced_to_x11 = false;
let frame = start_frame(choice.frame().clone(), choice.overridden(), forced_to_x11, opted_into_app);
custom_titlebar_from(&frame, opted_into_system)
}
pub(crate) fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
+85
View File
@@ -3,6 +3,7 @@
//! the size, position and maximized state saved with the UI preferences (`UiState::window`), moved
//! onto a monitor that is still connected.
use vectorcraft_ui_egui::DockMonitor;
use vectorcraft_ui_egui::state::WindowGeometry;
use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize};
@@ -14,6 +15,9 @@ pub const MIN_SIZE: [f32; 2] = [800.0, 500.0];
/// say how much of the screen they take): a monitor with less room opens it maximized.
const SCREEN_ROOM: [f32; 2] = [64.0, 128.0];
/// Seconds between readings of the monitor list, which picks up a monitor connected while the app runs.
const MONITORS_EVERY: f64 = 1.0;
/// A monitor: its top-left corner and size in physical pixels, and its scale factor.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Monitor {
@@ -67,6 +71,15 @@ impl Monitor {
i32::try_from(want.max(lo).min(hi)).unwrap_or_default()
})
}
/// This monitor for floating panels, in the points egui reports for a window on it: physical
/// pixels divided by the monitor's scale factor and the UI zoom.
fn docking(&self, name: Option<String>, zoom: f32) -> DockMonitor {
let scale = self.scale * zoom;
let [x, y] = self.pos;
let [w, h] = self.size;
DockMonitor { name, rect: [x, y, w, h].map(|v| v as f32 / scale), scale }
}
}
/// Where the window opens: `saved` (the last session's geometry) kept on a connected monitor, else
@@ -109,6 +122,33 @@ fn fit(size: [f32; 2], room: [f32; 2]) -> [f32; 2] {
std::array::from_fn(|i| size[i].min(room[i]).max(MIN_SIZE[i].min(room[i])).max(1.0))
}
/// Whether to list the monitors again: on the first frame, when the UI zoom changed, and at most
/// every [`MONITORS_EVERY`] seconds while the app draws. `listed` holds the last list's time and zoom.
pub fn monitors_due(listed: Option<(f64, f32)>, now: f64, zoom: f32) -> bool {
listed.is_none_or(|(at, listed_zoom)| listed_zoom != zoom || now - at >= MONITORS_EVERY)
}
/// The connected monitors for floating panels (`Services::dock_monitors`).
pub fn dock_monitors(window: &winit::window::Window, zoom: f32) -> Vec<DockMonitor> {
let monitors: Vec<_> = window.available_monitors().map(|m| (Monitor::new(m.position(), m.size(), m.scale_factor()), m.name())).collect();
docking_list(&monitors, zoom, cfg!(target_os = "macos"))
}
/// The list for floating panels, empty when `monitors` have different scales and `shared_points` is
/// false. macOS has one desktop of points. Elsewhere a new window multiplies its saved position by the
/// scale of the monitor it is created on, which can put a window saved on another scale off every
/// monitor. With an empty list craft-ui opens the window on the main window's monitor.
///
/// A name that two monitors share is left out, so craft-ui finds those monitors by their rects: macOS
/// can give two displays of one model the same name.
fn docking_list(monitors: &[(Monitor, Option<String>)], zoom: f32, shared_points: bool) -> Vec<DockMonitor> {
if !shared_points && monitors.windows(2).any(|pair| pair[0].0.scale != pair[1].0.scale) {
return Vec::new();
}
let unique = |name: &String| monitors.iter().filter(|(_, other)| other.as_ref() == Some(name)).count() == 1;
monitors.iter().map(|(monitor, name)| monitor.docking(name.clone().filter(unique), zoom)).collect()
}
/// Size and place the new window (eframe shows it after drawing the first frame) and return its
/// geometry. On Linux the window may not be mapped yet, so [`apply_pending_maximize`] must run
/// until the host reports maximized (fixes #3635).
@@ -204,6 +244,51 @@ mod tests {
assert_eq!(place(saved(Some([9000, 9000]), [1e9, 1e9], true), &[], None).size, DEFAULT_SIZE);
}
#[test]
fn floating_panels_get_monitors_in_the_points_a_window_on_them_reports() {
let dock = |m: Monitor, zoom| m.docking(Some("m".into()), zoom);
let plain = dock(monitor(1920, 0, 1920, 1080, 1.0), 1.0);
assert_eq!(plain, DockMonitor { name: Some("m".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0 });
// A window at (3000, 200) on this monitor reports (1500, 100).
let scaled = dock(monitor(1920, -200, 3840, 2160, 2.0), 1.0);
assert_eq!(scaled, DockMonitor { name: Some("m".into()), rect: [960.0, -100.0, 1920.0, 1080.0], scale: 2.0 });
// The UI zoom divides what egui reports as well.
let zoomed = dock(monitor(-2560, 0, 2560, 1440, 1.0), 1.25);
assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25 });
}
#[test]
fn monitors_of_different_scales_are_listed_only_on_a_desktop_of_shared_points() {
let named = |m: Monitor, name: &str| (m, Some(name.to_string()));
let same = [named(monitor(0, 0, 1920, 1080, 1.5), "a"), named(monitor(1920, 0, 1920, 1080, 1.5), "b")];
assert_eq!(docking_list(&same, 1.0, false).len(), 2);
let mixed = [named(monitor(0, 0, 3840, 2160, 2.0), "a"), named(monitor(3840, 0, 1920, 1080, 1.0), "b")];
assert_eq!(docking_list(&mixed, 1.0, false), Vec::new());
assert_eq!(docking_list(&mixed, 1.0, true).len(), 2);
assert_eq!(docking_list(&[], 1.0, false), Vec::new());
}
#[test]
fn a_name_that_two_monitors_share_is_left_out_of_the_list() {
let list = [
(monitor(0, 0, 1920, 1080, 1.0), Some("Monitor #1".to_string())),
(monitor(1920, 0, 1920, 1080, 1.0), Some("Monitor #1".to_string())),
(monitor(3840, 0, 1920, 1080, 1.0), Some("Monitor #2".to_string())),
(monitor(5760, 0, 1920, 1080, 1.0), None),
];
let names: Vec<_> = docking_list(&list, 1.0, false).into_iter().map(|m| m.name).collect();
assert_eq!(names, [None, None, Some("Monitor #2".to_string()), None]);
}
#[test]
fn the_monitor_list_is_read_on_the_first_frame_then_once_a_second_or_on_a_zoom_change() {
assert!(monitors_due(None, 0.0, 1.0));
assert!(!monitors_due(Some((5.0, 1.0)), 5.0, 1.0));
assert!(!monitors_due(Some((5.0, 1.0)), 5.5, 1.0));
assert!(monitors_due(Some((5.0, 1.0)), 6.0, 1.0));
assert!(monitors_due(Some((5.0, 1.0)), 5.5, 1.25));
}
#[test]
fn the_saved_window_comes_back_where_it_was() {
let two = [monitor(0, 0, 2560, 1440, 1.0), monitor(2560, 0, 1920, 1080, 1.0)];
+152 -39
View File
@@ -13,6 +13,13 @@
//! same undo step as the typing round it. The keypad digits themselves are taken out of the frame,
//! so they don't run a shortcut bound to Alt and a digit.
//!
//! With NumLock off the keypad keys arrive as Insert, End, Down, Page Down, Left, Clear, Right,
//! Home, Up and Page Up, and Windows still composes the code from them. They are told from the
//! separate navigation keys by the extended-key flag, which only the separate keys set
//! (<https://learn.microsoft.com/en-us/windows/win32/inputdev/about-keyboard-input#extended-key-flag>),
//! so with Alt held they count as digits and are taken out of the frame too, rather than moving
//! the caret before the character arrives.
//!
//! egui reports a keypad digit as the same key as the digit above the letters, so the other
//! platforms, whose systems have no such convention, can't tell them apart either.
@@ -28,10 +35,20 @@ const WM_CHAR: u32 = 0x0102;
const WM_SYSKEYDOWN: u32 = 0x0104;
const WM_SYSKEYUP: u32 = 0x0105;
const WM_SYSCHAR: u32 = 0x0106;
/// `VK_NUMPAD0` to `VK_NUMPAD9` (`winuser.h`): keypad digits with NumLock on. With it off the keys
/// are Insert, End, … and type no code.
/// `VK_NUMPAD0` to `VK_NUMPAD9` (`winuser.h`): keypad digits with NumLock on.
const VK_NUMPAD0: usize = 0x60;
const VK_NUMPAD9: usize = 0x69;
/// The keypad's virtual keys with NumLock off, by digit (`winuser.h`): `VK_INSERT`, `VK_END`,
/// `VK_DOWN`, `VK_NEXT`, `VK_LEFT`, `VK_CLEAR`, `VK_RIGHT`, `VK_HOME`, `VK_UP` and `VK_PRIOR`.
const NUMLOCK_OFF_KEYS: [usize; 10] = [0x2D, 0x23, 0x28, 0x22, 0x25, 0x0C, 0x27, 0x24, 0x26, 0x21];
/// The keys egui reports for the keypad with NumLock off, by digit (Clear has no egui key, so it
/// comes as the top-row digit key, `Num5`).
const NUMLOCK_OFF_EGUI_KEYS: [Key; 10] =
[Key::Insert, Key::End, Key::ArrowDown, Key::PageDown, Key::ArrowLeft, Key::Num5, Key::ArrowRight, Key::Home, Key::ArrowUp, Key::PageUp];
const DIGIT_KEYS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key::Num4, Key::Num5, Key::Num6, Key::Num7, Key::Num8, Key::Num9];
/// Bit 24 of a key message's `lParam`: an extended key, such as the navigation keys beside the
/// keypad (the keypad's own keys clear it).
const EXTENDED_KEY: isize = 1 << 24;
/// `VK_MENU`, `VK_LMENU` and `VK_RMENU`: Alt.
const ALT_KEYS: [usize; 3] = [0x12, 0xA4, 0xA5];
@@ -51,23 +68,42 @@ struct AltCodes {
high: Option<u16>,
/// Characters the codes typed, for the next frame.
typed: String,
/// Keypad digit presses and releases with Alt held since the last frame, which egui reports
/// as Alt and a digit: taken out of the frame.
keypad_events: usize,
/// The digits of the keypad presses and releases with Alt held since the last frame, which
/// egui reports as Alt and a digit (or, with NumLock off, Alt and a navigation key): taken
/// out of the frame.
keypad_events: Vec<usize>,
}
/// The digit a keypad key stands for in an Alt code: `wparam` is its virtual-key code and
/// `lparam` the message's flags.
fn keypad_digit(wparam: usize, lparam: isize) -> Option<usize> {
if (VK_NUMPAD0..=VK_NUMPAD9).contains(&wparam) {
return Some(wparam - VK_NUMPAD0);
}
if lparam & EXTENDED_KEY != 0 {
return None;
}
NUMLOCK_OFF_KEYS.iter().position(|&k| k == wparam)
}
impl AltCodes {
/// Note a keyboard message `message` with `wparam` (the virtual-key code, or a UTF-16 unit).
fn message(&mut self, message: u32, wparam: usize) {
let keypad = (VK_NUMPAD0..=VK_NUMPAD9).contains(&wparam);
match message {
/// Note a keyboard message `message` with `wparam` (the virtual-key code, or a UTF-16 unit)
/// and `lparam` (its flags).
fn message(&mut self, message: u32, wparam: usize, lparam: isize) {
let keypad = match message {
WM_SYSKEYDOWN | WM_SYSKEYUP => keypad_digit(wparam, lparam),
_ => None,
};
if let Some(d) = keypad {
// Windows sends a key pressed with Alt held as a system key.
WM_SYSKEYDOWN if keypad => {
if message == WM_SYSKEYDOWN {
self.digits += 1;
self.keypad_events += 1;
self.armed = false;
}
WM_SYSKEYUP if keypad => self.keypad_events += 1,
self.keypad_events.push(d);
return;
}
match message {
WM_KEYDOWN | WM_SYSKEYDOWN if ALT_KEYS.contains(&wparam) => {}
// Any other key ends the sequence and keeps its own meaning.
WM_KEYDOWN | WM_SYSKEYDOWN => self.reset(),
@@ -99,14 +135,23 @@ impl AltCodes {
/// out the keypad digits typed with Alt held.
fn drain(&mut self, events: &mut Vec<Event>) {
let mut keypad = std::mem::take(&mut self.keypad_events);
if keypad > 0 {
if !keypad.is_empty() {
events.retain(|e| {
let digit = matches!(e, Event::Key { key: Key::Num0 | Key::Num1 | Key::Num2 | Key::Num3 | Key::Num4 | Key::Num5 | Key::Num6 | Key::Num7 | Key::Num8 | Key::Num9, modifiers, .. } if modifiers.alt);
if digit && keypad > 0 {
keypad -= 1;
return false;
let Event::Key { key, modifiers, .. } = e else {
return true;
};
if !modifiers.alt {
return true;
}
// The first keypad key still to take out that egui reports as `key`.
let stands_for = |d: &usize| DIGIT_KEYS.get(*d) == Some(key) || NUMLOCK_OFF_EGUI_KEYS.get(*d) == Some(key);
match keypad.iter().position(stands_for) {
Some(i) => {
keypad.remove(i);
false
}
None => true,
}
true
});
}
if !self.typed.is_empty() {
@@ -129,7 +174,7 @@ pub fn msg_hook(msg: *const std::ffi::c_void) {
if (WM_KEYDOWN..=WM_SYSCHAR).contains(&msg.message) {
CODES.with(|c| {
if let Ok(mut c) = c.try_borrow_mut() {
c.message(msg.message, msg.wParam.0);
c.message(msg.message, msg.wParam.0, msg.lParam.0);
}
});
}
@@ -152,14 +197,14 @@ mod tests {
/// Alt held, keypad digits `code`, Alt released, and the character Windows then posts.
fn alt_code(c: &mut AltCodes, code: &str, posted: u16) {
c.message(WM_SYSKEYDOWN, ALT);
c.message(WM_SYSKEYDOWN, ALT, 0);
for d in code.bytes() {
let vk = VK_NUMPAD0 + usize::from(d - b'0');
c.message(WM_SYSKEYDOWN, vk);
c.message(WM_SYSKEYUP, vk);
c.message(WM_SYSKEYDOWN, vk, 0);
c.message(WM_SYSKEYUP, vk, 0);
}
c.message(WM_KEYUP, ALT);
c.message(WM_CHAR, usize::from(posted));
c.message(WM_KEYUP, ALT, 0);
c.message(WM_CHAR, usize::from(posted), 0);
}
fn key(key: Key, alt: bool, pressed: bool) -> Event {
@@ -186,11 +231,11 @@ mod tests {
fn a_character_without_a_code_before_it_is_left_to_winit() {
let mut c = AltCodes::default();
// A plain key press's character (winit types it), and Alt pressed and released alone.
c.message(WM_KEYDOWN, 0x41);
c.message(WM_CHAR, usize::from(b'a'));
c.message(WM_SYSKEYDOWN, ALT);
c.message(WM_KEYUP, ALT);
c.message(WM_CHAR, usize::from(b'b'));
c.message(WM_KEYDOWN, 0x41, 0);
c.message(WM_CHAR, usize::from(b'a'), 0);
c.message(WM_SYSKEYDOWN, ALT, 0);
c.message(WM_KEYUP, ALT, 0);
c.message(WM_CHAR, usize::from(b'b'), 0);
let mut events = vec![];
c.drain(&mut events);
assert!(events.is_empty(), "{events:?}");
@@ -199,12 +244,12 @@ mod tests {
#[test]
fn another_key_while_alt_is_held_cancels_the_code() {
let mut c = AltCodes::default();
c.message(WM_SYSKEYDOWN, ALT);
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1);
c.message(WM_SYSKEYDOWN, ALT, 0);
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0);
// Alt+F: a shortcut, not a code.
c.message(WM_SYSKEYDOWN, 0x46);
c.message(WM_KEYUP, ALT);
c.message(WM_CHAR, 0x41);
c.message(WM_SYSKEYDOWN, 0x46, 0);
c.message(WM_KEYUP, ALT, 0);
c.message(WM_CHAR, 0x41, 0);
let mut events = vec![];
c.drain(&mut events);
assert!(!events.iter().any(|e| matches!(e, Event::Text(_))), "{events:?}");
@@ -213,13 +258,81 @@ mod tests {
#[test]
fn a_code_above_the_basic_plane_arrives_as_two_halves() {
let mut c = AltCodes::default();
c.message(WM_SYSKEYDOWN, ALT);
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1);
c.message(WM_KEYUP, ALT);
c.message(WM_CHAR, 0xD83D);
c.message(WM_CHAR, 0xDE00);
c.message(WM_SYSKEYDOWN, ALT, 0);
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0);
c.message(WM_KEYUP, ALT, 0);
c.message(WM_CHAR, 0xD83D, 0);
c.message(WM_CHAR, 0xDE00, 0);
let mut events = vec![];
c.drain(&mut events);
assert_eq!(events, vec![Event::Text("😀".into())]);
}
/// Alt held, keypad digits `code` with NumLock off (keypad Insert, End, …, flags without the
/// extended-key bit), Alt released, and the character Windows then posts.
fn alt_code_numlock_off(c: &mut AltCodes, code: &str, posted: u16) {
c.message(WM_SYSKEYDOWN, ALT, 0);
for d in code.bytes() {
let vk = NUMLOCK_OFF_KEYS[usize::from(d - b'0')];
c.message(WM_SYSKEYDOWN, vk, 0);
c.message(WM_SYSKEYUP, vk, 0);
}
c.message(WM_KEYUP, ALT, 0);
c.message(WM_CHAR, usize::from(posted), 0);
}
#[test]
fn with_numlock_off_the_keypad_keys_type_the_code_and_leave_the_caret_alone() {
let mut c = AltCodes::default();
alt_code_numlock_off(&mut c, "0176", 0xB0);
// What egui reports for keypad 0, 1, 7 and 6 with NumLock off and Alt held, a press and a
// release each, then a plain Home typed after Alt came up.
let mut events = vec![];
for k in [Key::Insert, Key::End, Key::Home, Key::ArrowRight] {
events.push(key(k, true, true));
events.push(key(k, true, false));
}
events.push(key(Key::Home, false, true));
c.drain(&mut events);
assert_eq!(events, vec![key(Key::Home, false, true), Event::Text("°".into())]);
}
#[test]
fn with_numlock_off_keypad_five_counts_too() {
let mut c = AltCodes::default();
// Keypad 5 is Clear, which egui reports as the top-row 5. 0151 uses Insert, End and Clear;
// 0234 uses Insert, Down, Page Down and Left.
alt_code_numlock_off(&mut c, "0151", 0x2014);
alt_code_numlock_off(&mut c, "0234", 0xEA);
let mut events =
vec![key(Key::Num5, true, true), key(Key::ArrowDown, true, true), key(Key::PageDown, true, true), key(Key::ArrowLeft, true, true)];
c.drain(&mut events);
assert_eq!(events, vec![Event::Text("—ê".into())]);
}
#[test]
fn the_separate_navigation_keys_still_move_the_caret_and_cancel_the_code() {
let mut c = AltCodes::default();
c.message(WM_SYSKEYDOWN, ALT, 0);
c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[1], 0);
c.message(WM_SYSKEYUP, NUMLOCK_OFF_KEYS[1], 0);
// Alt+Home on the separate Home key (extended): a shortcut, not a digit.
c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY);
c.message(WM_SYSKEYUP, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY);
c.message(WM_KEYUP, ALT, 0);
c.message(WM_CHAR, 0x41, 0);
let mut events = vec![key(Key::End, true, true), key(Key::End, true, false), key(Key::Home, true, true), key(Key::Home, true, false)];
c.drain(&mut events);
assert_eq!(events, vec![key(Key::Home, true, true), key(Key::Home, true, false)]);
}
#[test]
fn numlock_off_keys_without_alt_are_left_alone() {
let mut c = AltCodes::default();
c.message(WM_KEYDOWN, NUMLOCK_OFF_KEYS[7], 0);
c.message(WM_KEYUP, NUMLOCK_OFF_KEYS[7], 0);
let mut events = vec![key(Key::Home, false, true), key(Key::Home, false, false)];
c.drain(&mut events);
assert_eq!(events.len(), 2);
}
}
+25 -1
View File
@@ -54,7 +54,7 @@ fn prints_usage(args: &[&str], env: &[(&str, &str)]) {
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
assert!(out.stderr.is_empty(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
assert!(stdout.starts_with("Usage: vectorcraft "), "{args:?}: {stdout}");
for flag in ["--control", "--automation-read-root", "--automation-write-root", "--in-window-menus", "--version", "--help"] {
for flag in ["--control", "--automation-read-root", "--automation-write-root", "--in-window-menus", "--safe-mode", "--version", "--help"] {
assert!(stdout.contains(flag), "{args:?}: usage doesn't mention {flag}: {stdout}");
}
// Headless work is the CLI's: the usage says where to go.
@@ -74,3 +74,27 @@ fn help_prints_usage_and_exits_before_startup() {
fn help_wins_over_a_bad_control_port_variable() {
prints_usage(&["--help"], &[("VECTORCRAFT_CONTROL_PORT", "abc")]);
}
/// An option the app doesn't know (a typo of `--safe-mode`) is an error, not a file to open with
/// plug-ins; a later `--help` still wins.
#[test]
fn an_unknown_option_is_an_error_and_not_a_file() {
for args in [&["--safe-mod"][..], &["drawing.svg", "--safe-mod"], &["-x"]] {
let out = run(args, &[]);
assert!(!out.status.success(), "{args:?}");
assert!(out.stdout.is_empty(), "{args:?}");
let stderr = String::from_utf8(out.stderr).unwrap();
let unknown = args.iter().find(|a| a.starts_with('-')).unwrap();
assert_eq!(
stderr,
format!("vectorcraft: unknown option {unknown}; see vectorcraft --help, or put -- before a file whose name starts with '-'\n"),
"{args:?}"
);
}
prints_usage(&["--safe-mod", "--help"], &[]);
// After `--`, a name starting with '-' is a file: the run goes on to the control port, which
// `run` makes fail.
let out = run(&["--", "-x.svg"], &[]);
let stderr = String::from_utf8(out.stderr).unwrap();
assert!(stderr.contains("VECTORCRAFT_CONTROL_PORT") && !stderr.contains("unknown option"), "{stderr}");
}
+5
View File
@@ -220,3 +220,8 @@ real_name = "Sven Lafebre"
[people.kylekanouse]
real_name = "Kyle Kanouse"
sync_github_name = true
[people.Hassan1305]
real_name = "Hassan Nawaz Khan"
display_name = "Hassan Nawaz Khan"
sync_github_name = false
+40 -2
View File
@@ -29,6 +29,14 @@ const MAX_DOCUMENT_CELLS: usize = 1 << 18;
/// Points of all strokes' pressure curves together (a stroke style may be shared by many layers).
const MAX_DOCUMENT_PRESSURE_POINTS: usize = 1 << 20;
/// Child references inspected, page rectangles produced, and outline segments retained, in all
/// (shared objects are visited once per link, so each visit is charged). Real documents stay
/// within a few times [`MAX_NODES`]; this leaves ~30x headroom over that.
const MAX_DOCUMENT_WORK: usize = 1 << 24;
/// Owned layer-name characters kept in all (each visit of a shared object keeps its own copy).
const MAX_DOCUMENT_NAME_CHARS: usize = 16 << 20;
/// What a whole read may still use. Shared objects can be linked from many layers, and embedded
/// documents are read with what their embedding document left, so linking or embedding the
/// same content many times can't multiply the work.
@@ -44,6 +52,10 @@ pub(crate) struct Budget {
pub(crate) cells: usize,
/// Points of pressure curves ([`MAX_DOCUMENT_PRESSURE_POINTS`] in all).
pub(crate) pressure: usize,
/// Child references, page rectangles and outline segments ([`MAX_DOCUMENT_WORK`] in all).
pub(crate) work: usize,
/// Layer-name characters ([`MAX_DOCUMENT_NAME_CHARS`] in all).
pub(crate) name_chars: usize,
}
impl Budget {
@@ -53,7 +65,15 @@ impl Budget {
chars: MAX_DOCUMENT_CHARS,
cells: MAX_DOCUMENT_CELLS,
pressure: MAX_DOCUMENT_PRESSURE_POINTS,
work: MAX_DOCUMENT_WORK,
name_chars: MAX_DOCUMENT_NAME_CHARS,
};
/// Take `n` units of work, or fail the read.
pub(crate) fn spend(&mut self, n: usize) -> Result<(), Error> {
self.work = self.work.checked_sub(n).ok_or(Error::Limit("too much shared geometry or page data"))?;
Ok(())
}
}
/// Read a document: archive, `doc.dat` and the model.
@@ -192,6 +212,7 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
return Ok(None);
}
let pages = pages(s, spread);
self.budget.spend(pages.len() + 1)?;
let default_size = s.floats::<2>(doc, b"DfSz").filter(|[w, h]| *w > 0.0 && *h > 0.0).map(|[w, h]| Rect { x0: 0.0, y0: 0.0, x1: w, y1: h });
let bounds = s.floats::<4>(spread, b"SprB").map(rect).or_else(|| pages.iter().copied().reduce(union)).or(default_size).unwrap_or(Rect {
x0: 0.0,
@@ -214,7 +235,10 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
let s = self.s;
let mut out = Vec::new();
let mut mask = None;
for c in s.objs(parent, b"Chld") {
let kids = s.objs(parent, b"Chld");
// Invisible masks and skipped children cost no node, so the visit is charged here.
self.budget.spend(kids.len())?;
for c in kids {
if s.is(c, b"MRst") {
// A mask layer inside a group or layer masks that container.
if s.bool(c, b"Visi") == Some(false) {
@@ -254,7 +278,8 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
let world = local.then(parent);
let class = s.class(id).unwrap_or(Tag(0));
// A layer name is short; a long one is cut, as every visit of a shared object keeps a copy.
let name: String = s.str(id, b"Desc").unwrap_or_default().chars().take(MAX_NAME_CHARS).collect();
let name: String = s.str(id, b"Desc").unwrap_or_default().chars().take(MAX_NAME_CHARS.min(self.budget.name_chars)).collect();
self.budget.name_chars -= name.chars().count();
let visible = s.bool(id, b"Visi").unwrap_or(true);
let locked = s.bool(id, b"Edtb").is_some_and(|e| !e);
let opacity = s.f64(id, b"Opac").map_or(1.0, |o| o.clamp(0.0, 1.0));
@@ -312,6 +337,7 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
self.warn(format!("a {} that could not be read", describe(class)));
return Ok(Kind::Unsupported);
};
self.budget.spend(local.subpaths.iter().map(|sp| sp.segments.len() + 1).sum())?;
let (fills, strokes) = paint::node_paint(self, id, world);
Kind::Shape { path: local.transformed(world), fills, strokes, even_odd }
}
@@ -645,3 +671,15 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
Kind::Artboard { rect, path: path.transformed(world), even_odd, background, strokes }
}
}
#[cfg(test)]
mod budget_tests {
use super::*;
#[test]
fn shared_work_is_bounded() {
let mut b = Budget::FULL;
assert!(b.spend(MAX_DOCUMENT_WORK).is_ok());
assert_eq!(b.spend(1), Err(Error::Limit("too much shared geometry or page data")));
}
}
+5 -4
View File
@@ -238,12 +238,13 @@ pub(crate) fn descriptor(r: &mut Reader, id: ObjId, local: Affine) -> Option<Pai
};
let grad = s.obj(fill, b"Grad")?;
let cols = s.objs(grad, b"Cols");
let posn: Vec<Vec<f64>> = match s.field(grad, b"Posn") {
Some(Value::Array(a)) => a.iter().filter_map(floats).collect(),
_ => Vec::new(),
// Convert only the positions that pair with a colour, as shared attributes repeat this per run.
let posn: &[Value] = match s.field(grad, b"Posn") {
Some(Value::Array(a)) => a,
_ => &[],
};
let mut stops = Vec::new();
for (c, p) in cols.iter().zip(&posn).take(MAX_STOPS) {
for (c, p) in cols.iter().zip(posn.iter().filter_map(floats)).take(MAX_STOPS) {
let color = color(r, *c)?;
let offset = p.first().copied().filter(|v| v.is_finite()).unwrap_or(0.0).clamp(0.0, 1.0);
let bias = p.get(1).copied().filter(|v| v.is_finite()).unwrap_or(0.5).clamp(0.0, 1.0);
+8 -1
View File
@@ -195,6 +195,11 @@ fn decode_within(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), worl
if let Some(name) = s.entry(bitmap, b"Bckg") {
let width = s.int(bitmap, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
let height = s.int(bitmap, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
// The whole source is decoded for every layer that reads it, so charge it all, not only the crop.
let Some(left) = r.budget.pixels.checked_sub(u64::from(width) * u64::from(height)) else {
return Err(Error::Limit("embedded image pixels"));
};
r.budget.pixels = left;
match original(r, name).and_then(|bytes| source_pixels(&bytes, width, height)) {
Ok(pixels) => Some((width as usize, pixels)),
Err(Error::Limit(e)) => return Err(Error::Limit(e)),
@@ -318,8 +323,10 @@ fn grid(s: &stream::Stream, bitmap: ObjId, c: usize, bps: usize) -> (usize, usiz
let height = s.int(bitmap, b"BmpH").and_then(|v| usize::try_from(v).ok()).unwrap_or(0);
let tw = s.int(bitmap, &tag(b"TWi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| width.saturating_mul(bps).div_ceil(TILE));
let th = s.int(bitmap, &tag(b"THi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| height.div_ceil(TILE));
// A grid larger than the bitmap has tiles no crop can reach: don't convert or scan them on every reference.
let tiles = width.saturating_mul(bps).div_ceil(TILE).saturating_mul(height.div_ceil(TILE));
let states: Vec<u8> = match s.field(bitmap, &tag(b"Sta", c)) {
Some(Value::Array(a)) => a.iter().map(|v| if let Value::UInt(u) = v { u8::try_from(*u).unwrap_or(255) } else { 255 }).collect(),
Some(Value::Array(a)) => a.iter().take(tiles).map(|v| if let Value::UInt(u) = v { u8::try_from(*u).unwrap_or(255) } else { 255 }).collect(),
_ => Vec::new(),
};
(tw, th, states)
+15 -4
View File
@@ -51,6 +51,9 @@ const MAX_TABLE_LINES: usize = 4096;
/// Cells a table may have (rows × columns): each becomes a text object with its edge lines.
const MAX_TABLE_CELLS: usize = 1 << 16;
/// Work charged for each copy of a run's formatting a table cell keeps.
const TABLE_RUN_COST: usize = 16;
/// A table node (`TxtT`): the grid, the cells' text and the lines on the cell edges.
pub(crate) fn table(r: &mut Reader, id: ObjId, world: Affine) -> Option<Table> {
let s = r.s;
@@ -108,9 +111,10 @@ pub(crate) fn table(r: &mut Reader, id: ObjId, world: Affine) -> Option<Table> {
let mut parts = run.text.split(CELL_BREAK).peekable();
while let Some(part) = parts.next() {
if !part.is_empty() {
// Each cell keeps its own copy of the run's formatting, so each copy is charged.
match target.and_then(|i| cells.get_mut(i)) {
Some(cell) => cell.runs.push(TextRun { text: part.to_string(), ..run.clone() }),
None => extra = true,
Some(cell) if r.budget.spend(TABLE_RUN_COST).is_ok() => cell.runs.push(TextRun { text: part.to_string(), ..run.clone() }),
_ => extra = true,
}
}
if parts.peek().is_some() {
@@ -157,6 +161,13 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
let mut placeholders = false;
let mut attribute_budget = Some(MAX_ATTRIBUTE_BYTES);
for block in s.objs(story, b"Blok") {
// Shared blocks and run lists are visited once per link, so every visit is charged, empty or not.
let paragraph_runs = s.obj(block, b"PAtt").map(|p| s.objs(p, b"Runs")).unwrap_or_default();
let attribute_runs = s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default();
if r.budget.spend(1 + paragraph_runs.len() + attribute_runs.len()).is_err() {
r.warn("text beyond the work one document may hold (truncated)");
break;
}
let Some(glyphs) = s.obj(block, b"Glyp") else {
r.warn("a text block without readable characters (left out)");
continue;
@@ -209,7 +220,7 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
// Paragraph formats by end index; a run without an index covers the rest of the block.
let mut paragraphs: Vec<(usize, Paragraph)> = Vec::new();
let mut open: Option<Paragraph> = None;
for run in s.obj(block, b"PAtt").map(|p| s.objs(p, b"Runs")).unwrap_or_default() {
for run in paragraph_runs {
let Some(attrs) = s.obj(run, b"Item") else { continue };
let a = paragraph(r, attrs);
first_align.get_or_insert(a.align);
@@ -238,7 +249,7 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
}
};
let mut start = 0usize;
for run in s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default() {
for run in attribute_runs {
let Some(index) = s.int(run, b"Indx").and_then(|v| usize::try_from(v).ok()) else {
r.warn("invalid text attribute range (bounded; unassigned characters use defaults)");
continue;
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "vectorcraft-apischema"
description = "Machine-readable parameter schemas for VectorCraft commands, with a validator and a params text writer"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[dependencies]
serde_json = { workspace = true }
+174
View File
@@ -0,0 +1,174 @@
//! For tests: a check of JSON Schema 2020-12 documents, and a validator of instances against them,
//! written from the keyword rules of the Core and Validation specifications
//! (<https://json-schema.org/draft/2020-12>). It reads only the JSON and shares no code with the
//! writer it checks. It covers the keywords the writer uses and reports any other keyword that
//! isn't an `x-` annotation.
use serde_json::Value;
const TYPES: &[&str] = &["null", "boolean", "object", "array", "number", "string", "integer"];
fn unique(items: &[Value]) -> bool {
items.iter().enumerate().all(|(i, x)| items.iter().take(i).all(|y| y != x))
}
fn schema_list(items: &Value, at: &str, key: &str) -> Result<(), String> {
let list = items.as_array().filter(|l| !l.is_empty()).ok_or_else(|| format!("{at}: `{key}` must be a nonempty array"))?;
for (i, x) in list.iter().enumerate() {
check_schema(x, &format!("{at}/{key}/{i}"))?;
}
Ok(())
}
/// Whether `schema` follows the 2020-12 rules for the keywords it uses, with where it doesn't.
pub fn check_schema(schema: &Value, at: &str) -> Result<(), String> {
let object = match schema {
Value::Bool(_) => return Ok(()),
Value::Object(o) => o,
other => return Err(format!("{at}: a schema must be an object or a boolean, not {other}")),
};
for (key, value) in object {
let number = || if value.is_number() { Ok(()) } else { Err(format!("{at}: `{key}` must be a number")) };
match key.as_str() {
"$schema" => {
let uri = value.as_str().ok_or_else(|| format!("{at}: `$schema` must be a string"))?;
if !uri.contains("://") || uri.ends_with('#') {
return Err(format!("{at}: `$schema` must be a normalized URI"));
}
}
"type" => {
let known = |v: &Value| v.as_str().is_some_and(|s| TYPES.contains(&s));
let ok = known(value) || value.as_array().is_some_and(|l| !l.is_empty() && unique(l) && l.iter().all(known));
if !ok {
return Err(format!("{at}: `type` must name JSON types, not {value}"));
}
}
"enum" => {
if !value.as_array().is_some_and(|l| !l.is_empty() && unique(l)) {
return Err(format!("{at}: `enum` must be a nonempty array of unique values"));
}
}
"properties" => {
let props = value.as_object().ok_or_else(|| format!("{at}: `properties` must be an object"))?;
for (name, x) in props {
check_schema(x, &format!("{at}/properties/{name}"))?;
}
}
"required" => {
if !value.as_array().is_some_and(|l| unique(l) && l.iter().all(Value::is_string)) {
return Err(format!("{at}: `required` must be an array of unique strings"));
}
}
"additionalProperties" | "items" => check_schema(value, &format!("{at}/{key}"))?,
"prefixItems" | "anyOf" => schema_list(value, at, key)?,
"minimum" | "maximum" | "exclusiveMinimum" | "exclusiveMaximum" => number()?,
"minItems" => {
if value.as_u64().is_none() {
return Err(format!("{at}: `minItems` must be a non-negative integer"));
}
}
"description" => {
if !value.is_string() {
return Err(format!("{at}: `description` must be a string"));
}
}
"deprecated" => {
if !value.is_boolean() {
return Err(format!("{at}: `deprecated` must be a boolean"));
}
}
"default" => {
if !instance_valid(schema, value) {
return Err(format!("{at}: `default` {value} does not validate against its schema"));
}
}
k if k.starts_with("x-") => {}
other => return Err(format!("{at}: unexpected keyword `{other}`")),
}
}
Ok(())
}
fn has_type(v: &Value, name: &str) -> bool {
match name {
"null" => v.is_null(),
"boolean" => v.is_boolean(),
"object" => v.is_object(),
"array" => v.is_array(),
"string" => v.is_string(),
"number" => v.is_number(),
"integer" => v.is_i64() || v.is_u64() || v.as_f64().is_some_and(|x| x.fract() == 0.0),
_ => false,
}
}
/// Whether the instance `v` is valid against `schema`.
pub fn instance_valid(schema: &Value, v: &Value) -> bool {
let s = match schema {
Value::Bool(b) => return *b,
Value::Object(o) => o,
_ => return false,
};
let type_ok = match s.get("type") {
None => true,
Some(Value::String(t)) => has_type(v, t),
Some(Value::Array(l)) => l.iter().filter_map(Value::as_str).any(|t| has_type(v, t)),
Some(_) => false,
};
if !type_ok {
return false;
}
if let Some(list) = s.get("enum").and_then(Value::as_array)
&& !list.contains(v)
{
return false;
}
if let Some(any) = s.get("anyOf").and_then(Value::as_array)
&& !any.iter().any(|x| instance_valid(x, v))
{
return false;
}
if let Some(x) = v.as_f64() {
let bound = |key: &str| s.get(key).and_then(Value::as_f64);
if bound("minimum").is_some_and(|m| x < m)
|| bound("maximum").is_some_and(|m| x > m)
|| bound("exclusiveMinimum").is_some_and(|m| x <= m)
|| bound("exclusiveMaximum").is_some_and(|m| x >= m)
{
return false;
}
}
if let Some(items) = v.as_array() {
if s.get("minItems").and_then(Value::as_u64).is_some_and(|n| (items.len() as u64) < n) {
return false;
}
let prefix = s.get("prefixItems").and_then(Value::as_array).map_or(&[][..], Vec::as_slice);
if items.iter().zip(prefix).any(|(x, p)| !instance_valid(p, x)) {
return false;
}
if let Some(rest) = s.get("items")
&& items.iter().skip(prefix.len()).any(|x| !instance_valid(rest, x))
{
return false;
}
}
if let Some(object) = v.as_object() {
let required = s.get("required").and_then(Value::as_array).map_or(&[][..], Vec::as_slice);
if required.iter().filter_map(Value::as_str).any(|k| !object.contains_key(k)) {
return false;
}
let props = s.get("properties").and_then(Value::as_object);
for (key, x) in object {
match props.and_then(|p| p.get(key)) {
Some(p) if !instance_valid(p, x) => return false,
Some(_) => {}
None => {
if s.get("additionalProperties").is_some_and(|a| !instance_valid(a, x)) {
return false;
}
}
}
}
}
true
}
+940
View File
@@ -0,0 +1,940 @@
//! Machine-readable parameter schemas for VectorCraft commands. A [`ParamSchema`] lists what each
//! parameter of a command is ([`Param`], [`Type`]): its type, whether it is required, what an
//! omitted value means, whether null counts as omitted, and the API levels it was added and
//! deprecated at. From one schema come:
//!
//! - [`ParamSchema::validate`], which checks a params object and names the parameter of the first
//! problem it finds ([`ParamError`]), and fills in the defaults of omitted values;
//! - [`ParamSchema::definition_problem`], which checks the schema itself;
//! - [`ParamSchema::params_text`], the params text a command lists;
//! - [`ParamSchema::to_json`], the schema as a JSON object in the shape of a JSON Schema 2020-12
//! object schema (<https://json-schema.org/draft/2020-12>), with VectorCraft's own fields as
//! `x-` keywords;
//! - [`hash`], a hash of a set of command schemas, which changes whenever any of them changes.
//!
//! Checking a value walks the schema, so its depth is the schema's, at most [`MAX_DEPTH`]. An error
//! shows a bounded part of a refused value and of a refused key, and the value is not written out
//! first, so a huge or deeply nested value costs no more to refuse than a small one.
//!
//! The crate knows no command and depends on no other VectorCraft crate.
#![forbid(unsafe_code)]
use std::fmt;
use serde_json::{Map, Value, json};
/// The JSON Schema dialect [`ParamSchema::to_json`] names in `$schema`.
pub const DIALECT: &str = "https://json-schema.org/draft/2020-12/schema";
/// How many objects and lists may nest inside a schema's params object.
pub const MAX_DEPTH: usize = 16;
/// The largest object id [`Type::Id`] takes: 2^53 - 1, the largest integer every JSON reader holds
/// exactly.
pub const MAX_ID: u64 = (1 << 53) - 1;
/// How many characters of a refused value an error shows.
const SHOWN_CHARS: usize = 40;
/// How many characters of a key an error shows.
const KEY_CHARS: usize = 64;
/// One end of a number's range.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Bound {
/// The value may equal the bound.
Inclusive(f64),
/// The value must be past the bound.
Exclusive(f64),
}
/// The type of a parameter's value.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Type {
/// A JSON number in the range the bounds give, measured in `unit` (`"pt"`, `"deg"`) when set.
Number { min: Option<Bound>, max: Option<Bound>, unit: Option<&'static str> },
/// A JSON number with no fractional part, in the range given. [`ParamSchema::validate`] gives
/// the command `2.0` as `2`.
Integer { min: Option<i64>, max: Option<i64> },
/// `true` or `false`.
Boolean,
/// Any string.
String,
/// One of the strings listed.
Enum(&'static [&'static str]),
/// An object id: an integer from 0 to [`MAX_ID`], read as [`Type::Integer`] reads one.
Id,
/// A list of object ids.
Ids,
/// A color: a string (`"#rrggbb"`, a color key), `[r, g, b]` or an object. The command reads
/// which color it is.
Color,
/// A point: `[x, y]`, two numbers.
Point,
/// An object with the parameters listed and no other key.
Object(&'static [Param]),
/// A list of values of one type.
Array(&'static Type),
}
impl Type {
/// A number with no range and no unit.
pub const NUMBER: Type = Type::Number { min: None, max: None, unit: None };
}
/// What an omitted value means.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Omitted {
/// The parameter is required, or the command describes the omitted case in its summary.
Nothing,
/// The value, as JSON text, that [`ParamSchema::validate`] fills in.
Value(&'static str),
/// A default the command works out itself (`"toggle"`, `"the selected text"`).
Note(&'static str),
}
/// What a command changes when it runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Writes {
/// Nothing: the command only reads.
Nothing,
/// State of the running app outside the document and the preferences (view state, the Caps
/// Lock state).
Session,
/// The preferences.
Preferences,
/// The document, with an undo step.
Document,
}
impl Writes {
fn name(self) -> &'static str {
match self {
Writes::Nothing => "nothing",
Writes::Session => "session",
Writes::Preferences => "preferences",
Writes::Document => "document",
}
}
}
/// One parameter of a command.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Param {
pub name: &'static str,
pub ty: Type,
pub required: bool,
pub omitted: Omitted,
/// A null value is read as if the parameter were omitted. Otherwise null is refused as a value
/// of the wrong type.
pub null_omitted: bool,
/// What the params text says about the value, in parentheses after its type.
pub doc: &'static str,
/// The API level the parameter was added at.
pub since: u32,
/// The API level the parameter was deprecated at.
pub deprecated: Option<u32>,
/// A value of the wrong type or out of range is not refused here: the command reads it as it
/// did before it had a schema. [`ParamSchema::to_json`] still writes the documented type, so a
/// JSON Schema validator refuses a value this passes.
pub lenient: bool,
}
impl Param {
/// A required parameter, added at API level 1.
pub const fn new(name: &'static str, ty: Type) -> Param {
Param { name, ty, required: true, omitted: Omitted::Nothing, null_omitted: false, doc: "", since: 1, deprecated: None, lenient: false }
}
/// The parameter may be omitted.
pub const fn optional(self) -> Param {
Param { required: false, ..self }
}
/// The parameter may be omitted, and then takes the value `json` (JSON text).
pub const fn defaults_to(self, json: &'static str) -> Param {
Param { required: false, omitted: Omitted::Value(json), ..self }
}
/// The parameter may be omitted, and the command then works out the value `note` describes.
pub const fn default_note(self, note: &'static str) -> Param {
Param { required: false, omitted: Omitted::Note(note), ..self }
}
/// A null value reads as an omitted one.
pub const fn null_omitted(self) -> Param {
Param { null_omitted: true, ..self }
}
pub const fn doc(self, doc: &'static str) -> Param {
Param { doc, ..self }
}
pub const fn since(self, level: u32) -> Param {
Param { since: level, ..self }
}
pub const fn deprecated(self, level: u32) -> Param {
Param { deprecated: Some(level), ..self }
}
pub const fn lenient(self) -> Param {
Param { lenient: true, ..self }
}
}
/// The parameters of one command, and what the command does with them.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ParamSchema {
pub params: &'static [Param],
/// What the command does, after the params object in the params text.
pub summary: &'static str,
/// What the command returns, after `→` in the params text; empty when the text leaves it out.
pub returns: &'static str,
/// The API level the command was added at.
pub since: u32,
/// The API level the command was deprecated at.
pub deprecated: Option<u32>,
/// What one run costs, in units of a light command (1), for callers that limit a script's work.
pub cost: u32,
pub writes: Writes,
}
impl ParamSchema {
/// A command added at API level 1, costing 1, that changes the document.
pub const fn new(params: &'static [Param], summary: &'static str) -> ParamSchema {
ParamSchema { params, summary, returns: "", since: 1, deprecated: None, cost: 1, writes: Writes::Document }
}
pub const fn returns(self, returns: &'static str) -> ParamSchema {
ParamSchema { returns, ..self }
}
pub const fn writes(self, writes: Writes) -> ParamSchema {
ParamSchema { writes, ..self }
}
pub const fn cost(self, cost: u32) -> ParamSchema {
ParamSchema { cost, ..self }
}
pub const fn since(self, level: u32) -> ParamSchema {
ParamSchema { since: level, ..self }
}
pub const fn deprecated(self, level: u32) -> ParamSchema {
ParamSchema { deprecated: Some(level), ..self }
}
/// The parameter named `name`.
pub fn param(&self, name: &str) -> Option<&'static Param> {
self.params.iter().find(|p| p.name == name)
}
/// The names of the top-level parameters, in order.
pub fn names(&self) -> Vec<&'static str> {
self.params.iter().map(|p| p.name).collect()
}
/// `params` checked against the schema: the first problem as an error naming the parameter,
/// or, when it has none, `params` with the defaults of its omitted values filled in (`None`
/// when no default was filled in, so `params` is used as it is). Null params read as `{}`.
pub fn validate(&self, params: &Value) -> Result<Option<Value>, ParamError> {
self.validate_as(params, false)
}
/// [`ParamSchema::validate`] for saved steps recorded by this version or an older one: a key
/// the schema doesn't name passes, at any depth, and the command does not read it. Values of
/// the parameters the schema names are checked as `validate` checks them.
pub fn validate_saved(&self, params: &Value) -> Result<Option<Value>, ParamError> {
self.validate_as(params, true)
}
fn validate_as(&self, params: &Value, saved: bool) -> Result<Option<Value>, ParamError> {
static EMPTY: std::sync::OnceLock<Map<String, Value>> = std::sync::OnceLock::new();
let given = match params {
Value::Object(o) => o,
Value::Null => EMPTY.get_or_init(Map::new),
v => return Err(ParamError { path: String::new(), problem: Problem::NotAnObject { got: shown(v) } }),
};
Ok(check_object(&At::Root, 0, self.params, given, saved)?.map(Value::Object))
}
/// What is wrong with the schema itself, or `None`: a parameter name that is empty, repeated
/// or holds `.`, `[` or `]`; a required parameter with a default; a default that isn't JSON or
/// doesn't pass its parameter's type; an enum with no names or a repeated name; a range with
/// an end that isn't finite or that no value can be in; nesting past [`MAX_DEPTH`].
pub fn definition_problem(&self) -> Option<String> {
object_problem("", self.params, 0)
}
/// The params text: the params object (`{name?: string, zoom: number > 0}`), then the summary,
/// then `→` and what the command returns.
pub fn params_text(&self) -> String {
let mut s = object_text(self.params, 0);
if !self.summary.is_empty() {
s.push(' ');
s.push_str(self.summary);
}
if !self.returns.is_empty() {
s.push_str(" → ");
s.push_str(self.returns);
}
s
}
/// The schema as a JSON Schema 2020-12 object schema. Defaults written as JSON go in
/// `default`, a parameter that accepts null as omitted is an `anyOf` with `{"type": "null"}`,
/// and VectorCraft's own fields are `x-since`, `x-deprecatedSince`, `x-lenient`, `x-unit`,
/// `x-kind`, `x-cost`, `x-writes` and `x-returns`. The root `type` is `["object", "null"]` when
/// no parameter is required, because null params read as `{}`, and `"object"` otherwise. A JSON
/// Schema validator accepts the values [`ParamSchema::validate`] accepts, except that an
/// `x-lenient` parameter's schema states only the documented type.
pub fn to_json(&self) -> Value {
let mut o = object_schema(self.params, 0);
if !self.params.iter().any(|p| p.required) {
o.insert("type".into(), json!(["object", "null"]));
}
o.insert("$schema".into(), DIALECT.into());
if !self.summary.is_empty() {
o.insert("description".into(), self.summary.into());
}
if !self.returns.is_empty() {
o.insert("x-returns".into(), self.returns.into());
}
o.insert("x-since".into(), self.since.into());
if let Some(level) = self.deprecated {
o.insert("deprecated".into(), true.into());
o.insert("x-deprecatedSince".into(), level.into());
}
o.insert("x-cost".into(), self.cost.into());
o.insert("x-writes".into(), self.writes.name().into());
Value::Object(o)
}
}
/// A problem [`ParamSchema::validate`] found, at `path`: the parameter's name, with the keys and
/// indices leading to a value inside one (`edits[1].name`). The path is empty for the params
/// object itself.
#[derive(Clone, Debug, PartialEq)]
pub struct ParamError {
pub path: String,
pub problem: Problem,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Problem {
/// The params are not an object.
NotAnObject { got: String },
/// The key at `path` is not a parameter of the object it is in, which takes `keys`.
Unknown { keys: Vec<&'static str> },
/// A required parameter is missing.
Missing,
/// The value is not of the parameter's type: `expected` says what it must be.
WrongType { expected: String, got: String },
/// The schema nests deeper than [`MAX_DEPTH`] here ([`ParamSchema::definition_problem`]).
TooDeep,
}
impl fmt::Display for ParamError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let path = &self.path;
match &self.problem {
Problem::NotAnObject { got } => write!(f, "the params must be an object, not {got}"),
Problem::Unknown { keys } if keys.is_empty() => write!(f, "unknown parameter `{path}`; the object takes no keys"),
Problem::Unknown { keys } => write!(f, "unknown parameter `{path}`; it takes: {}", keys.join(", ")),
Problem::Missing => write!(f, "missing `{path}`"),
Problem::WrongType { expected, got } => write!(f, "`{path}` must be {expected}, not {got}"),
Problem::TooDeep => write!(f, "`{path}` is nested too deeply"),
}
}
}
impl std::error::Error for ParamError {}
/// FNV-1a over the bytes of `text`, from `h`.
fn fnv1a(mut h: u64, text: &str) -> u64 {
for b in text.bytes() {
h ^= u64::from(b);
h = h.wrapping_mul(0x0000_0100_0000_01b3);
}
h
}
/// `v` as JSON text with the keys of each object in sorted order, whichever order the map keeps
/// them in.
fn canonical(v: &Value, out: &mut String) {
match v {
Value::Object(o) => {
let mut keys: Vec<&String> = o.keys().collect();
keys.sort();
out.push('{');
for (i, k) in keys.into_iter().enumerate() {
if i > 0 {
out.push(',');
}
out.push_str(&Value::from(k.as_str()).to_string());
out.push(':');
if let Some(x) = o.get(k) {
canonical(x, out);
}
}
out.push('}');
}
Value::Array(a) => {
out.push('[');
for (i, x) in a.iter().enumerate() {
if i > 0 {
out.push(',');
}
canonical(x, out);
}
out.push(']');
}
other => out.push_str(&other.to_string()),
}
}
/// A 64-bit FNV-1a hash of the commands' schemas, taken in the order of their ids: each id and
/// its [`ParamSchema::to_json`] text, with the keys of each object sorted. Any change to a schema,
/// or a schema added or removed, changes it.
pub fn hash<'a>(schemas: impl IntoIterator<Item = (&'a str, &'a ParamSchema)>) -> u64 {
let mut all: Vec<(&str, &ParamSchema)> = schemas.into_iter().collect();
all.sort_by_key(|(id, _)| *id);
all.iter().fold(0xcbf2_9ce4_8422_2325, |h, (id, schema)| {
let mut text = String::new();
canonical(&schema.to_json(), &mut text);
let h = fnv1a(h, id);
let h = fnv1a(h, "\n");
let h = fnv1a(h, &text);
fnv1a(h, "\n")
})
}
/// `key` as an error message shows it: cut to [`KEY_CHARS`] characters.
pub fn shown_key(key: &str) -> String {
let mut chars = key.chars();
let head: String = chars.by_ref().take(KEY_CHARS).collect();
if chars.next().is_some() { format!("{head}…") } else { head }
}
/// The JSON text of a value, stopping when its characters run out.
struct Shown {
text: String,
left: usize,
}
impl Shown {
/// Adds `s`; false when it didn't fit.
fn push(&mut self, s: &str) -> bool {
for c in s.chars() {
if self.left == 0 {
return false;
}
self.left -= 1;
self.text.push(c);
}
true
}
/// Adds the JSON text of string `s`, reading no more of it than can be shown.
fn push_string(&mut self, s: &str) -> bool {
let head: String = s.chars().take(self.left + 1).collect();
self.push(&Value::from(head).to_string())
}
/// Adds the JSON text of `v`; false when it didn't fit. Each object or list writes a bracket,
/// so the characters left bound the recursion.
fn push_value(&mut self, v: &Value) -> bool {
match v {
Value::String(s) => self.push_string(s),
Value::Array(items) => {
self.push("[") && items.iter().enumerate().all(|(i, x)| (i == 0 || self.push(",")) && self.push_value(x)) && self.push("]")
}
Value::Object(o) => {
self.push("{")
&& o.iter()
.enumerate()
.all(|(i, (k, x))| (i == 0 || self.push(",")) && self.push_string(k) && self.push(":") && self.push_value(x))
&& self.push("}")
}
other => self.push(&other.to_string()),
}
}
}
/// A value as an error message shows it: its JSON, cut to [`SHOWN_CHARS`] characters. Only what is
/// shown is read, however large the value is.
fn shown(v: &Value) -> String {
let mut out = Shown { text: String::new(), left: SHOWN_CHARS };
if !out.push_value(v) {
out.text.push('…');
}
out.text
}
fn join(path: &str, key: &str) -> String {
if path.is_empty() { key.to_string() } else { format!("{path}.{key}") }
}
/// Where a value is, from the value up to the params object. The path's text is written only for
/// an error.
#[derive(Clone, Copy)]
enum At<'a> {
Root,
Key(&'a At<'a>, &'a str),
Index(&'a At<'a>, usize),
}
impl At<'_> {
/// The path, `edits[1].name`, with each key as [`shown_key`] shows it.
fn text(&self) -> String {
let mut steps = Vec::new();
let mut at = self;
while let At::Key(up, _) | At::Index(up, _) = at {
steps.push(at);
at = up;
}
let mut out = String::new();
for step in steps.into_iter().rev() {
match step {
At::Key(_, key) => {
if !out.is_empty() {
out.push('.');
}
out.push_str(&shown_key(key));
}
At::Index(_, i) => out.push_str(&format!("[{i}]")),
At::Root => {}
}
}
out
}
}
/// Whether `v` nests no deeper than [`MAX_DEPTH`] counted from `depth`. The walk stops at the
/// limit, so it recurses at most [`MAX_DEPTH`] levels and allocates nothing.
fn nests_within(v: &Value, depth: usize) -> bool {
match v {
Value::Array(a) => depth < MAX_DEPTH && a.iter().all(|x| nests_within(x, depth + 1)),
Value::Object(o) => depth < MAX_DEPTH && o.values().all(|x| nests_within(x, depth + 1)),
_ => true,
}
}
/// The object `given` checked against `params` (unknown keys first, then each parameter in
/// order): with the defaults of omitted values filled in when there are any. `saved` keeps a key
/// the schema doesn't name, unless its value nests past [`MAX_DEPTH`].
fn check_object(
at: &At<'_>,
depth: usize,
params: &'static [Param],
given: &Map<String, Value>,
saved: bool,
) -> Result<Option<Map<String, Value>>, ParamError> {
let refused = |key: &String, v: &Value| !params.iter().any(|p| p.name == key.as_str()) && (!saved || !nests_within(v, depth));
if let Some((key, _)) = given.iter().find(|(k, v)| refused(k, v)) {
return Err(ParamError { path: At::Key(at, key).text(), problem: Problem::Unknown { keys: params.iter().map(|p| p.name).collect() } });
}
// The changes are applied once every value has passed, so no refused value is ever copied.
let mut changes: Vec<(&'static str, Value)> = Vec::new();
for p in params {
let here = At::Key(at, p.name);
match given.get(p.name) {
Some(Value::Null) if p.null_omitted => {}
Some(v) => {
if let Some(changed) = check_value(&here, depth, &p.ty, v, p.lenient, saved)? {
changes.push((p.name, changed));
}
continue;
}
None if p.required => return Err(ParamError { path: here.text(), problem: Problem::Missing }),
None => {}
}
// Omitted, or null read as omitted.
if let Omitted::Value(json) = p.omitted
&& let Ok(v) = serde_json::from_str::<Value>(json)
{
changes.push((p.name, v));
}
}
if changes.is_empty() {
return Ok(None);
}
let mut filled = given.clone();
for (name, v) in changes {
filled.insert(name.to_string(), v);
}
Ok(Some(filled))
}
/// What a value of type `ty` must be, as an error message says it.
fn expected(ty: &Type) -> String {
match ty {
Type::Number { min, max, unit } => {
format!("a number{}{}", range_text(min.as_ref(), max.as_ref()), unit.map(|u| format!(" ({u})")).unwrap_or_default())
}
Type::Integer { min, max } => {
format!("an integer{}", range_text(min.map(|m| Bound::Inclusive(m as f64)).as_ref(), max.map(|m| Bound::Inclusive(m as f64)).as_ref()))
}
Type::Boolean => "true or false".into(),
Type::String => "a string".into(),
Type::Enum(names) => format!("one of {}", names.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>().join(", ")),
Type::Id => "an object id (a non-negative integer)".into(),
Type::Ids => "a list of object ids".into(),
Type::Color => "a color (a string, [r, g, b] or an object)".into(),
Type::Point => "[x, y] (two numbers)".into(),
Type::Object(_) => "an object".into(),
Type::Array(_) => "a list".into(),
}
}
/// ` > 0`, ` 0 to 100`, ` >= 1 and < 10`: the range text after a number's type.
fn range_text(min: Option<&Bound>, max: Option<&Bound>) -> String {
match (min, max) {
(Some(Bound::Inclusive(a)), Some(Bound::Inclusive(b))) => format!(" {a} to {b}"),
(Some(a), Some(b)) => format!("{} and{}", low_text(a), high_text(b)),
(Some(a), None) => low_text(a),
(None, Some(b)) => high_text(b),
(None, None) => String::new(),
}
}
fn low_text(b: &Bound) -> String {
match b {
Bound::Inclusive(a) => format!(" >= {a}"),
Bound::Exclusive(a) => format!(" > {a}"),
}
}
fn high_text(b: &Bound) -> String {
match b {
Bound::Inclusive(a) => format!(" <= {a}"),
Bound::Exclusive(a) => format!(" < {a}"),
}
}
fn in_range(x: f64, min: Option<&Bound>, max: Option<&Bound>) -> bool {
let low = match min {
Some(Bound::Inclusive(a)) => x >= *a,
Some(Bound::Exclusive(a)) => x > *a,
None => true,
};
let high = match max {
Some(Bound::Inclusive(b)) => x <= *b,
Some(Bound::Exclusive(b)) => x < *b,
None => true,
};
low && high
}
/// The integer a JSON number with no fractional part stands for, as an integer value when it fits
/// in one (`2.0` is `2`); `None` for anything else.
fn whole(v: &Value) -> Option<Value> {
if v.is_i64() || v.is_u64() {
return Some(v.clone());
}
const TWO_63: f64 = 9_223_372_036_854_775_808.0;
const TWO_64: f64 = 18_446_744_073_709_551_616.0;
let x = v.as_f64().filter(|x| x.fract() == 0.0)?;
Some(if (-TWO_63..TWO_63).contains(&x) {
json!(x as i64)
} else if (0.0..TWO_64).contains(&x) {
json!(x as u64)
} else {
v.clone()
})
}
/// Whether the [`whole`] value `w` is in the range.
fn whole_in_range(w: &Value, min: Option<i64>, max: Option<i64>) -> bool {
match (w.as_i64(), w.as_u64(), w.as_f64()) {
(Some(x), _, _) => min.is_none_or(|m| x >= m) && max.is_none_or(|m| x <= m),
// Past i64::MAX: above any i64 bound.
(None, Some(_), _) => max.is_none(),
// Past what u64 holds: above any i64 bound.
(None, None, Some(x)) if x > 0.0 => max.is_none(),
// Below what i64 holds: under any i64 bound, so it meets every maximum and no minimum.
(None, None, Some(_)) => min.is_none(),
_ => false,
}
}
fn is_number(v: &Value) -> bool {
v.as_f64().is_some_and(f64::is_finite)
}
/// `v` checked against `ty` at `at`: with the defaults of omitted values inside it filled in, and
/// whole numbers written with a fraction made integers, when there are any. A lenient value of
/// the wrong type passes as it is, unless it nests past [`MAX_DEPTH`].
fn check_value(at: &At<'_>, depth: usize, ty: &Type, v: &Value, lenient: bool, saved: bool) -> Result<Option<Value>, ParamError> {
let done = |ok: bool| {
if ok || (lenient && nests_within(v, depth)) {
Ok(None)
} else {
Err(ParamError { path: at.text(), problem: Problem::WrongType { expected: expected(ty), got: shown(v) } })
}
};
let too_deep = || ParamError { path: at.text(), problem: Problem::TooDeep };
if matches!(ty, Type::Ids | Type::Color | Type::Point) && v.is_array() && depth >= MAX_DEPTH {
return Err(too_deep());
}
match ty {
Type::Number { min, max, .. } => done(v.as_f64().is_some_and(|x| x.is_finite() && in_range(x, min.as_ref(), max.as_ref()))),
Type::Integer { min, max } => match whole(v).filter(|w| whole_in_range(w, *min, *max)) {
Some(w) => Ok((w != *v).then_some(w)),
None => done(false),
},
Type::Boolean => done(v.is_boolean()),
Type::String => done(v.is_string()),
Type::Enum(names) => done(v.as_str().is_some_and(|s| names.contains(&s))),
Type::Id => match whole(v).filter(|w| w.as_u64().is_some_and(|x| x <= MAX_ID)) {
Some(w) => Ok((w != *v).then_some(w)),
None => done(false),
},
Type::Ids => match v.as_array() {
Some(items) => check_items(at, depth, &Type::Id, items, lenient, saved),
None => done(false),
},
Type::Color => done(match v {
Value::String(_) => true,
Value::Object(_) => nests_within(v, depth),
Value::Array(a) => a.len() >= 3 && a.iter().all(is_number),
_ => false,
}),
Type::Point => done(v.as_array().is_some_and(|a| a.len() == 2 && a.iter().all(is_number))),
Type::Object(params) => match v {
Value::Object(_) if depth >= MAX_DEPTH => Err(too_deep()),
Value::Object(o) => Ok(check_object(at, depth + 1, params, o, saved)?.map(Value::Object)),
_ => done(false),
},
Type::Array(item) => match v.as_array() {
Some(_) if depth >= MAX_DEPTH => Err(too_deep()),
Some(items) => check_items(at, depth + 1, item, items, lenient, saved),
None => done(false),
},
}
}
/// Each of `items` checked against `item`: the list with what [`check_value`] changed, when it
/// changed anything.
fn check_items(at: &At<'_>, depth: usize, item: &Type, items: &[Value], lenient: bool, saved: bool) -> Result<Option<Value>, ParamError> {
let mut changes: Vec<(usize, Value)> = Vec::new();
for (i, x) in items.iter().enumerate() {
if let Some(changed) = check_value(&At::Index(at, i), depth, item, x, lenient, saved)? {
changes.push((i, changed));
}
}
if changes.is_empty() {
return Ok(None);
}
let mut filled = items.to_vec();
for (i, v) in changes {
if let Some(slot) = filled.get_mut(i) {
*slot = v;
}
}
Ok(Some(Value::Array(filled)))
}
/// What is wrong with `params`, the object at `path` nested `depth` objects and lists deep.
fn object_problem(path: &str, params: &[Param], depth: usize) -> Option<String> {
if depth > MAX_DEPTH {
return Some(format!("`{path}` nests deeper than {MAX_DEPTH} levels"));
}
for (i, p) in params.iter().enumerate() {
let at = join(path, p.name);
if p.name.is_empty() || p.name.contains(['.', '[', ']']) {
return Some(format!("the parameter name `{at}` is empty or holds a path character"));
}
if params.iter().take(i).any(|q| q.name == p.name) {
return Some(format!("`{at}` is listed twice"));
}
if p.required && p.omitted != Omitted::Nothing {
return Some(format!("`{at}` is required and has a default"));
}
if let Some(problem) = type_problem(&at, &p.ty, depth) {
return Some(problem);
}
if let Omitted::Value(text) = p.omitted {
let Ok(v) = serde_json::from_str::<Value>(text) else { return Some(format!("the default of `{at}` isn't JSON: {text}")) };
if let Err(e) = check_value(&At::Root, 0, &p.ty, &v, false, false) {
return Some(format!("the default of `{at}` doesn't pass its type: {e}"));
}
}
}
None
}
fn type_problem(at: &str, ty: &Type, depth: usize) -> Option<String> {
let bound = |b: &Bound| match *b {
Bound::Inclusive(x) => (x, false),
Bound::Exclusive(x) => (x, true),
};
match ty {
Type::Number { min, max, .. } => {
let (low, high) = (min.as_ref().map(bound), max.as_ref().map(bound));
if low.iter().chain(high.iter()).any(|(x, _)| !x.is_finite()) {
return Some(format!("the range of `{at}` has an end that isn't finite"));
}
match (low, high) {
(Some((a, open_a)), Some((b, open_b))) if a > b || (a == b && (open_a || open_b)) => {
Some(format!("no value can be in the range of `{at}`"))
}
_ => None,
}
}
Type::Integer { min: Some(a), max: Some(b) } if a > b => Some(format!("no value can be in the range of `{at}`")),
Type::Enum([]) => Some(format!("the enum of `{at}` has no names")),
Type::Enum(names) if names.iter().enumerate().any(|(i, n)| names.iter().take(i).any(|m| m == n)) => {
Some(format!("the enum of `{at}` repeats a name"))
}
Type::Object(params) => object_problem(at, params, depth + 1),
Type::Array(_) if depth >= MAX_DEPTH => Some(format!("`{at}` nests deeper than {MAX_DEPTH} levels")),
Type::Array(item) => type_problem(&format!("{at}[]"), item, depth + 1),
_ => None,
}
}
/// `{a: number, b?: bool}`: the params object of a params text, `depth` objects and lists deep.
fn object_text(params: &[Param], depth: usize) -> String {
format!("{{{}}}", params.iter().map(|p| param_text(p, depth)).collect::<Vec<_>>().join(", "))
}
fn param_text(p: &Param, depth: usize) -> String {
let mut s = format!("{}{}: {}", p.name, if p.required { "" } else { "?" }, type_text(&p.ty, depth));
match p.omitted {
Omitted::Value(v) | Omitted::Note(v) => s.push_str(&format!(" (default: {v})")),
Omitted::Nothing => {}
}
if !p.doc.is_empty() {
s.push_str(&format!(" ({})", p.doc));
}
if p.deprecated.is_some() {
s.push_str(" (deprecated)");
}
s
}
fn type_text(ty: &Type, depth: usize) -> String {
match ty {
Type::Object(_) | Type::Array(_) if depth >= MAX_DEPTH => "…".into(),
Type::Number { min, max, unit } => {
format!("number{}{}", range_text(min.as_ref(), max.as_ref()), unit.map(|u| format!(" {u}")).unwrap_or_default())
}
Type::Integer { min, max } => {
format!("integer{}", range_text(min.map(|m| Bound::Inclusive(m as f64)).as_ref(), max.map(|m| Bound::Inclusive(m as f64)).as_ref()))
}
Type::Boolean => "bool".into(),
Type::String => "string".into(),
Type::Enum(names) => names.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>().join("|"),
Type::Id => "id".into(),
Type::Ids => "[id…]".into(),
Type::Color => "color".into(),
Type::Point => "[x, y]".into(),
Type::Object(params) => object_text(params, depth + 1),
Type::Array(item) => format!("[{}…]", type_text(item, depth + 1)),
}
}
/// `{"type": "object", "properties": …, "required": […], "additionalProperties": false}`.
fn object_schema(params: &[Param], depth: usize) -> Map<String, Value> {
let mut o = Map::new();
o.insert("type".into(), "object".into());
o.insert("properties".into(), Value::Object(params.iter().map(|p| (p.name.to_string(), param_schema(p, depth))).collect()));
let required: Vec<Value> = params.iter().filter(|p| p.required).map(|p| p.name.into()).collect();
if !required.is_empty() {
o.insert("required".into(), required.into());
}
o.insert("additionalProperties".into(), false.into());
o
}
fn param_schema(p: &Param, depth: usize) -> Value {
let inner = type_schema(&p.ty, depth);
let mut o = if p.null_omitted {
let mut o = Map::new();
o.insert("anyOf".into(), json!([inner, {"type": "null"}]));
o
} else {
match inner {
Value::Object(o) => o,
_ => Map::new(),
}
};
if !p.doc.is_empty() {
o.insert("description".into(), p.doc.into());
}
match p.omitted {
Omitted::Value(json) => {
if let Ok(v) = serde_json::from_str::<Value>(json) {
o.insert("default".into(), v);
}
}
Omitted::Note(note) => {
o.insert("x-default".into(), note.into());
}
Omitted::Nothing => {}
}
o.insert("x-since".into(), p.since.into());
if let Some(level) = p.deprecated {
o.insert("deprecated".into(), true.into());
o.insert("x-deprecatedSince".into(), level.into());
}
if p.lenient {
o.insert("x-lenient".into(), true.into());
}
Value::Object(o)
}
fn bound_keywords(o: &mut Map<String, Value>, min: Option<&Bound>, max: Option<&Bound>) {
let low = match min {
Some(Bound::Inclusive(a)) => Some(("minimum", a)),
Some(Bound::Exclusive(a)) => Some(("exclusiveMinimum", a)),
None => None,
};
let high = match max {
Some(Bound::Inclusive(b)) => Some(("maximum", b)),
Some(Bound::Exclusive(b)) => Some(("exclusiveMaximum", b)),
None => None,
};
for (key, x) in low.into_iter().chain(high) {
o.insert(key.into(), json!(x));
}
}
fn type_schema(ty: &Type, depth: usize) -> Value {
match ty {
Type::Object(_) | Type::Array(_) if depth >= MAX_DEPTH => Value::Bool(true),
Type::Number { min, max, unit } => {
let mut o = Map::new();
o.insert("type".into(), "number".into());
bound_keywords(&mut o, min.as_ref(), max.as_ref());
if let Some(u) = unit {
o.insert("x-unit".into(), (*u).into());
}
Value::Object(o)
}
Type::Integer { min, max } => {
let mut o = Map::new();
o.insert("type".into(), "integer".into());
if let Some(m) = min {
o.insert("minimum".into(), (*m).into());
}
if let Some(m) = max {
o.insert("maximum".into(), (*m).into());
}
Value::Object(o)
}
Type::Boolean => json!({"type": "boolean"}),
Type::String => json!({"type": "string"}),
Type::Enum(names) => json!({"enum": names}),
Type::Id => json!({"type": "integer", "minimum": 0, "maximum": MAX_ID, "x-kind": "id"}),
Type::Ids => json!({"type": "array", "items": {"type": "integer", "minimum": 0, "maximum": MAX_ID, "x-kind": "id"}}),
Type::Color => json!({
"anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "number"}, "minItems": 3}, {"type": "object"}],
"x-kind": "color",
}),
Type::Point => json!({
"type": "array",
"prefixItems": [{"type": "number"}, {"type": "number"}],
"items": false,
"minItems": 2,
"x-kind": "point",
}),
Type::Object(params) => Value::Object(object_schema(params, depth + 1)),
Type::Array(item) => json!({"type": "array", "items": type_schema(item, depth + 1)}),
}
}
#[cfg(test)]
mod conformance;
#[cfg(test)]
mod tests;
+536
View File
@@ -0,0 +1,536 @@
//! Tests of the validator, the params text and the JSON form, on schemas written here.
use serde_json::{Value, json};
use crate::*;
/// The schema with the one parameter `x` of type `ty`.
fn one(ty: Type) -> ParamSchema {
let params: &'static [Param] = Box::leak(Box::new([Param::new("x", ty)]));
ParamSchema::new(params, "")
}
/// Whether `{x: v}` passes the schema of `ty`; on a refusal, the error must name `x`.
fn passes(ty: Type, v: Value) -> bool {
match one(ty).validate(&json!({ "x": v })) {
Ok(_) => true,
Err(e) => {
assert!(e.path.starts_with('x'), "{e}");
assert!(e.to_string().contains("`x"), "{e}");
false
}
}
}
#[test]
fn numbers_are_checked_against_their_range() {
let any = Type::NUMBER;
assert!(passes(any, json!(-3.5)) && passes(any, json!(7)));
assert!(!passes(any, json!("7")) && !passes(any, json!(null)) && !passes(any, json!(true)));
let positive = Type::Number { min: Some(Bound::Exclusive(0.0)), max: None, unit: None };
assert!(passes(positive, json!(0.001)));
assert!(!passes(positive, json!(0)) && !passes(positive, json!(-1)));
let percent = Type::Number { min: Some(Bound::Inclusive(0.0)), max: Some(Bound::Inclusive(100.0)), unit: Some("%") };
assert!(passes(percent, json!(0)) && passes(percent, json!(100)));
assert!(!passes(percent, json!(100.5)));
let below = Type::Number { min: None, max: Some(Bound::Exclusive(1.0)), unit: None };
assert!(passes(below, json!(0.99)) && !passes(below, json!(1)));
assert_eq!(one(positive).validate(&json!({"x": 0})).unwrap_err().to_string(), "`x` must be a number > 0, not 0");
assert_eq!(one(percent).validate(&json!({"x": 101})).unwrap_err().to_string(), "`x` must be a number 0 to 100 (%), not 101");
}
#[test]
fn integers_take_no_fraction_and_keep_their_range() {
let any = Type::Integer { min: None, max: None };
assert!(passes(any, json!(-4)) && passes(any, json!(u64::MAX)));
assert!(!passes(any, json!(1.5)) && !passes(any, json!("2")));
let small = Type::Integer { min: Some(1), max: Some(25) };
assert!(passes(small, json!(1)) && passes(small, json!(25)));
assert!(!passes(small, json!(0)) && !passes(small, json!(26)) && !passes(small, json!(u64::MAX)));
assert!(passes(small, json!(25.0)) && !passes(small, json!(26.0)) && !passes(small, json!(1e300)) && !passes(small, json!(-1e300)));
let negative = Type::Integer { min: None, max: Some(-1_000_000_000_000_000_000) };
assert!(passes(negative, json!(-1e20)) && !passes(negative, json!(1e20)));
let lowest = Type::Integer { min: Some(i64::MIN), max: None };
assert!(!passes(lowest, json!(-1e20)) && passes(lowest, json!(1e20)));
}
/// JSON Schema counts a number with no fractional part as an integer: `2.0` passes, and the
/// command gets `2`.
#[test]
fn a_whole_number_written_with_a_fraction_is_an_integer() {
let any = Type::Integer { min: None, max: None };
assert_eq!(one(any).validate(&json!({"x": 2.0})).unwrap(), Some(json!({"x": 2})));
assert_eq!(one(any).validate(&json!({"x": 2})).unwrap(), None);
assert!(passes(any, json!(1e300)));
assert_eq!(one(Type::Id).validate(&json!({"x": 7.0})).unwrap(), Some(json!({"x": 7})));
assert_eq!(one(Type::Ids).validate(&json!({"x": [1, 2.0]})).unwrap(), Some(json!({"x": [1, 2]})));
assert!(passes(Type::Id, json!(MAX_ID)) && !passes(Type::Id, json!(MAX_ID + 1)) && !passes(Type::Id, json!(1e300)));
assert_eq!(one(Type::Ids).validate(&json!({"x": [1, "2"]})).unwrap_err().path, "x[1]");
}
/// A value with no finite number in it reads as null in JSON, and a number refuses it; the largest
/// finite numbers pass a number with no range.
#[test]
fn numbers_at_the_edges() {
assert!(!passes(Type::NUMBER, json!(f64::NAN)) && !passes(Type::NUMBER, json!(f64::INFINITY)));
assert!(passes(Type::NUMBER, json!(f64::MAX)) && passes(Type::NUMBER, json!(f64::MIN)));
let unit = Type::Number { min: Some(Bound::Inclusive(0.0)), max: Some(Bound::Inclusive(1.0)), unit: None };
assert!(passes(unit, json!(0.0)) && passes(unit, json!(1.0)) && !passes(unit, json!(-1e-300)) && !passes(unit, json!(1.0000001)));
}
/// A list too long to name one path per entry costs one pass, and the error names the entry.
#[test]
fn a_huge_list_is_checked_once_and_names_the_entry() {
let mut ids: Vec<Value> = (0..200_000u64).map(Value::from).collect();
assert_eq!(one(Type::Ids).validate(&json!({ "x": ids })).unwrap(), None);
ids.push(json!("no"));
let e = one(Type::Ids).validate(&json!({ "x": ids })).unwrap_err();
assert_eq!(e.path, "x[200000]");
assert!(e.to_string().chars().count() < 120, "{e}");
}
/// A list nested far past anything the schema can take: dropping or writing it out recurses per
/// level, which is why the test leaks it rather than dropping it.
fn nested_lists(levels: usize) -> Value {
(0..levels).fold(json!(1), |inner, _| Value::Array(vec![inner]))
}
/// A refused value is shown from its start only, however deep or long it is, so an error costs
/// the same for a hostile value as for a small one.
#[test]
fn a_refused_value_is_read_only_as_far_as_it_is_shown() {
let deep = nested_lists(500_000);
let params = json!({});
let mut map = params.as_object().unwrap().clone();
map.insert("x".into(), deep);
let params = Value::Object(map);
let e = one(Type::String).validate(&params).unwrap_err();
assert!(e.to_string().starts_with("`x` must be a string, not [[[[") && e.to_string().ends_with('…'), "{e}");
assert!(e.to_string().chars().count() <= 100, "{e}");
std::mem::forget(params);
let huge = "x".repeat(5_000_000);
let e = one(Type::Boolean).validate(&json!({ "x": huge })).unwrap_err();
assert!(e.to_string().chars().count() <= 100, "{}", e.to_string().len());
assert!(e.to_string().ends_with('…'));
let e = one(Type::Boolean).validate(&json!({"x": {"a": 1, "b": [1, 2]}})).unwrap_err();
assert_eq!(e.to_string(), "`x` must be true or false, not {\"a\":1,\"b\":[1,2]}");
let e = ParamSchema::new(&[], "").validate(&nested_lists(3)).unwrap_err();
assert_eq!(e.to_string(), "the params must be an object, not [[[1]]]");
}
/// A list entry made an integer, and a default filled in, don't copy a value that is still to be
/// checked: copying recurses per level.
#[test]
fn a_list_with_a_change_is_not_copied_before_all_of_it_is_checked() {
let params = Value::Object([("x".to_string(), Value::Array(vec![json!(2.0), nested_lists(500_000)]))].into_iter().collect());
assert_eq!(one(Type::Ids).validate(&params).unwrap_err().path, "x[1]");
std::mem::forget(params);
}
#[test]
fn an_object_with_a_default_is_not_copied_before_all_of_it_is_checked() {
const FILLED_FIRST: &[Param] = &[Param::new("a", Type::NUMBER).defaults_to("0"), Param::new("b", Type::String)];
let params = Value::Object([("b".to_string(), nested_lists(500_000))].into_iter().collect());
assert_eq!(ParamSchema::new(FILLED_FIRST, "").validate(&params).unwrap_err().path, "b");
std::mem::forget(params);
}
/// A value the schema doesn't look inside is measured before a default copies the object it is in.
const WITH_DEFAULT: &[Param] = &[Param::new("a", Type::NUMBER).defaults_to("0"), Param::new("b", Type::Color).optional()];
const LENIENT_AFTER_DEFAULT: &[Param] = &[Param::new("a", Type::NUMBER).defaults_to("0"), Param::new("b", Type::Boolean).optional().lenient()];
fn holding(key: &str, v: Value) -> Value {
Value::Object([(key.to_string(), v)].into_iter().collect())
}
/// The lists of fixed shape count toward the nesting limit as the other lists do.
#[test]
fn id_lists_points_and_color_lists_count_toward_the_nesting_limit() {
let check = |depth, ty: &Type, v: &Value| check_value(&At::Root, depth, ty, v, false, false);
for (ty, v) in [(Type::Ids, json!([1])), (Type::Point, json!([1, 2])), (Type::Color, json!([1, 0, 0]))] {
assert!(check(MAX_DEPTH - 1, &ty, &v).is_ok(), "{ty:?}");
assert_eq!(check(MAX_DEPTH, &ty, &v).unwrap_err().problem, Problem::TooDeep, "{ty:?}");
}
assert!(check(MAX_DEPTH, &Type::Color, &json!("#ff0000")).is_ok());
}
#[test]
fn a_saved_retired_key_past_the_nesting_limit_is_refused() {
let params = holding("older", nested_lists(500_000));
let e = ParamSchema::new(WITH_DEFAULT, "").validate_saved(&params).unwrap_err();
assert_eq!(e.path, "older");
assert!(matches!(e.problem, Problem::Unknown { .. }));
std::mem::forget(params);
let kept = ParamSchema::new(WITH_DEFAULT, "").validate_saved(&holding("older", nested_lists(MAX_DEPTH))).unwrap().unwrap();
assert_eq!(kept["a"], json!(0));
assert_eq!(kept["older"], nested_lists(MAX_DEPTH));
assert!(ParamSchema::new(WITH_DEFAULT, "").validate_saved(&holding("older", nested_lists(MAX_DEPTH + 1))).is_err());
}
#[test]
fn a_color_object_past_the_nesting_limit_is_refused() {
let params = holding("b", holding("k", nested_lists(500_000)));
let e = ParamSchema::new(WITH_DEFAULT, "").validate(&params).unwrap_err();
assert_eq!(e.path, "b");
assert!(matches!(e.problem, Problem::WrongType { .. }));
std::mem::forget(params);
assert!(ParamSchema::new(WITH_DEFAULT, "").validate(&json!({"b": {"r": 1, "g": 0, "b": 0}})).is_ok());
}
#[test]
fn a_lenient_value_past_the_nesting_limit_is_refused() {
let params = holding("b", nested_lists(500_000));
let e = ParamSchema::new(LENIENT_AFTER_DEFAULT, "").validate(&params).unwrap_err();
assert_eq!(e.path, "b");
assert!(matches!(e.problem, Problem::WrongType { .. }));
std::mem::forget(params);
assert_eq!(ParamSchema::new(LENIENT_AFTER_DEFAULT, "").validate(&json!({"b": [1]})).unwrap().unwrap()["b"], json!([1]));
}
/// A key is cut in the error, and an unknown key is refused whatever it holds.
#[test]
fn a_hostile_key_is_cut_and_refused() {
let key = "k".repeat(1_000_000);
let e = one(Type::Boolean).validate(&json!({ key: true, "x": true })).unwrap_err();
assert_eq!(e.path.chars().count(), KEY_CHARS + 1);
assert!(e.path.ends_with('…') && e.to_string().chars().count() < 200, "{}", e.path.len());
for key in ["", "a.b", "a[0]", "`", "\u{0}", "名前"] {
let e = one(Type::Boolean).validate(&json!({ key: true, "x": true })).unwrap_err();
assert_eq!(e.path, key);
assert!(matches!(e.problem, Problem::Unknown { .. }));
}
assert_eq!(shown_key("short"), "short");
}
/// A schema that refers to itself, which only a mistake can write: checking values stops at the
/// nesting limit, and the writers finish.
static ENDLESS: Type = Type::Array(&ENDLESS);
#[test]
fn a_schema_that_refers_to_itself_stops_at_the_nesting_limit() {
let s = one(ENDLESS);
let e = s.validate(&json!({ "x": nested_lists(MAX_DEPTH + 2) })).unwrap_err();
assert_eq!(e.problem, Problem::TooDeep);
assert!(e.path.starts_with("x[0][0]"));
assert!(s.definition_problem().is_some_and(|p| p.contains("nests deeper")));
assert!(s.params_text().contains('…'));
assert!(s.to_json()["properties"]["x"].is_object());
assert_ne!(hash([("a", &s)]), 0);
}
const BAD_DEFAULT: &[Param] = &[Param::new("x", Type::NUMBER).defaults_to("\"zero\"")];
const NOT_JSON: &[Param] = &[Param::new("x", Type::NUMBER).defaults_to("{")];
const TWICE: &[Param] = &[Param::new("x", Type::NUMBER), Param::new("x", Type::String)];
const EMPTY_NAME: &[Param] = &[Param::new("", Type::NUMBER)];
const PATH_NAME: &[Param] = &[Param::new("a.b", Type::NUMBER)];
const NO_NAMES: &[Param] = &[Param::new("x", Type::Enum(&[]))];
const SAME_NAMES: &[Param] = &[Param::new("x", Type::Enum(&["a", "a"]))];
const EMPTY_RANGE: &[Param] = &[Param::new("x", Type::Number { min: Some(Bound::Exclusive(1.0)), max: Some(Bound::Inclusive(1.0)), unit: None })];
const BACKWARD: &[Param] = &[Param::new("x", Type::Integer { min: Some(2), max: Some(1) })];
const NOT_FINITE: &[Param] = &[Param::new("x", Type::Number { min: None, max: Some(Bound::Inclusive(f64::INFINITY)), unit: None })];
const REQUIRED_DEFAULT: &[Param] = &[Param { required: true, omitted: Omitted::Value("1"), ..Param::new("x", Type::NUMBER) }];
const DEEP_FAULT: &[Param] = &[Param::new("edits", Type::Array(&Type::Object(TWICE)))];
#[test]
fn a_schema_that_is_wrong_in_itself_is_reported() {
for (params, why) in [
(BAD_DEFAULT, "doesn't pass its type"),
(NOT_JSON, "isn't JSON"),
(TWICE, "listed twice"),
(EMPTY_NAME, "empty or holds"),
(PATH_NAME, "empty or holds"),
(NO_NAMES, "no names"),
(SAME_NAMES, "repeats"),
(EMPTY_RANGE, "no value can be"),
(BACKWARD, "no value can be"),
(NOT_FINITE, "isn't finite"),
(REQUIRED_DEFAULT, "required"),
(DEEP_FAULT, "`edits[].x` is listed twice"),
] {
let problem = ParamSchema::new(params, "").definition_problem();
assert!(problem.as_deref().is_some_and(|p| p.contains(why)), "{params:?}: {problem:?}");
}
assert_eq!(ParamSchema::new(VIEW, "").definition_problem(), None);
assert_eq!(ParamSchema::new(&[], "").definition_problem(), None);
}
/// Saved steps keep keys the schema doesn't name, at any depth; the values it names are checked.
#[test]
fn saved_steps_pass_retired_keys_and_check_their_values() {
let edits = one(Type::Array(&Type::Object(EDIT)));
let retired = json!({"x": [{"name": "A", "old": 1}], "older": true});
assert!(edits.validate(&retired).is_err());
let filled = edits.validate_saved(&retired).unwrap().unwrap();
assert_eq!(filled["x"][0]["delete"], json!(false), "defaults are filled in");
assert_eq!(filled["older"], json!(true), "the keys stay");
assert_eq!(edits.validate_saved(&json!({"x": [{"name": 5}], "older": true})).unwrap_err().path, "x[0].name");
assert_eq!(edits.validate_saved(&json!({"older": true})).unwrap_err().problem, Problem::Missing);
}
/// Every type's JSON form follows the 2020-12 rules, and an independent validator of those rules
/// agrees with [`ParamSchema::validate`] on each value.
#[test]
fn the_json_form_and_the_validator_agree_with_the_2020_12_rules() {
const NULLABLE: &[Param] = &[Param::new("a", Type::String).optional().null_omitted(), Param::new("b", Type::Boolean).defaults_to("true")];
let types = [
Type::NUMBER,
Type::Number { min: Some(Bound::Exclusive(0.0)), max: Some(Bound::Inclusive(1.0)), unit: Some("pt") },
Type::Number { min: Some(Bound::Inclusive(-1.0)), max: Some(Bound::Exclusive(1.0)), unit: None },
Type::Integer { min: None, max: None },
Type::Integer { min: Some(1), max: Some(25) },
Type::Boolean,
Type::String,
Type::Enum(&["a", "b"]),
Type::Id,
Type::Ids,
Type::Color,
Type::Point,
Type::Object(EDIT),
Type::Object(NULLABLE),
Type::Object(&[]),
Type::Array(&Type::NUMBER),
Type::Array(&Type::Object(EDIT)),
];
let values = [
json!(null),
json!(true),
json!(0),
json!(1),
json!(2.0),
json!(25.5),
json!(-1),
json!(-1.0),
json!(1e300),
json!(MAX_ID),
json!(MAX_ID + 1),
json!(u64::MAX),
json!(""),
json!("a"),
json!("c"),
json!([]),
json!([1, 2]),
json!([1, 2, 3]),
json!([1, "2"]),
json!([[1]]),
json!({}),
json!({"name": "A"}),
json!({"name": "A", "delete": false}),
json!({"name": "A", "delete": null}),
json!({"name": "A", "other": 1}),
json!({"a": null, "b": false}),
json!({"a": 5}),
json!([{"name": "A"}]),
json!([{"name": 1}]),
];
for ty in types {
let schema = one(ty);
let written = schema.to_json();
conformance::check_schema(&written, "#").unwrap_or_else(|e| panic!("{ty:?}: {e}\n{written:#}"));
assert_eq!(written["$schema"], "https://json-schema.org/draft/2020-12/schema");
for v in &values {
let params = json!({ "x": v });
let local = schema.validate(&params).is_ok();
assert_eq!(local, conformance::instance_valid(&written, &params), "{ty:?} on {v}: {written}");
}
}
for params in [VIEW, EDIT, NULLABLE] {
let schema = ParamSchema::new(params, "").deprecated(1);
conformance::check_schema(&schema.to_json(), "#").unwrap();
}
}
/// The independent checker refuses what the 2020-12 rules refuse, so its passes above mean
/// something.
#[test]
fn the_2020_12_checker_refuses_invalid_schemas() {
for bad in [
json!(5),
json!({"type": "float"}),
json!({"enum": []}),
json!({"enum": [1, 1]}),
json!({"required": ["a", "a"]}),
json!({"required": [1]}),
json!({"properties": []}),
json!({"properties": {"a": 5}}),
json!({"items": 1}),
json!({"prefixItems": []}),
json!({"anyOf": []}),
json!({"minimum": "0"}),
json!({"minItems": -1}),
json!({"description": 5}),
json!({"deprecated": "yes"}),
json!({"type": "number", "default": "zero"}),
json!({"$schema": "not a uri"}),
json!({"minimun": 0}),
] {
assert!(conformance::check_schema(&bad, "#").is_err(), "{bad}");
}
assert!(conformance::instance_valid(&json!({"type": "integer"}), &json!(2.0)));
assert!(!conformance::instance_valid(&json!({"type": "integer"}), &json!(2.5)));
assert!(!conformance::instance_valid(&json!({"prefixItems": [{"type": "number"}], "items": false}), &json!([1, 2])));
}
#[test]
fn booleans_and_strings_take_only_their_own_type() {
assert!(passes(Type::Boolean, json!(true)) && passes(Type::Boolean, json!(false)));
assert!(!passes(Type::Boolean, json!("true")) && !passes(Type::Boolean, json!(1)) && !passes(Type::Boolean, json!(null)));
assert!(passes(Type::String, json!("")) && passes(Type::String, json!("View 1")));
assert!(!passes(Type::String, json!(5)) && !passes(Type::String, json!(["a"])));
assert_eq!(one(Type::Boolean).validate(&json!({"x": "yes"})).unwrap_err().to_string(), "`x` must be true or false, not \"yes\"");
}
#[test]
fn an_enum_takes_one_of_its_names() {
let modes = Type::Enum(&["rgb", "cmyk"]);
assert!(passes(modes, json!("rgb")) && passes(modes, json!("cmyk")));
assert!(!passes(modes, json!("RGB")) && !passes(modes, json!("lab")) && !passes(modes, json!(0)));
assert_eq!(one(modes).validate(&json!({"x": "lab"})).unwrap_err().to_string(), "`x` must be one of \"rgb\", \"cmyk\", not \"lab\"");
}
#[test]
fn ids_are_non_negative_integers() {
assert!(passes(Type::Id, json!(0)) && passes(Type::Id, json!(42)));
assert!(!passes(Type::Id, json!(-1)) && !passes(Type::Id, json!(1.5)) && !passes(Type::Id, json!("42")));
assert!(passes(Type::Ids, json!([])) && passes(Type::Ids, json!([3, 4])));
assert!(!passes(Type::Ids, json!(3)) && !passes(Type::Ids, json!([3, "4"])) && !passes(Type::Ids, json!([-3])));
}
#[test]
fn colors_and_points_have_their_shapes() {
assert!(passes(Type::Color, json!("#ff0000")) && passes(Type::Color, json!([1, 0, 0])) && passes(Type::Color, json!({"gray": 50})));
assert!(!passes(Type::Color, json!(5)) && !passes(Type::Color, json!([1, 0])) && !passes(Type::Color, json!([1, 0, "x"])));
assert!(passes(Type::Point, json!([0, -2.5])));
assert!(!passes(Type::Point, json!([1])) && !passes(Type::Point, json!([1, 2, 3])) && !passes(Type::Point, json!([1, "2"])));
assert!(!passes(Type::Point, json!({"x": 1, "y": 2})));
}
const EDIT: &[Param] = &[Param::new("name", Type::String), Param::new("delete", Type::Boolean).defaults_to("false")];
#[test]
fn objects_and_arrays_name_the_path_of_the_value_inside() {
let edits = Type::Array(&Type::Object(EDIT));
assert!(passes(edits, json!([])) && passes(edits, json!([{"name": "A"}, {"name": "B", "delete": true}])));
let err = |v: Value| one(edits).validate(&json!({ "x": v })).unwrap_err();
assert_eq!(err(json!([{"name": "A"}, {"name": "B", "delete": "no"}])).path, "x[1].delete");
assert_eq!(err(json!([{"name": "A"}, {"delete": true}])).to_string(), "missing `x[1].name`");
let unknown = err(json!([{"name": "A", "nmae": "B"}]));
assert_eq!((unknown.path.as_str(), unknown.problem), ("x[0].nmae", Problem::Unknown { keys: vec!["name", "delete"] }));
assert_eq!(err(json!({"name": "A"})).to_string(), "`x` must be a list, not {\"name\":\"A\"}");
assert_eq!(err(json!(["A"])).to_string(), "`x[0]` must be an object, not \"A\"");
// Defaults inside are filled in too.
let filled = one(edits).validate(&json!({"x": [{"name": "A"}]})).unwrap();
assert_eq!(filled, Some(json!({"x": [{"name": "A", "delete": false}]})));
}
const VIEW: &[Param] = &[
Param::new("name", Type::String).default_note("\"View N\"").null_omitted(),
Param::new("center", Type::Point),
Param::new("rotation", Type::Number { min: None, max: None, unit: Some("deg") }).defaults_to("0"),
];
#[test]
fn keys_requirements_nulls_and_defaults() {
let s = ParamSchema::new(VIEW, "save a view").returns("{name}");
// Unknown keys are refused first, naming the key and the keys the command takes.
let e = s.validate(&json!({"centre": [0, 0]})).unwrap_err();
assert_eq!((e.path.as_str(), e.problem), ("centre", Problem::Unknown { keys: vec!["name", "center", "rotation"] }));
assert_eq!(s.validate(&json!({})).unwrap_err(), ParamError { path: "center".into(), problem: Problem::Missing });
// Null counts as omitted only where the schema says so.
assert_eq!(s.validate(&json!({"center": [1, 2], "name": null, "rotation": 15})).unwrap(), None);
assert_eq!(s.validate(&json!({"center": [1, 2], "rotation": null})).unwrap_err().path, "rotation");
// An omitted value with a default gets it; one with a note is left to the command.
assert_eq!(s.validate(&json!({"center": [1, 2]})).unwrap(), Some(json!({"center": [1, 2], "rotation": 0})));
// Params that aren't an object are refused; null params are `{}`.
assert_eq!(s.validate(&json!(5)).unwrap_err().to_string(), "the params must be an object, not 5");
assert_eq!(s.validate(&Value::Null).unwrap_err().path, "center");
let none = ParamSchema::new(&[], "");
assert_eq!(none.validate(&Value::Null).unwrap(), None);
assert_eq!(none.validate(&json!({"a": 1})).unwrap_err().to_string(), "unknown parameter `a`; the object takes no keys");
}
const LENIENT: &[Param] = &[Param::new("on", Type::Boolean).optional().lenient(), Param::new("size", Type::NUMBER).optional().lenient()];
#[test]
fn lenient_parameters_pass_values_of_another_type_to_the_command() {
let s = ParamSchema::new(LENIENT, "");
assert_eq!(s.validate(&json!({"on": "yes", "size": "12"})).unwrap(), None);
// Unknown keys are still refused.
assert!(s.validate(&json!({"of": true})).is_err());
// The JSON form states the documented type, so a validator of that form refuses what passes here.
let written = s.to_json();
assert_eq!(written["properties"]["on"]["x-lenient"], true);
assert!(!conformance::instance_valid(&written, &json!({"on": "yes"})));
assert!(conformance::instance_valid(&written, &json!({"on": true})));
}
#[test]
fn the_params_text_lists_each_parameter_with_its_type() {
let s = ParamSchema::new(VIEW, "save a view").returns("{name}");
assert_eq!(s.params_text(), "{name?: string (default: \"View N\"), center: [x, y], rotation?: number deg (default: 0)} save a view → {name}");
const ALL: &[Param] = &[
Param::new("a", Type::Integer { min: Some(1), max: Some(25) }),
Param::new("b", Type::Enum(&["x", "y"])).optional(),
Param::new("c", Type::Ids).optional().doc("instead of the selection"),
Param::new("d", Type::Color).optional().deprecated(2),
Param::new("e", Type::Array(&Type::Object(EDIT))).optional(),
Param::new("f", Type::Number { min: Some(Bound::Exclusive(0.0)), max: Some(Bound::Inclusive(10.0)), unit: Some("pt") }).optional(),
];
assert_eq!(
ParamSchema::new(ALL, "").params_text(),
"{a: integer 1 to 25, b?: \"x\"|\"y\", c?: [id…] (instead of the selection), d?: color (deprecated), \
e?: [{name: string, delete?: bool (default: false)}…], f?: number > 0 and <= 10 pt}"
);
}
#[test]
fn the_json_form_is_an_object_schema() {
let s = ParamSchema::new(VIEW, "save a view").returns("{name}").writes(Writes::Document).cost(2);
let j = s.to_json();
assert_eq!(j["$schema"], DIALECT);
assert_eq!(j["type"], "object");
assert_eq!(j["additionalProperties"], false);
assert_eq!(j["required"], json!(["center"]));
assert_eq!(j["properties"]["name"]["anyOf"], json!([{"type": "string"}, {"type": "null"}]));
assert_eq!(j["properties"]["name"]["x-default"], "\"View N\"");
assert_eq!(j["properties"]["rotation"], json!({"type": "number", "x-unit": "deg", "default": 0, "x-since": 1}));
assert_eq!(j["properties"]["center"]["prefixItems"], json!([{"type": "number"}, {"type": "number"}]));
assert_eq!((j["x-cost"].clone(), j["x-writes"].clone(), j["x-returns"].clone()), (json!(2), json!("document"), json!("{name}")));
let range = one(Type::Number { min: Some(Bound::Exclusive(0.0)), max: Some(Bound::Inclusive(1.0)), unit: None }).to_json();
assert_eq!(range["properties"]["x"], json!({"type": "number", "exclusiveMinimum": 0.0, "maximum": 1.0, "x-since": 1}));
}
/// Null params read as `{}`, so the root of the JSON form allows null exactly when `{}` passes.
/// A nested object does not read null as `{}`.
#[test]
fn the_json_form_allows_null_params_when_no_parameter_is_required() {
const OPTIONAL: &[Param] = &[Param::new("inner", Type::Object(&[Param::new("y", Type::Boolean).optional()])).optional()];
let optional = ParamSchema::new(OPTIONAL, "");
let written = optional.to_json();
conformance::check_schema(&written, "#").unwrap();
assert_eq!(written["type"], json!(["object", "null"]));
assert_eq!(written["properties"]["inner"]["type"], "object");
let required = one(Type::Boolean);
assert_eq!(required.to_json()["type"], "object");
for schema in [optional, required] {
let written = schema.to_json();
for params in [json!(null), json!({}), json!(5), json!([]), json!("x"), json!({"inner": null}), json!({"inner": {}})] {
assert_eq!(schema.validate(&params).is_ok(), conformance::instance_valid(&written, &params), "{params} against {written}");
}
}
assert!(optional.validate(&json!(null)).is_ok());
assert!(required.validate(&json!(null)).is_err());
}
#[test]
fn the_hash_follows_every_schema_but_not_their_order() {
let a = ParamSchema::new(VIEW, "save a view");
let b = ParamSchema::new(LENIENT, "");
let h = hash([("view.a", &a), ("view.b", &b)]);
assert_eq!(h, hash([("view.b", &b), ("view.a", &a)]));
assert_ne!(h, hash([("view.a", &a)]));
assert_ne!(h, hash([("view.a", &a), ("view.c", &b)]));
let changed = ParamSchema::new(VIEW, "save a view").since(2);
assert_ne!(h, hash([("view.a", &changed), ("view.b", &b)]));
}
+4
View File
@@ -475,6 +475,10 @@ pub struct PatternBrush {
pub side_frame: Option<Rect>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub side_swatch: Option<String>,
/// Art for the corners where the path turns towards the side tile's top (`-y`); `inner_corner`
/// is the art for the corners where it turns the other way. Both are drawn as the corner that
/// joins a side tile on its right to one below it, and each corner tile is turned so that
/// those two arms meet the sides.
#[serde(skip_serializing_if = "Option::is_none")]
pub outer_corner: Option<Node>,
#[serde(default, skip_serializing_if = "Option::is_none")]
+96 -1
View File
@@ -1,6 +1,6 @@
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, StrokeLayer};
use vectorcraft_geom::{Affine, BezPath, Point, Rect, shapes};
use vectorcraft_geom::{Affine, BezPath, Point, Rect, Vec2, shapes};
use super::*;
@@ -299,6 +299,101 @@ fn pattern_places_corner_tiles() {
}
}
/// A pattern brush whose corner tiles have a 4 × 4 pt frame and, as art, a 2 × 2 pt square in the
/// top-left quarter of the frame. Corner art joins a side tile on its right to one below it, so
/// that quarter is on the outside of the turn. `inner` and `outer` say which kinds of corner have
/// art; `flips` are the brush's Flip Along and Flip Across.
fn marked_corner_brush(inner: bool, outer: bool, (flip_along, flip_across): (bool, bool)) -> Brush {
let marker =
Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, -2.0, 2.0, 0.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
let mut b = pattern_brush(PatternFit::Stretch, false);
if let BrushKind::Pattern(p) = &mut b.kind {
let frame = Some(Rect::new(0.0, -2.0, 4.0, 2.0));
if inner {
(p.inner_corner, p.inner_corner_frame) = (Some(marker.clone()), frame);
}
if outer {
(p.outer_corner, p.outer_corner_frame) = (Some(marker), frame);
}
(p.flip_along, p.flip_across) = (flip_along, flip_across);
}
b
}
/// Each combination of corner art (both kinds, inner only, outer only) and of the two flips.
fn marked_corner_brushes() -> Vec<(String, Brush)> {
let mut v = vec![];
for (inner, outer) in [(true, true), (true, false), (false, true)] {
for flips in [(false, false), (true, false), (false, true), (true, true)] {
v.push((format!("inner {inner}, outer {outer}, flips {flips:?}"), marked_corner_brush(inner, outer, flips)));
}
}
v
}
/// The bounds of the 2 × 2 pt corner markers among `out`, turned or not.
fn marker_bounds(out: &[Node]) -> Vec<Rect> {
out.iter().filter_map(Node::geometric_bounds).filter(|r| r.width() < 3.0 && r.height() < 3.0).collect()
}
/// Corner tiles are square to the sides at a right angle and turn 90° with each turn of the path:
/// on a square drawn either way round, each corner's marker fills the quarter of the band's corner
/// outside the turn, with the brush flipped or not and with art for one kind of corner only
/// (#6110).
#[test]
fn pattern_corner_tiles_are_square_to_the_sides() {
let doc = Document::new(1.0, 1.0);
let sq = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)).to_bezpath();
let mut reversed = BezPath::new();
reversed.move_to((0.0, 0.0));
for (x, y) in [(0.0, 100.0), (100.0, 100.0), (100.0, 0.0)] {
reversed.line_to((x, y));
}
reversed.close_path();
// The square turns the same way at all four corners, and the reversed square the other way,
// so one draws only inner corner tiles and the other only outer ones.
for (name, brush) in marked_corner_brushes() {
for path in [&sq, &reversed] {
let out = stroke_pieces(&doc, &brush, path, &stroke(1.0));
let marks = marker_bounds(&out);
assert_eq!(marks.len(), 4, "{name}: one marker a corner");
for (corner, outside) in SQUARE_CORNERS {
let want = Rect::from_points(corner, outside);
assert!(
marks
.iter()
.any(|r| near(r.x0, want.x0, 1e-6) && near(r.y0, want.y0, 1e-6) && near(r.x1, want.x1, 1e-6) && near(r.y1, want.y1, 1e-6)),
"{name}: the marker at {corner:?} fills {want:?}: {marks:?}"
);
}
}
}
}
/// At a corner that is not a right angle, a corner tile splits the difference between the two
/// sides: its marker lies on the line that halves the angle, outside the turn, for sharp and
/// shallow turns either way. Near a hairpin the marker moves smoothly towards the line the path
/// arrives on.
#[test]
fn pattern_corner_tiles_sit_on_the_corners_diagonal() {
let doc = Document::new(1.0, 1.0);
for (name, brush) in marked_corner_brushes() {
for turn in [-179.9_f64, -170.0, -135.0, -60.0, -45.0, 45.0, 60.0, 135.0, 170.0, 179.9] {
let (a, b) = (Vec2::new(1.0, 0.0), Vec2::new(turn.to_radians().cos(), turn.to_radians().sin()));
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
bp.line_to((50.0, 0.0));
bp.line_to(Point::new(50.0, 0.0) + b * 50.0);
let out = stroke_pieces(&doc, &brush, &bp, &stroke(1.0));
let marks = marker_bounds(&out);
assert_eq!(marks.len(), 1, "{name}, {turn}°: one corner marker");
let away = a - b;
let want = Point::new(50.0, 0.0) + away / away.hypot() * 2.0_f64.sqrt();
assert!(marks[0].center().distance(want) < 1e-6, "{name}, {turn}°: the marker is at {:?}, not {want:?}", marks[0].center());
}
}
}
/// The 10 × 4 pt side tile of [`pattern_brush`] with the given corner sources and no corner art.
fn auto_corner_brush(outer: Option<CornerSource>, inner: Option<CornerSource>) -> Brush {
let mut b = pattern_brush(PatternFit::Stretch, false);
+10 -6
View File
@@ -879,12 +879,16 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
};
trims.push(None);
corner_half = corner_half.max(bb.width() * k / 2.0);
let bis = a + b;
let bis = if bis.hypot() < 1e-9 { a } else { bis / bis.hypot() };
let xf = Affine::translate(t.verts[i].to_vec2())
* Affine::rotate(bis.y.atan2(bis.x))
* Affine::scale(k)
* Affine::translate(-bb.center().to_vec2());
// Inner and outer corner art is the corner that joins a side tile on its right to one
// below it, so its arms point along +x and +y (as the flips leave them). The tile is
// turned so that the line halving its arms lies on the line halving the sides at the
// corner, back along the incoming side and on along the outgoing one: at a right angle
// the arms meet the side tiles, and at other angles the difference is split between
// the two sides (#6110).
let arms = Vec2::new(if pb.flip_along { -1.0 } else { 1.0 }, if pb.flip_across { -1.0 } else { 1.0 });
let sides = b - a;
let angle = sides.y.atan2(sides.x) - arms.y.atan2(arms.x);
let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(k) * Affine::translate(-bb.center().to_vec2());
let mut n = art.clone();
n.transform(xf, true);
out.take(Some(n));
+72
View File
@@ -308,6 +308,78 @@ impl Default for DxfOptions {
}
}
/// A named set of DXF options (the `dxfPreset` param): the options it sets, and the ones a set of
/// options matches.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DxfPreset {
/// The options as chosen (the export's defaults for those left out).
#[default]
Custom,
/// For CNC and CAM cutting software: version 2000 (the oldest version that has both lightweight
/// polylines and lineweights), 1 mm = 1 unit, 256 indexed colors (all version 2000 holds), Maximize
/// Editability with Alter Paths off (every stroke a center line), Outline Text (type as paths),
/// and placed images as PNG.
Cnc,
}
impl DxfPreset {
pub const ALL: [Self; 2] = [Self::Custom, Self::Cnc];
/// The `dxfPreset` param value.
pub fn id(self) -> &'static str {
match self {
Self::Custom => "custom",
Self::Cnc => "cnc",
}
}
pub fn label(self) -> &'static str {
match self {
Self::Custom => "Custom",
Self::Cnc => "CNC / CAM",
}
}
/// A preset by id (`custom`, `cnc`), any case.
pub fn from_id(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|p| s.trim().eq_ignore_ascii_case(p.id()))
}
/// The options the preset sets (Custom: the defaults); the region and crop are the defaults.
pub fn options(self) -> DxfOptions {
match self {
Self::Custom => DxfOptions::default(),
Self::Cnc => DxfOptions {
version: DxfVersion::R2000,
unit: Unit::Millimeters,
scale: 1.0,
scale_lineweights: false,
colors: ColorDepth::Aci256,
raster: RasterFormat::Png,
preserve: Preserve::Editability,
alter_paths: false,
outline_text: true,
..DxfOptions::default()
},
}
}
/// The preset `o` matches: CNC / CAM when every option it sets is as it sets it, else Custom.
pub fn of(o: &DxfOptions) -> Self {
let c = Self::Cnc.options();
let same = o.version == c.version
&& o.unit == c.unit
&& o.scale == c.scale
&& o.scale_lineweights == c.scale_lineweights
&& o.colors == c.colors
&& o.raster == c.raster
&& o.preserve == c.preserve
&& o.alter_paths == c.alter_paths
&& o.outline_text == c.outline_text;
if same { Self::Cnc } else { Self::Custom }
}
}
/// An image file a drawing links to, to be written next to it under `name`.
#[derive(Clone, Debug)]
pub struct DxfImage {
+3 -3
View File
@@ -1227,10 +1227,10 @@ impl<'a> Scene<'a> {
let Some(&first) = run.first() else { continue };
let lo = run.iter().map(|g| g.byte).min().unwrap_or(first.byte);
let hi = run.iter().map(|g| g.byte + g.len).max().unwrap_or(lo);
// A right-to-left paragraph's marker is drawn with its tab first and its number's
// period at the number's left; the TEXT entity holds the characters in that order.
// A right-to-left paragraph's marker is drawn with its number's period at the
// number's left; the TEXT entity holds the characters in that order.
let marker = chunk.first().and_then(|(_, _, m)| *m).map(|m| match m.text.strip_suffix('.') {
Some(number) if m.tab == m.glyphs.start => format!(".{number}"),
Some(number) if layout.glyphs.get(m.tab).is_some_and(|g| g.rtl) => format!(".{number}"),
_ => m.text.clone(),
});
let Some(s) = marker.as_deref().or_else(|| plain.get(lo..hi).map(str::trim_end)).filter(|s| !s.trim().is_empty()) else { continue };
+45 -4
View File
@@ -823,6 +823,30 @@ fn units_scale_coordinates_and_set_insunits() {
assert!(export(&d, &DxfOptions { scale: f64::NAN, ..opts(&d) }).is_err());
}
#[test]
fn the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_strokes_as_lines() {
let mut d = text_doc("Cut", 20.0);
let layer = d.layers[0].id;
let frame = path(&mut d, shapes::rectangle(Rect::new(5.0, 5.0, 195.0, 95.0)), Paint::None, Paint::solid(Color::BLACK), 10.0);
d.insert(Some(layer), usize::MAX, frame).unwrap();
let o = DxfOptions { region: d.artboards[0].rect, ..DxfPreset::Cnc.options() };
let out = export(&d, &o).unwrap();
let p = pairs(&out.bytes);
assert_eq!(header(&p, "$ACADVER").as_deref(), Some("AC1015"));
assert_eq!(header(&p, "$INSUNITS").as_deref(), Some("4"));
let k = kinds(&out);
assert!(!k.iter().any(|k| matches!(k.as_str(), "TEXT" | "MTEXT" | "IMAGE")), "type is paths: {k:?}");
assert!(k.len() > 2, "the glyphs' outlines: {k:?}");
// The 10 pt stroke (wider than the widest lineweight) is one center line, not a filled outline.
assert_eq!(k.last().map(String::as_str), Some("LWPOLYLINE"), "{k:?}");
assert_ne!(k.get(k.len() - 2).map(String::as_str), Some("LWPOLYLINE"), "{k:?}");
assert!(out.images.is_empty());
assert_eq!(DxfPreset::of(&o), DxfPreset::Cnc);
assert_eq!(DxfPreset::of(&DxfOptions { colors: ColorDepth::True, ..o.clone() }), DxfPreset::Custom);
assert_eq!(DxfPreset::of(&DxfOptions::default()), DxfPreset::Custom);
assert_eq!(DxfPreset::from_id(" CNC "), Some(DxfPreset::Cnc));
}
#[test]
fn layers_become_dxf_layers() {
let mut d = shapes_doc();
@@ -1052,15 +1076,15 @@ fn a_bullet_is_text_of_its_own_before_its_paragraph() {
/// A numbered list paragraph's number and period are a TEXT entity of their own where they are
/// drawn, in the order they are drawn: in a right-to-left paragraph the period comes first, at the
/// number's left.
/// number's left, with the marker aligned left or right.
#[test]
fn a_number_is_text_of_its_own_before_its_paragraph() {
use vectorcraft_doc::text::{NumberStyle, ParaList};
let numbered = |text: &str, count: u32| {
use vectorcraft_doc::text::{ListAlign, NumberStyle, ParaList};
let numbered_aligned = |text: &str, count: u32, align: ListAlign| {
let mut d = text_doc(text, 20.0);
let id = d.layers[0].children().unwrap()[0].id;
if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) {
t.para.list = Some(ParaList::numbered(NumberStyle::Arabic));
t.para.list = Some(ParaList::numbered(NumberStyle::Arabic).aligned(align));
t.para.left_indent = 30.0;
t.para.first_line_indent = -30.0;
t.list_count = count;
@@ -1068,10 +1092,27 @@ fn a_number_is_text_of_its_own_before_its_paragraph() {
let out = export(&d, &DxfOptions { version: DxfVersion::R2018, preserve: Preserve::Editability, ..opts(&d) }).unwrap();
entities(&out).iter().map(|e| (get(e, 1).map(str::to_string), all(e, 10)[0])).collect::<Vec<_>>()
};
let numbered = |text: &str, count: u32| numbered_aligned(text, count, ListAlign::Left);
assert_eq!(numbered("Item", 11), [(Some("12.".to_string()), 10.0), (Some("Item".to_string()), 40.0)]);
let rtl = numbered("שלום", 11);
assert_eq!(rtl.iter().map(|(s, _)| s.clone().unwrap_or_default()).collect::<Vec<_>>(), ["שלום", ".12"]);
assert!(rtl[1].1 > rtl[0].1, "the number right of the text: {rtl:?}");
// Aligned right, the number keeps its order and moves right, against the text.
let right = numbered_aligned("Item", 11, ListAlign::Right);
assert_eq!((right[0].0.as_deref(), right[1].clone()), (Some("12."), (Some("Item".to_string()), 40.0)));
assert!(right[0].1 > 10.0 && right[0].1 < 40.0, "{right:?}");
let rtl = numbered_aligned("שלום", 11, ListAlign::Right);
assert_eq!(rtl.iter().map(|(s, _)| s.clone().unwrap_or_default()).collect::<Vec<_>>(), ["שלום", ".12"]);
// A mixed paragraph: the period follows the paragraph's direction, not the script of the
// words it holds, with either alignment.
let marker = |text: &str, align: ListAlign| {
let out = numbered_aligned(text, 11, align);
out.into_iter().filter_map(|(s, _)| s).find(|s| s.contains("12")).unwrap_or_default()
};
for align in [ListAlign::Left, ListAlign::Right] {
assert_eq!(marker("Item שלום", align), "12.", "{align:?}");
assert_eq!(marker("שלום Item", align), ".12", "{align:?}");
}
}
/// Area type that Shrink Text to Fit scales down is written at the height it draws at.
+191 -102
View File
@@ -1,19 +1,26 @@
//! "VectorCraft Generic CMYK (SWOP-like)": our own parametric press model.
//!
//! We can't redistribute Adobe's or ECI's characterisation profiles, so the built-in CMYK space is
//! a small physical model instead of an ICC LUT. It is *ours* and only SWOP-*like*: the numbers
//! are rounded, typical values for coated web offset, not a measured dataset.
//! a small physical model instead of an ICC LUT. It is *ours* and only SWOP-*like*. Two of its
//! figures are published values for SWOP printing: the tone value increase of each ink at 40% and
//! 50% from CGATS TR 001 (<https://registry.color.org/cmyk-registry/cgats_tr_001>), and the 300%
//! total ink limit (<https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications>).
//! The paper, solid and overprint colors and the black-generation curve are VectorCraft's own values.
//!
//! * **Forward (CMYK → XYZ):** each ink's nominal dot area is widened by a parabolic dot-gain
//! curve (`a + 4·g·a·(1−a)`, i.e. `g` gain at 50%); the effective areas mix the eight CMY
//! Neugebauer primaries with Demichel weights; black is mixed in the same way against
//! "primary + K" colours whose optical densities add but saturate towards a maximum density
//! (normalised so K on paper is exact), so rich blacks don't multiply to an unrealistic depth.
//! * **Forward (CMYK → XYZ):** each ink's nominal dot area `a` is widened by a tone curve
//! `a + 4·g·a·(1−a)·(1 + s·(2a−1))` that passes through the TR 001 tone value increase at 50%
//! (`g`) and 40% (which sets `s`). The effective areas mix the 16 Neugebauer primaries (paper and
//! every solid and overprint of C, M, Y and K, media-relative) with Demichel weights, linearly in
//! XYZ, so a single ink's colorimetric tone value increase (Murray–Davies) is the TR 001 value.
//! * **Inverse (Lab → CMYK):** damped, bounded Gauss–Newton on the forward model solves CMY for a
//! fixed K. Black generation is GCR: solve CMY with K = 0, take the grey component
//! `min(C, M, Y)`, map it through the black-generation curve to K, re-solve CMY. Under-colour
//! fixed K. Black generation is GCR: solve CMY with K = 0, take the gray component
//! `min(C, M, Y)`, add [`BlackGeneration::shortfall`] for each L* point by which that solve stays
//! lighter than the target, map the sum through the black curve to K, re-solve CMY. Under-color
//! removal enforces the total area coverage (TAC) limit by adding K and re-solving, then scaling
//! CMY as a last resort.
//! CMY as a last resort. The black point, which source black separates to and which displays as
//! black with black-point compensation, is [`BlackGeneration::black_point_k`] black with neutral
//! CMY filling the TAC. With compensation, a build darker than it in every XYZ channel also
//! displays as black (see [`GenericCmyk::display_xyz`]).
//! * **Rendering intents:** colorimetric intents map the source white to paper (relative) or not
//! (absolute) and clip; perceptual applies black-point compensation plus soft chroma compression
//! against a gamut boundary descriptor (segment maxima of the forward model); saturation keeps
@@ -24,50 +31,82 @@ use std::sync::OnceLock;
use super::Intent;
use super::lab::{D50, Lab, delta_e2000, lab_to_xyz, srgb_to_lab, xyz_to_lab, xyz_to_srgb};
/// Black generation strength.
/// Black generation.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BlackGeneration {
/// Grey component below which no black is generated.
pub start: f32,
/// Maximum black.
pub max_k: f32,
/// Curve exponent (>1 = lighter black in the midtones).
pub gamma: f32,
/// The black curve as `(x, K)` knots with rising `x`, read by linear interpolation. `x` is the
/// gray component of the solve without black plus [`Self::shortfall`] per L* point by which
/// that solve stays lighter than the target.
pub curve: [(f32, f32); 13],
/// Added to the gray component for each L* point the black-free solve stays too light.
pub shortfall: f32,
/// Black of the black point, whose CMY is neutral and fills the TAC.
pub black_point_k: f32,
}
/// Parameters of the parametric press model.
#[derive(Clone, Debug)]
pub struct GenericCmykParams {
pub name: &'static str,
/// Paper color (absolute Lab, D50).
pub paper: Lab,
/// Solid overprints, Demichel order: C, M, CM, Y, CY, MY, CMY.
pub solids: [Lab; 7],
pub black: Lab,
/// Dot gain at 50% per ink (C, M, Y, K).
pub dot_gain: [f32; 4],
/// Media-relative Lab of the solids and overprints, Demichel order (index `c | m<<1 | y<<2 |
/// k<<3`, paper left out): C, M, CM, Y, CY, MY, CMY, then K, CK, MK, CMK, YK, CYK, MYK, CMYK.
pub primaries: [Lab; 15],
/// Tone value increase at 50% per ink (C, M, Y, K).
pub tvi50: [f32; 4],
/// Tone value increase at 40% per ink (C, M, Y, K).
pub tvi40: [f32; 4],
/// Total area coverage limit (sum of inks, 1.0 = 100%).
pub tac: f32,
pub bg: BlackGeneration,
}
/// Rounded, typical SWOP-like values (not measured data).
/// The built-in SWOP-like press: TR 001 tone value increase, a 300% ink limit, and VectorCraft's
/// own paper, primaries and black curve.
pub fn swop_like() -> GenericCmykParams {
GenericCmykParams {
name: super::GENERIC_CMYK,
paper: Lab::new(93.0, -0.5, 2.5),
solids: [
Lab::new(55.0, -37.0, -50.0), // C
Lab::new(48.0, 74.0, -3.0), // M
Lab::new(24.0, 22.0, -46.0), // CM (blue)
Lab::new(89.0, -5.0, 93.0), // Y
Lab::new(50.0, -65.0, 27.0), // CY (green)
Lab::new(47.0, 68.0, 48.0), // MY (red)
Lab::new(24.0, 1.0, 0.0), // CMY
primaries: [
Lab::new(65.7, -42.6, -47.2), // C
Lab::new(55.5, 76.2, -9.4), // M
Lab::new(31.1, 20.3, -49.7), // CM (blue)
Lab::new(96.2, -7.0, 90.1), // Y
Lab::new(61.0, -68.4, 30.1), // CY (green)
Lab::new(55.0, 69.8, 45.0), // MY (red)
Lab::new(28.3, 0.7, -0.5), // CMY
Lab::new(21.5, 0.8, -0.9), // K
Lab::new(15.9, -8.4, -10.0), // CK
Lab::new(14.7, 15.4, -1.0), // MK
Lab::new(11.2, 8.9, -6.6), // CMK
Lab::new(20.2, -2.4, 12.0), // YK
Lab::new(15.7, -14.6, 4.6), // CYK
Lab::new(14.5, 11.2, 5.7), // MYK
Lab::new(11.0, -0.7, 0.1), // CMYK
],
black: Lab::new(19.0, 0.5, 0.5),
dot_gain: [0.20, 0.20, 0.20, 0.22],
tvi50: [0.200, 0.176, 0.168, 0.216],
tvi40: [0.200, 0.173, 0.167, 0.219],
tac: 3.0,
bg: BlackGeneration { start: 0.1, max_k: 0.95, gamma: 1.25 },
bg: BlackGeneration {
curve: [
(0.0, 0.0),
(0.25, 0.0),
(0.35, 0.006),
(0.45, 0.059),
(0.55, 0.139),
(0.65, 0.23),
(0.75, 0.322),
(0.85, 0.41),
(0.95, 0.511),
(1.05, 0.6),
(1.2, 0.733),
(1.35, 0.858),
(1.5, 1.0),
],
shortfall: 0.03,
black_point_k: 0.9,
},
}
}
@@ -83,11 +122,12 @@ const GBD_H: usize = 72; // 5° bins
pub struct GenericCmyk {
pub params: GenericCmykParams,
/// XYZ of the 8 CMY primaries (index = c | m<<1 | y<<2), without and with K.
prim: [[f32; 3]; 8],
prim_k: [[f32; 3]; 8],
/// Media-relative XYZ of the 16 primaries (index = c | m<<1 | y<<2 | k<<3; 0 is paper).
prim: [[f32; 3]; 16],
/// Shape `s` of each ink's tone curve, from its 40% and 50% tone value increase.
skew: [f32; 4],
paper_xyz: [f32; 3],
/// Media-relative XYZ of the darkest printable black (for black-point compensation).
/// Media-relative XYZ of the black point (for black-point compensation).
black_rel: [f32; 3],
gbd: OnceLock<Gbd>,
}
@@ -95,37 +135,17 @@ pub struct GenericCmyk {
impl GenericCmyk {
pub fn new(params: GenericCmykParams) -> Self {
let paper_xyz = lab_to_xyz(params.paper);
let mut prim = [[0.0f32; 3]; 8];
prim[0] = paper_xyz;
for (p, lab) in prim[1..].iter_mut().zip(params.solids.iter()) {
*p = lab_to_xyz(*lab);
let mut prim = [D50; 16];
for (p, lab) in prim[1..].iter_mut().zip(params.primaries.iter()) {
*p = lab_to_xyz(*lab).map(|v| v.max(1e-6));
}
let k_xyz = lab_to_xyz(params.black);
// Black over other inks: optical densities add, but saturate towards a maximum density
// (ink trapping / surface reflection), normalised so that K on paper is exact.
const D_MAX: f32 = 2.0;
let sat = |d: f32| D_MAX * (1.0 - (-d / D_MAX).exp());
let mut prim_k = [[0.0f32; 3]; 8];
for i in 0..8 {
for ch in 0..3 {
let di = -(prim[i][ch] / paper_xyz[ch]).max(1e-6).log10();
let dk = -(k_xyz[ch] / paper_xyz[ch]).max(1e-6).log10();
let d = sat(di + dk) * dk / sat(dk).max(1e-6);
prim_k[i][ch] = paper_xyz[ch] * 10f32.powf(-d.max(di));
}
}
let mut g = Self { params, prim, prim_k, paper_xyz, black_rel: [0.0; 3], gbd: OnceLock::new() };
// Darkest black within TAC: search a few rich blacks.
let mut best = [1.0f32; 3];
for k in [0.8f32, 0.9, 1.0] {
let rest = (g.params.tac - k).max(0.0) / 3.0;
let cmy = rest.min(1.0);
let x = g.to_xyz_rel([cmy, cmy, cmy, k]);
if x[1] < best[1] {
best = x;
}
}
g.black_rel = best;
// The curve's increase at 40% is 0.96·g·(1 − 0.2·s), so `s` follows from the 40% value.
let skew = [0, 1, 2, 3].map(|i| {
let g = params.tvi50[i];
if g > 1e-6 { (1.0 - params.tvi40[i] / (0.96 * g)) / 0.2 } else { 0.0 }
});
let mut g = Self { params, prim, skew, paper_xyz, black_rel: [0.0; 3], gbd: OnceLock::new() };
g.black_rel = g.to_xyz_rel(g.black_point_build());
g
}
@@ -133,35 +153,81 @@ impl GenericCmyk {
self.params.name
}
fn gain(a: f32, g: f32) -> f32 {
let a = a.clamp(0.0, 1.0);
(a + 4.0 * g * a * (1.0 - a)).clamp(0.0, 1.0)
/// The black point: [`BlackGeneration::black_point_k`] black, with C, M and Y
/// chosen so that they fill the TAC and the color is neutral (a* = b* = 0).
pub fn black_point_build(&self) -> [f32; 4] {
let k = self.params.bg.black_point_k.clamp(0.0, 1.0);
let rest = (self.params.tac - k).clamp(0.0, 3.0);
let build = |c: f32, m: f32| [c, m, (rest - c - m).clamp(0.0, 1.0), k];
let ab = |c: f32, m: f32| {
let l = self.to_lab_rel(build(c, m));
[l.a, l.b]
};
let lo = (rest - 2.0).max(0.0);
let hi = rest.min(1.0);
let (mut c, mut m) = ((rest / 3.0).clamp(lo, hi), (rest / 3.0).clamp(lo, hi));
for _ in 0..30 {
let r = ab(c, m);
if r[0].abs() + r[1].abs() < 1e-4 {
break;
}
let h = 1e-3;
let rc = ab(c - h, m);
let rm = ab(c, m - h);
let j = [[(r[0] - rc[0]) / h, (r[0] - rm[0]) / h], [(r[1] - rc[1]) / h, (r[1] - rm[1]) / h]];
let det = j[0][0] * j[1][1] - j[0][1] * j[1][0];
if det.abs() < 1e-9 {
break;
}
let dc = (-r[0] * j[1][1] + r[1] * j[0][1]) / det;
let dm = (-r[1] * j[0][0] + r[0] * j[1][0]) / det;
c = (c + dc.clamp(-0.1, 0.1)).clamp(lo, hi);
m = (m + dm.clamp(-0.1, 0.1)).clamp(lo, hi);
// Yellow takes the rest, so keep it within 0..1 as well.
let y = rest - c - m;
if y > 1.0 {
c += (y - 1.0) / 2.0;
m += (y - 1.0) / 2.0;
} else if y < 0.0 {
c += y / 2.0;
m += y / 2.0;
}
c = c.clamp(lo, hi);
m = m.clamp(lo, hi);
}
build(c.clamp(lo, hi), m.clamp(lo, hi))
}
/// Effective dot area of ink `i` at nominal area `a`: the TR 001-style tone curve.
fn gain(&self, i: usize, a: f32) -> f32 {
let a = if a.is_finite() { a.clamp(0.0, 1.0) } else { 0.0 };
let g = self.params.tvi50[i];
(a + 4.0 * g * a * (1.0 - a) * (1.0 + self.skew[i] * (2.0 * a - 1.0))).clamp(0.0, 1.0)
}
/// CMYK (0..1) → absolute XYZ (D50).
pub fn to_xyz(&self, cmyk: [f32; 4]) -> [f32; 3] {
let dg = self.params.dot_gain;
let c = Self::gain(cmyk[0], dg[0]);
let m = Self::gain(cmyk[1], dg[1]);
let y = Self::gain(cmyk[2], dg[2]);
let k = Self::gain(cmyk[3], dg[3]);
let mut out = [0.0f32; 3];
for i in 0..8 {
let w = (if i & 1 != 0 { c } else { 1.0 - c }) * (if i & 2 != 0 { m } else { 1.0 - m }) * (if i & 4 != 0 { y } else { 1.0 - y });
if w == 0.0 {
continue;
}
for (ch, o) in out.iter_mut().enumerate() {
*o += w * ((1.0 - k) * self.prim[i][ch] + k * self.prim_k[i][ch]);
}
}
out
let x = self.to_xyz_rel(cmyk);
[x[0] * self.paper_xyz[0] / D50[0], x[1] * self.paper_xyz[1] / D50[1], x[2] * self.paper_xyz[2] / D50[2]]
}
/// Media-relative XYZ (paper = D50 white).
pub fn to_xyz_rel(&self, cmyk: [f32; 4]) -> [f32; 3] {
let x = self.to_xyz(cmyk);
[x[0] * D50[0] / self.paper_xyz[0], x[1] * D50[1] / self.paper_xyz[1], x[2] * D50[2] / self.paper_xyz[2]]
let e = [0, 1, 2, 3].map(|i| self.gain(i, cmyk[i]));
let mut out = [0.0f32; 3];
for (i, p) in self.prim.iter().enumerate() {
let mut w = 1.0;
for (bit, a) in e.iter().enumerate() {
w *= if i & (1 << bit) != 0 { *a } else { 1.0 - a };
}
if w == 0.0 {
continue;
}
for (o, v) in out.iter_mut().zip(p) {
*o += w * v;
}
}
out
}
pub fn to_lab_rel(&self, cmyk: [f32; 4]) -> Lab {
@@ -174,7 +240,9 @@ impl GenericCmyk {
/// Display XYZ: media-relative (paper shows as white) or absolute (simulate paper colour).
/// With `bpc` (media-relative only) the press black displays as black, undoing the
/// compensation [`Self::gamut_map`] applies on the way in, so sRGB black separated to the
/// darkest rich black shows as black again.
/// black point shows as black again. Each XYZ channel is clamped at 0 on its own, so a build
/// darker than the black point in every channel shows as black, and one darker in only some
/// channels shows as a colored near-black.
pub fn display_xyz(&self, cmyk: [f32; 4], absolute: bool, bpc: bool) -> [f32; 3] {
if absolute {
return self.to_xyz(cmyk);
@@ -192,7 +260,7 @@ impl GenericCmyk {
xyz_to_srgb(self.display_xyz(cmyk, absolute, bpc))
}
/// Lab of the darkest printable black (media-relative).
/// Lab of the black point (media-relative), see [`Self::black_point_build`].
pub fn black_point(&self) -> Lab {
xyz_to_lab(self.black_rel)
}
@@ -231,6 +299,21 @@ impl GenericCmyk {
}
g[p] = -(0..3).map(|i| j[i][p] * r[i]).sum::<f32>();
}
// An ink at a bound whose descent direction points out of the box stays where it is; the step moves the other inks.
for p in 0..3 {
if (x[p] <= 0.0 && g[p] < 0.0) || (x[p] >= 1.0 && g[p] > 0.0) {
a[p] = [0.0; 3];
for row in &mut a {
row[p] = 0.0;
}
a[p][p] = 1.0;
g[p] = 0.0;
}
}
// Every ink is held at a bound, or the gradient is zero: no step can lower the error.
if g == [0.0; 3] {
break;
}
let mut improved = false;
for _ in 0..8 {
let mut al = a;
@@ -268,12 +351,21 @@ impl GenericCmyk {
rgb.map(|v| ((1.0 - v - k) / d).clamp(0.0, 1.0))
}
fn black_for_grey(&self, grey: f32) -> f32 {
let bg = self.params.bg;
if grey <= bg.start {
return 0.0;
/// Black for `x` on the black curve (see [`BlackGeneration::curve`]).
fn black_for(&self, x: f32) -> f32 {
let curve = &self.params.bg.curve;
let mut prev = curve[0];
if x <= prev.0 {
return prev.1.clamp(0.0, 1.0);
}
(((grey - bg.start) / (1.0 - bg.start)).clamp(0.0, 1.0).powf(bg.gamma) * bg.max_k).clamp(0.0, 1.0)
for &(kx, kk) in &curve[1..] {
if x <= kx {
let t = if kx > prev.0 { (x - prev.0) / (kx - prev.0) } else { 1.0 };
return (prev.1 + (kk - prev.1) * t).clamp(0.0, 1.0);
}
prev = (kx, kk);
}
prev.1.clamp(0.0, 1.0)
}
/// Separate a media-relative Lab (already gamut-mapped) into CMYK with GCR/UCR and the TAC limit.
@@ -282,13 +374,10 @@ impl GenericCmyk {
return [0.0; 4];
}
let cmy0 = self.solve_cmy(target, 0.0, Self::initial_cmy(target, 0.0));
let grey = cmy0[0].min(cmy0[1]).min(cmy0[2]);
let mut k = self.black_for_grey(grey);
// If CMY alone can't get dark enough, black must carry the rest.
let gray = cmy0[0].min(cmy0[1]).min(cmy0[2]);
// When CMY alone can't get dark enough, black carries the rest.
let l0 = self.to_lab_rel([cmy0[0], cmy0[1], cmy0[2], 0.0]).l;
if l0 > target.l + 1.0 {
k = k.max(((l0 - target.l) / l0.max(1.0)).clamp(0.0, 1.0));
}
let mut k = self.black_for(gray + self.params.bg.shortfall * (l0 - target.l).max(0.0));
let mut cmy = if k > 0.0 { self.solve_cmy(target, k, Self::initial_cmy(target, k)) } else { cmy0 };
// UCR: trade CMY for K until within the TAC limit.
for _ in 0..6 {
+121 -2
View File
@@ -245,8 +245,8 @@ fn loads_system_cmyk_icc() {
assert_eq!(c.cmyk_to_srgb([0.0; 4], false).map(|v| (v * 255.0).round() as u8), [255, 255, 255]);
}
/// With black-point compensation, sRGB black separates to the press's darkest black and that black
/// displays as black again (hex 000000 -> C67 M67 Y67 K100 -> 000000, not a dark grey).
/// With black-point compensation, sRGB black separates to the press's black point and that black
/// displays as black again (hex 000000 -> C75 M68 Y67 K90 -> 000000, not a dark gray).
#[test]
fn generic_cmyk_black_round_trips_with_bpc() {
let c = cms();
@@ -259,6 +259,125 @@ fn generic_cmyk_black_round_trips_with_bpc() {
assert!(raw.iter().all(|v| *v > 0.05), "{raw:?}");
}
/// Each ink's 40% and 50% tints gain like CGATS TR 001 (SWOP): the colorimetric tone value increase
/// (Murray–Davies on X for cyan, Y for magenta and black, Z for yellow) is C 20.0, M 17.6, Y 16.8 and
/// K 21.6 points at 50%, and C 20.0, M 17.3, Y 16.7 and K 21.9 points at 40%.
#[test]
fn generic_cmyk_tints_gain_like_tr001() {
let g = generic();
let tvi = |ink: usize, a: f32| {
let ch = [0, 1, 2, 1][ink];
let mut cmyk = [0.0f32; 4];
cmyk[ink] = a;
let tint = g.to_xyz_rel(cmyk)[ch];
cmyk[ink] = 1.0;
let solid = g.to_xyz_rel(cmyk)[ch];
let paper = g.to_xyz_rel([0.0; 4])[ch];
(paper - tint) / (paper - solid) - a
};
for (ink, (at50, at40)) in [(0.200, 0.200), (0.176, 0.173), (0.168, 0.167), (0.216, 0.219)].into_iter().enumerate() {
assert!((tvi(ink, 0.5) - at50).abs() < 0.002, "ink {ink} at 50%: {}", tvi(ink, 0.5));
assert!((tvi(ink, 0.4) - at40).abs() < 0.002, "ink {ink} at 40%: {}", tvi(ink, 0.4));
}
}
/// More of any ink never makes a Generic CMYK color lighter, in any XYZ channel: on a 10% grid of
/// builds within the 300% ink limit, adding 10% of one ink keeps X, Y and Z or lowers them.
#[test]
fn generic_cmyk_more_ink_is_never_lighter() {
let g = generic();
let steps = (0..=10).map(|i| i as f32 / 10.0);
for c in steps.clone() {
for m in steps.clone() {
for y in steps.clone() {
for k in steps.clone() {
let base = [c, m, y, k];
if base.iter().sum::<f32>() > 3.0 - 0.1 + 1e-4 {
continue;
}
let x0 = g.to_xyz_rel(base);
for ink in 0..4 {
if base[ink] >= 1.0 {
continue;
}
let mut more = base;
more[ink] += 0.1;
let x1 = g.to_xyz_rel(more);
assert!((0..3).all(|ch| x1[ch] <= x0[ch] + 1e-5), "{base:?} plus ink {ink}: {x0:?} to {x1:?}");
}
}
}
}
}
}
/// sRGB black separates to 90% black under neutral CMY that fills the 300% ink limit, light grays
/// carry no black, and black rises steadily from the light end of the gray ramp to the dark end.
#[test]
fn generic_cmyk_black_generation_follows_the_black_curve() {
let c = cms();
let black = c.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric);
assert!((black[3] - 0.9).abs() < 0.005, "{black:?}");
assert!((black.iter().sum::<f32>() - 3.0).abs() < 0.01, "{black:?}");
let lab = c.cmyk_to_lab(black);
assert!(lab.a.abs() < 0.05 && lab.b.abs() < 0.05, "neutral: {lab:?}");
let light = c.srgb_to_cmyk([0.7; 3], Intent::RelativeColorimetric);
assert_eq!(light[3], 0.0, "{light:?}");
let mut prev = 0.0;
for v in (0..=50).rev().map(|i| i as f32 / 50.0) {
let k = c.srgb_to_cmyk([v; 3], Intent::RelativeColorimetric)[3];
assert!(k >= prev - 1e-4, "gray {v}: K {k} after {prev}");
prev = k;
}
}
/// A color whose solve holds an ink at a bound separates to the same inks when its values change by
/// a few float steps: hex f01482 (cyan held at 0) and hex ed1e79 (magenta held at 100%), each with
/// its red stepped one `f32` at a time over 4,001 values (about 0.00024 in all), stay within 0.001
/// on every ink.
#[test]
fn generic_cmyk_separates_nearby_colors_at_the_gamut_edge_alike() {
let c = cms();
let spread = |pink: [f32; 3]| {
let (mut lo, mut hi) = ([f32::MAX; 4], [f32::MIN; 4]);
for step in -2000i32..=2000 {
let mut rgb = pink;
rgb[0] = f32::from_bits(pink[0].to_bits().wrapping_add_signed(step));
let ink = c.srgb_to_cmyk(rgb, Intent::RelativeColorimetric);
for i in 0..4 {
lo[i] = lo[i].min(ink[i]);
hi[i] = hi[i].max(ink[i]);
}
}
(lo, hi)
};
let (lo, hi) = spread([240.0f32 / 255.0, 20.0 / 255.0, 130.0 / 255.0]);
assert!((0..4).all(|i| hi[i] - lo[i] < 1e-3), "{lo:?} to {hi:?}");
assert_eq!(lo[0], 0.0, "{lo:?}");
let (lo, hi) = spread([237.0f32 / 255.0, 30.0 / 255.0, 121.0 / 255.0]);
assert!((0..4).all(|i| hi[i] - lo[i] < 1e-3), "{lo:?} to {hi:?}");
assert_eq!(hi[1], 1.0, "{hi:?}");
}
/// A color whose solve holds cyan and magenta at 1 separates to the same inks when its values change
/// by a few float steps: sRGB (0, 0, 0.25) with its blue stepped one `f32` at a time over 121 values
/// stays within 0.001 on every ink.
#[test]
fn generic_cmyk_separates_nearby_colors_with_inks_at_full_alike() {
let c = cms();
let (mut lo, mut hi) = ([f32::MAX; 4], [f32::MIN; 4]);
for step in -60i32..=60 {
let blue = f32::from_bits(0.25f32.to_bits().wrapping_add_signed(step));
let ink = c.srgb_to_cmyk([0.0, 0.0, blue], Intent::RelativeColorimetric);
for i in 0..4 {
lo[i] = lo[i].min(ink[i]);
hi[i] = hi[i].max(ink[i]);
}
}
assert!((0..4).all(|i| hi[i] - lo[i] < 1e-3), "{lo:?} to {hi:?}");
assert_eq!((lo[0], lo[1]), (1.0, 1.0), "{lo:?}");
}
#[test]
fn lab_colours_round_trip_through_the_cms() {
let c = cms_no_bpc();
+47 -5
View File
@@ -395,6 +395,15 @@ impl Source {
}
}
/// The centers of a `cols` × `rows` grid of cells over `b`, row by row.
fn cell_centers(b: Rect, cols: u16, rows: u16) -> impl Iterator<Item = Point> {
let (cw, ch) = (b.width() / cols as f64, b.height() / rows as f64);
(0..rows as usize * cols as usize).map(move |k| {
let (i, j) = (k % cols as usize, k / cols as usize);
Point::new(b.x0 + (i as f64 + 0.5) * cw, b.y0 + (j as f64 + 0.5) * ch)
})
}
/// A freeform gradient ready to sample ([`Freeform::field`]).
#[derive(Clone, Debug)]
pub struct Field {
@@ -429,11 +438,7 @@ impl Field {
/// Samples at the centres of a `cols` × `rows` grid of cells over `b`, row by row: RGB and
/// opacity (as [`Self::sample`]).
pub fn grid(&self, b: Rect, cols: u16, rows: u16) -> impl Iterator<Item = ([f32; 3], f32)> + '_ {
let (cw, ch) = (b.width() / cols as f64, b.height() / rows as f64);
(0..rows as usize * cols as usize).map(move |k| {
let (i, j) = (k % cols as usize, k / cols as usize);
self.sample(Point::new(b.x0 + (i as f64 + 0.5) * cw, b.y0 + (j as f64 + 0.5) * ch))
})
cell_centers(b, cols, rows).map(move |p| self.sample(p))
}
/// Display RGB and opacity at `p`.
@@ -503,6 +508,27 @@ impl ModelField {
};
(c, a)
}
/// [`Self::sample`] at the centers of a `cols` × `rows` grid of cells over `b`, row by row.
pub fn grid(&self, b: Rect, cols: u16, rows: u16) -> impl Iterator<Item = (Color, f32)> + '_ {
cell_centers(b, cols, rows).map(move |p| self.sample(p))
}
/// Display RGB and opacity at `p`: the display color of [`Self::sample`], or the display RGB
/// the points mix in when their models differ.
pub fn display_sample(&self, p: Point) -> ([f32; 3], f32) {
if self.model.is_none() {
return self.first.sample(p);
}
let (c, a) = self.sample(p);
(c.to_rgb(), a)
}
/// [`Self::display_sample`] at the centers of a `cols` × `rows` grid of cells over `b`, row by
/// row.
pub fn display_grid(&self, b: Rect, cols: u16, rows: u16) -> impl Iterator<Item = ([f32; 3], f32)> + '_ {
cell_centers(b, cols, rows).map(move |p| self.display_sample(p))
}
}
#[cfg(test)]
@@ -530,6 +556,22 @@ mod tests {
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4)
}
#[test]
fn the_model_field_grid_and_display_samples_match_its_sample() {
let mut f = two(0.0);
(f.points[0].color, f.points[1].color) = (Color::cmyk(1.0, 0.0, 0.0, 0.0), Color::cmyk(0.0, 0.0, 0.0, 1.0));
let field = f.model_field(50.0);
let b = Rect::new(0.0, 0.0, 100.0, 20.0);
let (cells, shown): (Vec<_>, Vec<_>) = (field.grid(b, 5, 1).collect(), field.display_grid(b, 5, 1).collect());
let (mid, a) = field.sample(Point::new(50.0, 10.0));
assert_eq!(cells[2], (mid, a));
assert_eq!(shown[2], (mid.to_rgb(), a));
// Points in different models give their display mix.
(f.points[0].color, f.points[1].color) = (red(), Color::gray(0.5));
let (rgb, _) = f.model_field(50.0).display_sample(Point::new(50.0, 0.0));
assert!(close(rgb, [0.75, 0.25, 0.25]), "{rgb:?}");
}
#[test]
fn the_sample_at_a_point_is_its_colour() {
let f = two(0.0);
+75 -11
View File
@@ -456,6 +456,41 @@ impl Gradient {
}
Some(out)
}
/// A gradient whose stops are all CMYK as a ramp of C, M, Y, K and opacity: the stops' own
/// inks, an off-center midpoint halfway between its two stops' inks, and a Perceptual
/// gradient's curve as [`Self::ink_mixes`] mixes the inks. `None` when a stop is in another
/// model, there are no stops, or [`Self::ink_mixes`] gives none for the curve.
fn ink_ramp(&self) -> Option<Ramp<5>> {
let inks: Vec<[f32; 4]> = self
.stops
.iter()
.map(|s| match s.color {
Color::Cmyk { c, m, y, k } => Some([c, m, y, k]),
_ => None,
})
.collect::<Option<_>>()?;
if inks.is_empty() {
return None;
}
let entry = |i: usize, w: f32, o: f32| {
let (a, b) = (inks[i], inks.get(i + 1).copied().unwrap_or(inks[i]));
let [c, m, y, k]: [f32; 4] = std::array::from_fn(|n| a[n] + (b[n] - a[n]) * w);
[c, m, y, k, o]
};
if !self.method.is_classic() {
return Some(Ramp { stops: self.ink_mixes()?.into_iter().map(|(t, i, w, o)| (t, entry(i, w, o))).collect() });
}
let mut stops = Vec::with_capacity(inks.len());
for (i, s) in self.stops.iter().enumerate() {
stops.push((s.offset, entry(i, 0.0, s.opacity)));
if let Some(n) = self.stops.get(i + 1)
&& (s.midpoint - 0.5).abs() > 1e-3
{
stops.push((s.offset + (n.offset - s.offset) * s.midpoint, entry(i, 0.5, (s.opacity + n.opacity) / 2.0)));
}
}
Some(Ramp { stops })
}
/// The same ramp the other way round: the stops in reverse order at mirrored offsets, each
/// segment's midpoint mirrored with it.
pub fn reverse(&mut self) {
@@ -895,19 +930,45 @@ impl GradientPaint {
fill: bool,
rgb: &dyn Fn(&Color) -> [f32; 3],
) -> impl Iterator<Item = [u8; 4]> + use<> {
self.grid(Ramp::new(&self.gradient, rgb), bounds, area, cols, rows, cells, fill, false)
}
/// [`Self::pixels`] of a linear or radial gradient whose stops are all CMYK, as C, M, Y, K
/// and opacity levels mixed from the stops' inks; `None` when a stop is in another model,
/// there are no stops, or a Perceptual curve has too many stops for [`Gradient::ink_mixes`].
/// Dither's noise adds no ink where the ramp has none.
pub fn ink_pixels(&self, bounds: Rect, area: Rect, cols: u16, rows: u16, fill: bool) -> Option<impl Iterator<Item = [u8; 5]> + use<>> {
let ramp = self.gradient.ink_ramp()?;
Some(self.grid(ramp, bounds, area, cols, rows, [0..cols, 0..rows], fill, true))
}
/// `ramp` sampled at each cell's center in columns `cells[0]` and rows `cells[1]` of the grid,
/// its last channel (opacity) rounded and each other channel with dither's noise, except
/// (`inks`) where that channel is empty.
#[allow(clippy::too_many_arguments)]
fn grid<const N: usize>(
&self,
ramp: Ramp<N>,
bounds: Rect,
area: Rect,
cols: u16,
rows: u16,
cells: [std::ops::Range<u16>; 2],
fill: bool,
inks: bool,
) -> impl Iterator<Item = [u8; N]> + use<N> {
let (kind, geom, dither) = (self.gradient.kind, self.resolve(bounds), fill && self.gradient.dither);
let ramp = Ramp::new(&self.gradient, rgb);
let (cw, ch) = (area.width() / f64::from(cols.max(1)), area.height() / f64::from(rows.max(1)));
let (x0, y0) = (area.x0, area.y0);
let [across, down] = cells.map(|r| u32::from(r.start)..u32::from(r.end));
down.flat_map(move |j| across.clone().map(move |i| (i, j))).map(move |(i, j)| {
let p = Point::new(x0 + (f64::from(i) + 0.5) * cw, y0 + (f64::from(j) + 0.5) * ch);
let c = ramp.at(geom.param_at(kind, p) as f32);
let level = |k: usize| {
let noise = if dither { dither_noise(i, j, k as u32) } else { 0.0 };
std::array::from_fn(|k| {
if k + 1 == N {
return (c[k].clamp(0.0, 1.0) * 255.0).round() as u8;
}
let noise = if dither && !(inks && c[k] <= 0.0) { dither_noise(i, j, k as u32) } else { 0.0 };
(c[k].clamp(0.0, 1.0) * 255.0 + noise).round().clamp(0.0, 255.0) as u8
};
[level(0), level(1), level(2), (c[3].clamp(0.0, 1.0) * 255.0).round() as u8]
})
})
}
}
@@ -916,9 +977,9 @@ impl GradientPaint {
/// (display RGB, or an ink's coverage): its stops, midpoints and a Perceptual gradient's
/// in-between colours as stops (as [`Gradient::expanded_stops`]), each turned into that space
/// once, with colour and opacity mixed linearly between them, each on its own (as the renderer's
/// vector gradients mix them).
pub struct Ramp {
stops: Vec<(f32, [f32; 4])>,
/// vector gradients mix them). `N` counts the channels, with opacity last.
pub struct Ramp<const N: usize = 4> {
stops: Vec<(f32, [f32; N])>,
}
impl Ramp {
@@ -932,10 +993,13 @@ impl Ramp {
.collect();
Self { stops }
}
}
impl<const N: usize> Ramp<N> {
/// Unpremultiplied colour and opacity at `t`, padded past the ends (transparent black
/// without stops).
pub fn at(&self, t: f32) -> [f32; 4] {
let Some(&(t0, first)) = self.stops.first() else { return [0.0; 4] };
pub fn at(&self, t: f32) -> [f32; N] {
let Some(&(t0, first)) = self.stops.first() else { return [0.0; N] };
// Not after the first stop (or not a number): its colour.
if t.partial_cmp(&t0) != Some(std::cmp::Ordering::Greater) {
return first;
@@ -947,7 +1011,7 @@ impl Ramp {
return std::array::from_fn(|k| ca[k] + (cb[k] - ca[k]) * u);
}
}
self.stops.last().map_or([0.0; 4], |s| s.1)
self.stops.last().map_or([0.0; N], |s| s.1)
}
}
+93
View File
@@ -604,3 +604,96 @@ fn ink_mixes_use_the_mix_position_when_the_lightness_turns_back() {
}
assert!(mixes.windows(2).filter(|p| p[1].1 == 0).all(|p| p[0].2 <= p[1].2), "the weights rise: {mixes:?}");
}
fn cmyk_stop(offset: f32, c: f32, m: f32, y: f32, k: f32) -> GradientStop {
GradientStop::new(offset, Color::cmyk(c, m, y, k))
}
/// The `n` × 1 grid of `g` as a left-to-right linear gradient's ink pixels.
fn ink_row(g: Gradient, n: u16, fill: bool) -> Vec<[u8; 5]> {
let b = Rect::new(0.0, 0.0, f64::from(n), 1.0);
GradientPaint::new(g).ink_pixels(b, b, n, 1, fill).expect("CMYK stops").collect()
}
#[test]
fn ink_pixels_mix_the_stops_inks_in_cmyk() {
let mut g = Gradient::new(GradientKind::Linear, vec![cmyk_stop(0.0, 1.0, 0.0, 0.0, 0.0), cmyk_stop(1.0, 0.0, 0.0, 0.0, 1.0)]);
g.stops[1].opacity = 0.5;
let px = ink_row(g.clone(), 10, true);
let at = |x: f32| (x * 255.0).round() as u8;
for (i, p) in px.iter().enumerate() {
let t = (i as f32 + 0.5) / 10.0;
assert_eq!(*p, [at(1.0 - t), 0, 0, at(t), at(1.0 - t * 0.5)], "pixel {i}");
}
// An off-center midpoint is halfway between the two stops' inks, not a display RGB mix.
g.stops[0].midpoint = 0.25;
let px = ink_row(g.clone(), 4, false);
assert_eq!(&px[0][..4], &[at(0.75), 0, 0, at(0.25)], "halfway to the midpoint");
assert_eq!(&px[1][..4], &[at(0.5 * 5.0 / 6.0), 0, 0, at(0.5 + 0.5 / 6.0)], "a sixth of the way past it");
// A hard stop keeps both sides.
let hard = Gradient::new(
GradientKind::Linear,
vec![
cmyk_stop(0.0, 1.0, 0.0, 0.0, 0.0),
cmyk_stop(0.5, 1.0, 0.0, 0.0, 0.0),
cmyk_stop(0.5, 0.0, 1.0, 0.0, 0.0),
cmyk_stop(1.0, 0.0, 1.0, 0.0, 0.0),
],
);
let px = ink_row(hard, 4, false);
assert_eq!((&px[1][..4], &px[2][..4]), (&[255, 0, 0, 0][..], &[0, 255, 0, 0][..]));
}
#[test]
fn ink_pixels_dither_only_the_inks_the_ramp_has() {
let mut g = Gradient::new(GradientKind::Linear, vec![cmyk_stop(0.0, 0.2, 0.0, 0.0, 0.4), cmyk_stop(1.0, 0.8, 0.0, 0.0, 0.4)]);
g.dither = true;
let noisy = ink_row(g.clone(), 64, true);
let plain = ink_row(g.clone(), 64, false);
assert_ne!(noisy, plain, "a fill has noise, a stroke none");
for (n, p) in noisy.iter().zip(&plain) {
assert_eq!((n[1], n[2]), (0, 0), "no ink on the empty plates: {n:?}");
assert!(n[0].abs_diff(p[0]) <= 1 && n[3].abs_diff(p[3]) <= 1, "{n:?} {p:?}");
assert_eq!(n[4], 255, "opacity has no noise");
}
assert!(noisy.iter().zip(&plain).any(|(n, p)| n[3] != p[3]), "K gets its own noise");
assert!(noisy.iter().zip(&plain).any(|(n, p)| (n[0] != p[0]) != (n[3] != p[3])), "the noise differs from channel to channel");
}
#[test]
fn ink_pixels_follow_the_perceptual_curve_as_ink_mixes() {
let mut g = Gradient::new(GradientKind::Linear, vec![cmyk_stop(0.0, 0.0, 0.0, 0.0, 0.0), cmyk_stop(1.0, 1.0, 0.0, 0.0, 0.0)]);
g.method = GradientMethod::Perceptual;
let mixes = g.ink_mixes().unwrap();
let ramp = g.ink_ramp().unwrap();
assert_eq!(ramp.stops.len(), mixes.len());
for ((t, ink), (o, i, w, _)) in ramp.stops.iter().zip(&mixes) {
assert_eq!((*t, ink[0]), (*o, if *i == 0 { *w } else { 1.0 }), "cyan at {t}");
}
let px = ink_row(g, 2, false);
assert!(px[0][0] > 0 && px[0][0] < px[1][0], "{px:?}");
assert!(px.iter().all(|p| p[1] == 0 && p[2] == 0 && p[3] == 0), "{px:?}");
}
#[test]
fn ink_pixels_need_every_stop_in_cmyk() {
let b = Rect::new(0.0, 0.0, 2.0, 1.0);
let with = |stop: GradientStop| GradientPaint::new(Gradient::new(GradientKind::Linear, vec![cmyk_stop(0.0, 1.0, 0.0, 0.0, 0.0), stop]));
assert!(with(cmyk_stop(1.0, 0.0, 0.0, 0.0, 1.0)).ink_pixels(b, b, 2, 1, true).is_some());
for other in [Color::rgb(1.0, 0.0, 0.0), Color::gray(0.5), Color::lab(50.0, 10.0, 10.0)] {
assert!(with(GradientStop::new(1.0, other)).ink_pixels(b, b, 2, 1, true).is_none(), "{other:?}");
}
assert!(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![])).ink_pixels(b, b, 2, 1, true).is_none(), "no stops");
}
/// A Perceptual curve over the limit of [`Gradient::ink_mixes`] has no inks; a Classic gradient of as many stops does.
#[test]
fn ink_pixels_stop_at_the_ink_mixes_limit() {
let stops: Vec<_> = (0..=MAX_INK_TINTS).map(|i| cmyk_stop(i as f32 / MAX_INK_TINTS as f32, (i % 2) as f32, 0.0, 0.0, 0.0)).collect();
let classic = Gradient::new(GradientKind::Linear, stops);
let perceptual = Gradient { method: GradientMethod::Perceptual, ..classic.clone() };
assert!(!perceptual.fits_ink_tints());
let b = Rect::new(0.0, 0.0, 2.0, 1.0);
assert!(GradientPaint::new(perceptual).ink_pixels(b, b, 2, 1, false).is_none());
assert!(GradientPaint::new(classic).ink_pixels(b, b, 2, 1, false).is_some());
}
+42 -30
View File
@@ -143,38 +143,11 @@ impl Color {
}
/// HSB with hue in degrees 0..360, saturation and brightness 0..1.
pub fn to_hsb(&self) -> [f32; 3] {
let [r, g, b] = self.to_rgb();
let max = r.max(g).max(b);
let min = r.min(g).min(b);
let d = max - min;
let h = if d <= 0.0 {
0.0
} else if max == r {
60.0 * (((g - b) / d).rem_euclid(6.0))
} else if max == g {
60.0 * ((b - r) / d + 2.0)
} else {
60.0 * ((r - g) / d + 4.0)
};
// f32 rounding in rem_euclid can yield exactly 360; wrap back to 0.
let h = if h >= 360.0 { 0.0 } else { h };
let s = if max <= 0.0 { 0.0 } else { d / max };
[h, s, max]
rgb_to_hsb(self.to_rgb())
}
pub fn from_hsb(h: f32, s: f32, v: f32) -> Self {
let h = h.rem_euclid(360.0) / 60.0;
let c = v * s;
let x = c * (1.0 - (h % 2.0 - 1.0).abs());
let (r, g, b) = match h as u32 {
0 => (c, x, 0.0),
1 => (x, c, 0.0),
2 => (0.0, c, x),
3 => (0.0, x, c),
4 => (x, 0.0, c),
_ => (c, 0.0, x),
};
let m = v - c;
Color::Rgb { r: r + m, g: g + m, b: b + m }
let [r, g, b] = hsb_to_rgb([h, s, v]);
Color::Rgb { r, g, b }
}
/// `#rrggbb` (display RGB).
pub fn to_hex(&self) -> String {
@@ -327,6 +300,45 @@ impl Color {
}
}
/// HSB (hue in degrees 0..360, saturation and brightness 0..1) of RGB numbers 0..1, with no color
/// conversion ([`Color::to_hsb`] reads the display color first).
pub fn rgb_to_hsb([r, g, b]: [f32; 3]) -> [f32; 3] {
let max = r.max(g).max(b);
let min = r.min(g).min(b);
let d = max - min;
let h = if d <= 0.0 {
0.0
} else if max == r {
60.0 * (((g - b) / d).rem_euclid(6.0))
} else if max == g {
60.0 * ((b - r) / d + 2.0)
} else {
60.0 * ((r - g) / d + 4.0)
};
// f32 rounding in rem_euclid can yield exactly 360; wrap back to 0.
let h = if h >= 360.0 { 0.0 } else { h };
let s = if max <= 0.0 { 0.0 } else { d / max };
[h, s, max]
}
/// RGB numbers 0..1 of HSB `[h, s, v]` (hue in degrees, saturation and brightness 0..1): the inverse
/// of [`rgb_to_hsb`].
pub fn hsb_to_rgb([h, s, v]: [f32; 3]) -> [f32; 3] {
let h = h.rem_euclid(360.0) / 60.0;
let c = v * s;
let x = c * (1.0 - (h % 2.0 - 1.0).abs());
let (r, g, b) = match h as u32 {
0 => (c, x, 0.0),
1 => (x, c, 0.0),
2 => (0.0, c, x),
3 => (0.0, x, c),
4 => (x, 0.0, c),
_ => (c, 0.0, x),
};
let m = v - c;
[r + m, g + m, b + m]
}
/// `new` expressed in the colour model of `orig` ([`Color::in_model`]): results of colour operations
/// (harmonies, blends, inversions, recolouring) keep the model of the colour they came from.
pub fn keep_model(orig: Color, new: Color) -> Color {
+27 -1
View File
@@ -8,7 +8,6 @@ mod layers;
mod profile;
mod stroke_style;
pub(crate) use layers::HEAD_REACH;
pub use layers::{Effect, FillLayer, StrokeGradientMode, StrokeLayer, stroke_paint_bounds};
pub use profile::{AngleProfile, PressureProfile, ProfilePreset, SavedProfile, WidthProfile};
pub use stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign};
@@ -296,6 +295,28 @@ impl Appearance {
scale(e, s);
}
}
/// The id of Effect › SVG Filters' effect, whose `origin` parameter is a point of the document.
pub const SVG_FILTER: &str = "svg.filter";
/// Does any effect (the object's or a fill's or stroke's) hold an SVG filter?
pub fn has_svg_filter(&self) -> bool {
self.effects.iter().chain(self.items.iter().flat_map(|i| i.effects().iter())).any(|e| e.id == Self::SVG_FILTER)
}
/// Move the `origin` of every SVG filter effect (where its user space starts in the document)
/// by `a`, as the object it is on moves.
pub fn transform_svg_filters(&mut self, a: kurbo::Affine) {
let items = self.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut());
for e in self.effects.iter_mut().chain(items).filter(|e| e.id == Self::SVG_FILTER) {
let at =
|i: usize| e.params.get("origin").and_then(|o| o.get(i)).and_then(serde_json::Value::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0);
let p = a * kurbo::Point::new(at(0), at(1));
if p.x.is_finite() && p.y.is_finite() && e.params.is_object() {
e.params["origin"] = serde_json::json!([p.x, p.y]);
}
}
}
/// Gradient paints of the fills and strokes.
fn gradients_mut(&mut self) -> impl Iterator<Item = &mut vectorcraft_color::GradientPaint> {
self.items.iter_mut().filter_map(|i| match i {
@@ -354,6 +375,11 @@ impl Appearance {
pub fn has_placed_gradient(&self) -> bool {
self.has_gradient(true)
}
/// Does a fill or stroke carry a gradient that is drawn at a place in document space: a placed
/// one, or a freeform gradient with points of its own whose vector is fitted to the bounds?
pub fn has_positioned_gradient(&self) -> bool {
self.gradients().any(|g| g.is_placed() || g.has_freeform_points())
}
/// Fix unplaced gradients to their fit on `bounds` (the object's geometric bounds; strokes fit
/// the stroke-inflated box), so they can follow transforms that refitting wouldn't reproduce.
pub fn pin_gradients(&mut self, bounds: vectorcraft_geom::Rect) {
+3 -6
View File
@@ -139,10 +139,6 @@ impl StrokeGradientMode {
}
}
/// How far any arrowhead reaches from its tip, in units of its weight (the open arrow's arms are
/// cut square a little behind its 4 × 4 box).
pub(crate) const HEAD_REACH: f64 = 4.6;
fn ten() -> f64 {
10.0
}
@@ -188,7 +184,8 @@ impl StrokeLayer {
}
}
/// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least
/// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide.
/// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide (see
/// [`Arrowhead::reach`] and [`Arrowhead::half_width`]).
pub fn arrow_weight(&self, end: bool) -> f64 {
let pct = if end { self.arrow_scale.1 } else { self.arrow_scale.0 };
(self.width * pct / 100.0).max(0.25)
@@ -197,7 +194,7 @@ impl StrokeLayer {
/// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap.
pub fn head_reach(&self, end: bool) -> f64 {
let head = if end { self.end_arrow } else { self.start_arrow };
head.map_or(0.0, |_| HEAD_REACH * self.arrow_weight(end) + self.width / 2.0)
head.map_or(0.0, |k| k.reach() * self.arrow_weight(end) + self.width / 2.0)
}
/// How far the arrowheads can reach from the path's end points (0 without heads).
pub fn arrow_reach(&self) -> f64 {
+27 -1
View File
@@ -49,6 +49,10 @@ impl Dash {
}
}
/// How far the arrowheads drawn in the 4 × 4 box reach from their tip, in units of their weight
/// (the open arrow's arms are cut square a little behind the box).
const HEAD_REACH: f64 = 4.6;
/// An arrowhead shape. Saved by variant name: new shapes are appended, never renamed or reordered.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Arrowhead {
@@ -94,13 +98,18 @@ pub enum Arrowhead {
Kite,
TriangleBar,
Oval,
/// Two arms of the head's weight (the line's weight at 100 % scale, for lines of 0.25 pt or
/// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as
/// the other heads.
LineArrow,
}
impl Arrowhead {
/// Every arrowhead, in menu order (arrows, then outlined shapes, then bars and marks).
pub const ALL: [Arrowhead; 40] = [
pub const ALL: [Arrowhead; 41] = [
Arrowhead::Arrow,
Arrowhead::ArrowOpen,
Arrowhead::LineArrow,
Arrowhead::Barbed,
Arrowhead::Concave,
Arrowhead::DoubleArrow,
@@ -141,6 +150,22 @@ impl Arrowhead {
Arrowhead::Fork,
];
/// How far any part of the head can be from its tip, in units of its weight.
pub fn reach(self) -> f64 {
match self {
// Its farthest corners are 4 + ½√2 back and 4 − ½√2 out.
Arrowhead::LineArrow => 5.75,
_ => HEAD_REACH,
}
}
/// How far the head spreads either side of its line, in units of its weight.
pub fn half_width(self) -> f64 {
match self {
Arrowhead::LineArrow => 4.0,
_ => 2.0,
}
}
/// The name the arrowhead menus show.
pub fn label(self) -> &'static str {
match self {
@@ -184,6 +209,7 @@ impl Arrowhead {
Arrowhead::Kite => "Kite",
Arrowhead::TriangleBar => "Triangle to Bar",
Arrowhead::Oval => "Oval",
Arrowhead::LineArrow => "Line Arrow",
}
}
}
+10 -3
View File
@@ -219,7 +219,7 @@ fn profile_presets_round_trip_their_ids() {
#[test]
fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
// Saved files store these names: they may only ever be appended to.
const SAVED: [&str; 40] = [
const SAVED: [&str; 41] = [
"Triangle",
"TriangleOpen",
"Circle",
@@ -260,6 +260,7 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
"Kite",
"TriangleBar",
"Oval",
"LineArrow",
];
for name in SAVED {
let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap();
@@ -293,9 +294,15 @@ fn outset_covers_arrowheads() {
st.arrow_scale = (100.0, 200.0);
assert_eq!(st.arrow_weight(false), 4.0);
assert_eq!(st.arrow_weight(true), 8.0);
assert_eq!((st.head_reach(false), st.head_reach(true)), (0.0, HEAD_REACH * 8.0 + 2.0));
let reach = Arrowhead::Triangle.reach();
assert_eq!((st.head_reach(false), st.head_reach(true)), (0.0, reach * 8.0 + 2.0));
// A 32 pt head whose tip sits up to its length (plus the cap) past the end point.
assert_eq!(a.outset(), HEAD_REACH * 8.0 + 2.0);
assert_eq!(a.outset(), reach * 8.0 + 2.0);
// The line arrow's arms spread twice as wide, so it reaches further from its tip.
a.stroke_mut().unwrap().end_arrow = Some(Arrowhead::LineArrow);
assert!(Arrowhead::LineArrow.reach() > reach);
assert_eq!(a.outset(), Arrowhead::LineArrow.reach() * 8.0 + 2.0);
a.stroke_mut().unwrap().end_arrow = Some(Arrowhead::Triangle);
a.stroke_mut().unwrap().width = 0.01;
assert_eq!(a.stroke().unwrap().arrow_weight(true), 0.25, "heads keep a minimum size");
}
+54
View File
@@ -106,6 +106,60 @@ impl super::Document {
d.layers.insert(0, Arc::new(layer));
Some(d)
}
/// Where an artboard the size of artboard `i` goes on `side` of it, [`ARTBOARD_GAP`] away,
/// when there is room for it there: every side within [`crate::MAX_COORD`] of the origin and
/// no other artboard overlapping it (touching edges don't overlap). `None` when there is no
/// such artboard or no room.
pub fn room_beside_artboard(&self, i: usize, side: ArtboardSide) -> Option<Rect> {
let src = self.artboards.get(i)?.rect;
let r = src + side.offset(src);
let in_canvas = [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= crate::MAX_COORD);
let clear = self.artboards.iter().all(|a| !(r.x0 < a.rect.x1 && a.rect.x0 < r.x1 && r.y0 < a.rect.y1 && a.rect.y0 < r.y1));
(in_canvas && clear).then_some(r)
}
}
/// The space between an artboard and one added or duplicated beside it (VectorCraft's own value,
/// the space New Artboard and Duplicate Artboards leave right of the last artboard).
pub const ARTBOARD_GAP: f64 = 20.0;
/// A side of an artboard, where an artboard added or duplicated beside it goes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ArtboardSide {
Left,
Right,
Top,
Bottom,
}
impl ArtboardSide {
pub const ALL: [Self; 4] = [Self::Top, Self::Right, Self::Bottom, Self::Left];
/// The side a command's `side` param names: "left", "right", "top" or "bottom".
pub fn parse(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|s| s.name() == name)
}
pub fn name(self) -> &'static str {
match self {
Self::Left => "left",
Self::Right => "right",
Self::Top => "top",
Self::Bottom => "bottom",
}
}
/// How far a copy of `r` moves to sit on this side of it, [`ARTBOARD_GAP`] away (y down).
pub fn offset(self, r: Rect) -> vectorcraft_geom::Vec2 {
let (w, h) = (r.width() + ARTBOARD_GAP, r.height() + ARTBOARD_GAP);
match self {
Self::Left => vectorcraft_geom::Vec2::new(-w, 0.0),
Self::Right => vectorcraft_geom::Vec2::new(w, 0.0),
Self::Top => vectorcraft_geom::Vec2::new(0.0, -h),
Self::Bottom => vectorcraft_geom::Vec2::new(0.0, h),
}
}
}
/// A document's locked artboards ([`Document::locked_artboards`]).
+35 -2
View File
@@ -11,12 +11,16 @@ use serde::{Deserialize, Serialize};
use crate::{Document, NodeId};
/// One asset: what it is called (its files' names) and the objects it exports, cropped to their
/// visual bounds.
/// visual bounds, or for a 3D asset its object's solids as a mesh file.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ExportAsset {
pub id: u64,
pub name: String,
pub nodes: Vec<NodeId>,
/// A 3D asset's mesh format (`usda`, `usdz`, `gltf` or `obj`): its object exports as a 3D
/// file. `None` for art exported as pictures.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub format_3d: Option<String>,
}
/// What the assets are named when they aren't named after their object: `Asset 1`, `Asset 2`…
@@ -30,7 +34,16 @@ impl Document {
/// The name of the next unnamed asset: one more than the highest `Asset N` so far.
pub fn next_asset_name(&self) -> String {
let n = self.assets.iter().filter_map(|a| a.name.strip_prefix(ASSET)?.parse::<u64>().ok()).max().unwrap_or(0);
let n = self
.assets
.iter()
.filter_map(|a| {
let digits = a.name.strip_prefix(ASSET)?;
// `parse` alone would accept a leading `+`.
digits.bytes().all(|b| b.is_ascii_digit()).then(|| digits.parse::<u64>().ok()).flatten()
})
.max()
.unwrap_or(0);
format!("{ASSET}{}", n.saturating_add(1))
}
@@ -57,3 +70,23 @@ impl Document {
v.into_iter().map(|(_, id)| id).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn name_after(names: &[&str]) -> String {
let mut doc = Document::new(100.0, 100.0);
for (i, n) in names.iter().enumerate() {
doc.assets.push(ExportAsset { id: i as u64 + 1, name: (*n).to_string(), nodes: vec![], format_3d: None });
}
doc.next_asset_name()
}
#[test]
fn next_asset_name_ignores_non_digit_suffixes() {
assert_eq!(name_after(&["Asset +5"]), "Asset 1");
assert_eq!(name_after(&["Asset ", "Asset 5x"]), "Asset 1");
assert_eq!(name_after(&["Asset 5"]), "Asset 6");
}
}
+411 -75
View File
@@ -19,7 +19,7 @@ use std::f64::consts::PI;
use std::sync::Arc;
use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint};
use vectorcraft_geom::kurbo::ParamCurveArclen;
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv};
use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
use crate::appearance::{Appearance, AppearanceItem, Dash, StrokeLayer, WidthProfile};
@@ -699,6 +699,34 @@ fn compound(path: PathData, rule: FillRule, counts: &[usize], total: usize) -> N
/// Interpolate text `x` → `y` into `o` (a copy of the nearer): the transform by its parts, an
/// area frame anchor by anchor, and each run's colours, stroke weight and size from the runs at
/// the same place (by character) of both.
/// The run of `of` at fraction `u` of its characters.
fn run_at(of: &TextObject, u: f64) -> Option<&crate::text::TextRun> {
let total: usize = of.runs.iter().map(|r| r.text.chars().count()).sum();
let target = (u * total as f64) as usize;
let mut seen = 0;
for r in &of.runs {
seen += r.text.chars().count();
if seen > target {
return Some(r);
}
}
of.runs.last()
}
/// The fraction of the characters of `runs` at the middle of each run.
fn run_middles(runs: &[crate::text::TextRun]) -> Vec<f64> {
let total: usize = runs.iter().map(|r| r.text.chars().count()).sum::<usize>().max(1);
let mut start = 0usize;
runs.iter()
.map(|r| {
let len = r.text.chars().count();
let u = (start as f64 + len as f64 / 2.0) / total as f64;
start += len;
u
})
.collect()
}
fn lerp_text(o: &mut TextObject, x: &TextObject, y: &TextObject, t: f64, tc: f64) {
o.xf = lerp_affine(x.xf, y.xf, t);
if let (crate::text::TextKind::Area { frame: f }, crate::text::TextKind::Area { frame: fx }, crate::text::TextKind::Area { frame: fy }) =
@@ -706,27 +734,10 @@ fn lerp_text(o: &mut TextObject, x: &TextObject, y: &TextObject, t: f64, tc: f64
{
*f = lerp_path(fx, fy, t);
}
// The run of `of` at fraction `u` of its characters.
fn run_at(of: &TextObject, u: f64) -> Option<&crate::text::TextRun> {
let total: usize = of.runs.iter().map(|r| r.text.chars().count()).sum();
let target = (u * total as f64) as usize;
let mut seen = 0;
for r in &of.runs {
seen += r.text.chars().count();
if seen > target {
return Some(r);
}
}
of.runs.last()
}
let total: usize = o.runs.iter().map(|r| r.text.chars().count()).sum::<usize>().max(1);
let mut start = 0usize;
let tf = tc as f32;
let mut resized = false;
for r in &mut o.runs {
let len = r.text.chars().count();
let u = (start as f64 + len as f64 / 2.0) / total as f64;
start += len;
let middles = run_middles(&o.runs);
for (r, u) in o.runs.iter_mut().zip(middles) {
let (Some(rx), Some(ry)) = (run_at(x, u), run_at(y, u)) else { continue };
let (sx, sy) = (&rx.style, &ry.style);
r.style.fill = lerp_paint(&sx.fill, &sy.fill, tf);
@@ -739,6 +750,7 @@ fn lerp_text(o: &mut TextObject, x: &TextObject, y: &TextObject, t: f64, tc: f64
if resized {
o.cached_bounds = None;
o.cached_baselines.clear();
o.cached_ink = None;
}
}
@@ -752,33 +764,115 @@ pub fn lerp_node(a: &Node, b: &Node, t: f64) -> Node {
// Step counts
// =====================================================================================
/// Largest channel difference (0..1) between the solid colours of two objects' top fill and stroke.
fn color_distance(a: &Node, b: &Node) -> f32 {
let mut d = 0.0f32;
let mut cmp = |x: &Paint, y: &Paint| {
let cols = |p: &Paint| -> Vec<Color> {
match p {
Paint::Solid { color, .. } => vec![*color],
Paint::Gradient(g) => g.gradient.stops.iter().map(|s| s.color).collect(),
_ => vec![],
}
};
let (cx, cy) = (cols(x), cols(y));
for (i, c) in cx.iter().enumerate() {
if let Some(o) = cy.get(i).or(cy.first()) {
let (p, q) = (c.to_rgb(), o.to_rgb());
for k in 0..3 {
d = d.max((p[k] - q[k]).abs());
}
}
}
/// Largest channel difference between two solid colors, as a fraction of the channel's range: two
/// tints of the same swatch by their tints, RGB by its 0 to 255 values over 256, CMYK and gray by
/// their percentages, and colors in different spaces (or Lab) by the difference of their RGB
/// values over 255. A solid paint against no paint, or anything that isn't solid, differs by 0:
/// [`lerp_paint`] switches such paints halfway rather than mixing them.
fn paint_difference(x: &Paint, y: &Paint) -> f64 {
let (Paint::Solid { color: p, swatch: sp, tint: tp }, Paint::Solid { color: q, swatch: sq, tint: tq }) = (x, y) else {
return 0.0;
};
cmp(&a.appearance.fill_paint(), &b.appearance.fill_paint());
cmp(&a.appearance.stroke_paint(), &b.appearance.stroke_paint());
d
if sp.is_some() && sp == sq && tp != tq {
return f64::from((tp - tq).abs());
}
let most = |a: &[f32], b: &[f32]| a.iter().zip(b).fold(0.0f64, |m, (u, v)| m.max(f64::from((u - v).abs())));
match (p, q) {
(Color::Rgb { r, g, b }, Color::Rgb { r: r2, g: g2, b: b2 }) => most(&[*r, *g, *b], &[*r2, *g2, *b2]) * 255.0 / 256.0,
(Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) => most(&[*c, *m, *y, *k], &[*c2, *m2, *y2, *k2]),
(Color::Gray { k }, Color::Gray { k: k2 }) => most(&[*k], &[*k2]),
_ => most(&p.to_rgb(), &q.to_rgb()),
}
}
/// Number of intermediate steps between two keys `len` apart (along the spine).
/// Largest difference (see [`paint_difference`]) between pairs of fills and strokes, or `None`
/// when any of them is a gradient or a pattern.
fn paints_difference(pairs: &[(&Paint, &Paint)]) -> Option<f64> {
let mut d = 0.0f64;
for (x, y) in pairs {
if [x, y].iter().any(|p| matches!(p, Paint::Gradient(_) | Paint::Pattern { .. })) {
return None;
}
d = d.max(paint_difference(x, y));
}
Some(d)
}
/// Largest channel difference (0..1, see [`paint_difference`]) between the solid colors of two
/// keys: their top fill and stroke, the runs of two text objects paired as [`lerp_text`] pairs
/// them, and the members of two groups paired as [`Lerp::new`] pairs them. `None` when any of
/// these holds a gradient or a pattern, whose steps Smooth Color counts by distance.
fn color_distance(a: &Node, b: &Node) -> Option<f64> {
let mut d =
paints_difference(&[(&a.appearance.fill_paint(), &b.appearance.fill_paint()), (&a.appearance.stroke_paint(), &b.appearance.stroke_paint())])?;
match (&a.kind, &b.kind) {
(NodeKind::Group { children: ca, clip: k1 }, NodeKind::Group { children: cb, clip: k2 }) if k1 == k2 && !(*k1 && ca.len() != cb.len()) => {
for (x, y) in ca.iter().zip(cb) {
d = d.max(color_distance(x, y)?);
}
}
(NodeKind::Text(x), NodeKind::Text(y)) => {
// The runs `lerp_text` pairs: those of `x` and of `y` at the middle of each run of either.
for u in run_middles(&x.runs).into_iter().chain(run_middles(&y.runs)) {
let (Some(rx), Some(ry)) = (run_at(x, u), run_at(y, u)) else { continue };
d = d.max(paints_difference(&[(&rx.style.fill, &ry.style.fill), (&rx.style.stroke, &ry.style.stroke)])?);
}
}
_ => {}
}
d.is_finite().then_some(d)
}
/// Smooth Color's steps between two keys by distance: the largest distance between their
/// corresponding visible bounding-box edges, in mean key widths (left and right edges) or heights
/// (top and bottom), rounded, less one, from 1 to 1000. Keys with no width are measured in their
/// mean height across as well, keys with no height in their mean width, and keys with neither in
/// points.
fn spatial_steps(ba: Rect, bb: Rect) -> usize {
let (w, h) = ((ba.width() + bb.width()) / 2.0, (ba.height() + bb.height()) / 2.0);
let size = |s: f64, other: f64| {
if s > 1e-9 {
s
} else if other > 1e-9 {
other
} else {
1.0
}
};
let (w, h) = (size(w, h), size(h, w));
let q = ((ba.x0 - bb.x0).abs().max((ba.x1 - bb.x1).abs()) / w).max((ba.y0 - bb.y0).abs().max((ba.y1 - bb.y1).abs()) / h);
if !q.is_finite() {
return 1;
}
((q + 0.5).floor() - 1.0).clamp(1.0, 1000.0) as usize
}
/// `255 × d` steps for a color difference `d` (see [`color_distance`]), a half step rounding down,
/// from 1 to 254.
fn level_steps(d: f64) -> f64 {
// The tolerance keeps a difference that lands on a half step (128 of 256 RGB values gives
// 127.5), stored as an `f32`, from rounding up.
(255.0 * d - 0.5 - 1e-4).ceil().clamp(1.0, 254.0)
}
/// Smooth Color's steps between two keys whose colors differ by `d` (see [`color_distance`]):
/// [`level_steps`], and at most eight per point of the largest of the keys' widths and heights
/// and the distance between their centers along either axis.
fn color_steps(d: f64, ba: Rect, bb: Rect) -> usize {
let by_color = level_steps(d);
let (ca, cb) = (ba.center(), bb.center());
let reach = [(ca.x - cb.x).abs(), (ca.y - cb.y).abs(), ba.width(), ba.height(), bb.width(), bb.height()].into_iter().fold(0.0f64, f64::max);
let by_density = (8.0 * reach + 0.5).floor().clamp(1.0, 254.0);
if !by_density.is_finite() {
return by_color as usize;
}
by_color.min(by_density) as usize
}
/// Number of intermediate steps between two keys. Specified Distance counts along the spine, `len`
/// long between them. Smooth Color counts from the keys' colors and visible bounds, whatever the
/// spine: keys whose colors differ make [`color_steps`] ([`level_steps`] when either key has no
/// bounds), and others make [`spatial_steps`] (1 when either key has no bounds).
pub fn blend_step_count(a: &Node, b: &Node, spacing: BlendSpacing, len: f64) -> usize {
match spacing {
BlendSpacing::Steps(n) => n.clamp(1, 1000) as usize,
@@ -787,17 +881,14 @@ pub fn blend_step_count(a: &Node, b: &Node, spacing: BlendSpacing, len: f64) ->
((len / d).round() as i64 - 1).clamp(0, 1000) as usize
}
BlendSpacing::SmoothColor => {
let cd = color_distance(a, b);
if cd > 1.0 / 255.0 {
((cd * 255.0 / 2.0).ceil() as usize).clamp(1, 256)
} else {
// Same colours: base the count on the distance between the objects.
let (ba, bb) = (a.geometric_bounds(), b.geometric_bounds());
let dist = match (ba, bb) {
(Some(x), Some(y)) => (x.x0 - y.x0).abs().max((x.x1 - y.x1).abs()).max((x.y0 - y.y0).abs()).max((x.y1 - y.y1).abs()),
_ => len,
};
((dist / 2.0).ceil() as usize).clamp(1, 256)
let bounds = a.visual_bounds().zip(b.visual_bounds());
match (color_distance(a, b), bounds) {
// Colors that differ by less than a thousandth of a step count as the same.
(Some(d), Some((ba, bb))) if d * 255.0 > 1e-3 => color_steps(d, ba, bb),
(Some(d), None) if d * 255.0 > 1e-3 => level_steps(d) as usize,
// Same colors, gradients and patterns: the distance between the objects.
(_, Some((ba, bb))) => spatial_steps(ba, bb),
(_, None) => 1,
}
}
}
@@ -814,9 +905,16 @@ pub struct Spine {
cum: Vec<f64>,
anchors: Vec<f64>,
closed: bool,
/// The subpath the spine was flattened from, kept so [`Spine::at_length`] can read the
/// original curves' tangents. Only the first subpath is stored: the others never affect a
/// spine.
subpath: SubPath,
}
impl Spine {
/// Build a spine from the first subpath of `path`: flatten it to a polyline, record cumulative
/// arc lengths, and the arc length at each anchor. `None` when `path` has no subpath, or when
/// the first one flattens to fewer than two points (so it has no length to walk).
pub fn new(path: &PathData) -> Option<Self> {
let sp = path.subpaths.first()?;
let mut pts: Vec<Point> = Vec::new();
@@ -853,8 +951,9 @@ impl Spine {
if pts.len() < 2 {
return None;
}
Some(Self { pts, cum, anchors, closed: sp.closed })
Some(Self { pts, cum, anchors, closed: sp.closed, subpath: sp.clone() })
}
/// The spine's flattened length in arc length.
pub fn length(&self) -> f64 {
*self.cum.last().unwrap_or(&0.0)
}
@@ -912,20 +1011,32 @@ impl Spine {
pub fn at(&self, f: f64) -> (Point, f64) {
self.at_length(f.clamp(0.0, 1.0) * self.length())
}
/// Point and tangent angle (radians) at arc length `s` (clamped to the spine).
/// Point and tangent angle (radians) at arc length `s` (clamped to the spine). The point and
/// tangent come from the original curve at that arc length, not from the flattened polyline: a
/// flattened chord's direction is piecewise constant, so steps oriented to a curved spine with
/// `Align to Path` jump between chords instead of following the curve smoothly.
pub fn at_length(&self, s: f64) -> (Point, f64) {
let last = self.pts.len().saturating_sub(2);
let s = if s.is_finite() { s.clamp(0.0, self.length()) } else { 0.0 };
let i = match self.cum.binary_search_by(|c| c.total_cmp(&s)) {
Ok(i) => i.min(last),
Err(i) => i.saturating_sub(1).min(last),
};
let (Some(p0), Some(p1), Some(c0), Some(c1)) = (self.pts.get(i), self.pts.get(i + 1), self.cum.get(i), self.cum.get(i + 1)) else {
return (self.pts.first().copied().unwrap_or_default(), 0.0);
};
let u = ((s - c0) / (c1 - c0).max(1e-12)).clamp(0.0, 1.0);
let d = *p1 - *p0;
(p0.lerp(*p1, u), d.y.atan2(d.x))
let sp = &self.subpath;
let n = sp.segment_count();
let mut start = 0.0;
for i in 0..n {
let c = sp.segment(i);
let end = self.anchor_length(i + 1).unwrap_or(self.length());
if s <= end || i + 1 == n {
let local_s = (s - start).max(0.0) / (end - start).max(1e-12) * c.arclen(1e-9);
let t = c.inv_arclen(local_s, 1e-9).clamp(0.0, 1.0);
let e = c.eval(t);
let tv = c.deriv().eval(t).to_vec2();
// Where a handle sits on its anchor the derivative vanishes there: take the
// direction between points a little before and after instead.
let tv = if tv.hypot2() < 1e-24 { c.eval((t + 1e-3).min(1.0)) - c.eval((t - 1e-3).max(0.0)) } else { tv };
return (Point::new(e.x, e.y), tv.y.atan2(tv.x));
}
start = end;
}
// Only a spine without segments gets here: the loop returns at the last one.
(self.pts.first().copied().unwrap_or_default(), 0.0)
}
}
@@ -1148,13 +1259,19 @@ fn requested_steps(keys: &[Arc<Node>], spec: &BlendSpec, rail: Option<&Rail>) ->
.collect()
}
/// Most steps `spacing` makes between two keys, whatever their size and distance
/// ([`blend_step_count`]'s clamps).
fn most_steps(spacing: BlendSpacing) -> usize {
/// Most steps `spacing` makes between keys `a` and `b`, whatever their size and distance
/// ([`blend_step_count`]'s clamps). A copy of a blend is moved and scaled, never recolored
/// ([`Shape::Other`]), so Smooth Color between colors that differ makes no more than their color
/// change asks for, whatever the copy's scale or rotation. By distance, a copy turned by Align to
/// Path can measure its edges differently, so it counts as up to 1000.
fn most_steps(a: &Node, b: &Node, spacing: BlendSpacing) -> usize {
match spacing {
BlendSpacing::Steps(n) => n.clamp(1, 1000) as usize,
BlendSpacing::Distance(_) => 1000,
BlendSpacing::SmoothColor => 256,
BlendSpacing::SmoothColor => match color_distance(a, b) {
Some(d) if d * 255.0 > 1e-3 => level_steps(d) as usize,
_ => 1000,
},
}
}
@@ -1182,8 +1299,8 @@ struct StepCount {
impl StepCount {
/// Steps the blends in `n` make in all when drawn, each keeping to [`MAX_BLEND_STEPS`].
/// `copy`: `n` is part of a blend's step, a copy moved and scaled into place. A blend spaced
/// by distance (or by distance where the colours match) makes more steps scaled up, so a
/// copy counts the most its spacing can make between each pair, an upper bound for any scale.
/// by distance, or by Smooth Color, can make more steps scaled up, so a copy counts the most
/// its spacing can make between each pair ([`most_steps`]), an upper bound for any scale.
fn node(&mut self, n: &Node, copy: bool) -> usize {
let at = (std::ptr::from_ref(n) as usize, copy);
if let Some(&known) = self.known.get(&at) {
@@ -1249,7 +1366,11 @@ impl StepCount {
fn most(&mut self, keys: &[Arc<Node>], spec: &BlendSpec) -> usize {
let inside = self.nodes(keys, true);
let each = self.steps(keys);
let demand = each.iter().map(|&c| c.saturating_mul(most_steps(spec.spacing))).fold(0, usize::saturating_add);
let most = keys.windows(2).map(|w| match w {
[a, b] => most_steps(a, b, spec.spacing),
_ => 0,
});
let demand = each.iter().zip(most).map(|(&c, m)| c.saturating_mul(m)).fold(0, usize::saturating_add);
inside.saturating_add(demand.min(MAX_BLEND_STEPS.saturating_sub(inside)))
}
}
@@ -1346,6 +1467,45 @@ mod tests {
assert_eq!(out[0].geometric_bounds().unwrap().center(), Point::new(5.0, 5.0), "keys stay put");
}
#[test]
fn orientations_follow_a_curved_spine_smoothly() {
// A curved spine: from (0, 0) with handles (+50, +50) / (-50, -50) to (100, 0) with handles
// (+50, -50) / (-50, +50) — the classic up-bow arc.
let spine = PathData::single(SubPath::new(
vec![Anchor::smooth(Point::new(0.0, 0.0), Point::new(50.0, 50.0)), Anchor::smooth(Point::new(100.0, 0.0), Point::new(50.0, -50.0))],
false,
));
let sp = Spine::new(&spine).unwrap();
// Many steps along the bow: each step's tangent comes from the curve at its arc length,
// not from a flattened chord — so the orientations must sweep the true angle, smoothly.
let len = sp.length();
let mut prev: Option<f64> = None;
for i in 1..=200 {
let (pt, ang) = sp.at_length(len * i as f64 / 201.0);
if let Some(p) = prev {
let step = (ang - p).abs().min(2.0 * std::f64::consts::PI - (ang - p).abs());
assert!(step < 0.1, "tangent step {} is too big at {} ({}, {})", step, i, pt.x, pt.y);
}
prev = Some(ang);
}
}
/// Where the spine starts at an anchor whose handle sits on it, the first step still faces along
/// the curve (towards the next handle), not along a direction of zero length.
#[test]
fn a_handle_on_its_anchor_still_gives_the_curve_direction() {
let spine = PathData::single(SubPath::new(
vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor::smooth(Point::new(100.0, 0.0), Point::new(150.0, -50.0))],
false,
));
let sp = Spine::new(&spine).unwrap();
let (p, angle) = sp.at_length(0.0);
assert!(p.x.abs() < 1e-6 && p.y.abs() < 1e-6, "{p:?}");
assert!((angle - std::f64::consts::FRAC_PI_4).abs() < 0.05, "faces the in handle at (50, 50): {angle}");
let (_, end) = sp.at_length(sp.length());
assert!(end.is_finite(), "{end}");
}
#[test]
fn easing_keeps_the_ends_and_stays_monotone() {
use crate::live::{BlendEase, BlendEaseType as K};
@@ -1634,4 +1794,180 @@ mod tests {
assert_eq!(blend_steps(&keys[..50], &spec), vec![1000; 49]);
assert_eq!(fit_steps(&[10, 20], &[1, 1], MAX_BLEND_STEPS), vec![0, 0]);
}
/// A key for the Smooth Color tests: a rectangle of `size` (width, height) centered on `c`,
/// with `fill`, and `stroke` at `width`.
fn smooth_key(c: (f64, f64), size: (f64, f64), fill: Paint, stroke: Paint, width: f64) -> Node {
let ((cx, cy), (w, h)) = (c, size);
let rect = Rect::new(cx - w / 2.0, cy - h / 2.0, cx + w / 2.0, cy + h / 2.0);
Node::path(NodeId(1), shapes::rectangle(rect), Appearance::basic(fill, stroke, width))
}
/// Smooth Color's steps between two filled `size` rectangles centered on `a` and `b`.
fn smooth(a: (f64, f64), b: (f64, f64), size: (f64, f64), fill_a: Color, fill_b: Color) -> usize {
let key = |c, fill| smooth_key(c, size, Paint::solid(fill), Paint::None, 0.0);
blend_step_count(&key(a, fill_a), &key(b, fill_b), BlendSpacing::SmoothColor, a.0.max(b.0) - a.0.min(b.0))
}
/// Smooth Color counts 255 steps for a full change of the channel that changes most, a half
/// step rounding down: RGB values over 256, CMYK and gray in percent, a spot color by its
/// tint, colors in different spaces by their RGB values over 255, a fill or a stroke,
/// whichever changes more.
#[test]
fn smooth_color_counts_a_step_per_level_of_color_change() {
let (a, b, size) = ((50.0, 150.0), (250.0, 150.0), (20.0, 20.0));
let black = Color::rgb8(0, 0, 0);
for (level, steps) in [(1, 1), (2, 2), (5, 5), (64, 64), (127, 127), (128, 127), (129, 128), (200, 199), (254, 253), (255, 254)] {
assert_eq!(smooth(a, b, size, black, Color::rgb8(level, 0, 0)), steps, "black to red {level}");
assert_eq!(smooth(a, b, size, black, Color::rgb8(level, level, level)), steps, "black to gray {level}");
}
assert_eq!(smooth(a, b, size, Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255)), 254);
assert_eq!(smooth(a, b, size, black, Color::rgb8(64, 128, 0)), 127, "the channel that changes most");
assert_eq!(smooth(a, b, size, Color::rgb8(17, 42, 93), Color::rgb8(91, 147, 220)), 127);
for (percent, steps) in [(0.2, 1), (1.0, 3), (5.0, 13), (10.0, 25), (25.0, 64), (50.0, 127), (100.0, 254)] {
let p = percent / 100.0;
assert_eq!(smooth(a, b, size, Color::cmyk(0.0, 0.0, 0.0, 0.0), Color::cmyk(p, 0.0, 0.0, 0.0)), steps, "cyan {percent}%");
assert_eq!(smooth(a, b, size, Color::gray(0.0), Color::gray(p)), steps, "gray {percent}%");
}
let spot = |tint: f32| Paint::Solid { color: Color::rgb8(255, 0, 0).tinted(tint), swatch: Some("Spot".into()), tint };
let key = |c, fill| smooth_key(c, size, fill, Paint::None, 0.0);
assert_eq!(blend_step_count(&key(a, spot(1.0)), &key(b, spot(0.5)), BlendSpacing::SmoothColor, 200.0), 127, "a tint of 50%");
let stroked = |c, fill: Color, stroke: Color| smooth_key(c, size, Paint::solid(fill), Paint::solid(stroke), 1.0);
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
assert_eq!(blend_step_count(&stroked(a, red, black), &stroked(b, red, blue), BlendSpacing::SmoothColor, 200.0), 254, "the stroke changes");
let outline = |c, stroke: Color| smooth_key(c, size, Paint::None, Paint::solid(stroke), 1.0);
assert_eq!(blend_step_count(&outline(a, red), &outline(b, blue), BlendSpacing::SmoothColor, 200.0), 254, "strokes alone");
assert_eq!(smooth(a, b, size, Color::rgb8(255, 255, 127), Color::cmyk(0.0, 0.0, 0.0, 0.0)), 128, "RGB against CMYK white");
assert_eq!(smooth(a, b, size, Color::rgb8(255, 255, 127), Color::rgb8(255, 255, 255)), 127, "RGB against RGB white");
}
/// Smooth Color reads the colors of group members paired in order and of text runs, and
/// counts a solid paint against no paint by distance, since such a paint switches halfway
/// instead of mixing.
#[test]
fn smooth_color_reads_the_colors_inside_groups_and_text() {
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
let square = |x: f64, c: Color| Arc::new(smooth_key((x, 150.0), (20.0, 20.0), Paint::solid(c), Paint::None, 0.0));
let group = |x: f64, top: Color| Node::new(NodeId(1), NodeKind::Group { children: vec![square(x, red), square(x, top)], clip: false });
let steps = |a: &Node, b: &Node| blend_step_count(a, b, BlendSpacing::SmoothColor, 200.0);
assert_eq!(steps(&group(50.0, red), &group(250.0, blue)), 254, "groups whose members change color");
assert_eq!(steps(&group(50.0, red), &group(250.0, red)), 9, "groups of the same colors");
let text = |x: f64, c: Color| {
let style = crate::CharStyle { fill: Paint::solid(c), ..Default::default() };
Node::new(NodeId(1), NodeKind::Text(Box::new(crate::TextObject::point(Point::new(x, 150.0), "Hi", style))))
};
assert_eq!(steps(&text(50.0, red), &text(250.0, blue)), 254, "text whose runs change color");
let mut two_runs = text(250.0, red);
if let NodeKind::Text(t) = &mut two_runs.kind {
let style = crate::CharStyle { fill: Paint::solid(blue), ..t.runs[0].style.clone() };
t.runs.push(crate::text::TextRun::new("Hi", style));
}
assert_eq!(steps(&text(50.0, red), &two_runs), 254, "a run that turns blue against one red run");
let empty = |x: f64| smooth_key((x, 150.0), (20.0, 20.0), Paint::None, Paint::None, 0.0);
assert_eq!(steps(&smooth_key((50.0, 150.0), (20.0, 20.0), Paint::solid(red), Paint::None, 0.0), &empty(250.0)), 9, "a fill against none");
let nothing = |c: Color| Node::path(NodeId(1), PathData::new(vec![]), Appearance::basic(Paint::solid(c), Paint::None, 0.0));
assert_eq!(steps(&nothing(red), &nothing(blue)), 254, "keys without bounds whose colors differ");
assert_eq!(steps(&nothing(red), &nothing(red)), 1, "keys without bounds of the same color");
}
/// Smooth Color makes at most eight steps per point of the largest of the keys' widths and
/// heights and the distance between their centers along either axis.
#[test]
fn smooth_color_makes_at_most_eight_steps_a_point() {
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
for (dx, steps) in [(0.0, 160), (20.0, 160), (20.1, 161), (25.0, 200), (31.5, 252), (40.0, 254)] {
assert_eq!(smooth((50.0, 150.0), (50.0 + dx, 150.0), (20.0, 20.0), red, blue), steps, "{dx} pt apart");
}
assert_eq!(smooth((100.0, 150.0), (100.0, 175.0), (20.0, 20.0), red, blue), 200, "25 pt apart vertically");
assert_eq!(smooth((100.0, 150.0), (100.0, 150.0), (5.0, 5.0), red, blue), 40, "5 pt squares on each other");
assert_eq!(smooth((100.0, 150.0), (100.0, 150.0), (25.0, 5.0), red, blue), 200, "the longer side counts");
assert_eq!(smooth((100.0, 150.0), (100.0, 150.0), (1.0, 1.0), red, blue), 8);
}
/// Smooth Color between keys of the same colors counts the largest distance between their
/// corresponding visible edges in mean key widths or heights, rounded, less one; so do keys
/// with gradients, whatever their colors.
#[test]
fn smooth_color_between_the_same_colors_counts_by_distance() {
let red = Color::rgb8(255, 0, 0);
let same = |a, b, size| smooth(a, b, size, red, red);
for (dx, steps) in [(25.0, 1), (50.0, 2), (100.0, 4), (200.0, 9), (400.0, 19), (800.0, 39)] {
assert_eq!(same((50.0, 150.0), (50.0 + dx, 150.0), (20.0, 20.0)), steps, "20 pt squares {dx} pt apart");
}
for (side, steps) in [(5.0, 39), (10.0, 19), (40.0, 4), (80.0, 2)] {
assert_eq!(same((50.0, 150.0), (250.0, 150.0), (side, side)), steps, "{side} pt squares");
}
assert_eq!(same((50.0, 150.0), (250.0, 150.0), (80.0, 10.0)), 2, "wide");
assert_eq!(same((50.0, 150.0), (250.0, 150.0), (10.0, 80.0)), 19, "tall");
assert_eq!(same((50.0, 250.0), (250.0, 50.0), (20.0, 20.0)), 9, "diagonal");
assert_eq!(same((50.0, 250.0), (250.0, 50.0), (80.0, 10.0)), 19, "wide and diagonal");
assert_eq!(same((50.0, 150.0), (1050.0, 150.0), (1.0, 1.0)), 999);
assert_eq!(same((50.0, 150.0), (1052.0, 150.0), (1.0, 1.0)), 1000, "at most 1000");
assert_eq!(same((50.0, 150.0), (50.0, 150.0), (20.0, 20.0)), 1, "at least one");
assert_eq!(same((50.0, 150.0), (250.0, 150.0), (0.0, 20.0)), 9, "vertical lines, measured in their height");
assert_eq!(same((50.0, 150.0), (50.0, 350.0), (20.0, 0.0)), 9, "horizontal lines, measured in their width");
assert_eq!(same((50.0, 150.0), (60.0, 150.0), (0.0, 0.0)), 9, "points, measured in points");
let key = |c, size, stroke: f64| smooth_key(c, size, Paint::solid(red), Paint::solid(Color::BLACK), stroke);
let wide =
blend_step_count(&key((50.0, 150.0), (10.0, 20.0), 0.0), &key((250.0, 150.0), (80.0, 20.0), 0.0), BlendSpacing::SmoothColor, 200.0);
assert_eq!(wide, 4, "keys of different widths");
let strokes =
blend_step_count(&key((50.0, 150.0), (20.0, 20.0), 1.0), &key((250.0, 150.0), (20.0, 20.0), 10.0), BlendSpacing::SmoothColor, 200.0);
assert_eq!(strokes, 7, "strokes widen the visible edges");
let gradient = |a: Color, b: Color| {
Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
Default::default(),
vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)],
))))
};
let shaded = |c, fill| smooth_key(c, (20.0, 20.0), fill, Paint::None, 0.0);
let blue = Color::rgb8(0, 0, 255);
for (from, to) in [(gradient(red, blue), gradient(red, blue)), (gradient(red, blue), gradient(blue, red))] {
assert_eq!(blend_step_count(&shaded((50.0, 150.0), from), &shaded((250.0, 150.0), to), BlendSpacing::SmoothColor, 200.0), 9);
}
}
/// A Smooth Color blend counts each pair of keys on its own.
#[test]
fn smooth_color_counts_each_pair_of_keys() {
let key = |x: f64, c: Color| Arc::new(smooth_key((x, 150.0), (20.0, 20.0), Paint::solid(c), Paint::None, 0.0));
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
let spec = BlendSpec::default();
assert_eq!(blend_steps(&[key(50.0, red), key(150.0, red), key(250.0, blue)], &spec), vec![4, 254]);
assert_eq!(blend_steps(&[key(50.0, red), key(150.0, blue), key(250.0, red)], &spec), vec![254, 254]);
}
/// A Smooth Color blend between different colors inside another blend's keys counts as the
/// steps its colors ask for, so the outer blend keeps the steps it asks for within
/// [`MAX_BLEND_STEPS`]: 200 steps, each a copy making 254 more. The copies keep their keys'
/// colors, also halfway between a red-to-blue and a blue-to-red blend.
#[test]
fn a_smooth_color_blend_in_a_key_counts_its_color_steps() {
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
let key = |x: f64, c: Color| smooth_key((x, 150.0), (20.0, 20.0), Paint::solid(c), Paint::None, 0.0);
let inner = |x: f64, from: Color, to: Color| blend_of(key(x, from), key(x + 100.0, to), BlendSpacing::SmoothColor);
let outer = blend_of(inner(0.0, red, blue), inner(500.0, red, blue), BlendSpacing::Steps(200));
let (keys, spec) = blend_parts(&outer).unwrap();
assert_eq!(blend_steps(keys, spec), vec![200]);
let crossed = blend_of(inner(0.0, red, blue), inner(500.0, blue, red), BlendSpacing::Steps(199));
let (keys, spec) = blend_parts(&crossed).unwrap();
assert_eq!(blend_steps(keys, spec), vec![199]);
let drawn = blend_expand(keys, spec);
let Some(NodeKind::Blend { children, .. }) = drawn.get(100).map(|n| &n.kind) else { panic!("a copy of a blend halfway") };
let fills: Vec<_> = children.iter().map(|k| k.appearance.fill_paint().color()).collect();
assert!(fills == [Some(red), Some(blue)] || fills == [Some(blue), Some(red)], "{fills:?}");
}
/// A Smooth Color blend between the same colors inside another blend's keys counts as up to
/// 1000 steps, which a copy turned to a path can ask for: 200 steps of copies of it come
/// down to 99.
#[test]
fn a_smooth_color_blend_of_the_same_colors_in_a_key_counts_up_to_1000_steps() {
let red = Color::rgb8(255, 0, 0);
let key = |x: f64| smooth_key((x, 150.0), (20.0, 20.0), Paint::solid(red), Paint::None, 0.0);
let inner = |x: f64| blend_of(key(x), key(x + 100.0), BlendSpacing::SmoothColor);
let outer = blend_of(inner(0.0), inner(500.0), BlendSpacing::Steps(200));
let (keys, spec) = blend_parts(&outer).unwrap();
assert_eq!(blend_steps(keys, spec), vec![99]);
}
}
+2 -2
View File
@@ -313,8 +313,8 @@ mod tests {
d.guides = vec![Guide { layer: Some(NodeId(40)), ..Guide::new(false, 5.0) }, Guide { layer: Some(d.layers[0].id), ..Guide::new(true, 5.0) }];
d.saved_selections = vec![crate::records::SavedSelection { name: "s".into(), objects: vec![NodeId(10), NodeId(11)] }].into();
d.assets = vec![
crate::assets::ExportAsset { id: 1, name: "far".into(), nodes: vec![NodeId(11)] },
crate::assets::ExportAsset { id: 2, name: "both".into(), nodes: vec![NodeId(10), NodeId(11)] },
crate::assets::ExportAsset { id: 1, name: "far".into(), nodes: vec![NodeId(11)], format_3d: None },
crate::assets::ExportAsset { id: 2, name: "both".into(), nodes: vec![NodeId(10), NodeId(11)], format_3d: None },
];
d.variables.bindings.insert(NodeId(11), ["v".to_string()].into());
d.variables.bindings.insert(NodeId(10), ["w".to_string()].into());
+13
View File
@@ -34,6 +34,7 @@ impl Document {
graphic_styles,
char_styles,
para_styles,
composite_fonts,
text_threads,
symbols,
graph_designs,
@@ -68,6 +69,7 @@ impl Document {
print_setup,
assets,
svg_scripts,
svg_filters,
puppet,
new_art,
dimensions,
@@ -89,6 +91,7 @@ impl Document {
&& *graphic_styles == other.graphic_styles
&& *char_styles == other.char_styles
&& *para_styles == other.para_styles
&& *composite_fonts == other.composite_fonts
&& *text_threads == other.text_threads
&& symbols.len() == other.symbols.len()
&& symbols.iter().zip(&other.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
@@ -135,6 +138,7 @@ impl Document {
&& *print_setup == other.print_setup
&& *assets == other.assets
&& *svg_scripts == other.svg_scripts
&& *svg_filters == other.svg_filters
&& match (puppet, &other.puppet) {
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
(a, b) => a.is_none() && b.is_none(),
@@ -211,6 +215,7 @@ impl Document {
graphic_styles: default_graphic_styles().into(),
char_styles: Default::default(),
para_styles: Default::default(),
composite_fonts: Default::default(),
text_threads: vec![],
symbols: vec![],
graph_designs: vec![],
@@ -245,6 +250,7 @@ impl Document {
print_setup: None,
assets: vec![],
svg_scripts: vec![],
svg_filters: vec![],
puppet: None,
new_art: Default::default(),
dimensions: false,
@@ -270,6 +276,11 @@ impl Document {
self.next_id
}
/// Makes the next id at least `id`, so ids below it are not given out again.
pub fn raise_next_id(&mut self, id: u64) {
self.next_id = self.next_id.max(id);
}
/// Ensure `next_id` is above every id in the tree (after deserializing foreign data).
pub fn fix_next_id(&mut self) {
// Ids from [`MAX_NEXT_ID`] up (a damaged or hand-made file: #1718) are left out, as is a
@@ -352,6 +363,7 @@ impl Document {
}
false
}
crate::id_index::note_tree_walk();
let mut p = vec![];
find(&self.layers, id, &mut p).then_some(p)
}
@@ -393,6 +405,7 @@ impl Document {
});
}
if !want.is_empty() {
crate::id_index::note_tree_walk();
let mut rest = HashMap::with_capacity(want.len());
walk(&self.layers, &want, &mut Vec::new(), &mut rest);
out.extend(rest);
+62 -1
View File
@@ -123,6 +123,47 @@ impl Document {
std::borrow::Cow::Owned(d)
}
/// The roots of every tree of the document's art: the layers, symbol definitions, graph designs,
/// pattern swatches and the original of the pattern being edited. Opacity masks hang off nodes
/// in these trees.
pub fn art_roots(&self) -> impl Iterator<Item = &Arc<Node>> {
self.layers
.iter()
.chain(self.symbols.iter().map(|s| &s.art))
.chain(self.graph_designs.iter().map(|g| &g.art))
.chain(self.patterns.iter().flat_map(|p| p.art.iter()))
.chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter()))
}
/// [`Self::art_roots`], to change.
pub fn art_roots_mut(&mut self) -> impl Iterator<Item = &mut Arc<Node>> {
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()))
}
/// Does `wants` hold for a node anywhere in the document's art ([`Self::art_roots`]) or its
/// opacity masks?
pub fn any_node(&self, wants: impl Fn(&Node) -> bool) -> bool {
let mut any = false;
for root in self.art_roots() {
crate::swatches::walk_with_masks(root, &mut |n| any |= wants(n));
}
any
}
/// Change with `f` every node for which `wants` holds, anywhere in the document's art (as
/// [`Self::any_node`] looks). Only the trees that hold such a node are copied out of the art
/// they share.
pub fn edit_nodes_where(&mut self, wants: impl Fn(&Node) -> bool, mut f: impl FnMut(&mut Node)) {
for root in self.art_roots_mut() {
edit_branches_where(root, &wants, &mut f);
}
}
/// Round every path's anchors and handles to `decimals` decimal places: path objects (with
/// Live Corners' uncut outlines), blend spines, envelopes' top-object outlines and Intertwine
/// areas, in the layers, symbol definitions, graph designs, pattern swatches (the one being
@@ -164,7 +205,7 @@ impl Document {
}
}
NodeKind::Envelope { kind, .. } => {
if let EnvelopeKind::TopObject { path } = kind.as_mut() {
if let EnvelopeKind::TopObject { path, .. } = kind.as_mut() {
round_path(path);
}
}
@@ -194,6 +235,26 @@ impl Document {
}
}
/// Change with `f` the nodes of `n`'s tree (opacity-mask art included) for which `wants` holds,
/// copying out of the shared art only the branches that hold one.
fn edit_branches_where(n: &mut Arc<Node>, wants: &impl Fn(&Node) -> bool, f: &mut impl FnMut(&mut Node)) {
let mut any = false;
crate::swatches::walk_with_masks(n, &mut |c| any |= wants(c));
if !any {
return;
}
let node = Arc::make_mut(n);
if wants(node) {
f(node);
}
if let Some(m) = node.extras_if_any().and_then(|e| e.mask.as_mut()) {
edit_branches_where(&mut m.art, wants, f);
}
for c in node.children_mut().into_iter().flatten() {
edit_branches_where(c, wants, f);
}
}
/// Round with `round` the anchors of the paths in `v`, nodes in their file form kept as JSON: every
/// `{"subpaths": [{"anchors": [{"p", "in", "out"}]}]}` outside type (`{"type": "text"}`), as
/// [`Document::round_geometry`] rounds the nodes it holds.
+5 -1
View File
@@ -347,12 +347,16 @@ impl Document {
t.first_para_continues = false;
t.cached_bounds = None;
t.cached_baselines.clear();
t.cached_ink = None;
}
let on_path = n.extras().objects_on_path.is_some();
let mut renamed = std::collections::HashMap::new();
if let Some(ch) = n.children_mut() {
let old: Vec<Arc<Node>> = std::mem::take(ch);
*ch = old.iter().map(|c| Arc::new(self.reid(c))).collect();
renamed.extend(old.iter().zip(ch.iter()).map(|(o, c)| (o.id, c.id)));
if on_path {
renamed.extend(old.iter().zip(ch.iter()).map(|(o, c)| (o.id, c.id)));
}
}
// An Objects on Path group names its path and its objects by id: the copy names the copies.
if let Some(e) = n.extras_if_any()
+14
View File
@@ -321,6 +321,20 @@ pub struct SeriesPaint {
/// Opacity (0..1) of the topmost stroke of each path directly in the series group, as [`Self::fill_opacity`].
#[serde(skip_serializing_if = "Option::is_none")]
pub stroke_opacity: Option<f32>,
/// Blend mode of the topmost fill of each path directly in the series group, as [`Self::fill_opacity`]. Absent: Normal.
#[serde(skip_serializing_if = "Option::is_none")]
pub fill_blend: Option<vectorcraft_color::BlendMode>,
/// Blend mode of the topmost stroke of each path directly in the series group, as [`Self::fill_opacity`]. Absent:
/// Normal.
#[serde(skip_serializing_if = "Option::is_none")]
pub stroke_blend: Option<vectorcraft_color::BlendMode>,
/// Object opacity (0..1) of each path directly in the series group, taken from the object opacity set on one of them.
/// Absent: fully opaque.
#[serde(skip_serializing_if = "Option::is_none")]
pub opacity: Option<f32>,
/// Object blend mode of each path directly in the series group, as [`Self::opacity`]. Absent: Normal.
#[serde(skip_serializing_if = "Option::is_none")]
pub blend: Option<vectorcraft_color::BlendMode>,
}
/// Graph data and options. `rows` are categories (one per row of the Graph Data window), each
+297 -19
View File
@@ -84,8 +84,9 @@ impl Default for HitOptions {
/// The shapes that an image's own fills and strokes paint, each with its fill rule and the fill or
/// stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated
/// above this crate, so the engine registers one with [`set_image_paint`].
pub type ImagePaint = fn(&Node) -> Vec<(BezPath, FillRule, AppearanceItem)>;
/// above this crate, so the engine registers one with [`set_image_paint`]. It looks up swatches and
/// patterns in the document it is given.
pub type ImagePaint = fn(Option<&Document>, &Node) -> Vec<(BezPath, FillRule, AppearanceItem)>;
static IMAGE_PAINT: OnceLock<ImagePaint> = OnceLock::new();
@@ -98,8 +99,8 @@ pub fn set_image_paint(f: ImagePaint) {
/// The shapes that the image `n`'s own fills and strokes paint ([`set_image_paint`]), none while
/// nothing is registered.
pub(crate) fn image_paint(n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(n))
pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(doc, n))
}
/// One level of evaluation of a live object in a document, as the canvas draws it: type in an
@@ -127,11 +128,14 @@ fn live_inputs() -> u64 {
}
/// A live object evaluated by [`live_art`] on this thread: the object, its document's symbols (by
/// name and art) and patterns and the [`LiveInputs`] as they were, the art and its [`art_size`].
/// name and art), patterns, swatches and color groups and the [`LiveInputs`] as they were, the art
/// and its [`art_size`].
struct EvaluatedLive {
node: Node,
symbols: Vec<(String, Arc<Node>)>,
patterns: Vec<crate::PatternDef>,
swatches: crate::Shared<Vec<vectorcraft_color::Swatch>>,
swatch_groups: crate::Shared<Vec<vectorcraft_color::SwatchGroup>>,
inputs: u64,
art: Rc<Vec<Node>>,
size: usize,
@@ -145,6 +149,8 @@ impl EvaluatedLive {
&& self.symbols.iter().zip(&doc.symbols).all(|((name, art), s)| *name == s.name && Arc::ptr_eq(art, &s.art))
&& self.node == *n
&& self.patterns == doc.patterns
&& self.swatches == doc.swatches
&& self.swatch_groups == doc.swatch_groups
}
}
@@ -183,8 +189,8 @@ thread_local! {
/// The art live object `n` of `doc` draws ([`set_live_art`]); [`crate::live::expand_live`] while
/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc`, a pattern of
/// `doc` or the [`LiveInputs`] have changed since, and on every click while it or the document's
/// symbols or patterns hold a placed document ([`holds_placed`]).
/// `doc`, its swatches or color groups, or the [`LiveInputs`] have changed since, and on every
/// click while it or the document's symbols or patterns hold a placed document ([`holds_placed`]).
fn live_art(doc: &Document, n: &Node) -> Rc<Vec<Node>> {
let inputs = live_inputs();
let kept = EVALUATED.with_borrow_mut(|kept| {
@@ -205,7 +211,16 @@ fn live_art(doc: &Document, n: &Node) -> Rc<Vec<Node>> {
return art;
}
let symbols = doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect();
let e = EvaluatedLive { node: n.clone(), symbols, patterns: doc.patterns.clone(), inputs, art: art.clone(), size };
let e = EvaluatedLive {
node: n.clone(),
symbols,
patterns: doc.patterns.clone(),
swatches: doc.swatches.clone(),
swatch_groups: doc.swatch_groups.clone(),
inputs,
art: art.clone(),
size,
};
EVALUATED.with_borrow_mut(|kept| {
kept.insert(0, e);
kept.truncate(LIVE_KEPT);
@@ -437,7 +452,7 @@ pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<NodeI
/// whole, and an unlocked layer, group, blend or envelope in Edit Contents is searched inside.
fn locked_children(parent: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, out: &mut Vec<NodeId>) {
let Some(children) = parent.children() else { return };
if parent.clips() && children.first().is_some_and(|clip| !clip_contains(clip, p)) {
if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p)) {
return;
}
for i in hit_order(parent, children, p) {
@@ -653,6 +668,15 @@ fn clip_outline_hit(parent: &Node, clip: &Node, p: Point, opt: HitOptions, symbo
clip_outline(clip, p, opt)
}
/// Does isolation mode (`scope`) edit what `parent` holds: is `parent` the isolated container, or
/// the parent of the single object isolated? Then the selection tools hit the art that the
/// clipping mask of `parent` hides, and the Unlock submenu lists it (#3748). The reference
/// app's help says that the parts outside a clipping mask can still be edited
/// (<https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-clipping-masks.html>).
fn edits_inside(parent: &Node, scope: Option<NodeId>) -> bool {
scope.is_some_and(|s| s == parent.id || parent.children().is_some_and(|c| c.iter().any(|c| c.id == s)))
}
fn hit_children(
parent: &Node,
p: Point,
@@ -670,8 +694,10 @@ fn hit_children(
chain.push(clip.id);
return Some(Hit { leaf: clip.id, ancestry: chain.clone(), kind, contents_of: None, layers: 1 });
}
// Elsewhere a clip group (or a layer with a clipping mask) only hits inside it.
if !clip_contains(clip, p) {
// Elsewhere a clip group (or a layer with a clipping mask) only hits inside it, except for
// the selection tools in isolation mode within it.
let edited = opt.clip_outlines && editable_only && edits_inside(parent, opt.scope);
if !edited && !clip_contains(clip, p) {
return None;
}
}
@@ -860,7 +886,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
if opt.outline {
return None;
}
image_paint(n).iter().rev().find_map(|(bp, rule, item)| match item {
image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item {
AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke),
AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill),
})
@@ -936,6 +962,257 @@ fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option
}
}
/// The art of a symbol instance with its own appearance changes, in the symbol's coordinates, and
/// how the canvas places each object of it: through the symbol's 9-slice guides when the instance
/// is scaled by them ([`Document::place_symbol_art`]), otherwise by the instance's transform.
struct InstanceArt {
art: Node,
map: Option<crate::NineSliceMap>,
xf: vectorcraft_geom::Affine,
}
impl InstanceArt {
/// The art of symbol instance `inst`. `None` for anything else, a missing symbol, or art that
/// placing through the guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of,
/// which [`Document::place_symbol_art`] does not place and the canvas does not draw.
fn of(doc: &Document, inst: &Node) -> Option<Self> {
let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None };
let sym = doc.symbols.iter().find(|s| s.name == *symbol)?;
let art = crate::symbol_overrides::dynamic_art(&sym.art, inst);
let map = doc.symbol_slice_map(symbol, *xf);
if map.as_ref().is_some_and(|m| m.most_placed(&art, doc) > crate::MAX_SYMBOL_NODES) {
return None;
}
Some(Self { art, map, xf: *xf })
}
/// The map that the objects inside group or layer `n` are moved by as one piece: `whole`, the
/// map of an object around `n` that is moved as one piece, or else the map of the 9-slice cell
/// `n` lies in ([`crate::NineSliceMap::one_cell`]). `None` when `n` is placed through the guides
/// object by object.
fn whole(&self, n: &Node, doc: &Document, whole: Option<vectorcraft_geom::Affine>) -> Option<vectorcraft_geom::Affine> {
whole.or_else(|| self.map.as_ref()?.one_cell(n, doc))
}
/// Object `n` of the art placed on the canvas as it is drawn, clip groups included: moved by
/// `whole` when an object around it is moved as one piece ([`Self::whole`]). `None` when
/// placing it through the guides could make more than [`crate::MAX_SYMBOL_NODES`] objects, as
/// [`Document::place_symbol_art`] refuses it.
fn place(&self, n: &Node, doc: &Document, whole: Option<vectorcraft_geom::Affine>) -> Option<Node> {
match (&self.map, whole) {
(_, Some(a)) => Some(moved(n, a)),
(Some(m), None) => (m.most_placed(n, doc) <= crate::MAX_SYMBOL_NODES).then(|| m.place(n, doc)),
(None, None) => Some(moved(n, self.xf)),
}
}
/// Object `n` of the art placed on the canvas without clip groups
/// ([`crate::NineSliceMap::place_unclipped`]), as [`Self::place`] places it and within the
/// same limit ([`Document::place_symbol_art_unclipped`]).
fn place_unclipped(&self, n: &Node, doc: &Document, whole: Option<vectorcraft_geom::Affine>) -> Option<Node> {
match (&self.map, whole) {
(_, Some(a)) => Some(moved(n, a)),
(Some(m), None) => (m.most_placed_unclipped(n, doc) <= crate::MAX_SYMBOL_NODES).then(|| m.place_unclipped(n, doc)),
(None, None) => Some(moved(n, self.xf)),
}
}
}
/// `n` transformed by `xf`, its strokes at their own weight.
fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
let mut out = n.clone();
out.transform(xf, false);
out
}
/// The object of symbol instance `inst`'s art under `p`, for Direct Selection on a dynamic symbol's
/// instance: its path of child indices from the art's root ([`crate::symbol_overrides::part`]), the
/// topmost object hit inside the art's groups. With [`HitOptions::clip_outlines`], a press on the
/// outline of the clipping path of a clip group or a clipping layer picks that path before the art
/// it clips, as [`hit_test`] does outside symbols. Hidden, locked and template objects are passed
/// over, as [`hit_test`] passes over them when it looks for editable objects, and so are a Shaper
/// group's original shapes, which the canvas does not draw, and guide paths with
/// [`HitOptions::skip_guides`]. Nothing is picked in art that placing through the symbol's 9-slice
/// guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, which the canvas does not
/// draw. `None` when `inst` is not a symbol instance or no editable object of its art is under `p`.
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
struct Find<'a> {
doc: &'a Document,
art: &'a InstanceArt,
p: Point,
opt: HitOptions,
symbols: &'a SymbolBoxes<'a>,
}
impl Find<'_> {
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>) -> bool {
self.art.place(n, self.doc, whole).is_some_and(|n| hit_any(&n, self.p, self.opt, self.symbols).is_some())
}
fn skips_guide(&self, n: &Node) -> bool {
self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
}
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>) -> bool {
if !n.visible || n.locked || n.is_template() || self.skips_guide(n) {
return false;
}
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole) };
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
return self.hit(n, whole);
}
let whole = self.art.whole(n, self.doc, whole);
if n.clips()
&& let Some(first) = children.first()
{
let Some(clip) = self.art.place_unclipped(first, self.doc, whole) else { return false };
if self.opt.clip_outlines
&& first.visible
&& !first.locked
&& !self.skips_guide(first)
&& clip_outline(&clip, self.p, self.opt).is_some()
{
path.push(0);
return true;
}
if !clip_contains(&clip, self.p) {
return false;
}
}
for (i, c) in children.iter().enumerate().rev() {
// A Shaper group's original shapes are not drawn; symbol art has no isolation scope.
if shaper_hides(n, i, None) {
continue;
}
let Ok(i) = u32::try_from(i) else { continue };
path.push(i);
if self.find(c, path, whole) {
return true;
}
path.pop();
}
false
}
}
let art = InstanceArt::of(doc, inst)?;
let symbols = doc.symbol_boxes();
let mut path = vec![];
Find { doc, art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None).then_some(path)
}
/// The outlines of the object at `path` in symbol instance `inst`'s art (see [`symbol_part_at`]),
/// placed on the canvas as it is drawn: its paths' outlines, and the bounds of objects without a
/// path. Inside a clip group (an object drawn once in each 9-slice cell it reaches is one clip
/// group per cell) they are cut to the bounds of the group's clip path, which is not outlined. An
/// object inside a clip group or a clipping layer of the art, other than its clipping path, is cut
/// to the bounds of that clipping path as well, which contain the region where [`symbol_part_at`]
/// picks it.
/// `None` for art past the 9-slice object limit that [`symbol_part_at`] applies.
pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option<BezPath> {
let art = InstanceArt::of(doc, inst)?;
let part = crate::symbol_overrides::part(&art.art, path)?;
let mut out = BezPath::new();
let mut limit = None;
let mut whole = None;
let mut n = &art.art;
for &i in path {
let children = n.children()?;
whole = art.whole(n, doc, whole);
if i != 0
&& n.clips()
&& let Some(first) = children.first()
&& let Some(clip) = art.place_unclipped(first, doc, whole)?.geometric_bounds()
{
match meet(Some(clip), limit) {
Some(r) => limit = Some(r),
None => return Some(out),
}
}
n = children.get(usize::try_from(i).ok()?)?;
}
outline_within(&art.place(part, doc, whole)?, limit, &mut out);
Some(out)
}
/// [`symbol_part_outline`] for placed object `n`, cut to `limit` when there is one.
fn outline_within(n: &Node, limit: Option<Rect>, out: &mut BezPath) {
use vectorcraft_geom::kurbo::Shape;
if let Some(pd) = n.path_data() {
match limit {
Some(r) => push_cut(out, &pd.to_bezpath(), r),
None => out.extend(pd.to_bezpath()),
}
} else if n.children().is_none()
&& let Some(b) = n.geometric_bounds()
&& let Some(b) = meet(Some(b), limit)
{
out.extend(b.to_path(0.1));
}
let Some(children) = n.children() else { return };
if n.clips()
&& let Some((first, rest)) = children.split_first()
{
let inner = match first.geometric_bounds() {
Some(c) => match meet(Some(c), limit) {
Some(r) => Some(r),
None => return,
},
None => limit,
};
rest.iter().for_each(|c| outline_within(c, inner, out));
return;
}
children.iter().for_each(|c| outline_within(c, limit, out));
}
/// The overlap of `a` and `b` (`a` alone without `b`), `None` when they do not overlap.
fn meet(a: Option<Rect>, b: Option<Rect>) -> Option<Rect> {
let a = a?;
let Some(b) = b else { return Some(a) };
let r = Rect::new(a.x0.max(b.x0), a.y0.max(b.y0), a.x1.min(b.x1), a.y1.min(b.y1));
(r.x0 <= r.x1 && r.y0 <= r.y1).then_some(r)
}
/// The parts of path `p`, flattened to lines, that lie inside `r`, appended to `out`.
fn push_cut(out: &mut BezPath, p: &BezPath, r: Rect) {
use vectorcraft_geom::kurbo::PathEl;
let (mut at, mut start, mut last) = (Point::ZERO, Point::ZERO, None::<Point>);
vectorcraft_geom::kurbo::flatten(p.iter(), 0.1, |el| {
let to = match el {
PathEl::MoveTo(q) => {
(at, start, last) = (q, q, None);
return;
}
PathEl::LineTo(q) => q,
PathEl::ClosePath => start,
_ => return,
};
if let Some((a, b)) = cut_segment(at, to, r) {
if last != Some(a) {
out.move_to(a);
}
out.line_to(b);
last = Some(b);
}
at = to;
});
}
/// The part of segment `a` to `b` inside `r`, `None` when none of it is.
fn cut_segment(a: Point, b: Point, r: Rect) -> Option<(Point, Point)> {
let d = b - a;
let (mut t0, mut t1) = (0.0_f64, 1.0_f64);
for (p, q) in [(-d.x, a.x - r.x0), (d.x, r.x1 - a.x), (-d.y, a.y - r.y0), (d.y, r.y1 - a.y)] {
if p.abs() < 1e-12 {
if q < 0.0 {
return None;
}
} else if p < 0.0 {
t0 = t0.max(q / p);
} else {
t1 = t1.min(q / p);
}
}
(t0 <= t1).then(|| (a + d * t0, a + d * t1))
}
/// The path of compound path `n` under `p`, for the Group Selection tool: the one whose outline is
/// within `tol`, else the innermost one whose area holds `p` (a hole inside an outer shape, an
/// island inside a hole). `None` when `n` isn't a compound path or no part is under `p`.
@@ -954,7 +1231,9 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
/// out those on a locked artboard ([`crate::LockedArtboards::holds_id`]). Symbol instances are measured
/// by their art ([`Node::geometric_bounds_with`]). The art of a clip group or of a layer with a
/// clipping mask counts only when the marquee meets the region its clipping path clips to, and then
/// only within that region's bounds.
/// only within that region's bounds. In isolation mode the clipping mask of the isolated container,
/// or of the parent of the single object isolated, does not limit the marquee, as it does not limit
/// the selection tools' clicks.
pub fn marquee(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool) -> Vec<NodeId> {
marquee_with(doc, r, scope, leaves, false)
}
@@ -972,16 +1251,15 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
// Isolated art whose layer, or a group around it, was locked or hidden afterwards: the
// marquee touches none of it, as clicks don't (#5309).
Some(s) if !doc.is_editable(s.id) => vec![],
Some(s) => match (s.children(), marquee_in(s, r)) {
(Some(c), Some(r)) => c.iter().enumerate().filter(|(i, _)| !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
(Some(_), None) => vec![],
Some(s) => match s.children() {
Some(c) => c.iter().enumerate().filter(|(i, _)| !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
// A single object isolated: only it.
(None, _) => doc
None => doc
.parent_of(s.id)
.and_then(|p| doc.node(p))
.and_then(|p| Some((p.children()?, marquee_in(p, r)?)))
.and_then(|p| p.children())
.into_iter()
.flat_map(|(c, r)| c.iter().filter(|c| c.id == s.id).map(move |c| (c, r)))
.flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, r)))
.collect(),
},
// The objects of the layers, looking through sublayers (hidden, locked and template ones
+238 -4
View File
@@ -255,7 +255,9 @@ fn a_selected_objects_hidden_art_on_a_preview_off_layer_counts_on_its_outline()
/// #2345: a marquee touches a clip group only where its art shows. Over the clipped-away
/// half alone it selects nothing, and around a rectangle drawn beside the group's mask it
/// takes that rectangle alone; reaching into the mask takes the group. The same holds for
/// Group Selection's leaves and in isolation mode.
/// Group Selection's leaves. In isolation mode (#3748) the isolated group's own mask does not
/// limit the marquee, as it does not limit clicks: with the group or the art isolated, the
/// marquee takes the hidden art.
#[test]
fn a_marquee_leaves_a_clip_group_by_its_clipped_away_art() {
let mut d = Document::new(300.0, 200.0);
@@ -270,8 +272,9 @@ fn a_marquee_leaves_a_clip_group_by_its_clipped_away_art() {
let hidden = Rect::new(150.0, -10.0, 210.0, 50.0);
assert!(marquee(&d, hidden, None, false).is_empty());
assert!(marquee(&d, hidden, None, true).is_empty());
assert!(marquee(&d, hidden, Some(g), false).is_empty());
assert!(marquee(&d, hidden, Some(art_id), false).is_empty());
assert_eq!(marquee(&d, hidden, Some(g), false), vec![art_id]);
assert_eq!(marquee(&d, hidden, Some(g), true), vec![art_id]);
assert_eq!(marquee(&d, hidden, Some(art_id), false), vec![art_id]);
// This marquee surrounds the rectangle beside and crosses the hidden art's bottom edge.
assert_eq!(marquee(&d, Rect::new(140.0, 70.0, 195.0, 140.0), None, false), vec![beside]);
// This marquee crosses the shown half's top edge and goes on into the hidden half.
@@ -602,11 +605,41 @@ fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() {
fn a_kept_evaluation_is_stale_after_the_live_inputs_change() {
let d = Document::new(100.0, 100.0);
let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
let e = EvaluatedLive { node: n.clone(), symbols: vec![], patterns: vec![], inputs: 7, art: std::rc::Rc::new(vec![]), size: 0 };
let e = kept_evaluation(&d, &n);
assert!(e.is_of(&d, &n, 7));
assert!(!e.is_of(&d, &n, 8));
}
/// An evaluation of `n` in `d`, with inputs 7, holding no symbols, patterns or art.
fn kept_evaluation(d: &Document, n: &Node) -> EvaluatedLive {
EvaluatedLive {
node: n.clone(),
symbols: vec![],
patterns: vec![],
swatches: d.swatches.clone(),
swatch_groups: d.swatch_groups.clone(),
inputs: 7,
art: std::rc::Rc::new(vec![]),
size: 0,
}
}
/// A kept evaluation is stale once a swatch changes, in a color group too: a painted live effect's
/// pieces name swatches.
#[test]
fn a_kept_evaluation_is_stale_after_a_swatch_changes() {
let mut d = Document::new(100.0, 100.0);
let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
let e = kept_evaluation(&d, &n);
assert!(e.is_of(&d, &n, 7));
d.swatches.first_mut().unwrap().name = "Renamed".into();
assert!(!e.is_of(&d, &n, 7));
let mut d = Document::new(100.0, 100.0);
let e = kept_evaluation(&d, &n);
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Added".into(), swatches: vec![] });
assert!(!e.is_of(&d, &n, 7));
}
/// A rectangle (40, 40)–(140, 140) clipping a filled 200 × 200 square drawn over its edges, in a
/// clip group (or, `layer`, as the first layer's clipping mask): the group (or the layer), the
/// clipping path and the art.
@@ -682,6 +715,82 @@ fn select_behind_takes_a_layer_masks_outline_first() {
assert_eq!(objects_at(&d, Point::new(138.5, 90.0), HitOptions::default(), None), vec![art, clip]);
}
/// #3748: in isolation mode the selection tools hit the art that the isolated clip group (or
/// the isolated layer with a clipping mask) hides outside its mask, and the art when it is the
/// single object isolated; the mask's outline is still hit first. Outside isolation mode, and
/// for the tools that act on what is drawn, the hidden art is not hit. The Unlock submenu
/// lists the hidden art when it is locked.
#[test]
fn isolation_reaches_the_art_a_clipping_mask_hides() {
let hidden = Point::new(170.0, 90.0);
for layer in [false, true] {
let (mut d, g, clip, art) = masked_square(layer);
let isolated = HitOptions { scope: Some(g), ..SELECTING };
assert!(hit_test(&d, hidden, SELECTING).is_none(), "layer {layer}: not isolated");
let h = hit_test(&d, hidden, isolated);
assert_eq!(h.map(|h| (h.leaf, h.top_object(Some(g)))), Some((art, art)), "layer {layer}");
assert_eq!(objects_at(&d, hidden, SELECTING, Some(g)), vec![art], "layer {layer}");
assert_eq!(hit_test(&d, Point::new(140.0, 90.0), isolated).map(|h| h.leaf), Some(clip), "layer {layer}: the outline first");
let one = HitOptions { scope: Some(art), ..SELECTING };
assert_eq!(hit_test(&d, hidden, one).map(|h| h.leaf), Some(art), "layer {layer}: the art isolated");
assert!(hit_test(&d, hidden, HitOptions { scope: Some(g), ..HitOptions::default() }).is_none(), "layer {layer}: drawn art only");
assert!(hit_test_visible(&d, hidden, isolated).is_none(), "layer {layer}: sampling");
d.node_mut(art).unwrap().locked = true;
assert_eq!(locked_objects_at(&d, hidden, HitOptions { scope: Some(g), ..HitOptions::default() }), vec![art], "layer {layer}");
assert!(locked_objects_at(&d, hidden, HitOptions::default()).is_empty(), "layer {layer}: not isolated");
}
}
/// #3748, nested clip groups: with the outer clip group isolated, a click or a marquee takes
/// the art its own mask hides, while the mask of a clip group inside it still limits that
/// group's art. With the inner clip group isolated, or its art, the inner mask does not.
#[test]
fn isolation_reaches_hidden_art_only_for_the_isolated_clip_group() {
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let (outer, outer_clip, outer_art, inner, inner_clip, inner_art) =
(d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id());
let mask = |id, r| {
let mut path = Node::path(id, shapes::rectangle(r), Appearance::basic(Paint::None, Paint::None, 0.0));
if let NodeKind::Path { clipping, .. } = &mut path.kind {
*clipping = true;
}
Arc::new(path)
};
let art = |id, r| Arc::new(Node::path(id, shapes::rectangle(r), Appearance::default_art()));
let inner_group = Node::new(
inner,
NodeKind::Group {
children: vec![mask(inner_clip, Rect::new(60.0, 60.0, 120.0, 120.0)), art(inner_art, Rect::new(40.0, 40.0, 160.0, 160.0))],
clip: true,
},
);
let children =
vec![mask(outer_clip, Rect::new(20.0, 20.0, 180.0, 180.0)), art(outer_art, Rect::new(190.0, 20.0, 260.0, 180.0)), Arc::new(inner_group)];
d.insert(Some(l), 0, Node::new(outer, NodeKind::Group { children, clip: true })).unwrap();
// `outer_hidden` is outside the outer mask, on the outer group's own art; `inner_hidden` is
// inside the outer mask and outside the inner one, on the inner group's art.
let (outer_hidden, inner_hidden, shown) = (Point::new(220.0, 100.0), Point::new(150.0, 100.0), Point::new(90.0, 90.0));
let leaf = |p, scope| hit_test(&d, p, HitOptions { scope, ..SELECTING }).map(|h| h.leaf);
assert_eq!((leaf(outer_hidden, None), leaf(inner_hidden, None)), (None, None), "not isolated");
assert_eq!(leaf(outer_hidden, Some(outer)), Some(outer_art), "outer isolated: its own hidden art");
assert_eq!(leaf(inner_hidden, Some(outer)), None, "outer isolated: the inner mask still clips");
let h = hit_test(&d, shown, HitOptions { scope: Some(outer), ..SELECTING });
assert_eq!(h.map(|h| (h.leaf, h.top_object(Some(outer)))), Some((inner_art, inner)), "outer isolated: shown art");
assert_eq!(leaf(inner_hidden, Some(inner)), Some(inner_art), "inner isolated");
assert_eq!(leaf(outer_hidden, Some(inner)), None, "inner isolated: the outer group's art");
assert_eq!(leaf(inner_hidden, Some(inner_art)), Some(inner_art), "the inner art isolated");
// These marquees cross the right edge of the outer art (outside the outer mask) and of the
// inner art (inside the outer mask, outside the inner one).
let (outer_edge, inner_edge) = (Rect::new(255.0, 95.0, 265.0, 105.0), Rect::new(155.0, 95.0, 165.0, 105.0));
assert_eq!(marquee(&d, outer_edge, Some(outer), false), vec![outer_art]);
assert!(marquee(&d, inner_edge, Some(outer), false).is_empty());
assert!(marquee(&d, inner_edge, Some(outer), true).is_empty());
assert_eq!(marquee(&d, inner_edge, Some(inner), false), vec![inner_art]);
assert!(marquee(&d, inner_edge, None, false).is_empty());
assert!(marquee(&d, outer_edge, None, false).is_empty());
}
/// Art in a sublayer is an object of its own: a click or a marquee takes it, not the
/// sublayer; hidden, locked and template sublayers block both.
#[test]
@@ -1373,3 +1482,128 @@ fn cull_box_holds_the_reach_of_paths_and_compound_paths() {
assert!(holds(cull, reach), "{cull:?} does not hold {reach:?}");
assert_eq!(checked, 201);
}
/// In a dynamic symbol's art, a layer with a clipping mask clips its objects as a clip group does:
/// Direct Selection picks an object only where the mask shows it, and outlines it there.
#[test]
fn an_object_a_clipping_layer_in_symbol_art_hides_is_not_picked_there() {
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let (mask, art) = half_clipped(&mut d);
let mut layer = Node::layer(d.alloc_id(), "Masked", crate::LayerColor::Preset(2));
if let NodeKind::Layer { children, .. } = &mut layer.kind {
*children = vec![Arc::new(mask), Arc::new(art)];
}
layer.set_clips(true);
let root = Node::group(d.alloc_id(), vec![Arc::new(layer)]);
d.symbols.push(crate::Symbol { dynamic: true, name: "Clipped".into(), art: Arc::new(root) });
let inst = d.alloc_id();
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Clipped".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
let n = d.node(inst).unwrap();
let opt = HitOptions::default();
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), Some(vec![0, 1]), "where the mask shows the art");
assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 50.0), opt), None, "where the mask hides it");
let b = vectorcraft_geom::kurbo::Shape::bounding_box(&symbol_part_outline(&d, n, &[0, 1]).unwrap());
assert!((b.x1 - 100.0).abs() < 1e-6, "the outline is cut to the mask: {b:?}");
// Its outline inside the group around the layer is cut too.
let b = vectorcraft_geom::kurbo::Shape::bounding_box(&symbol_part_outline(&d, n, &[0]).unwrap());
assert!((b.x1 - 100.0).abs() < 1e-6, "the layer's outline is cut to the mask: {b:?}");
}
/// In a dynamic symbol's art that placing through its 9-slice guides could make more than
/// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the
/// canvas draws nothing of it. At the art's natural size the same art is picked.
#[test]
fn symbol_art_past_the_object_limit_picks_nothing() {
use vectorcraft_color::{Gradient, GradientPaint};
let mut d = Document::new(400.0, 400.0);
let l = d.layers[0].id;
let leaf = Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()));
let inner = Arc::new(Node::group(d.alloc_id(), vec![leaf; 1_800]));
let mut mask = crate::OpacityMask::new(Node::group(d.alloc_id(), vec![inner; 1_800]), true);
mask.linked = false;
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
// Drawn in six cells, each with its own copy of the mask's 3,240,000 squares.
let mut big = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), Appearance::basic(gradient, Paint::None, 0.0));
big.extras_mut().mask = Some(Box::new(mask));
let plain = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 50.0, 100.0, 100.0)), Appearance::default_art());
let root = Node::group(d.alloc_id(), vec![Arc::new(plain), Arc::new(big)]);
d.symbols.push(crate::Symbol { dynamic: true, name: "Big".into(), art: Arc::new(root) });
d.set_symbol_nine_slice("Big", Some(crate::SymbolNineSlice::default()));
let scaled = d.alloc_id();
let natural = d.alloc_id();
let xf = vectorcraft_geom::Affine::scale_non_uniform(2.0, 1.5);
d.insert(Some(l), 0, Node::new(scaled, NodeKind::SymbolInstance { symbol: "Big".into(), xf })).unwrap();
d.insert(Some(l), 0, Node::new(natural, NodeKind::SymbolInstance { symbol: "Big".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
assert!(d.place_symbol_art("Big", &d.symbols[0].art, xf).is_none(), "the art is past the limit");
let opt = HitOptions::default();
let n = d.node(scaled).unwrap();
assert_eq!(symbol_part_at(&d, n, Point::new(100.0, 110.0), opt), None, "the plain square");
assert_eq!(symbol_part_at(&d, n, Point::new(100.0, 40.0), opt), None, "the masked path");
assert!(symbol_part_outline(&d, n, &[0]).is_none());
assert!(symbol_part_outline(&d, n, &[1]).is_none());
let n = d.node(natural).unwrap();
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 75.0), opt), Some(vec![0]));
assert!(symbol_part_outline(&d, n, &[0]).is_some());
}
/// A clip group that lies in one 9-slice cell is moved by that cell as one piece, everything in it
/// included, so an object in it is picked and outlined there even when placing that object through
/// the guides on its own would pass [`crate::MAX_SYMBOL_NODES`] objects.
#[test]
fn objects_of_a_clip_group_in_one_cell_are_placed_with_it() {
use vectorcraft_color::{Gradient, GradientPaint};
let mut d = Document::new(400.0, 400.0);
let l = d.layers[0].id;
let leaf = Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()));
let inner = Arc::new(Node::group(d.alloc_id(), vec![leaf; 1_800]));
let mut mask = crate::OpacityMask::new(Node::group(d.alloc_id(), vec![inner; 1_800]), true);
mask.linked = false;
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
let mut big = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(gradient, Paint::None, 0.0));
big.extras_mut().mask = Some(Box::new(mask));
let clip = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art());
let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(big.clone())]);
group.set_clips(true);
let frame = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art());
let root = Node::group(d.alloc_id(), vec![Arc::new(frame), Arc::new(group)]);
d.symbols.push(crate::Symbol { dynamic: true, name: "Corner".into(), art: Arc::new(root) });
d.set_symbol_nine_slice("Corner", Some(crate::SymbolNineSlice::default()));
let inst = d.alloc_id();
let xf = vectorcraft_geom::Affine::scale_non_uniform(2.0, 1.5);
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Corner".into(), xf })).unwrap();
let m = d.symbol_slice_map("Corner", xf).unwrap();
assert!(m.most_placed(&big, &d) > crate::MAX_SYMBOL_NODES, "the object alone is past the limit");
assert!(d.place_symbol_art("Corner", &d.symbols[0].art, xf).is_some(), "the art is drawn");
let n = d.node(inst).unwrap();
assert_eq!(symbol_part_at(&d, n, Point::new(10.0, 10.0), HitOptions::default()), Some(vec![1, 1]));
let b = vectorcraft_geom::kurbo::Shape::bounding_box(&symbol_part_outline(&d, n, &[1, 1]).unwrap());
assert!((b.x1 - 20.0).abs() < 1e-6 && (b.y1 - 20.0).abs() < 1e-6, "cut to the clip in its corner: {b:?}");
}
/// In a dynamic symbol's art, Direct Selection does not pick a Shaper group's original shapes,
/// which the canvas does not draw: a click over an original shape whose face the group erased
/// picks nothing, and a click over the face it shows picks the face.
#[test]
fn a_shaper_groups_original_shapes_in_symbol_art_are_not_picked() {
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 100.0, 100.0));
let a = Node::path(d.alloc_id(), square(0.0), Appearance::default_art());
let b = Node::path(d.alloc_id(), square(50.0), Appearance::default_art());
let mut sources = Node::group(d.alloc_id(), vec![Arc::new(a), Arc::new(b)]);
sources.name = Some(crate::shaper::SOURCES.into());
sources.opacity = 0.0;
let mut face = Node::path(d.alloc_id(), square(0.0), Appearance::default_art());
face.name = Some(format!("{}0", crate::shaper::FILL_PREFIX));
let mut group = Node::group(d.alloc_id(), vec![Arc::new(sources), Arc::new(face)]);
group.extras_mut().shaper = Some(Box::default());
let root = Node::group(d.alloc_id(), vec![Arc::new(group)]);
d.symbols.push(crate::Symbol { dynamic: true, name: "Shaped".into(), art: Arc::new(root) });
let inst = d.alloc_id();
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Shaped".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
let n = d.node(inst).unwrap();
let opt = HitOptions::default();
assert_eq!(symbol_part_at(&d, n, Point::new(130.0, 50.0), opt), None, "over the erased original shape");
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), Some(vec![0, 1]), "over the shown face");
}
+19
View File
@@ -90,6 +90,24 @@ impl Paths {
/// object and look the next one up, again and again).
const MISSES_PER_REBUILD: u32 = 4;
thread_local! {
/// [`tree_walks`] of this thread.
static TREE_WALKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// How many times lookups by id on this thread have walked a document's tree, reading up to all of
/// its nodes: one count per search of the tree and per rebuild of the cache. An edit that looks its
/// objects up one at a time counts about one walk per object; one that looks them all up at once
/// counts a few.
pub fn tree_walks() -> u64 {
TREE_WALKS.get()
}
/// Adds one to [`tree_walks`].
pub(crate) fn note_tree_walk() {
TREE_WALKS.set(TREE_WALKS.get().saturating_add(1));
}
/// The cache, shared by clones of a document (each checks every path it uses against its own tree).
#[derive(Default)]
pub struct IdIndex(RwLock<Option<Arc<Paths>>>, std::sync::atomic::AtomicU32);
@@ -125,6 +143,7 @@ impl IdIndex {
}
}
}
note_tree_walk();
let mut out = Paths::default();
walk(layers, u32::MAX, &mut out);
let out = Arc::new(out);
+1
View File
@@ -71,6 +71,7 @@ impl Document {
}
if changed {
t.cached_bounds = None;
t.cached_ink = None;
}
changed
}
+15 -6
View File
@@ -19,6 +19,7 @@ pub mod graph;
mod halftone_radii;
pub mod hit;
mod id_index;
pub use id_index::tree_walks;
pub mod inks;
mod inline;
pub mod intertwine;
@@ -108,7 +109,7 @@ pub use placed_document::{PageBox, PlacedDocument};
pub use profiles::ColorProfiles;
pub use puppet::{PuppetPin, PuppetPins};
pub use rastersettings::{RasterColorModel, RasterEffectsSettings};
pub use selection::{AnchorRef, SegmentRef, Selection};
pub use selection::{AnchorRef, SegmentRef, Selection, SymbolPart};
pub use setup::{Background, DocSetup, ExportText, GridSize, Quotes};
pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOptions, SliceSource};
pub use style_libs::StyleLibrary;
@@ -116,10 +117,11 @@ pub use text::FontHeightReference;
pub use text::GlyphChoice;
pub use text::{
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
JustificationOptions, Justify, Kinsoku, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign, RubyPosition,
RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign,
WrapShape,
JustificationOptions, Justify, Kinsoku, KinsokuShoriType, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign,
RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap,
VerticalAlign, WrapShape,
};
pub use text::{CharClass, CompositeFont, CompositePart, CompositeParts};
pub use trace::TraceView;
pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables};
pub use vectorcraft_color as color;
@@ -140,7 +142,7 @@ mod limits;
mod records;
mod units;
pub use artboard::{Artboard, LockedArtboards, RetiredArtboardId, VIDEO_PIXEL_ASPECT_RANGE, VIDEO_SAFE_INSETS};
pub use artboard::{ARTBOARD_GAP, Artboard, ArtboardSide, LockedArtboards, RetiredArtboardId, VIDEO_PIXEL_ASPECT_RANGE, VIDEO_SAFE_INSETS};
pub use canvas_range::BeyondCanvas;
#[cfg(test)]
use document_ext::free_id;
@@ -149,7 +151,7 @@ pub use guides::{GridPrefs, Guide, RulerMode};
#[cfg(test)]
use limits::MAX_NEXT_ID;
pub use limits::{DocError, FORMAT_VERSION, MAX_COORD};
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, Symbol, SymbolEdit};
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit};
pub use units::{ColorMode, Unit, parse_number};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -194,6 +196,9 @@ pub struct Document {
/// Paragraph styles (besides the built-in [Normal Paragraph Style]).
#[serde(default, skip_serializing_if = "skip::is_empty_vec")]
pub para_styles: Shared<Vec<TextStyleDef>>,
/// Type › Composite Fonts…: the composite fonts defined in the document, by name.
#[serde(default, skip_serializing_if = "skip::is_empty_vec")]
pub composite_fonts: Shared<Vec<CompositeFont>>,
/// Threaded text: area-type frames one story flows through, in order.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub text_threads: Vec<Vec<NodeId>>,
@@ -309,6 +314,10 @@ pub struct Document {
/// given) SVG export links with `<script>` elements, in order.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub svg_scripts: Vec<String>,
/// Effect › SVG Filters: the SVG filters the document holds (at most [`SvgFilter::MAX`]), in
/// the order the submenu lists them.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub svg_filters: Vec<SvgFilter>,
/// Puppet Warp pins on the selected artwork while the tool edits it ([`PuppetPins`]): editing
/// state, never saved.
#[serde(skip)]
+96
View File
@@ -415,6 +415,68 @@ impl Document {
}
}
/// [`Self::update_links`] for the links `pick` holds for only, in one pass; only the nodes on the
/// way to one are copied.
pub fn update_links_where(&mut self, pick: impl Fn(&LinkInfo) -> bool, mut f: impl FnMut(&mut LinkInfo)) {
fn link_of(n: &Node) -> Option<&LinkInfo> {
match &n.kind {
NodeKind::Image(image) => image.link.as_ref(),
NodeKind::PlacedDocument(placed) => Some(&placed.link),
_ => None,
}
}
/// `n` updated in place, a copy of it when shared; left as it is when it holds no picked link.
fn update(n: &mut Arc<Node>, pick: &dyn Fn(&LinkInfo) -> bool, f: &mut dyn FnMut(&mut LinkInfo)) {
// Each child is updated through a second handle, so an updated child is a new node and a new
// pointer marks a change.
let mask = n.extras().mask.as_ref().and_then(|m| {
let mut art = Arc::clone(&m.art);
update(&mut art, pick, f);
(!Arc::ptr_eq(&art, &m.art)).then_some(art)
});
let mut children = vec![];
for (i, c) in n.children().into_iter().flatten().enumerate() {
let mut new = Arc::clone(c);
update(&mut new, pick, f);
if !Arc::ptr_eq(&new, c) {
children.push((i, new));
}
}
let own = link_of(n).is_some_and(pick);
if !own && mask.is_none() && children.is_empty() {
return;
}
let n = Arc::make_mut(n);
let link = match &mut n.kind {
NodeKind::Image(image) => image.link.as_mut(),
NodeKind::PlacedDocument(placed) => Some(&mut placed.link),
_ => None,
};
if let Some(link) = link.filter(|_| own) {
f(link);
}
if let (Some(art), Some(m)) = (mask, n.extras_if_any().and_then(|e| e.mask.as_mut())) {
m.art = art;
}
if let Some(slots) = n.children_mut() {
for (i, c) in children {
if let Some(slot) = slots.get_mut(i) {
*slot = c;
}
}
}
}
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| &mut p.art));
for root in roots {
update(root, &pick, &mut f);
}
}
/// Change every image object (in the layers, symbol definitions and pattern swatches, opacity-mask
/// art included) for which `pick` holds; only the subtrees holding one are copied.
pub fn update_images(&mut self, pick: impl Fn(&ImageObject) -> bool, mut f: impl FnMut(&mut ImageObject)) {
@@ -486,6 +548,40 @@ mod tests {
.unwrap()
}
/// `update_links_where` changes only the picked links, in a copy of the nodes on the way to them;
/// the other nodes stay shared with the document it was cloned from.
#[test]
fn update_links_where_copies_only_the_nodes_it_changes() {
let mut d = Document::new(10.0, 10.0);
image(&mut d, "a", Some(LinkInfo::new("/art/a.png")));
image(&mut d, "b", Some(LinkInfo::new("/art/b.png")));
image(&mut d, "c", None);
let mut copy = d.clone();
let mut calls = 0;
copy.update_links_where(
|l| l.path == "/art/a.png",
|l| {
calls += 1;
l.relative = Some("art/a.png".into());
},
);
assert_eq!(calls, 1);
let node = |d: &Document, key: &str| {
d.layers[0].children().unwrap().iter().find(|n| matches!(&n.kind, NodeKind::Image(im) if im.key == key)).unwrap().clone()
};
let relative = |n: &Node| match &n.kind {
NodeKind::Image(im) => im.link.as_ref().and_then(|l| l.relative.clone()),
_ => None,
};
assert_eq!((relative(&node(&copy, "a")), relative(&node(&d, "a"))), (Some("art/a.png".into()), None));
assert!(Arc::ptr_eq(&node(&copy, "b"), &node(&d, "b")) && Arc::ptr_eq(&node(&copy, "c"), &node(&d, "c")));
assert!(!Arc::ptr_eq(&copy.layers[0], &d.layers[0]));
// Nothing picked: nothing is copied.
let mut same = d.clone();
same.update_links_where(|_| false, |_| {});
assert!(Arc::ptr_eq(&same.layers[0], &d.layers[0]));
}
#[test]
fn the_placeholder_is_a_png() {
let png = missing_placeholder().unwrap();
+300 -2
View File
@@ -53,8 +53,9 @@ pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation,
#[cfg(test)]
use blend_spec::{blend_color_shift, blend_ramp};
pub use envelope::{
EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, envelope_bounds, envelope_content_boxes,
envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of, envelope_overlay, envelope_stroke_margin, smooth_handles,
EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, TypeInk, envelope_bounds, envelope_content_bounds,
envelope_content_boxes, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of, envelope_overlay, envelope_stroke_margin,
set_type_ink, smooth_handles,
};
pub(crate) use expand::max_outset;
pub use expand::{
@@ -173,6 +174,303 @@ mod tests {
assert!((c.x - 105.0).abs() < 1e-6 && (c.y + 10.0).abs() < 1e-6, "{c:?}");
}
/// A 100 × 50 outline whose top side runs (0,0) → (30,0) → (100,0) as two straight segments.
fn top_split_at_30() -> PathData {
let a = |x: f64, y: f64| Anchor::corner(Point::new(x, y));
PathData::single(SubPath::new(vec![a(0.0, 0.0), a(30.0, 0.0), a(100.0, 0.0), a(100.0, 50.0), a(0.0, 50.0)], true))
}
/// The length of `c`'s control polygon.
fn polygon(c: CubicBez) -> f64 {
c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3)
}
/// An anchor and its incoming and outgoing handles.
type Knot = ((f64, f64), (f64, f64), (f64, f64));
/// A closed path through `pts`.
fn outline(pts: &[Knot]) -> PathData {
let a = |&(p, i, o): &Knot| Anchor { p: p.into(), h_in: i.into(), h_out: o.into(), ..Anchor::corner(p.into()) };
PathData::single(SubPath::new(pts.iter().map(a).collect(), true))
}
#[test]
fn a_top_object_side_of_straight_segments_spreads_by_length() {
// The top side runs (0,0) → (30,0) → (100,0): each straight piece takes its length's share.
let kind = EnvelopeKind::TopObject { path: top_split_at_30(), corners: None };
let map = envelope_mapper(&kind, Rect::new(0.0, 0.0, 100.0, 50.0));
for (q, want) in [((50.0, 0.0), (50.0, 0.0)), ((15.0, 0.0), (15.0, 0.0)), ((80.0, 0.0), (80.0, 0.0)), ((50.0, 25.0), (50.0, 25.0))] {
let p = map(Point::new(q.0, q.1));
assert!(p.distance(Point::new(want.0, want.1)) < 1e-6, "{q:?} → {p:?}, want {want:?}");
}
}
#[test]
fn a_top_object_shares_a_side_by_control_polygon_length() {
// Two curves of unequal polygons make the top side; the anchor between them lands at the
// first one's share, and inside each curve the content follows its parameter.
let first = CubicBez::new((0.0, 0.0), (10.0, -20.0), (30.0, -20.0), (40.0, 0.0));
let second = CubicBez::new((40.0, 0.0), (60.0, 10.0), (90.0, 10.0), (100.0, 0.0));
let path = outline(&[
((0.0, 0.0), (0.0, 0.0), (10.0, -20.0)),
((40.0, 0.0), (30.0, -20.0), (60.0, 10.0)),
((100.0, 0.0), (90.0, 10.0), (100.0, 0.0)),
((100.0, 80.0), (100.0, 80.0), (100.0, 80.0)),
((0.0, 80.0), (0.0, 80.0), (0.0, 80.0)),
]);
let c = Coons::from_top_object(&path, None).unwrap();
let share = polygon(first) / (polygon(first) + polygon(second));
assert!(c.eval(share, 0.0).distance(Point::new(40.0, 0.0)) < 1e-9, "{:?}", c.eval(share, 0.0));
for f in [0.25, 0.5, 0.75] {
let p = c.eval(share * f, 0.0);
assert!(p.distance(first.eval(f)) < 1e-9, "first curve at {f}: {p:?}");
let p = c.eval(share + (1.0 - share) * f, 0.0);
assert!(p.distance(second.eval(f)) < 1e-9, "second curve at {f}: {p:?}");
}
}
#[test]
fn a_rounded_rectangle_top_object_stays_close_to_the_identity() {
// The corners fall at the middle of each corner arc. Each half arc takes the share of its
// control polygon, so the straight edges stay close to where the content was.
let r = Rect::new(0.0, 0.0, 200.0, 100.0);
let path = shapes::rounded_rectangle(r, 10.0);
let c = Coons::from_top_object(&path, None).unwrap();
let [tl, tr, br, bl] = c.corners();
let k = 10.0 * (1.0 - std::f64::consts::FRAC_1_SQRT_2);
for (p, want) in [(tl, (k, k)), (tr, (200.0 - k, k)), (br, (200.0 - k, 100.0 - k)), (bl, (k, 100.0 - k))] {
assert!(p.distance(Point::from(want)) < 0.01, "corner {p:?}, want {want:?}");
}
for (u, v) in [(0.25, 0.0), (0.5, 0.0), (0.8, 1.0), (0.0, 0.5), (0.5, 0.5), (1.0, 0.3)] {
let p = c.eval(u, v);
assert!(p.distance(Point::new(200.0 * u, 100.0 * v)) < 3.0, "({u}, {v}) → {p:?}");
}
// The top edge starts after the first half arc's share.
let sp = &path.subpaths[0];
let edge = Point::new(10.0, 0.0);
let arc = (0..sp.segment_count())
.filter(|i| !sp.segment_is_line(*i))
.map(|i| sp.segment(i))
.find(|s| s.p0.distance(edge) < 1e-9 || s.p3.distance(edge) < 1e-9)
.unwrap();
let half = polygon(if arc.p3.distance(edge) < 1e-9 { arc.subsegment(0.5..1.0) } else { arc.subsegment(0.0..0.5) });
let p = c.eval(half / (2.0 * half + 180.0), 0.0);
assert!(p.distance(Point::new(10.0, 0.0)) < 1e-6, "{p:?}");
}
#[test]
fn a_top_object_corner_inside_a_bulging_curve_is_the_nearest_outline_point() {
// The top left anchor's handle bulges out past the corner, so the anchor turns inward
// there and the corner falls inside the curve.
// The outline's bounding box starts at (-7.957, -22.222); the top curve's point nearest
// that corner, found by sampling the curve 2,000,000 times, is (-5.072093, -18.127254).
let path = outline(&[
((0.0, 0.0), (0.0, 0.0), (-50.0, -50.0)),
((200.0, 0.0), (150.0, 0.0), (200.0, 0.0)),
((200.0, 100.0), (200.0, 100.0), (200.0, 100.0)),
((0.0, 100.0), (0.0, 100.0), (0.0, 100.0)),
]);
let want = Point::new(-5.072093, -18.127254);
let tl = Coons::from_top_object(&path, None).unwrap().corners()[0];
assert!(tl.distance(want) < 1e-5, "{tl:?}, want {want:?}");
assert!(tl.distance(Point::ZERO) > 1.0, "{tl:?}");
}
#[test]
fn a_top_object_corner_takes_an_anchor_only_near_its_box_corner() {
// A chamfered top left corner of a 200 × 100 outline. With both chamfer anchors within
// 47.5% of the box from its corner, the nearer anchor is the corner.
let chamfer = |a: (f64, f64), b: (f64, f64)| {
let c = |p: (f64, f64)| (p, p, p);
outline(&[c(a), c(b), c((200.0, 0.0)), c((200.0, 100.0)), c((0.0, 100.0))])
};
let tl = Coons::from_top_object(&chamfer((0.0, 46.0), (94.0, 0.0)), None).unwrap().corners()[0];
assert!(tl.distance(Point::new(0.0, 46.0)) < 1e-9, "{tl:?}");
// Farther out, neither anchor counts: the corner is the chamfer's point nearest the box corner.
let tl = Coons::from_top_object(&chamfer((0.0, 50.0), (100.0, 0.0)), None).unwrap().corners()[0];
assert!(tl.distance(Point::new(20.0, 40.0)) < 1e-6, "{tl:?}");
}
#[test]
fn a_top_object_corner_skips_smooth_and_inward_anchors() {
// A top left anchor whose outgoing handle turns from its incoming one by `deg` degrees
// (positive turns out of the outline). The top side bulges up past it.
let shape = |deg: f64| {
let a = deg.to_radians();
let (hx, hy) = (50.0 * a.cos() + 40.0 * a.sin(), 40.0 * a.cos() - 50.0 * a.sin());
outline(&[
((50.0, -300.0), (25.0, -280.0), (50.0 + hx, -300.0 - hy)),
((250.0, -300.0), (200.0, -340.0), (250.0, -300.0)),
((250.0, -200.0), (250.0, -200.0), (250.0, -200.0)),
((50.0, -200.0), (50.0, -200.0), (50.0, -230.0)),
])
};
let corner = |deg: f64| Coons::from_top_object(&shape(deg), None).unwrap().corners()[0];
let anchor = Point::new(50.0, -300.0);
for deg in [0.0, 0.4, 0.6, -1.5] {
assert!(corner(deg).distance(anchor) > 1.0, "{deg}°: {:?}", corner(deg));
}
for deg in [0.9, 1.5, 10.0] {
assert!(corner(deg).distance(anchor) < 1e-9, "{deg}°: {:?}", corner(deg));
}
}
#[test]
fn a_top_object_corner_skips_an_inward_anchor_between_straight_segments() {
// A 200 × 100 outline of straight segments with a notch at its top left: (40,40) is the
// anchor nearest the box corner, but it turns into the outline, so (60,0) is the corner.
let c = |p: (f64, f64)| (p, p, p);
let path = outline(&[c((60.0, 0.0)), c((200.0, 0.0)), c((200.0, 100.0)), c((0.0, 100.0)), c((0.0, 60.0)), c((40.0, 40.0))]);
let tl = Coons::from_top_object(&path, None).unwrap().corners()[0];
assert!(tl.distance(Point::new(60.0, 0.0)) < 1e-9, "{tl:?}");
}
#[test]
fn a_top_object_corner_tie_goes_to_the_first_anchor() {
// Both chamfer anchors lie 30 from the box corner: the first one along the outline, in
// the order it was drawn, wins.
let c = |p: (f64, f64)| (p, p, p);
let tl = |pts: &[Knot]| Coons::from_top_object(&outline(pts), None).unwrap().corners()[0];
let from_left = tl(&[c((0.0, 30.0)), c((30.0, 0.0)), c((100.0, 0.0)), c((100.0, 100.0)), c((0.0, 100.0))]);
assert!(from_left.distance(Point::new(0.0, 30.0)) < 1e-9, "{from_left:?}");
let from_top = tl(&[c((30.0, 0.0)), c((100.0, 0.0)), c((100.0, 100.0)), c((0.0, 100.0)), c((0.0, 30.0))]);
assert!(from_top.distance(Point::new(30.0, 0.0)) < 1e-9, "{from_top:?}");
// Drawn counter-clockwise, the anchor met first in that order wins.
let back = tl(&[c((0.0, 100.0)), c((100.0, 100.0)), c((100.0, 0.0)), c((30.0, 0.0)), c((0.0, 30.0))]);
assert!(back.distance(Point::new(30.0, 0.0)) < 1e-9, "{back:?}");
let back = tl(&[c((0.0, 30.0)), c((0.0, 100.0)), c((100.0, 100.0)), c((100.0, 0.0)), c((30.0, 0.0))]);
assert!(back.distance(Point::new(0.0, 30.0)) < 1e-9, "{back:?}");
}
#[test]
fn a_reflected_top_object_keeps_the_corners_a_file_gives() {
// Reflecting the outline across x = 0 keeps its anchors in the same order, now running
// counter-clockwise: the corners stay on the same anchors, so the content is reflected too.
let mut path = top_split_at_30();
path.transform(Affine::FLIP_X);
let c = Coons::from_top_object(&path, Some([1, 2, 3, 4])).unwrap();
let want = [(-30.0, 0.0), (-100.0, 0.0), (-100.0, 50.0), (0.0, 50.0)].map(Point::from);
assert!(c.corners().iter().zip(want).all(|(p, q)| p.distance(q) < 1e-9), "{:?}", c.corners());
let p = c.eval(0.5, 0.5);
assert!(p.distance(Point::new(-50.0, 17.5)) < 1e-9, "{p:?}");
}
#[test]
fn a_top_object_keeps_the_corners_a_file_gives() {
let same = |a: [Point; 4], b: [Point; 4]| a.iter().zip(b).all(|(p, q)| p.distance(q) < 1e-9);
let want = [(30.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)].map(Point::from);
let c = Coons::from_top_object(&top_split_at_30(), Some([1, 2, 3, 4])).unwrap();
assert!(same(c.corners(), want), "{:?}", c.corners());
// Drawn the other way round, with the corners counted along that order.
let mut back = top_split_at_30();
back.subpaths[0].reverse();
let c = Coons::from_top_object(&back, Some([3, 2, 1, 0])).unwrap();
assert!(same(c.corners(), want), "{:?}", c.corners());
// Corners that repeat, run out of order or go past the outline are found from it instead.
let found = [(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)].map(Point::from);
for bad in [[0, 0, 3, 4], [2, 1, 3, 4], [1, 2, 3, 9]] {
let c = Coons::from_top_object(&top_split_at_30(), Some(bad)).unwrap();
assert!(same(c.corners(), found), "{bad:?}: {:?}", c.corners());
}
}
#[test]
fn a_split_curve_moves_the_top_object_share_to_its_new_anchor() {
// Splitting the top curve at t = 0.3 keeps its shape but changes the polygon shares: the
// new anchor lands at the first piece's share, not at u = 0.3.
let top = CubicBez::new((0.0, 0.0), (40.0, -40.0), (160.0, -40.0), (200.0, 0.0));
let (a, b) = (top.subsegment(0.0..0.3), top.subsegment(0.3..1.0));
let path = outline(&[
((0.0, 0.0), (0.0, 0.0), a.p1.into()),
(a.p3.into(), a.p2.into(), b.p1.into()),
((200.0, 0.0), b.p2.into(), (200.0, 0.0)),
((200.0, 100.0), (200.0, 100.0), (200.0, 100.0)),
((0.0, 100.0), (0.0, 100.0), (0.0, 100.0)),
]);
let c = Coons::from_top_object(&path, None).unwrap();
let share = polygon(a) / (polygon(a) + polygon(b));
assert!(c.eval(share, 0.0).distance(a.p3) < 1e-9, "{:?}", c.eval(share, 0.0));
assert!((share - 0.3).abs() > 0.01, "{share}");
}
#[test]
fn a_rectangle_top_object_is_the_identity() {
let r = Rect::new(10.0, 20.0, 110.0, 70.0);
let c = Coons::from_top_object(&shapes::rectangle(r), None).unwrap();
for (u, v) in [(0.125, 0.3), (0.9, 0.05), (0.37, 0.81)] {
let p = c.eval(u, v);
assert!(p.distance(Point::new(10.0 + 100.0 * u, 20.0 + 50.0 * v)) < 1e-9, "({u}, {v}) → {p:?}");
}
}
#[test]
fn a_straight_line_top_object_maps_onto_its_bounding_box() {
let line = PathData::single(SubPath::new(vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor::corner(Point::new(100.0, 40.0))], false));
let p = Coons::from_top_object(&line, None).unwrap().eval(0.25, 0.75);
assert!(p.distance(Point::new(25.0, 30.0)) < 1e-9, "{p:?}");
}
#[test]
fn a_top_object_spreads_a_segment_by_its_parameter() {
// The top side is one straight segment whose handles sit at 60 and 80: its parameter
// reaches the middle at x = 63.75, not at 45.
let mut top = vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor::corner(Point::new(90.0, 0.0))];
top[0].h_out = Point::new(60.0, 0.0);
top[1].h_in = Point::new(80.0, 0.0);
top.extend([Anchor::corner(Point::new(90.0, 40.0)), Anchor::corner(Point::new(0.0, 40.0))]);
let kind = EnvelopeKind::TopObject { path: PathData::single(SubPath::new(top, true)), corners: None };
let map = envelope_mapper(&kind, Rect::new(0.0, 0.0, 10.0, 10.0));
let p = map(Point::new(5.0, 0.0));
assert!(p.distance(Point::new(63.75, 0.0)) < 1e-6, "{p:?}");
let p = map(Point::new(5.0, 10.0));
assert!(p.distance(Point::new(45.0, 40.0)) < 1e-6, "{p:?}");
}
#[test]
fn a_top_object_follows_a_curved_side_by_its_parameter() {
// The top side bends down from (0,0) to (100,0) through handles at (20,30) and (90,30):
// halfway along its parameter it passes (53.75, 22.5).
let mut top = vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor::corner(Point::new(100.0, 0.0))];
top[0].h_out = Point::new(20.0, 30.0);
top[1].h_in = Point::new(90.0, 30.0);
top.extend([Anchor::corner(Point::new(100.0, 80.0)), Anchor::corner(Point::new(0.0, 80.0))]);
let path = PathData::single(SubPath::new(top, true));
let c = Coons::from_top_object(&path, None).unwrap();
for (u, t) in [(0.5, 0.5), (0.25, 0.25), (0.8125, 0.8125)] {
let want = CubicBez::new((0.0, 0.0), (20.0, 30.0), (90.0, 30.0), (100.0, 0.0)).eval(t);
let p = c.eval(u, 0.0);
assert!(p.distance(want) < 1e-6, "u {u}: {p:?} vs {want:?}");
}
// Drawn the other way round, the outline gives the same patch.
let mut back = path.clone();
back.subpaths[0].reverse();
let p = Coons::from_top_object(&back, None).unwrap().eval(0.5, 0.0);
assert!(p.distance(Point::new(53.75, 22.5)) < 1e-6, "{p:?}");
}
#[test]
fn a_top_object_side_of_many_segments_keeps_each_corner() {
// The top side zigzags through `n` straight segments, between y = 0 and y = 2.
for n in [3, 100] {
let w = f64::from(n);
let zig = |i: i32| Point::new(f64::from(i) * 100.0 / w, if i % 2 == 1 { 2.0 } else { 0.0 });
let mut pts: Vec<Anchor> = (0..=n).map(|i| Anchor::corner(zig(i))).collect();
pts.extend([Anchor::corner(Point::new(100.0, 50.0)), Anchor::corner(Point::new(0.0, 50.0))]);
let c = Coons::from_top_object(&PathData::single(SubPath::new(pts, true)), None).unwrap();
for i in (1..n).filter(|i| n < 10 || [1, 37, 38, 99].contains(i)) {
let p = c.eval(f64::from(i) / w, 0.0);
assert!(p.distance(zig(i)) < 1e-9, "{n} segments, anchor {i}: {p:?}");
}
}
}
#[test]
fn a_gradient_mesh_outline_keeps_its_sides_measured_by_length() {
let c = Coons::from_path(&top_split_at_30()).unwrap();
let p = c.eval(0.5, 0.0);
assert!(p.distance(Point::new(50.0, 0.0)) < 1e-6, "{p:?}");
}
#[test]
fn grid_identity() {
let r = Rect::new(0.0, 0.0, 100.0, 100.0);
+405 -20
View File
@@ -1,6 +1,7 @@
use super::expand::{Hooks, Outliner, Warper, map_node};
use super::mesh::{GradientMesh, MeshPoint, grid_len, grid_points, nodes_bounds, surface_of};
use super::mesh::{GradientMesh, MeshPoint, grid_len, grid_points, surface_of};
use super::{Affine, Arc, Color, Deserialize, Node, NodeId, NodeKind, PathData, Point, Rect, Serialize, Vec2, yes};
use vectorcraft_geom::Homography;
/// How an envelope distorts its content.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -31,7 +32,14 @@ pub enum EnvelopeKind {
handles: Vec<[Vec2; 4]>,
},
/// The content's bounding box maps onto the outline of this path.
TopObject { path: PathData },
TopObject {
path: PathData,
/// The anchors (indices into the outline, the path's largest subpath, in its own order)
/// at the top left, top right, bottom right and bottom left corners, as a saved file gives
/// them. `None`: the corners are found from the outline.
#[serde(default, skip_serializing_if = "Option::is_none")]
corners: Option<[u32; 4]>,
},
}
/// Envelope Options → Preserve Shape Using: how a distorted raster keeps the envelope's shape.
@@ -127,19 +135,294 @@ impl EnvelopeOptions {
}
}
/// The bounds of `content` in the axes of `frame`, with its strokes and geometric. Strokes scale
/// with the frame as [`Node::transform`] scales them.
/// The bounds of `content` in the axes of `frame`, with its strokes and geometric, type measured by
/// its glyph outlines (see [`envelope_content_bounds`]). Strokes scale with the frame as
/// [`Node::transform`] scales them.
pub fn envelope_content_boxes(content: &[Arc<Node>], frame: Affine) -> Option<(Rect, Rect)> {
let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY };
let to_frame = frame.inverse();
let (stroked, plain) = content.iter().fold((None, None), |(stroked, plain), c| {
let mut m = (**c).clone();
m.transform(to_frame, true);
(vectorcraft_geom::union_opt(stroked, m.visual_bounds()), vectorcraft_geom::union_opt(plain, m.geometric_bounds()))
(vectorcraft_geom::union_opt(stroked, content_box(c, true, to_frame)), vectorcraft_geom::union_opt(plain, content_box(c, false, to_frame)))
});
Some((stroked?, plain?))
}
/// The geometric bounds an envelope around `content` on the page axes maps from: type, alone or
/// in groups and layers, is measured by its glyph outlines, underlines and strikethroughs instead
/// of its laid-out box. Type keeps its laid-out box while nothing is registered with
/// [`set_type_ink`], and when it draws nothing.
pub fn envelope_content_bounds(content: &[Arc<Node>]) -> Option<Rect> {
content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, false, Affine::IDENTITY)))
}
/// The box of type's glyph outlines, underlines and strikethroughs with its text space mapped by
/// the given transform (outlines mapped point by point) and, for type in perspective, then drawn
/// through its projection and mapped by the second transform. `None` when it draws nothing. Type is
/// laid out above this crate, so the text crate registers one with [`set_type_ink`].
pub type TypeInk = fn(&crate::TextObject, Affine, Option<(Homography, Affine)>) -> Option<Rect>;
/// What [`TypeInk`] maps type's text space by: a transform, and a projection with the transform
/// after it.
type TypeMap = (Affine, Option<(Homography, Affine)>);
static TYPE_INK: std::sync::OnceLock<(TypeInk, crate::hit::LiveInputs)> = std::sync::OnceLock::new();
/// Register how envelopes measure type, and a number that changes whenever what it reads besides
/// the type changes, such as the installed fonts (the first registration stays).
pub fn set_type_ink(f: TypeInk, inputs: crate::hit::LiveInputs) {
// Already set: the same measure, registered by another session, an import or a renderer.
let _ = TYPE_INK.set((f, inputs));
}
/// How many entries each table of [`TypeInks`] holds before it is emptied.
const TYPE_INK_KEPT: usize = 1024;
/// `map`, bit for bit, for a table key.
fn map_bits(map: &TypeMap) -> [u64; 21] {
let mut bits = [0; 21];
let (m, projection) = map;
for (b, v) in bits.iter_mut().zip(m.as_coeffs()) {
*b = v.to_bits();
}
if let Some((h, after)) = projection {
for (b, v) in bits[6..].iter_mut().zip(h.to_array().into_iter().chain(after.as_coeffs())) {
*b = v.to_bits();
}
}
bits
}
/// A key of [`TypeInks::nodes`]: the object's address, the map its outlines are measured in (an
/// affine map without its move) and the inputs number registered with [`set_type_ink`].
type NodeKey = (usize, [u64; 21], u64);
/// A key of [`TypeInks::content`]: two 64-bit hashes of the type without its transform's move and
/// its layout caches ([`content_hash`]), the map its outlines are measured in, and the inputs number.
type ContentKey = ([u64; 2], [u64; 21], u64);
/// Type measured by [`type_ink`] on one thread, by the map it is measured in and the inputs
/// number: by the object (an unchanged object is found without being read),
/// and by its content (a moved or copied object is found without laying it out again). Neither
/// table keeps a copy of the type.
#[derive(Default)]
struct TypeInks {
/// By the object's address, with a weak pointer that keeps the address from being reused.
nodes: std::collections::HashMap<NodeKey, (std::sync::Weak<Node>, Option<Rect>)>,
/// By the type's content.
content: std::collections::HashMap<ContentKey, Option<Rect>>,
}
/// Where [`TypeInks::find`] did not find type: its keys in both tables (no content key for type
/// that could not be hashed whole).
struct Missing {
by_node: NodeKey,
content: Option<ContentKey>,
}
impl TypeInks {
/// The kept box of type node `n` (holding `t`) mapped by `map`, or the keys to keep it under
/// once it is measured.
fn find(&mut self, n: &Arc<Node>, t: &crate::TextObject, map: &TypeMap, inputs: u64) -> Result<Option<Rect>, Box<Missing>> {
// While the table holds a weak pointer to `n`'s allocation, no other object can be at that
// address, and `n` can't be changed in place (`Arc::get_mut` refuses it and `Arc::make_mut`
// moves it).
let by_node = (Arc::as_ptr(n) as usize, map_bits(map), inputs);
if let Some((_, ink)) = self.nodes.get(&by_node) {
return Ok(*ink);
}
// Shrink Text to Fit lays type out by its size on the page, so only a move keeps its layout.
let [a, b, c, d, _, _] = t.xf.as_coeffs();
let mut text = t.clone();
text.xf = Affine::new([a, b, c, d, 0.0, 0.0]);
text.cached_bounds = None;
text.cached_baselines.clear();
text.cached_ink = None;
let content = content_hash(&text).map(|hash| (hash, by_node.1, inputs));
match content.and_then(|key| self.content.get(&key)) {
Some(ink) => {
let ink = *ink;
self.keep_node(n, by_node, ink);
Ok(ink)
}
None => Err(Box::new(Missing { by_node, content })),
}
}
/// Keep the box `ink` measured for type node `n` under the keys `missing`.
fn keep(&mut self, n: &Arc<Node>, missing: Missing, ink: Option<Rect>) {
if let Some(key) = missing.content {
if self.content.len() >= TYPE_INK_KEPT {
self.content.clear();
}
self.content.insert(key, ink);
}
self.keep_node(n, missing.by_node, ink);
}
fn keep_node(&mut self, n: &Arc<Node>, by_node: NodeKey, ink: Option<Rect>) {
if self.nodes.len() >= TYPE_INK_KEPT {
self.nodes.retain(|_, (weak, _)| weak.strong_count() > 0);
if self.nodes.len() >= TYPE_INK_KEPT {
self.nodes.clear();
}
}
self.nodes.insert(by_node, (Arc::downgrade(n), ink));
}
}
/// Two independent 64-bit hashes of `text` as saved (the layout caches are not saved), with what
/// layout reads that is not saved: whether its first paragraph continues a thread and the bounds
/// of its inline graphics. `None` when it can't be written whole.
fn content_hash(text: &crate::TextObject) -> Option<[u64; 2]> {
use std::hash::Hasher;
/// Feeds what is written to two hashers.
struct Feed([std::collections::hash_map::DefaultHasher; 2]);
impl std::io::Write for Feed {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
for h in &mut self.0 {
h.write(buf);
}
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let mut feed = Feed(Default::default());
// The second hasher starts from another state.
feed.0[1].write_u8(1);
serde_json::to_writer(&mut feed, text).ok()?;
let inline_bounds = text.runs.iter().filter_map(|r| r.inline.as_ref()).map(|i| i.bounds.map(|b| [b.x0, b.y0, b.x1, b.y1].map(f64::to_bits)));
for h in &mut feed.0 {
h.write_u8(u8::from(text.first_para_continues));
for b in inline_bounds.clone() {
match b {
None => h.write_u8(0),
Some(bits) => {
h.write_u8(1);
bits.into_iter().for_each(|v| h.write_u64(v));
}
}
}
}
let [a, b] = feed.0;
Some([a.finish(), b.finish()])
}
std::thread_local! {
/// The type [`type_ink`] measured on this thread.
static TYPE_INKS: std::cell::RefCell<TypeInks> = std::cell::RefCell::new(TypeInks::default());
}
/// The box of the glyph outlines of type node `n` (holding `t`) with its text space mapped by `m`
/// ([`set_type_ink`]) and, for type in perspective, drawn through `projection` and mapped by its
/// second transform; measured again when `t`, the maps (without a move of `m` when there is no
/// projection) or the registered inputs number change. `None` while nothing is registered.
fn type_ink(n: &Arc<Node>, t: &crate::TextObject, m: Affine, projection: Option<(Homography, Affine)>) -> Option<Option<Rect>> {
let (f, inputs) = TYPE_INK.get()?;
let inputs = inputs();
// Without a projection the type is measured without the move, which is added to the box.
let [a, b, c, d, e, g] = m.as_coeffs();
let (map, offset) = match projection {
None => ((Affine::new([a, b, c, d, 0.0, 0.0]), None), Vec2::new(e, g)),
Some(p) => ((m, Some(p)), Vec2::ZERO),
};
let ink = match TYPE_INKS.with_borrow_mut(|kept| kept.find(n, t, &map, inputs)) {
Ok(ink) => ink,
Err(missing) => {
// Measured outside the borrow: laying type out may measure other type.
let ink = f(t, map.0, map.1);
TYPE_INKS.with_borrow_mut(|kept| kept.keep(n, *missing, ink));
ink
}
};
Some(ink.map(|r| r + offset))
}
/// Add to `typed` the address of `n` and of each group and layer in it that holds type, which
/// [`content_box`] measures by its glyphs; is there type in `n`? One walk of the tree.
fn find_type(n: &Node, typed: &mut std::collections::HashSet<usize>) -> bool {
let holds = match &n.kind {
NodeKind::Text(_) => true,
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().fold(false, |holds, c| find_type(c, typed) | holds),
_ => false,
};
if holds {
typed.insert(n as *const Node as usize);
}
holds
}
/// The box of `n` an envelope maps from, in the axes `to` takes the page to: its geometric bounds,
/// or with `stroked` its visual bounds (strokes scaled by `to` as [`Node::transform`] scales them),
/// with type measured by its glyph outlines ([`type_ink`]) instead of its laid-out box, in groups
/// and layers too. Type is laid out as it is on the page, and its outlines are then taken into
/// those axes. A character's strokes reach as far past its glyphs as past the laid-out box.
fn content_box(n: &Arc<Node>, stroked: bool, to: Affine) -> Option<Rect> {
let mut typed = std::collections::HashSet::new();
find_type(n, &mut typed);
content_box_in(n, stroked, to, &typed)
}
/// [`content_box`], with the addresses of the objects in `n` that hold type ([`find_type`]).
fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collections::HashSet<usize>) -> Option<Rect> {
// `n` in the axes of `to`.
let moved = || {
if to == Affine::IDENTITY {
return std::borrow::Cow::Borrowed(&**n);
}
let mut m = (**n).clone();
m.transform(to, true);
std::borrow::Cow::Owned(m)
};
let own = |m: &Node| if stroked { m.visual_bounds() } else { m.geometric_bounds() };
if !typed.contains(&(Arc::as_ptr(n) as usize)) {
return own(&moved());
}
match &n.kind {
NodeKind::Text(t) => {
// Type in perspective: its outlines as its projection draws them.
let ink = match n.projection() {
None => type_ink(n, t, to * t.xf, None),
Some(h) => type_ink(n, t, t.xf, Some((h, to))),
}
.flatten();
let m = moved();
let Some(ink) = ink else { return own(&m) };
if !stroked {
return Some(ink);
}
let (Some(v), Some(g)) = (m.visual_bounds(), m.geometric_bounds()) else { return Some(ink) };
Some(Rect::new(
ink.x0 - (g.x0 - v.x0).max(0.0),
ink.y0 - (g.y0 - v.y0).max(0.0),
ink.x1 + (v.x1 - g.x1).max(0.0),
ink.y1 + (v.y1 - g.y1).max(0.0),
))
}
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
// A clipping path that paints strokes over the clip edge, as in `Node::visual_bounds`.
let clip = children.first()?;
content_box_in(clip, stroked && matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)), to, typed)
}
NodeKind::Layer { .. } | NodeKind::Group { .. } => {
let layer = matches!(n.kind, NodeKind::Layer { .. });
let members = n.editing_children().iter();
if stroked {
// The container's own strokes, scaled by `to` as `Node::transform` scales them,
// without copying its members.
let mut own_strokes = Node::new(n.id, NodeKind::Group { children: Vec::new(), clip: false });
own_strokes.appearance = n.appearance.clone();
own_strokes.transform(to, true);
own_strokes.visual_of_members(members.map(|c| content_box_in(c, true, to, typed)))
} else {
members.filter(|c| c.visible || !layer).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box_in(c, false, to, typed)))
}
}
_ => own(&moved()),
}
}
/// The [`EnvelopeOptions::bounds_margin`] of content with bounds `stroked` and `plain`. `None` for
/// content with no width or no height, or for margins an `f32` can't hold.
pub fn envelope_stroke_margin(stroked: Rect, plain: Rect) -> Option<[f32; 4]> {
@@ -243,7 +526,7 @@ pub fn envelope_overlay(n: &Node) -> Option<(PathData, Option<GradientMesh>)> {
Some((grid.lines(), Some(grid)))
}
EnvelopeKind::Warp { .. } => Some((EnvelopeMap::of(n)?.surface_mesh(4, 4, Color::BLACK).lines(), None)),
EnvelopeKind::TopObject { path } => Some((path.clone(), None)),
EnvelopeKind::TopObject { path, .. } => Some((path.clone(), None)),
}
}
@@ -265,20 +548,13 @@ pub struct EnvelopeMap<'a> {
}
impl<'a> EnvelopeMap<'a> {
/// The map of an envelope of `kind` around `content` with `frame` and `options`. `None` when
/// the content has no bounds.
/// The map of an envelope of `kind` around `content` with `frame` and `options`, from the
/// content's bounds with type measured by its glyph outlines ([`envelope_content_bounds`]).
/// `None` when the content has no bounds.
pub fn new(content: &[Arc<Node>], kind: &'a EnvelopeKind, frame: Affine, options: EnvelopeOptions) -> Option<Self> {
let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY };
let to_frame = frame.inverse();
let src = if frame == Affine::IDENTITY {
nodes_bounds(content)?
} else {
content.iter().try_fold(None, |acc, c| {
let mut m = (**c).clone();
m.transform(to_frame, false);
Some(vectorcraft_geom::union_opt(acc, m.geometric_bounds()))
})??
};
let src = content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, false, to_frame)))?;
let src = options.source_box(src);
Some(Self { src, frame, to_frame, surface: surface_of(kind, src, frame) })
}
@@ -374,7 +650,116 @@ pub fn envelope_bounds(content: &[Arc<Node>], kind: &EnvelopeKind, frame: Affine
let first = *points.first()?;
Some(points.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p)))
}
EnvelopeKind::TopObject { path } => path.bounds(),
EnvelopeKind::TopObject { path, .. } => path.bounds(),
EnvelopeKind::Warp { .. } => EnvelopeMap::new(content, kind, frame, options)?.bounds(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{CharStyle, TextObject};
/// Look `n` up in `kept`, measuring it (and counting the measures) when it isn't there.
fn look_up(kept: &mut TypeInks, n: &Arc<Node>, linear: Affine, measured: &mut usize) -> Option<Rect> {
let NodeKind::Text(t) = &n.kind else { panic!("type") };
match kept.find(n, t, &(linear, None), 0) {
Ok(ink) => ink,
Err(missing) => {
*measured += 1;
let ink = Some(Rect::new(0.0, 0.0, *measured as f64, 1.0));
kept.keep(n, *missing, ink);
ink
}
}
}
fn type_node(i: usize, text: &str) -> Arc<Node> {
let t = TextObject::point(Point::new(i as f64 * 10.0, 0.0), text, CharStyle::default());
Arc::new(Node::new(NodeId(i as u64), NodeKind::Text(Box::new(t))))
}
/// Many type objects are each measured once however often they are looked up; a moved or copied
/// object is found by its content, and a changed one or another transform is measured again.
#[test]
fn measured_type_is_kept_for_many_objects() {
let mut kept = TypeInks::default();
let mut measured = 0;
let nodes: Vec<_> = (0..200).map(|i| type_node(i, &format!("Type {i}"))).collect();
for _ in 0..5 {
for n in &nodes {
look_up(&mut kept, n, Affine::IDENTITY, &mut measured);
}
}
assert_eq!(measured, 200);
let mut moved = (*nodes[7]).clone();
moved.transform(Affine::translate((300.0, 40.0)), true);
let moved = Arc::new(moved);
assert_eq!(look_up(&mut kept, &moved, Affine::IDENTITY, &mut measured), look_up(&mut kept, &nodes[7], Affine::IDENTITY, &mut measured));
assert_eq!(measured, 200, "a moved object is found by its content");
let changed = type_node(7, "Changed");
look_up(&mut kept, &changed, Affine::IDENTITY, &mut measured);
assert_eq!(measured, 201, "a changed object is measured again");
look_up(&mut kept, &nodes[7], Affine::rotate(0.5), &mut measured);
assert_eq!(measured, 202, "another transform is measured again");
}
/// Type that differs only in what layout reads but files don't save (a first paragraph that
/// continues a thread, the resolved bounds of an inline graphic) is measured again.
#[test]
fn type_that_differs_in_what_is_not_saved_is_measured_again() {
let mut kept = TypeInks::default();
let mut measured = 0;
let mut t = TextObject::point(Point::ZERO, "Type", CharStyle::default());
t.runs.push(crate::TextRun::new("", CharStyle::default()));
t.runs[1].inline = Some(crate::InlineArt { symbol: "S".into(), scale: 1.0, baseline_shift: 0.0, bounds: None });
let node = |t: &TextObject| Arc::new(Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone()))));
look_up(&mut kept, &node(&t), Affine::IDENTITY, &mut measured);
look_up(&mut kept, &node(&t), Affine::IDENTITY, &mut measured);
assert_eq!(measured, 1, "a copy is found by its content");
t.first_para_continues = true;
look_up(&mut kept, &node(&t), Affine::IDENTITY, &mut measured);
assert_eq!(measured, 2, "a first paragraph that continues a thread");
if let Some(inline) = &mut t.runs[1].inline {
inline.bounds = Some(Rect::new(0.0, 0.0, 10.0, 20.0));
}
look_up(&mut kept, &node(&t), Affine::IDENTITY, &mut measured);
assert_eq!(measured, 3, "an inline graphic's bounds");
}
/// A stroked group of type in a scaled frame reaches past its members by its own strokes scaled
/// with the frame, as the group moved into the frame does; deeply nested groups are measured in
/// one walk each.
#[test]
fn a_stroked_group_of_type_is_measured_with_its_strokes_in_the_frame() {
let text = type_node(1, "Group");
let mut group = Node::group(NodeId(2), vec![text.clone()]);
group.appearance = crate::Appearance::basic(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 4.0).into();
let group = Arc::new(group);
let to = Affine::scale(2.0);
let mut moved = (*group).clone();
moved.transform(to, true);
let want = moved.visual_of_members(std::iter::once(content_box(&text, true, to)));
assert!(want.is_some());
assert_eq!(content_box(&group, true, to), want);
let mut nested = group;
for i in 0..300 {
nested = Arc::new(Node::group(NodeId(10 + i), vec![nested]));
}
assert!(content_box(&nested, false, Affine::IDENTITY).is_some());
}
/// A table that fills up is emptied instead of growing, and what is looked up after that is
/// measured again.
#[test]
fn the_tables_stay_bounded() {
let mut kept = TypeInks::default();
let mut measured = 0;
let nodes: Vec<_> = (0..TYPE_INK_KEPT + 10).map(|i| type_node(i, &format!("Type {i}"))).collect();
for n in &nodes {
look_up(&mut kept, n, Affine::IDENTITY, &mut measured);
}
assert!(kept.content.len() <= TYPE_INK_KEPT && kept.nodes.len() <= TYPE_INK_KEPT, "{} {}", kept.content.len(), kept.nodes.len());
assert_eq!(measured, TYPE_INK_KEPT + 10);
}
}
+262 -7
View File
@@ -73,13 +73,16 @@ const SIDE: usize = 65;
/// Four boundary curves (top TL→TR, right TR→BR, bottom BL→BR, left TL→BL), each resampled to
/// [`SIDE`] points, from the outline of a closed path split at the points nearest its bounding
/// box corners.
/// box corners. [`Coons::from_top_object`] samples its sides at the places `knots` gives instead.
#[derive(Clone, Debug)]
pub struct Coons {
top: Vec<Point>,
right: Vec<Point>,
bottom: Vec<Point>,
left: Vec<Point>,
/// Where along its side (0 to 1, rising) each point of the top, right, bottom and left side
/// lies; `None` when the points are evenly spaced.
knots: Option<Box<[Vec<f64>; 4]>>,
}
impl Coons {
@@ -87,9 +90,11 @@ impl Coons {
pub fn rect(r: Rect) -> Self {
let line = |a: Point, b: Point| (0..SIDE).map(|i| a.lerp(b, i as f64 / (SIDE - 1) as f64)).collect::<Vec<_>>();
let (tl, tr, br, bl) = (Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1));
Self { top: line(tl, tr), right: line(tr, br), bottom: line(bl, br), left: line(tl, bl) }
Self { top: line(tl, tr), right: line(tr, br), bottom: line(bl, br), left: line(tl, bl), knots: None }
}
/// The patch of `path`'s outline, each side measured by its length: equal steps in `u` or `v`
/// cover equal lengths of the side.
pub fn from_path(path: &PathData) -> Option<Self> {
// The largest subpath is the outline.
let sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?;
@@ -136,7 +141,145 @@ impl Coons {
bottom.reverse();
let mut left = resample(&arc(bl, tl), SIDE);
left.reverse();
Some(Self { top, right, bottom, left })
Some(Self { top, right, bottom, left, knots: None })
}
/// The patch of a top object's outline (the largest subpath of `path`), split into four sides
/// at its corners. Each piece of a side between two anchors or corners takes a share of `u` or
/// `v` in proportion to the length of its control polygon, spread along the piece by its own
/// curve parameter. A segment without handles counts as a cubic with its handles a third of
/// the way along, so the content spreads evenly along it. `corners` are the anchors (indices
/// into the outline, in its own order) at the top left, top right, bottom right and bottom
/// left, as a saved file gives them. They stay on those anchors when they run the way the
/// outline does or the opposite way, so a reflected outline keeps them; without them, or when
/// they don't fit the outline, each corner is found from the outline ([`top_object_corner`]).
/// A straight segment closes an open subpath, and segments of no length are left out. A top
/// object's envelope maps onto this patch.
pub fn from_top_object(path: &PathData, corners: Option<[u32; 4]>) -> Option<Self> {
let sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?;
let mut sp = sp.clone();
let count = sp.anchors.len();
// Stored corners count only when they are distinct anchors met in order around the outline.
let fits = |c: &[usize; 4]| {
if !c.iter().all(|i| *i < count) {
return false;
}
let gaps: Vec<usize> = (0..4).map(|k| (c[(k + 1) % 4] + count - c[k]) % count).collect();
gaps.iter().all(|g| *g > 0) && gaps.iter().sum::<usize>() == count
};
let given = corners.map(|c| c.map(|i| i as usize));
// Stored corners met in the outline's own order keep it as drawn, even counter-clockwise
// (a reflected outline). Otherwise orient it clockwise in y-down (TL → TR → BR → BL).
let mut corners = given.filter(fits);
let reversed = corners.is_none() && sp.signed_area() < 0.0;
if reversed {
sp.reverse();
corners = given.map(|c| c.map(|i| count.saturating_sub(1).saturating_sub(i))).filter(fits);
}
// Each segment, and whether it is straight: a straight one's parameter runs evenly along it.
let line = |a: Point, b: Point| (CubicBez::new(a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b), true);
let mut segs: Vec<(usize, (CubicBez, bool))> = (0..sp.segment_count())
.map(|i| {
let c = sp.segment(i);
(i, if sp.segment_is_line(i) { line(c.p0, c.p3) } else { (c, false) })
})
.collect();
if !sp.closed
&& let (Some(a), Some(b)) = (sp.anchors.last(), sp.anchors.first())
{
segs.push((count.saturating_sub(1), line(a.p, b.p)));
}
segs.retain(|(_, (c, _))| [c.p1, c.p2, c.p3].iter().any(|p| p.distance(c.p0) > 1e-9));
// The kept segment that anchor `k` starts (a segment of no length starts where the next begins).
let starts: Vec<usize> = segs.iter().map(|(i, _)| *i).collect();
// Where each kept segment and the anchor it starts at come in the outline as drawn: a tie
// between corners goes to the one met first there.
let order: Vec<(usize, usize)> = starts
.iter()
.map(|&i| if reversed { (count.saturating_sub(1).saturating_sub(i), (2 * count).saturating_sub(2 + i) % count.max(1)) } else { (i, i) })
.collect();
let segs: Vec<(CubicBez, bool)> = segs.into_iter().map(|(_, s)| s).collect();
let r = segs.iter().map(|(c, _)| c.bounding_box()).reduce(|a, b| a.union(b)).or_else(|| path.bounds())?;
// An outline of fewer than three points (a straight line there and back) maps onto its
// bounding box, as in `from_path`.
if segs.len() < 2 || (segs.len() == 2 && segs.iter().all(|(_, straight)| *straight)) {
return Some(Self::rect(r));
}
let n = segs.len() as f64;
let at = |s: f64| {
let s = s.rem_euclid(n);
let i = (s.floor() as usize).min(segs.len() - 1);
segs.get(i).map_or(Point::ZERO, |(c, _)| c.eval((s - i as f64).clamp(0.0, 1.0)))
};
// The side from `a` to `b`: its points, and where along it (0 to 1) each lies. It runs
// through pieces of segments, split at `a` and `b`. Each piece takes its share of the side
// by the length of its control polygon and holds points at even steps of its parameter
// (at least 16, and at least `SIDE` points on the side), its ends included. A side of
// many pieces takes fewer points in each, so it holds at most `MAX_SIDE_POINTS` points,
// or one for each piece when it has more pieces than that.
let side = |a: f64, b: f64| {
let span = (b - a).rem_euclid(n);
if !(span.is_finite() && span > 0.0) {
return (vec![at(a), at(a)], vec![0.0, 1.0]);
}
let mut pieces: Vec<CubicBez> = vec![];
let (mut s, end) = (a, a + span);
while s < end - 1e-12 && pieces.len() <= segs.len() {
let i = s.floor();
let next = (i + 1.0).min(end);
if let Some((c, _)) = segs.get((i as usize) % segs.len()) {
pieces.push(c.subsegment((s - i).clamp(0.0, 1.0)..(next - i).clamp(0.0, 1.0)));
}
s = next;
}
let polygon = |c: &CubicBez| c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3);
let mut weights: Vec<f64> = pieces.iter().map(polygon).collect();
let mut total: f64 = weights.iter().sum();
if !(total.is_finite() && total > 0.0) {
weights.iter_mut().for_each(|w| *w = 1.0);
total = weights.len().max(1) as f64;
}
let count = pieces.len().max(1);
let per = 16usize.max((SIDE - 1).div_ceil(count));
let per = if count * per < MAX_SIDE_POINTS { per } else { (MAX_SIDE_POINTS / count).max(1) };
let mut pts = vec![pieces.first().map_or_else(|| at(a), |c| c.p0)];
let mut knots = vec![0.0];
let mut before = 0.0;
for (c, w) in pieces.iter().zip(&weights) {
for k in 1..=per {
let f = k as f64 / per as f64;
pts.push(c.eval(f));
knots.push((before + w * f) / total);
}
before += w;
}
if let Some(last) = knots.last_mut() {
*last = 1.0;
}
(pts, knots)
};
let (tl, tr, br, bl) = match corners {
// Anchor `k` sits at the start of the first kept segment from it on.
Some(c) => {
let place = |k: usize| starts.iter().position(|i| *i >= k).unwrap_or(0) as f64;
(place(c[0]), place(c[1]), place(c[2]), place(c[3]))
}
None => {
let corner = |q: Point| top_object_corner(&segs, &order, r, q);
(corner(Point::new(r.x0, r.y0)), corner(Point::new(r.x1, r.y0)), corner(Point::new(r.x1, r.y1)), corner(Point::new(r.x0, r.y1)))
}
};
let flip = |(mut p, mut u): (Vec<Point>, Vec<f64>)| {
p.reverse();
u.reverse();
u.iter_mut().for_each(|x| *x = 1.0 - *x);
(p, u)
};
let (top, top_u) = side(tl, tr);
let (right, right_u) = side(tr, br);
let (bottom, bottom_u) = flip(side(br, bl));
let (left, left_u) = flip(side(bl, tl));
Some(Self { top, right, bottom, left, knots: Some(Box::new([top_u, right_u, bottom_u, left_u])) })
}
/// The point at `u` along a side; past its ends the end segments go on straight (art an
@@ -147,10 +290,36 @@ impl Coons {
side[i].lerp(side[i + 1], s - i as f64)
}
/// The point at `u` along a side whose points lie at `knots` (rising, 0 to 1); past its ends
/// the end segments go on straight, as in [`Self::sample`].
fn sample_at(side: &[Point], knots: &[f64], u: f64) -> Point {
if side.len() < 2 || side.len() != knots.len() {
return side.first().copied().unwrap_or_default();
}
let i = knots.partition_point(|k| *k <= u).clamp(1, side.len() - 1) - 1;
let (k0, k1) = (knots[i], knots[i + 1]);
let f = if k1 > k0 { (u - k0) / (k1 - k0) } else { 0.0 };
side[i].lerp(side[i + 1], f)
}
/// The point at `u` along side `which` (0 top, 1 right, 2 bottom, 3 left).
fn side_at(&self, which: usize, u: f64) -> Point {
let side = match which {
0 => &self.top,
1 => &self.right,
2 => &self.bottom,
_ => &self.left,
};
match self.knots.as_deref().and_then(|k| k.get(which)) {
Some(knots) => Self::sample_at(side, knots, u),
None => Self::sample(side, u),
}
}
/// The surface point at (u, v) ∈ [0,1]².
pub fn eval(&self, u: f64, v: f64) -> Point {
let (t, b, l, r) = (Self::sample(&self.top, u), Self::sample(&self.bottom, u), Self::sample(&self.left, v), Self::sample(&self.right, v));
let (p00, p10, p01, p11) = (self.top[0], self.top[SIDE - 1], self.bottom[0], self.bottom[SIDE - 1]);
let (t, b, l, r) = (self.side_at(0, u), self.side_at(2, u), self.side_at(3, v), self.side_at(1, v));
let [p00, p10, p11, p01] = self.corners();
let c = (1.0 - v) * t.to_vec2() + v * b.to_vec2() + (1.0 - u) * l.to_vec2() + u * r.to_vec2()
- ((1.0 - u) * (1.0 - v) * p00.to_vec2() + u * (1.0 - v) * p10.to_vec2() + (1.0 - u) * v * p01.to_vec2() + u * v * p11.to_vec2());
c.to_point()
@@ -158,7 +327,93 @@ impl Coons {
/// The four corners TL, TR, BR, BL.
pub fn corners(&self) -> [Point; 4] {
[self.top[0], self.top[SIDE - 1], self.bottom[SIDE - 1], self.bottom[0]]
let end = |side: &[Point]| side.last().copied().unwrap_or_default();
[self.top[0], end(&self.top), end(&self.bottom), self.bottom[0]]
}
}
/// The most points one side of [`Coons::from_top_object`] holds while it adds points between its
/// anchors.
const MAX_SIDE_POINTS: usize = 1 << 16;
/// How far into the outline's bounding box, as a share of its width and of its height, a corner
/// of a top object looks for an anchor.
const CORNER_REACH: f64 = 0.475;
/// A handle this long (in points) or shorter makes its anchor a corner of a top object.
const SHORT_HANDLE: f64 = 0.01;
/// An anchor whose tangent directions, as unit vectors, differ by less than this in x and in y is
/// smooth, and is not a corner of a top object.
const SMOOTH_TURN: f64 = 0.01;
/// A top object's corner this close (in curve parameter) to either end of its segment moves onto
/// the anchor there.
const CORNER_END_SNAP: f64 = 0.005;
/// Is the anchor at `a`, reached by handle `h_in` and left by handle `h_out` on an outline that
/// runs clockwise on screen, a corner of a top object? A handle of [`SHORT_HANDLE`] or shorter
/// makes it one. Otherwise its tangent directions must differ by [`SMOOTH_TURN`] or more and turn
/// clockwise, so it points out of the outline. A straight segment's handles here are the ones
/// [`Coons::from_top_object`] gives it, a third of the way along, so an anchor between two
/// straight segments longer than three times [`SHORT_HANDLE`] is a corner only when it turns out
/// of the outline.
fn top_object_corner_anchor(h_in: Point, a: Point, h_out: Point) -> bool {
let (vin, vout) = (a - h_in, h_out - a);
let (len_in, len_out) = (vin.hypot(), vout.hypot());
if len_in <= SHORT_HANDLE || len_out <= SHORT_HANDLE {
return true;
}
let (ui, uo) = (vin / len_in, vout / len_out);
if (ui.x - uo.x).abs() < SMOOTH_TURN && (ui.y - uo.y).abs() < SMOOTH_TURN {
return false;
}
ui.cross(uo) >= 0.0
}
/// Where along `segs` (segment index + parameter, in [0, n)) the corner of a top object nearest
/// corner `q` of its bounding box `r` lies, for an outline that runs clockwise on screen. It is
/// the nearest anchor to `q` that is a corner ([`top_object_corner_anchor`]) and lies within
/// [`CORNER_REACH`] of the box's width and height from `q`. Without one, it is the nearest point
/// of the outline to `q`, moved onto its segment's anchor when within [`CORNER_END_SNAP`] of
/// either end. `order` gives where each segment's first anchor and the segment itself come in the
/// outline as drawn, which may run the other way; on a tie the one met first there wins.
fn top_object_corner(segs: &[(CubicBez, bool)], order: &[(usize, usize)], r: Rect, q: Point) -> f64 {
use vectorcraft_geom::kurbo::ParamCurveNearest;
let n = segs.len();
if n == 0 {
return 0.0;
}
let rank = |i: usize| order.get(i).copied().unwrap_or((i, i));
let (reach_x, reach_y) = (r.width() * CORNER_REACH, r.height() * CORNER_REACH);
let mut best: Option<(f64, usize, usize)> = None;
for i in 0..n {
let (Some((prev, _)), Some((cur, _))) = (segs.get((i + n - 1) % n), segs.get(i)) else { continue };
let a = cur.p0;
if (a.x - q.x).abs() > reach_x || (a.y - q.y).abs() > reach_y || !top_object_corner_anchor(prev.p2, a, cur.p1) {
continue;
}
let (d, k) = (a.distance_squared(q), rank(i).0);
if best.is_none_or(|(b, bk, _)| d < b || (d == b && k < bk)) {
best = Some((d, k, i));
}
}
if let Some((_, _, i)) = best {
return i as f64;
}
let tol = (r.width() + r.height()).max(1e-6) * 1e-9;
let nearest = segs
.iter()
.enumerate()
.map(|(i, (c, _))| (c.nearest(q, tol), i))
.min_by(|a, b| a.0.distance_sq.total_cmp(&b.0.distance_sq).then(rank(a.1).1.cmp(&rank(b.1).1)));
let Some((near, i)) = nearest else { return 0.0 };
if near.t > CORNER_END_SNAP && near.t < 1.0 - CORNER_END_SNAP {
i as f64 + near.t
} else if near.t < 0.5 {
i as f64
} else {
((i + 1) % n) as f64
}
}
@@ -1033,7 +1288,7 @@ pub(super) fn surface_of<'a>(kind: &'a EnvelopeKind, src: Rect, frame: Affine) -
let (rows, cols) = (*rows as usize, *cols as usize);
Box::new(move |u: f64, v: f64| grid_eval(rows, cols, points, u, v))
}
EnvelopeKind::TopObject { path } => match Coons::from_path(path) {
EnvelopeKind::TopObject { path, corners } => match Coons::from_top_object(path, *corners) {
Some(co) => Box::new(move |u: f64, v: f64| co.eval(u, v)),
None => Box::new(flat),
},
+5
View File
@@ -103,6 +103,11 @@ impl Document {
let styles = |s: &Vec<TextStyleDef>| vec_bytes(s) + s.iter().map(|s| s.name.capacity() + map_bytes(&s.attrs)).sum::<usize>();
n += shared(&self.char_styles, &newer.char_styles, styles);
n += shared(&self.para_styles, &newer.para_styles, styles);
n += shared(&self.composite_fonts, &newer.composite_fonts, |c| {
let part = |p: &crate::CompositePart| p.font.capacity() + p.style.capacity();
vec_bytes(c)
+ c.iter().map(|f| f.name.capacity() + crate::CharClass::ALL.into_iter().map(|k| part(f.parts.get(k))).sum::<usize>()).sum::<usize>()
});
n += shared(&self.saved_selections, &newer.saved_selections, |s| {
vec_bytes(s) + s.iter().map(|s: &SavedSelection| s.name.capacity() + vec_bytes(&s.objects)).sum::<usize>()
});
+1
View File
@@ -31,6 +31,7 @@ pub use ids::{LAYER_COLORS, LayerColor, NodeId};
pub use kind::{ImageObject, MAX_BUFFERED_VALUES, NodeKind, with_buffered_value_budget};
pub use live_shape::{LiveShape, Scaling};
pub use opacity::{Knockout, OpacityMask, whiten};
pub use ops::{flattens, keeps_gradient_fit};
use wire::NodeWire;
pub use wire::{MAX_READ_NODES, with_node_budget};
+4
View File
@@ -27,6 +27,10 @@ pub struct ObjectAttributes {
/// the element's event attributes; nothing in VectorCraft runs them.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub events: Vec<(String, String)>,
/// The CSS classes the object had in an imported SVG, written back to `class` on export
/// (beside the generated `cls-N` classes).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub classes: Vec<String>,
/// Attributes in other applications' XML namespaces, in order, kept from SVG import to SVG
/// export: what another tool notes on an object (a plotter's pen, a cutter's passes) survives
/// a round trip through VectorCraft. Nothing in VectorCraft reads them. They are the object's,
+4
View File
@@ -69,6 +69,9 @@ pub struct NodeExtras {
/// As an envelope with margins in Edit Contents, the margins its strokes gave when Edit Contents
/// began ([`crate::live::EnvelopeOptions::bounds_margin`]).
pub envelope_edit_margin: Option<[f32; 4]>,
/// Transform panel › Align to Pixel Grid: the path's or compound path's horizontal and vertical
/// segments stay on the pixel grid when it is transformed.
pub pixel_aligned: bool,
}
/// No extras: what [`Node::extras`] gives for a node without any.
@@ -95,6 +98,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
shape_mode: crate::ShapeMode::Add,
symbol_overrides: Vec::new(),
envelope_edit_margin: None,
pixel_aligned: false,
};
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
+4
View File
@@ -329,6 +329,10 @@ pub struct Scaling {
/// Pattern fills and strokes move with the art (Transform Patterns; General › Transform
/// Pattern Tiles is its default): their tiles transform too, instead of staying put.
pub patterns: bool,
/// Gradients fitted to the object stay fitted under a transform that flattens it to a line or
/// a point (no area left), as a Transform effect leaves them, instead of being fixed to their
/// fit and flattened to one color with the object.
pub keep_fit_when_flat: bool,
}
impl Scaling {
+24 -8
View File
@@ -239,10 +239,12 @@ impl Node {
NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))),
// The frame and each shape the image's own fills and strokes paint, a stroke's grown by
// the farthest it can reach from its shape.
NodeKind::Image(_) => crate::hit::image_paint(self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| {
let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
}),
NodeKind::Image(_) => {
crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| {
let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
})
}
// Keys and steps placed on a spine, turned to it with Align to Path, can reach past the
// keys and the spine.
NodeKind::Blend { children, spec } => {
@@ -431,7 +433,7 @@ impl Node {
// Type and symbols in perspective keep looking the same, moved by `a`.
self.transform_projection(a);
// Refitting an unplaced gradient only reproduces moves and uniform scales.
if !keeps_gradient_fit(a) {
if !keeps_gradient_fit(a) && !(sc.keep_fit_when_flat && flattens(a)) {
self.pin_gradients();
}
let k = Scaling::factor(a);
@@ -448,6 +450,9 @@ impl Node {
if self.appearance.gradients().next().is_some() {
self.appearance.transform_gradients(a);
}
if self.appearance.has_svg_filter() {
self.appearance.transform_svg_filters(a);
}
if sc.patterns {
crate::pattern::transform_pattern_paints(self, a);
}
@@ -508,7 +513,7 @@ impl Node {
*h = (lin * h.to_point()).to_vec2();
}
}
EnvelopeKind::TopObject { path } => path.transform(a),
EnvelopeKind::TopObject { path, .. } => path.transform(a),
EnvelopeKind::Warp { .. } => {}
}
}
@@ -767,13 +772,24 @@ impl Node {
}
}
/// Is `a` a move plus a positive uniform scale (after which a refit gradient still matches)?
fn keeps_gradient_fit(a: Affine) -> bool {
/// Is `a` a move plus a positive uniform scale (after which a refit gradient still matches)? The
/// terms are compared within 1e-12 of the scale (at least of 1). A scale of 0 or less, a turn, a
/// reflection and an uneven scale give false, and so does a map that flattens the object
/// ([`flattens`]), which callers that keep a fitted gradient there check apart.
pub fn keeps_gradient_fit(a: Affine) -> bool {
let [m0, m1, m2, m3, _, _] = a.as_coeffs();
let eps = 1e-12 * m0.abs().max(1.0);
m0 > 0.0 && m1.abs() <= eps && m2.abs() <= eps && (m0 - m3).abs() <= eps
}
/// Does `a` flatten what it maps to a line or a point (its determinant 0, within 1e-12 of the
/// squares of its terms), or is it not finite?
pub fn flattens(a: Affine) -> bool {
let [m0, m1, m2, m3, _, _] = a.as_coeffs();
let norm = m0 * m0 + m1 * m1 + m2 * m2 + m3 * m3;
!a.is_finite() || a.determinant().abs() <= 1e-12 * norm
}
impl Node {
/// Whether a document point lies in this object's filled regions ([`Node::clip_shapes`]; true
/// everywhere for objects without them, such as type, whose boxes stand in).
+5 -1
View File
@@ -22,6 +22,7 @@ fn extras_are_written_flat_in_order() {
e.compound_shape = true;
e.shape_mode = crate::ShapeMode::Exclude;
e.envelope_edit_margin = Some([0.5, 0.5, 0.25, 0.25]);
e.pixel_aligned = true;
}
/// The top-level keys of a JSON object, in the order written.
struct Keys(Vec<String>);
@@ -67,9 +68,11 @@ fn extras_are_written_flat_in_order() {
"compound_shape",
"shape_mode",
"envelope_edit_margin",
"pixel_aligned",
];
assert_eq!(keys, order);
assert_eq!(v["shape_mode"], "exclude");
assert_eq!(v["pixel_aligned"], true);
assert_eq!(serde_json::from_value::<Node>(v).unwrap(), n);
let plain = Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), Appearance::default_art());
let back: Node = serde_json::from_value(serde_json::to_value(&plain).unwrap()).unwrap();
@@ -218,7 +221,8 @@ fn assert_round_corners(n: &Node, back: Affine, r: f64) {
}
}
const KEEP_CORNERS: Scaling = Scaling { strokes: false, effects: None, keep_type_strokes: false, keep_corners: true, patterns: false };
const KEEP_CORNERS: Scaling =
Scaling { strokes: false, effects: None, keep_type_strokes: false, keep_corners: true, patterns: false, keep_fit_when_flat: false };
#[test]
fn uneven_scales_keep_live_corners_circular() {
+5
View File
@@ -54,6 +54,7 @@ impl Serialize for Node {
is_default(&e.shape_mode),
e.symbol_overrides.is_empty(),
e.envelope_edit_margin.is_none(),
is_default(&e.pixel_aligned),
];
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
let mut skip = skips.into_iter();
@@ -96,6 +97,7 @@ impl Serialize for Node {
field!("shape_mode", &e.shape_mode);
field!("symbol_overrides", &e.symbol_overrides);
field!("envelope_edit_margin", &e.envelope_edit_margin);
field!("pixel_aligned", &e.pixel_aligned);
st.end()
}
}
@@ -236,6 +238,8 @@ pub(super) struct NodeWire {
symbol_overrides: Vec<crate::SymbolOverride>,
#[serde(default)]
envelope_edit_margin: Option<[f32; 4]>,
#[serde(default)]
pixel_aligned: bool,
}
impl From<NodeWire> for Node {
@@ -263,6 +267,7 @@ impl From<NodeWire> for Node {
shape_mode: w.shape_mode,
symbol_overrides: w.symbol_overrides,
envelope_edit_margin: w.envelope_edit_margin,
pixel_aligned: w.pixel_aligned,
};
Node {
id: w.id,
+2 -1
View File
@@ -572,7 +572,8 @@ mod tests {
place(&mut g, &symbols);
g.transform(Affine::new([2.0, 0.0, 0.0, 1.0, 0.0, 0.0]), false);
let rec = g.extras().objects_on_path.as_deref().cloned().unwrap();
assert_eq!((rec.spacing, rec.start), (Some(40.0), 20.0));
// The spine measures arc length along the curve, so within rounding of the exact values.
assert!(rec.spacing.is_some_and(|d| (d - 40.0).abs() < 1e-9) && (rec.start - 20.0).abs() < 1e-9, "{rec:?}");
place(&mut g, &symbols);
let x = |id| g.children().and_then(|c| c.iter().find(|c| c.id == id).cloned()).unwrap().geometric_bounds().unwrap().center().x;
assert!((x(NodeId(2)) - 20.0).abs() < 1e-9 && (x(NodeId(3)) - 60.0).abs() < 1e-9, "{} {}", x(NodeId(2)), x(NodeId(3)));
+32
View File
@@ -60,6 +60,38 @@ impl ImageBlob {
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
Some(Self::png(png))
}
/// The image as a grayscale PNG: `f` gives each pixel's gray level from its (straight) RGB, and
/// the PNG has an alpha channel only when some pixel isn't opaque. `f` runs once per distinct
/// color. `None` when the image can't be decoded, or when its file stores grayscale already
/// and no visible pixel changed.
pub fn map_gray(&self, mut f: impl FnMut([u8; 3]) -> u8) -> Option<ImageBlob> {
let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?;
let (width, height) = img.dimensions();
let mut memo: HashMap<[u8; 3], u8> = HashMap::new();
let mut changed = self.gray_source().is_none();
let mut opaque = true;
let mut gray_alpha = Vec::with_capacity(img.len() / 2);
for px in img.pixels() {
let rgb = [px.0[0], px.0[1], px.0[2]];
let level = *memo.entry(rgb).or_insert_with(|| f(rgb));
changed |= px.0[3] > 0 && [level; 3] != rgb;
opaque &= px.0[3] == 255;
gray_alpha.extend_from_slice(&[level, px.0[3]]);
}
if !changed {
return None;
}
let mut png = Vec::new();
let mut out = Cursor::new(&mut png);
if opaque {
let levels = gray_alpha.iter().step_by(2).copied().collect();
image::GrayImage::from_raw(width, height, levels)?.write_to(&mut out, image::ImageFormat::Png).ok()?;
} else {
image::GrayAlphaImage::from_raw(width, height, gray_alpha)?.write_to(&mut out, image::ImageFormat::Png).ok()?;
}
Some(Self::png(png))
}
}
/// How a grayscale image's file stores its pixels ([`ImageBlob::gray_source`]).
+394 -45
View File
@@ -1,13 +1,12 @@
//! Where a path's strokes paint, from the path's geometry without building their outlines: the
//! visual bounds and the clicks of a stroke take in its alignment, its width profile, miter spikes
//! up to the miter limit, projecting caps and arrowheads.
//! up to the miter limit, projecting caps and arrowheads. Butt caps end at the path's end points.
use vectorcraft_geom::bez::{CORNER_COS, has_length, kink, segments, subpaths, tangent, unit};
use vectorcraft_geom::hit::fill_contains;
use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveNearest};
use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveExtrema, ParamCurveNearest};
use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathSeg, Point, Rect, Shape, Vec2};
use crate::appearance::HEAD_REACH;
use crate::{Appearance, ArrowAlign, Dash, LineCap, LineJoin, StrokeAlign, StrokeLayer, WidthProfile};
/// Arc-length accuracy for placing a point along a profile (document points).
@@ -101,6 +100,82 @@ fn profile_at(profile: &WidthProfile, segs: &[PathSeg], closed: bool, i: usize,
w
}
/// Does the curvature of `seg` stay below one over `side` all along it? A curve's first derivative
/// is a mix of its three control differences, and its second a mix of their two differences, which
/// bound the curvature from above. Then the edges of a stroke reaching `side` from it do not fold
/// back, and those edges reach farthest at the ends of `seg` or where its tangent is square to an
/// axis.
fn gentle(seg: &PathSeg, side: f64) -> bool {
let c = seg.to_cubic();
let d = [c.p1 - c.p0, c.p2 - c.p1, c.p3 - c.p2].map(|v| v * 3.0);
let along = unit(d[0] + d[1] + d[2]);
let slowest = d.iter().map(|v| v.dot(along)).fold(f64::INFINITY, f64::min);
let bend = 2.0 * (d[1] - d[0]).hypot().max((d[2] - d[1]).hypot());
slowest > 0.0 && side * bend < slowest * slowest
}
/// The box a stroke reaching `side` from `seg` paints across it, from the directions its tangent
/// can take: the tangent is a mix of the nonzero control differences, so when their directions all
/// lie within a quarter turn of the directions' sum, every point across the stroke is in `seg`'s
/// box moved `side` along a normal of one of those directions. `None` when they do not. A handle on
/// its end point adds no direction, so a straight curve with one measures as a line.
fn turning_box(seg: &PathSeg, side: f64) -> Option<Rect> {
let c = seg.to_cubic();
let d = [c.p1 - c.p0, c.p2 - c.p1, c.p3 - c.p2];
let moving = || d.iter().map(|v| (*v, v.hypot())).filter(|(_, h)| *h > 0.0).map(|(v, h)| v / h);
let along = unit(moving().fold(Vec2::ZERO, |s, v| s + v));
if moving().any(|v| v.dot(along) <= 0.0) {
return None;
}
let angle = |v: &Vec2| along.cross(*v).atan2(along.dot(*v));
let lo = moving().min_by(|a, b| angle(a).total_cmp(&angle(b)))?;
let hi = moving().max_by(|a, b| angle(a).total_cmp(&angle(b)))?;
let n = |t: Vec2| (Vec2::new(t.y, -t.x) * side).to_point();
let one_side = round_join_box(Point::ZERO, lo, hi, side).unwrap_or_else(|| Rect::from_points(n(lo), n(hi)));
let reach = one_side.union(Rect::new(-one_side.x1, -one_side.y1, -one_side.x0, -one_side.y0));
let b = ParamCurveExtrema::bounding_box(seg);
Some(Rect::new(b.x0 + reach.x0, b.y0 + reach.y0, b.x1 + reach.x1, b.y1 + reach.y1))
}
/// The box a stroke reaching `side` from `seg` paints when it stops square at both ends of `seg`:
/// the corners at the ends and the points across the stroke where the tangent is square to an axis.
/// A curve that bends tighter than `side` is halved up to `depth` times, and a piece still bending
/// that much is measured by [`turning_box`], or grown by `side` on every side when its tangent
/// turns too far.
fn swept_box(seg: &PathSeg, side: f64, depth: u32) -> Rect {
if !matches!(seg, PathSeg::Line(_)) && !gentle(seg, side) {
if depth == 0 {
return turning_box(seg, side).unwrap_or_else(|| ParamCurveExtrema::bounding_box(seg).inflate(side, side));
}
return swept_box(&seg.subsegment(0.0..0.5), side, depth - 1).union(swept_box(&seg.subsegment(0.5..1.0), side, depth - 1));
}
let across = |t: f64| {
let (p, tn) = (seg.eval(t), tangent(seg, t));
let n = Vec2::new(-tn.y, tn.x) * side;
[p + n, p - n]
};
let [a, b] = across(0.0);
seg.extrema().into_iter().chain([1.0]).flat_map(across).fold(Rect::from_points(a, b), |r, p| r.union_pt(p))
}
/// The box of the arc a round join paints `side` from `at`, where the path turns from tangent
/// `t_in` to `t_out`: the arc runs on the outer side of the turn, and its box comes from its ends
/// and the points on it square to an axis. A joint where the path turns back on itself is given
/// the whole disc's box, and one where it does not turn paints no arc (`None`).
fn round_join_box(at: Point, t_in: Vec2, t_out: Vec2, side: f64) -> Option<Rect> {
let (t_in, t_out) = (unit(t_in), unit(t_out));
let turn = t_in.cross(t_out);
if turn.abs() < 1e-12 {
return (t_in.dot(t_out) < 0.0).then(|| Rect::from_center_size(at, (2.0 * side, 2.0 * side)));
}
let s = turn.signum();
let outer = |t: Vec2| Vec2::new(t.y, -t.x) * s;
let (a, b) = (outer(t_in), outer(t_out));
let axes = [Vec2::new(1.0, 0.0), Vec2::new(-1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(0.0, -1.0)];
let arc = Rect::from_points(at + a * side, at + b * side);
Some(axes.into_iter().filter(|d| a.cross(*d) * s >= 0.0 && d.cross(b) * s >= 0.0).fold(arc, |r, d| r.union_pt(at + d * side)))
}
/// Is `p` inside the convex polygon `pts` (either winding), or within `tol` of it?
fn in_convex(pts: &[Point], p: Point, tol: f64) -> bool {
let n = pts.len();
@@ -115,39 +190,81 @@ fn in_convex(pts: &[Point], p: Point, tol: f64) -> bool {
impl StrokeLayer {
/// Does bounding this stroke need its path's shape: miter spikes, projecting caps, arrowheads,
/// or an alignment that depends on whether the path is closed? Else it reaches evenly round it.
/// an alignment that depends on whether the path is closed, or butt caps, which stop at the
/// ends of an open path? Else it reaches evenly round it.
fn needs_shape(&self) -> bool {
self.join == LineJoin::Miter
|| self.cap == LineCap::Square
|| self.cap != LineCap::Round
|| self.start_arrow.is_some()
|| self.end_arrow.is_some()
|| self.align != StrokeAlign::Center
}
/// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown
/// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of
/// The box this stroke paints along `segs`, the segments with length of an open subpath, when
/// its caps are butt caps: each segment's [`swept_box`] and, with round joins, the arc each
/// joint between segments paints ([`round_join_box`]), a shallow one included.
/// `None` when `segs` is empty. Butt dashes stop inside the same box. The heads and miter tips
/// are measured apart. A segment in the middle is measured only when its own box grown by
/// `side`, which holds everything it paints, is not inside the box so far.
fn butt_body(&self, segs: &[PathSeg], side: f64) -> Option<Rect> {
let (first, last) = (segs.first()?, segs.last()?);
let ends = swept_box(first, side, 3).union(swept_box(last, side, 3));
let body = segs.iter().skip(1).take(segs.len().saturating_sub(2)).fold(ends, |b, s| {
if b.contains_rect(ParamCurveExtrema::bounding_box(s).inflate(side, side)) { b } else { b.union(swept_box(s, side, 3)) }
});
if self.join != LineJoin::Round {
return Some(body);
}
Some(joints(segs, false).fold(body, |b, (at, t_in, t_out)| round_join_box(at, t_in, t_out, side).map_or(b, |j| b.union(j))))
}
/// The box this stroke paints along `bp` (geometric bounds `bounds`): an open subpath with butt
/// caps by [`Self::butt_body`], every other subpath by the box of its segments grown by its
/// reach, with `tips` and, when `measure_tips`, the miter spikes the limit keeps, the corners of
/// projecting caps and the reach of the arrowheads round their end points.
pub fn bounds_on(&self, bp: &BezPath, bounds: Rect) -> Rect {
fn reach_along(&self, bp: &BezPath, bounds: Rect, tips: Option<Rect>, measure_tips: bool) -> Rect {
let els = bp.elements();
let mut out = bounds;
let subs = subpaths(bp);
let mut out = tips.map_or(bounds, |t| bounds.union(t));
let mut side_max: f64 = 0.0;
// Every subpath reaches evenly unless one is open and butt-capped; only then is each
// subpath's own box needed.
let even_only = self.cap != LineCap::Butt || subs.iter().all(|s| s.1);
let mut even = even_only.then_some(bounds);
// Dashes put a cap on every dash: projecting ones reach a corner's diagonal anywhere.
let capped_dashes = self.cap == LineCap::Square && self.dash.as_ref().is_some_and(Dash::is_dashed);
for (r, closed) in subpaths(bp) {
for (r, closed) in subs {
let side = self.side_reach(closed);
side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side });
let butt = self.cap == LineCap::Butt && !closed;
if !butt {
side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side });
}
if side <= 0.0 {
continue;
}
let square = self.cap == LineCap::Square && !closed;
let miters = measure_tips && self.join == LineJoin::Miter;
if !(butt || square || miters || !even_only) {
continue;
}
let segs = drawn(&els[r]);
if self.join == LineJoin::Miter {
if miters {
for (at, t_in, t_out) in joints(&segs, closed) {
if let Some([_, tip, _]) = miter(at, t_in, t_out, side, self.miter_limit) {
out = out.union_pt(tip);
}
}
}
if self.cap == LineCap::Square && !closed {
if butt {
if let Some(body) = self.butt_body(&segs, side) {
out = out.union(body);
}
continue;
}
if !even_only {
even = vectorcraft_geom::union_opt(even, segs.iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)));
}
if square {
for (at, dir) in ends(&segs).into_iter().flatten() {
let n = Vec2::new(-dir.y, dir.x) * side;
out = out.union_pt(at + dir * side + n).union_pt(at + dir * side - n);
@@ -158,7 +275,15 @@ impl StrokeLayer {
let r = self.head_reach(end);
out = out.union(Rect::from_center_size(at, (2.0 * r, 2.0 * r)));
}
out.union(bounds.inflate(side_max, side_max))
even.map_or(out, |e| out.union(e.inflate(side_max, side_max)))
}
/// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown
/// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of
/// projecting caps and the reach of the arrowheads round their end points. An open subpath
/// with butt caps does not reach past its ends ([`Self::butt_body`]).
pub fn bounds_on(&self, bp: &BezPath, bounds: Rect) -> Rect {
self.reach_along(bp, bounds, None, true)
}
/// The tip of the miter spike this stroke paints where segment `b` follows segment `a` in a
@@ -176,30 +301,7 @@ impl StrokeLayer {
/// every joint of `bp` ([`Self::miter_tip`]) or `None` when there are none, instead of measured
/// along `bp`. It measures the projecting caps and arrowheads as [`Self::bounds_on`] does.
pub fn bounds_with_tips(&self, bp: &BezPath, bounds: Rect, tips: Option<Rect>) -> Rect {
let els = bp.elements();
let mut out = tips.map_or(bounds, |t| bounds.union(t));
let mut side_max: f64 = 0.0;
// Dashes put a cap on every dash: projecting ones reach a corner's diagonal anywhere.
let capped_dashes = self.cap == LineCap::Square && self.dash.as_ref().is_some_and(Dash::is_dashed);
for (r, closed) in subpaths(bp) {
let side = self.side_reach(closed);
side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side });
if side <= 0.0 {
continue;
}
if self.cap == LineCap::Square && !closed {
let segs = drawn(&els[r]);
for (at, dir) in ends(&segs).into_iter().flatten() {
let n = Vec2::new(-dir.y, dir.x) * side;
out = out.union_pt(at + dir * side + n).union_pt(at + dir * side - n);
}
}
}
for (at, _, end) in head_ends(self, bp) {
let r = self.head_reach(end);
out = out.union(Rect::from_center_size(at, (2.0 * r, 2.0 * r)));
}
out.union(bounds.inflate(side_max, side_max))
self.reach_along(bp, bounds, tips, false)
}
/// Does this stroke along `bp` (filled with `rule`) paint within `tol` of `p`? Inside and
@@ -283,18 +385,19 @@ impl StrokeLayer {
}
/// Is `p` within `tol` of where the start (`end == false`) or end arrowhead at `at` (the path
/// leaving along `out`) can paint? Heads are at most about 4.6 weights long and 4 wide. With
/// leaving along `out`) can paint? A head reaches [`crate::Arrowhead::reach`] weights from its tip and
/// [`crate::Arrowhead::half_width`] either side of its line (4.6 and 2 for most). With
/// [`ArrowAlign::Extend`] a head points along `out` with its tip up to its length (or the cap)
/// past the end; with [`ArrowAlign::Tip`] its tip is on the end and it lies back along the
/// chord the path bends through under it, so anywhere within its length of the end.
fn head_contains(&self, at: Point, out: Vec2, end: bool, p: Point, tol: f64) -> bool {
let hw = self.arrow_weight(end);
let v = p - at;
let Some(kind) = (if end { self.end_arrow } else { self.start_arrow }) else { return false };
let (hw, v) = (self.arrow_weight(end), p - at);
match self.arrow_align {
ArrowAlign::Tip => v.hypot() <= HEAD_REACH * hw + tol,
ArrowAlign::Tip => v.hypot() <= kind.reach() * hw + tol,
ArrowAlign::Extend => {
let along = v.dot(out);
v.cross(out).abs() <= 2.0 * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -HEAD_REACH * hw - tol
v.cross(out).abs() <= kind.half_width() * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -kind.reach() * hw - tol
}
}
}
@@ -314,7 +417,7 @@ impl Appearance {
}
/// [`Self::stroked_bounds`] with the box of each visible stroke that needs the path's shape
/// (miter spikes, projecting caps, arrowheads or an alignment) given by `shaped`.
/// (miter spikes, projecting or butt caps, arrowheads or an alignment) given by `shaped`.
pub fn stroked_bounds_by(&self, bounds: Rect, mut shaped: impl FnMut(&StrokeLayer) -> Rect) -> Rect {
self.painted_strokes().fold(bounds, |acc, s| {
if !s.needs_shape() {
@@ -325,6 +428,30 @@ impl Appearance {
})
}
/// Does this appearance have a visible butt-capped stroke?
pub fn has_butt_stroke(&self) -> bool {
self.painted_strokes().any(|s| s.cap == LineCap::Butt)
}
/// Does a visible butt-capped stroke of this appearance run along an open subpath of `bp` with
/// a segment that starts or ends at a slant, not square to the axes, once placed by `a`? The
/// visual box's margin at the stroke's corners there depends on their direction, which a scale
/// out of proportion changes.
pub fn has_slanted_butt_stroke(&self, bp: &BezPath, a: vectorcraft_geom::Affine) -> bool {
if !self.has_butt_stroke() {
return false;
}
let slanted = |v: Vec2| {
let d = unit(a * v.to_point() - a * Point::ZERO);
(d.x * d.y).abs() > 1e-9
};
let els = bp.elements();
subpaths(bp)
.into_iter()
.filter(|(_, closed)| !closed)
.any(|(r, _)| drawn(&els[r]).iter().any(|s| slanted(tangent(s, 0.0)) || slanted(tangent(s, 1.0))))
}
/// Does a visible stroke of this appearance along `bp` (filled with `rule`) paint within
/// `tol` of `p` ([`StrokeLayer::hits`])?
pub fn stroke_hit(&self, bp: &BezPath, rule: FillRule, p: Point, tol: f64) -> bool {
@@ -332,6 +459,31 @@ impl Appearance {
}
}
/// How many symbol instances [`crate::Node::has_slanted_butt_stroke`] looks into for one object
/// before it answers yes without looking further.
pub const SLANT_INSTANCES: usize = 4096;
impl crate::Node {
/// Does a visible butt-capped stroke of this object, of an object in it or of an object in a
/// symbol instance's art from `symbols`, placed by `a`, run along an open path with a segment
/// at a slant ([`Appearance::has_slanted_butt_stroke`])? Past [`SLANT_INSTANCES`] instances it
/// answers yes.
pub fn has_slanted_butt_stroke(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine) -> bool {
self.slanted_butt(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES))
}
/// [`Self::has_slanted_butt_stroke`] with `left` instances still to look into.
fn slanted_butt(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine, left: &std::cell::Cell<usize>) -> bool {
if let crate::NodeKind::SymbolInstance { symbol, xf } = &self.kind {
let Some(l) = left.get().checked_sub(1) else { return true };
left.set(l);
return symbols.measure_art(symbol, |art| art.slanted_butt(symbols, a * *xf, left)).unwrap_or(false);
}
(self.appearance.has_butt_stroke() && self.stroke_path().is_some_and(|bp| self.appearance.has_slanted_butt_stroke(&bp, a)))
|| self.children().is_some_and(|c| c.iter().any(|c| c.slanted_butt(symbols, a, left)))
}
}
#[cfg(test)]
mod tests {
use vectorcraft_color::{Color, Paint};
@@ -378,7 +530,7 @@ mod tests {
let (small, big) = (at(100.0).bounds_on(&l, b), at(300.0).bounds_on(&l, b));
assert!(big.x1 > small.x1 + 15.0 && big.y1 > small.y1 + 7.0, "{small:?} → {big:?}");
// A 300% head on a 2 pt stroke is 24 pt long and wide: its tip, past the end, is inside.
assert!(big.x1 >= 100.0 + 24.0 && big.y1 >= 12.0 && big.x0 == -1.0, "{big:?}");
assert!(big.x1 >= 100.0 + 24.0 && big.y1 >= 12.0 && big.x0 == 0.0, "{big:?}");
// The start has no head.
assert_eq!(at(300.0).head_reach(false), 0.0);
}
@@ -405,6 +557,203 @@ mod tests {
assert_eq!(stroke(4.0, |s| s.align = StrokeAlign::Outside).bounds_on(&sq, b), b.inflate(4.0, 4.0));
}
/// An open path through `points`.
fn polyline(points: &[(f64, f64)]) -> BezPath {
let mut bp = BezPath::new();
for (i, p) in points.iter().enumerate() {
if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) }
}
bp
}
#[test]
fn butt_caps_stop_at_the_ends_of_an_open_path() {
let butt = |f: fn(&mut StrokeLayer)| {
stroke(2.0, |s| {
s.cap = LineCap::Butt;
f(s);
})
};
// A vertical line reaches sideways only.
let v = polyline(&[(50.0, 10.0), (50.0, 60.0)]);
assert_eq!(butt(|_| {}).bounds_on(&v, v.bounding_box()), Rect::new(49.0, 10.0, 51.0, 60.0));
// A 3-4-5 diagonal: its corners reach 0.8 pt across x and 0.6 pt across y.
let d = polyline(&[(0.0, 0.0), (30.0, 40.0)]);
let b = butt(|_| {}).bounds_on(&d, d.bounding_box());
for (got, want) in [(b.x0, -0.8), (b.y0, -0.6), (b.x1, 30.8), (b.y1, 40.6)] {
assert!((got - want).abs() < 1e-9, "{b:?}");
}
// The dashes of a butt stroke stop inside the line as well, and an open path ignores the
// alignment.
let dashed = butt(|s| s.dash = Some(Dash { pattern: vec![4.0, 2.0], offset: 0.0, align_corners: false }));
assert_eq!(dashed.bounds_on(&v, v.bounding_box()), Rect::new(49.0, 10.0, 51.0, 60.0));
assert_eq!(butt(|s| s.align = StrokeAlign::Inside).bounds_on(&v, v.bounding_box()), Rect::new(49.0, 10.0, 51.0, 60.0));
// A round cap reaches half the weight past each end, a square one the corners.
let round = butt(|s| s.cap = LineCap::Round).bounds_on(&v, v.bounding_box());
assert_eq!(round, Rect::new(49.0, 9.0, 51.0, 61.0));
let square = butt(|s| s.cap = LineCap::Square).bounds_on(&v, v.bounding_box());
assert_eq!(square, Rect::new(49.0, 9.0, 51.0, 61.0));
// Two strokes union.
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0);
ap.stroke_mut().unwrap().cap = LineCap::Butt;
let wide = stroke(10.0, |s| s.cap = LineCap::Round);
ap.items.push(crate::AppearanceItem::Stroke(wide));
let vb = v.bounding_box();
assert_eq!(ap.stroked_bounds(vb, || v.clone()), Rect::new(45.0, 5.0, 55.0, 65.0));
}
#[test]
fn a_butt_paths_joins_and_curves_stay_inside_the_box() {
// A corner in the middle: the round join reaches a full half weight straight down, outside
// the turn, the ends do not, and a miter reaches its tip.
let zig = polyline(&[(0.0, 0.0), (20.0, 20.0), (40.0, 0.0)]);
let round = stroke(4.0, |s| {
s.cap = LineCap::Butt;
s.join = LineJoin::Round;
})
.bounds_on(&zig, zig.bounding_box());
assert!((round.y1 - 22.0).abs() < 1e-9, "the round join's reach: {round:?}");
assert!((round.x0 + 2.0_f64.sqrt()).abs() < 1e-9 && (round.x1 - 40.0 - 2.0_f64.sqrt()).abs() < 1e-9, "the ends' corners: {round:?}");
// A round join paints its arc on the outer side of a turn too shallow to count as a
// corner, and nothing where the path goes straight on.
let round_butt = stroke(4.0, |s| {
s.cap = LineCap::Butt;
s.join = LineJoin::Round;
});
let shallow = polyline(&[(0.0, 0.25), (50.0, 0.0), (100.0, 0.25)]);
let b = round_butt.bounds_on(&shallow, shallow.bounding_box());
assert!((b.y0 + 2.0).abs() < 1e-12, "{b:?}");
let straight = polyline(&[(0.0, 0.0), (0.1, 0.0), (100.0, 0.0)]);
assert_eq!(round_butt.bounds_on(&straight, straight.bounding_box()), Rect::new(0.0, -2.0, 100.0, 2.0));
let miter = stroke(4.0, |s| s.cap = LineCap::Butt).bounds_on(&zig, zig.bounding_box());
assert!((miter.y1 - (20.0 + 2.0 * 2.0_f64.sqrt())).abs() < 1e-9, "the miter tip: {miter:?}");
// An arc over the top whose ends leave the page straight down: the top reaches half the
// weight past the path, and the bottom stops at the ends.
let mut arc = BezPath::new();
arc.move_to((0.0, 50.0));
arc.curve_to((0.0, 22.4), (22.4, 0.0), (50.0, 0.0));
arc.curve_to((77.6, 0.0), (100.0, 22.4), (100.0, 50.0));
let b = stroke(4.0, |s| s.cap = LineCap::Butt).bounds_on(&arc, arc.bounding_box());
assert!((b.y0 + 2.0).abs() < 1e-9 && (b.x0 + 2.0).abs() < 1e-9 && (b.x1 - 102.0).abs() < 1e-9, "{b:?}");
assert!((b.y1 - 50.0).abs() < 1e-9, "{b:?}");
}
#[test]
fn a_butt_curve_with_a_handle_on_its_end_point_stops_near_that_end() {
let butt = stroke(2.0, |s| s.cap = LineCap::Butt);
// A straight curve whose first or last handle sits on its end point measures like a line.
let mut first = BezPath::new();
first.move_to((50.0, 10.0));
first.curve_to((50.0, 10.0), (50.0, 40.0), (50.0, 60.0));
let mut last = BezPath::new();
last.move_to((50.0, 10.0));
last.curve_to((50.0, 20.0), (50.0, 60.0), (50.0, 60.0));
for bp in [first, last] {
assert_eq!(butt.bounds_on(&bp, bp.bounding_box()), Rect::new(49.0, 10.0, 51.0, 60.0));
}
// A bend that leaves its start straight up from a handle on the start point: the stroke
// reaches only a little below the start, not half the weight.
let mut bend = BezPath::new();
bend.move_to((0.0, 50.0));
bend.curve_to((0.0, 50.0), (0.0, 0.0), (50.0, 0.0));
let b = stroke(4.0, |s| s.cap = LineCap::Butt).bounds_on(&bend, bend.bounding_box());
assert!(b.y1 >= 50.0 && b.y1 < 50.2, "{b:?}");
assert!((b.x0 + 2.0).abs() < 1e-9 && (b.y0 + 2.0).abs() < 1e-9 && (b.x1 - 50.0).abs() < 1e-9, "{b:?}");
// Nearly a cusp: the curve turns back at its lowest point, where its tangent is level and
// the stroke reaches the full half weight below it.
let (a0, a1, a2) = (1e5 * 81.0 / 256.0, -1e5 * 9.0 / 8.0, 1e5);
let x = |i: f64| 2e-9 * i / 3.0;
let mut cusp = BezPath::new();
cusp.move_to((x(0.0), a0));
cusp.curve_to((x(1.0), a0 + a1 / 3.0), (x(2.0), a0 + 2.0 * a1 / 3.0 + a2 / 3.0), (x(3.0), a0 + a1 + a2));
let b = butt.bounds_on(&cusp, cusp.bounding_box());
assert!(b.y0 <= -1.0 + 1e-6, "{b:?}");
// A curve far shorter than the weight still reaches half the weight above where its
// tangent is level.
let mut tiny = BezPath::new();
tiny.move_to((0.0, 0.9e-12));
tiny.curve_to((0.3e-12, -0.5e-12), (1.7e-12, -0.2e-12), (2e-12, 1e-12));
let b = butt.bounds_on(&tiny, tiny.bounding_box());
assert!(b.y0 <= -1.0 + 1e-9, "{b:?}");
}
#[test]
fn a_butt_stroke_is_slanted_where_a_segment_starts_or_ends_at_a_slant() {
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0);
ap.stroke_mut().unwrap().cap = LineCap::Butt;
let id = vectorcraft_geom::Affine::IDENTITY;
assert!(!ap.has_slanted_butt_stroke(&polyline(&[(0.0, 0.0), (0.0, 50.0), (30.0, 50.0)]), id));
// Square ends, slanted segments in the middle.
let apex = polyline(&[(0.0, 50.0), (0.0, 40.0), (10.0, 0.0), (20.0, 40.0), (20.0, 50.0)]);
assert!(ap.has_slanted_butt_stroke(&apex, id));
// A rotation slants a vertical line; a round cap is never slanted.
let v = polyline(&[(0.0, 0.0), (0.0, 50.0)]);
assert!(ap.has_slanted_butt_stroke(&v, vectorcraft_geom::Affine::rotate(0.3)));
ap.stroke_mut().unwrap().cap = LineCap::Round;
assert!(!ap.has_slanted_butt_stroke(&apex, id));
}
#[test]
fn the_slant_check_looks_into_at_most_4096_symbol_instances() {
// S0 is a vertical butt line. Each of S1 to S12 holds two instances of the symbol before
// it, so an instance of S12 holds 8,191 instances and none of them is slanted. Past 4,096
// the check answers yes.
let mut d = Document::new(400.0, 400.0);
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0);
ap.stroke_mut().unwrap().cap = LineCap::Butt;
let line = Node::path(d.alloc_id(), PathData::from_bezpath(&polyline(&[(0.0, 0.0), (0.0, 10.0)])), ap);
d.symbols.push(crate::Symbol { dynamic: false, name: "S0".into(), art: std::sync::Arc::new(line) });
for k in 1..=12 {
let mut instance = |dx: f64| {
let xf = vectorcraft_geom::Affine::translate((dx, 0.0));
std::sync::Arc::new(Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: format!("S{}", k - 1), xf }))
};
let pair = vec![instance(0.0), instance(20.0)];
let art = Node::group(d.alloc_id(), pair);
d.symbols.push(crate::Symbol { dynamic: false, name: format!("S{k}"), art: std::sync::Arc::new(art) });
}
let top = Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: "S12".into(), xf: vectorcraft_geom::Affine::IDENTITY });
let symbols = d.symbol_boxes();
assert!(top.has_slanted_butt_stroke(&symbols, vectorcraft_geom::Affine::IDENTITY));
assert!(symbols.art_measured() <= SLANT_INSTANCES, "{}", symbols.art_measured());
// One instance of S1 holds three instances, all looked into.
let one = Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: "S1".into(), xf: vectorcraft_geom::Affine::IDENTITY });
assert!(!one.has_slanted_butt_stroke(&d.symbol_boxes(), vectorcraft_geom::Affine::IDENTITY));
}
#[test]
fn a_compound_path_measures_each_of_its_subpaths_by_its_own_ends() {
// A closed square at the top and an open line below it: only the square reaches past its
// own edges.
let mut bp = BezPath::new();
bp.extend(square().elements().iter().copied());
bp.move_to((50.0, 150.0));
bp.line_to((50.0, 200.0));
let st = stroke(4.0, |s| s.cap = LineCap::Butt);
assert_eq!(st.bounds_on(&bp, bp.bounding_box()), Rect::new(-2.0, -2.0, 102.0, 200.0));
}
#[test]
fn a_middle_segment_can_set_the_box_of_a_butt_path() {
// The flat middle segment reaches a full half weight above the path, and the ends' corners
// reach 10/51 of it below.
let hat = polyline(&[(0.0, 50.0), (10.0, 0.0), (20.0, 0.0), (30.0, 50.0)]);
let b = stroke(2.0, |s| {
s.cap = LineCap::Butt;
s.join = LineJoin::Bevel;
})
.bounds_on(&hat, hat.bounding_box());
let corner = 10.0 / (10.0_f64 * 10.0 + 50.0 * 50.0).sqrt();
assert!((b.y0 + 1.0).abs() < 1e-9 && (b.y1 - 50.0 - corner).abs() < 1e-9, "{b:?}");
}
#[test]
fn bounds_with_tips_measures_a_butt_line_as_bounds_on_does() {
let v = polyline(&[(50.0, 10.0), (50.0, 60.0)]);
let st = stroke(2.0, |s| s.cap = LineCap::Butt);
assert_eq!(st.bounds_with_tips(&v, v.bounding_box(), None), Rect::new(49.0, 10.0, 51.0, 60.0));
}
#[test]
fn clicks_hit_outside_strokes_on_their_side_only() {
let sq = square();
+17
View File
@@ -126,6 +126,23 @@ impl SavedSelection {
}
}
/// An SVG filter the document holds (Effect › SVG Filters): a `<filter>` element named by its
/// `id`, listed in the SVG Filters submenu and in Apply SVG Filter.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SvgFilter {
/// The filter element's `id`.
pub name: String,
/// The `<filter>` element's XML, as it was written.
pub xml: String,
}
impl SvgFilter {
/// Most SVG filters a document holds.
pub const MAX: usize = 64;
/// Longest filter element, in bytes.
pub const MAX_XML: usize = 64 * 1024;
}
/// A symbol definition.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Symbol {
+48
View File
@@ -54,6 +54,20 @@ pub struct Selection {
/// the engine then sets the document's from it. Editing state, never saved.
#[serde(skip)]
pub new_art: Arc<HashSet<NodeId>>,
/// An object of a dynamic symbol instance's art, selected with Direct Selection: the instance
/// is the one selected object, and solid fill and stroke changes go to its own appearance for
/// that object ([`crate::symbol_overrides`]). Any other selection change clears it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub symbol_part: Option<SymbolPart>,
}
/// See [`Selection::symbol_part`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SymbolPart {
/// The symbol instance.
pub instance: NodeId,
/// The object in the symbol's art, as [`crate::symbol_overrides::part`] names it.
pub path: Vec<u32>,
}
impl Selection {
@@ -79,6 +93,13 @@ impl Selection {
self.slices.clear();
self.guides.clear();
self.key_guide = None;
self.symbol_part = None;
}
/// Select only instance `instance`, with the object at `path` of its symbol's art (see
/// [`Selection::symbol_part`]).
pub fn set_symbol_part(&mut self, instance: NodeId, path: Vec<u32>) {
self.set([instance]);
self.symbol_part = Some(SymbolPart { instance, path });
}
/// Is there a key for Align: an object or a guide?
pub fn has_key(&self) -> bool {
@@ -93,6 +114,7 @@ impl Selection {
pub fn add(&mut self, id: NodeId) {
self.target = None;
self.slices.clear();
self.symbol_part = None;
if !self.objects.contains(&id) {
self.objects.push(id);
}
@@ -100,6 +122,7 @@ impl Selection {
pub fn remove(&mut self, id: NodeId) {
self.target = None;
self.slices.clear();
self.symbol_part = None;
self.objects.retain(|x| *x != id);
self.anchors.remove(&id);
self.segments.remove(&id);
@@ -128,6 +151,7 @@ impl Selection {
/// Add ruler guide `i` to the selection, or take it out, keeping the selected objects (a
/// Shift-click on a guide).
pub fn toggle_guide(&mut self, i: usize) {
self.symbol_part = None;
if let Some(k) = self.guides.iter().position(|g| *g == i) {
self.guides.remove(k);
if self.key_guide == Some(i) {
@@ -207,6 +231,27 @@ impl Selection {
if self.key.is_some() || self.objects.is_empty() || self.key_guide.is_some_and(|k| !self.guides.contains(&k)) {
self.key_guide = None;
}
// A selected part needs its instance selected alone, with no guides, its symbol dynamic
// and the object still in the symbol's art as a path, compound path or type, where neither
// it nor a group or layer around it is hidden, locked or a template.
let editable_part = |art: &crate::Node, path: &[u32]| {
crate::symbol_overrides::part(art, path).is_some_and(crate::symbol_overrides::takes_part_paint)
&& (0..=path.len())
.all(|k| crate::symbol_overrides::part(art, &path[..k]).is_some_and(|n| n.visible && !n.locked && !n.is_template()))
};
let part_kept = self.symbol_part.as_ref().is_some_and(|sp| {
self.objects == [sp.instance]
&& self.guides.is_empty()
&& found.get(&sp.instance).and_then(|p| doc.node_at(p)).is_some_and(|n| match &n.kind {
NodeKind::SymbolInstance { symbol, .. } => {
doc.symbols.iter().find(|s| s.name == *symbol).is_some_and(|s| s.dynamic && editable_part(&s.art, &sp.path))
}
_ => false,
})
});
if !part_kept {
self.symbol_part = None;
}
}
/// Deselect the objects that are hidden or locked, themselves or through a group or layer
/// around them (and so the key object when it is one): hidden or locked art can't stay
@@ -238,6 +283,9 @@ impl Selection {
}
self.target = None;
self.slices.clear();
if self.symbol_part.as_ref().is_some_and(|sp| gone.contains(&sp.instance)) {
self.symbol_part = None;
}
self.objects.retain(|o| !gone.contains(o));
self.anchors.retain(|id, _| !gone.contains(id));
self.segments.retain(|id, _| !gone.contains(id));
+76
View File
@@ -41,6 +41,82 @@ fn guides_are_selected_on_their_own() {
assert_eq!(s.guides, vec![0]);
}
/// A picked object of a dynamic symbol's instance stays picked while it and the groups and layers
/// around it in the symbol's art are visible, unlocked and not a template. An art edit that hides
/// or locks it, or one around it, or makes a layer around it a template, drops the pick.
#[test]
fn a_picked_symbol_part_is_dropped_once_it_cannot_be_edited() {
let rect = || vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
let mut d = Document::new(100.0, 100.0);
let l = d.layers[0].id;
let leaf = Node::path(d.alloc_id(), rect(), crate::Appearance::default_art());
let group = Node::group(d.alloc_id(), vec![Arc::new(leaf)]);
let layer = Node::layer(d.alloc_id(), "Inner", crate::LayerColor::Preset(2));
let root = Node::group(d.alloc_id(), vec![Arc::new(group), Arc::new(layer)]);
d.symbols.push(crate::Symbol { dynamic: true, name: "Parts".into(), art: Arc::new(root.clone()) });
let inst = d.alloc_id();
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Parts".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
// The layer in the art holds a path too.
let in_layer = Node::path(d.alloc_id(), rect(), crate::Appearance::default_art());
let mut art = root;
if let Some(NodeKind::Layer { children, .. }) = art.children_mut().and_then(|c| c.get_mut(1)).map(|c| &mut Arc::make_mut(c).kind) {
children.push(Arc::new(in_layer));
}
d.symbols[0].art = Arc::new(art.clone());
let picked = |d: &Document, path: &[u32]| {
let mut s = Selection::default();
s.set_symbol_part(inst, path.to_vec());
s.prune(d);
s.symbol_part.is_some()
};
assert!(picked(&d, &[0, 0]) && picked(&d, &[1, 0]), "editable parts stay picked");
assert!(!picked(&d, &[0]) && !picked(&d, &[1]) && !picked(&d, &[]), "a group or layer does not stay picked");
let edited = |change: &dyn Fn(&mut Node)| {
let mut d = d.clone();
let mut art = art.clone();
change(&mut art);
d.symbols[0].art = Arc::new(art);
d
};
let child = |art: &mut Node, path: &[usize]| -> Node {
let mut n = &*art;
for &i in path {
n = &n.children().unwrap()[i];
}
n.clone()
};
let set = |art: &mut Node, path: &[usize], n: Node| {
let mut at = art;
for &i in path {
at = Arc::make_mut(&mut at.children_mut().unwrap()[i]);
}
*at = n;
};
let hidden = edited(&|art| {
let mut n = child(art, &[0, 0]);
n.visible = false;
set(art, &[0, 0], n);
});
assert!(!picked(&hidden, &[0, 0]), "the part is hidden");
let locked_group = edited(&|art| {
let mut n = child(art, &[0]);
n.locked = true;
set(art, &[0], n);
});
assert!(!picked(&locked_group, &[0, 0]), "the group around it is locked");
assert!(picked(&locked_group, &[1, 0]), "a part outside the locked group stays");
let template = edited(&|art| {
let mut n = child(art, &[1]);
if let NodeKind::Layer { template, .. } = &mut n.kind {
*template = true;
}
set(art, &[1], n);
});
assert!(!picked(&template, &[1, 0]), "the layer around it is a template");
let hidden_root = edited(&|art| art.visible = false);
assert!(!picked(&hidden_root, &[0, 0]), "the art is hidden");
}
#[test]
fn guides_show_and_lock_with_their_layer() {
let mut d = Document::new(100.0, 100.0);
+21
View File
@@ -120,6 +120,21 @@ impl Quotes {
prev.is_none_or(|p| p.is_whitespace() || matches!(p, '(' | '[' | '{' | '—' | '–') || quote_opened.unwrap_or_else(|| self.is_open(p)))
}
/// The straight quote a typed curly quote stands for: `"` for `”` (U+201D) and nothing else.
/// The macOS Serbian Cyrillic layout has no straight `"` and types `”` on Shift+2, so with
/// Typographer's Quotes on, a `”` typed alone where a quote opens takes the document's opening
/// quote ([`Quotes::opens_after`]); where a quote closes it stays `”`. `“ „` and the single
/// quotes `‘ ’ ‚` stay as typed: that layout's apostrophe key already types `’`, as Serbian
/// wants, and `’90s` keeps its apostrophe.
pub fn typed_as_straight(c: char) -> Option<char> {
(c == '”').then_some('"')
}
/// Does a quote typed after `prev` (the character before it, `None` at the start) open?
pub fn opens_after(&self, prev: Option<char>) -> bool {
self.opens(prev, None)
}
/// `text` with straight quotes (`"` and `'`) replaced by these quotes: opening or closing by
/// context (an apostrophe is a closing single quote). `prev` is the character before `text`,
/// and is updated to its last character, so text can be converted in pieces.
@@ -420,6 +435,12 @@ mod tests {
}
let mut prev = None;
assert_eq!(language_quotes("croatian").unwrap().apply("\"a 'b' c\"", &mut prev), "„a ‚b‘ c“");
// Only a typed `”` stands for a straight quote; the other curly quotes stay as typed.
assert_eq!(Quotes::typed_as_straight('”'), Some('"'));
assert!(['“', '„', '‘', '’', '‚', '"', '\'', '«', '»', '「', 'a'].iter().all(|&c| Quotes::typed_as_straight(c).is_none()));
// A quote opens at the start and after a space, and closes after a letter.
assert!(Quotes::ENGLISH.opens_after(None) && Quotes::ENGLISH.opens_after(Some(' ')));
assert!(!Quotes::ENGLISH.opens_after(Some('a')));
// Bulgarian: „…“ at either level, as CLDR has it.
let mut prev = None;
assert_eq!(language_quotes("bulgarian").unwrap().apply("\"a 'b' c\"", &mut prev), "„a „b“ c“");
+33
View File
@@ -158,6 +158,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[
BuiltinStyleLibrary { id: "gradient-finishes", name: "Gradient Finishes", make: gradient_finishes },
BuiltinStyleLibrary { id: "shape-effects", name: "Shape Effects", make: shape_effects },
BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency },
BuiltinStyleLibrary { id: "game-hud", name: "Game HUD", make: game_hud },
];
/// Built-in library `id`, made once.
@@ -453,6 +454,34 @@ fn blends_transparency() -> Vec<GraphicStyle> {
]
}
/// Game HUD: fills and glows for health, mana, damage and quest chrome (original arcade/HUD look).
fn game_hud() -> Vec<GraphicStyle> {
vec![
style("Health Fill", vec![F(fill("#e74c3c")), S(stroke("#5c1a1a", 1.25))], vec![]),
style(
"Mana Glow",
vec![F(fill("#3498db"))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 85.0, "blur": 7.0, "color": "#5dade2"}))],
),
style(
"Damage Flash",
vec![F(fill("#ff6b35"))],
vec![fx("stylize.innerGlow", json!({"mode": "screen", "opacity": 80.0, "blur": 8.0, "color": "#ffe66d", "source": "edge"}))],
),
style("Quest Outline", vec![F(fill("#f7f3e8")), S(round("#2c3e50", 3.0))], vec![]),
style(
"Coin Shine",
vec![F(fill("#f1c40f")), S(stroke("#b7950b", 1.5))],
vec![fx("stylize.dropShadow", json!({"mode": "multiply", "opacity": 40.0, "x": 2.0, "y": 3.0, "blur": 4.0, "color": "#1d1b2a"}))],
),
style(
"Boss Alert",
vec![F(fill("#1a1a2e")), S(round("#e94560", 2.5))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 75.0, "blur": 6.0, "color": "#e94560"}))],
),
]
}
#[cfg(test)]
mod tests {
use super::*;
@@ -475,6 +504,10 @@ mod tests {
}
assert!(Arc::ptr_eq(&builtin_style_library("hand-drawn").unwrap(), &builtin_style_library("hand-drawn").unwrap()), "made once");
assert!(builtin_style_library("nope").is_none());
let game = builtin_style_library("game-hud").unwrap();
assert_eq!(game.name, "Game HUD");
let names: Vec<&str> = game.styles.iter().map(|g| g.name.as_str()).collect();
assert_eq!(names, ["Health Fill", "Mana Glow", "Damage Flash", "Quest Outline", "Coin Shine", "Boss Alert"]);
}
#[test]
+127 -3
View File
@@ -7,6 +7,7 @@
//! those links (and colours) wherever art and swatches hold them, copying only the nodes that
//! change.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use vectorcraft_color::swatch::REGISTRATION;
@@ -85,6 +86,12 @@ impl Document {
fn numbered_swatch_name(&self, base: &str, from: usize) -> String {
(from..).map(|i| format!("{base} {i}")).find(|n| !self.swatch_name_taken(n)).unwrap_or_else(|| base.to_string())
}
/// Names for several new swatches: [`FreeSwatchNames::take`] gives what
/// [`Document::free_swatch_name`] gives once the swatches named before it are added.
pub fn free_swatch_names(&self) -> FreeSwatchNames {
let taken = self.swatches_iter().map(|s| s.name.clone()).chain(self.swatch_groups.iter().map(|g| g.name.clone()));
FreeSwatchNames { taken: taken.chain([REGISTRATION.to_string()]).collect(), next: HashMap::new() }
}
/// The name a new swatch of `paint` gets by default, unused in the document: a colour's values
/// ([`color_name`], made free like [`Document::free_swatch_name`]), or "New Gradient Swatch 1",
/// "New Pattern Swatch 1"…
@@ -169,7 +176,7 @@ impl Document {
pub fn visit_paints(&self, f: &mut dyn FnMut(&Paint)) {
let mut tree = |n: &Node| {
walk_with_masks(n, &mut |m| {
node_paints(m).for_each(&mut *f);
node_paints(m).chain(override_paints(m)).for_each(&mut *f);
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| f(&Paint::solid(p.color)));
}
@@ -200,6 +207,52 @@ pub fn color_name(c: Color) -> String {
}
}
/// The swatch and color group names of a document ([`Document::free_swatch_names`]) and the names
/// handed out since, for naming many new swatches without searching the document for each name.
#[derive(Clone, Debug)]
pub struct FreeSwatchNames {
taken: HashSet<String>,
/// For each base and first number already numbered, the number its next numbered name is
/// looked for from: names are only ever added, so the numbers below it stay taken.
next: HashMap<(String, usize), usize>,
}
impl FreeSwatchNames {
/// `base`, or the first of "base 2", "base 3"… not taken, as [`Document::free_swatch_name`]
/// gives it; the name is taken from then on.
pub fn take(&mut self, base: &str) -> String {
let name = if self.taken.contains(base) { self.numbered(base, 2) } else { base.to_string() };
self.taken.insert(name.clone());
name
}
/// The name [`Document::new_swatch_name`] gives a new swatch of `paint`; the name is taken
/// from then on.
pub fn take_new(&mut self, paint: &Paint) -> String {
let base = match paint {
Paint::Solid { swatch: Some(n), tint, .. } if *tint < 1.0 => return self.take(&format!("{n} {}%", tint_percent(*tint))),
Paint::Solid { color, .. } => return self.take(&color_name(*color)),
Paint::Gradient(_) => "New Gradient Swatch",
_ => "New Pattern Swatch",
};
let name = self.numbered(base, 1);
self.taken.insert(name.clone());
name
}
/// Count `name` as taken (a swatch or color group added another way).
pub fn insert(&mut self, name: &str) {
self.taken.insert(name.to_string());
}
/// The first of "base `from`", "base `from + 1`"… not taken.
fn numbered(&mut self, base: &str, from: usize) -> String {
let key = (base.to_string(), from);
let start = self.next.get(&key).copied().unwrap_or(from);
let (i, name) =
(start..).map(|i| (i, format!("{base} {i}"))).find(|(_, n)| !self.taken.contains(n)).unwrap_or_else(|| (start, base.to_string()));
self.next.insert(key, i + 1);
name
}
}
/// What [`Document::map_solid_paints`] applies to each linkable colour: `(colour, link, tint)`,
/// true when it changed them.
pub type LinkFn<'a> = dyn FnMut(&mut Color, &mut Option<String>, &mut f32) -> bool + 'a;
@@ -222,10 +275,11 @@ fn map_style_paint(attrs: &mut serde_json::Map<String, serde_json::Value>, key:
}
/// Every colour in the subtree of `n` with the swatch it links to: solid fills, strokes, text runs
/// and gradient stops (with their link), then mesh points (unlinked), in paint order.
/// and gradient stops (with their link), a dynamic symbol instance's own paints
/// ([`override_paints`]), then mesh points (unlinked), in paint order.
pub fn node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) {
n.walk(&mut |m| {
for p in node_paints(m) {
for p in node_paints(m).chain(override_paints(m)) {
match p {
Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()),
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())),
@@ -262,6 +316,12 @@ pub fn node_paints(n: &Node) -> impl Iterator<Item = &Paint> {
n.appearance.items.iter().map(item_paint).chain(runs.iter().flat_map(|r| [&r.style.fill, &r.style.stroke])).chain(n.extras().colorize.as_deref())
}
/// The paints a dynamic symbol instance keeps for objects of its art
/// ([`crate::symbol_overrides`]), which [`node_paints`] leaves out.
pub fn override_paints(n: &Node) -> impl Iterator<Item = &Paint> {
n.extras().symbol_overrides.iter().flat_map(|o| [o.fill.as_ref(), o.stroke.as_ref()]).flatten()
}
/// Mutable [`node_paints`], in the same order.
pub fn node_paints_mut(n: &mut Node) -> impl Iterator<Item = &mut Paint> {
let runs = match &mut n.kind {
@@ -300,6 +360,20 @@ fn map_node(n: &Node, f: &mut LinkFn) -> Option<(Node, usize)> {
}
out = Some(m);
}
// A dynamic symbol instance's own paints for objects of its art (`symbol_overrides`).
if !n.extras().symbol_overrides.is_empty() {
let mut overrides = n.extras().symbol_overrides.clone();
let mut k = 0;
for p in overrides.iter_mut().flat_map(|o| [&mut o.fill, &mut o.stroke]).flatten() {
if matches!(p, Paint::Solid { .. } | Paint::Gradient(_)) && p.map_links(f) {
k += 1;
}
}
if k > 0 {
out.get_or_insert_with(|| n.clone()).extras_mut().symbol_overrides = overrides;
count += k;
}
}
if let Some(ch) = n.children() {
for (i, c) in ch.iter().enumerate() {
if let Some((new, k)) = map_node(c, f) {
@@ -419,6 +493,56 @@ mod tests {
assert_eq!(d.new_swatch_name(&Paint::solid(Color::rgb(1.0, 0.0, 0.0))), "R=255 G=0 B=0");
}
#[test]
fn free_swatch_names_match_naming_each_swatch_as_it_is_added() {
let (mut d, _, _) = doc();
let mut names = d.free_swatch_names();
for base in ["Brand", "Brand", "Mine", "Fresh", "Fresh", "Brand 2", "Brand", REGISTRATION, "Fresh 3", "Fresh", "Mine 2"] {
let want = d.free_swatch_name(base);
assert_eq!(names.take(base), want, "{base}");
d.swatches.push(Swatch { name: want, paint: Paint::solid(Color::BLACK), global: false, spot: false });
}
let added: Vec<&str> = d.swatches.iter().rev().take(11).rev().map(|w| w.name.as_str()).collect();
assert_eq!(
added,
["Brand 2", "Brand 3", "Mine 2", "Fresh", "Fresh 2", "Brand 2 2", "Brand 4", "[Registration] 2", "Fresh 3", "Fresh 4", "Mine 2 2"]
);
}
#[test]
fn free_swatch_names_match_new_swatch_names_as_swatches_are_added() {
let (mut d, _, _) = doc();
let red = Color::rgb(1.0, 0.0, 0.0);
d.swatches.push(Swatch { name: "New Gradient Swatch 2".into(), paint: Paint::solid(red), global: false, spot: false });
let mut names = d.free_swatch_names();
// A name taken another way (a group made alongside) counts for both.
names.insert("R=255 G=0 B=0 3");
d.swatch_groups.push(SwatchGroup { name: "R=255 G=0 B=0 3".into(), swatches: vec![] });
let tint = Paint::Solid { color: red, swatch: Some("Brand".into()), tint: 0.4 };
let gradient = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(Default::default())));
let paints = [Paint::solid(red), Paint::solid(red), gradient.clone(), tint.clone(), Paint::solid(red), gradient.clone(), tint, gradient];
let mut added = vec![];
for paint in paints {
let want = d.new_swatch_name(&paint);
assert_eq!(names.take_new(&paint), want);
d.swatches.push(Swatch { name: want.clone(), paint, global: false, spot: false });
added.push(want);
}
assert_eq!(
added,
[
"R=255 G=0 B=0",
"R=255 G=0 B=0 2",
"New Gradient Swatch 1",
"Brand 40%",
"R=255 G=0 B=0 4",
"New Gradient Swatch 3",
"Brand 40% 2",
"New Gradient Swatch 4"
]
);
}
#[test]
fn mapping_copies_only_changed_nodes() {
let (mut d, a, b) = doc();
+12
View File
@@ -451,6 +451,18 @@ impl NineSliceMap {
self.most_at(art, &boxes, 0)
}
/// The affine map that [`Self::place`] and [`Self::place_unclipped`] move object `n` by as one
/// piece, with everything in it: the map of the cell its box lies in, or of the cell at the
/// origin when it has no box. `None` when its box crosses a guide.
pub fn one_cell(&self, n: &Node, doc: &Document) -> Option<Affine> {
let boxes = doc.symbol_boxes().quick();
let Some(b) = n.geometric(Some(&boxes)).map(|b| self.natural.transform_rect_bbox(b)).filter(|b| finite(*b)) else {
return Some(self.cell_at(Point::ZERO));
};
let (cols, rows) = (self.x.cells(b.x0, b.x1), self.y.cells(b.y0, b.y1));
(cols[0] == cols[1] && rows[0] == rows[1]).then(|| self.cell_xf(cols[0], rows[0]))
}
/// [`Self::most_placed`] for [`Self::place_unclipped`]: the most objects it makes of `art`.
pub fn most_placed_unclipped(&self, art: &Node, doc: &Document) -> u64 {
Self { clips: false, ..*self }.most_placed(art, doc)
+40
View File
@@ -49,6 +49,10 @@ impl SymbolOverride {
r.style.fill = p.clone();
}
if let Some(p) = &self.stroke {
// A painted stroke on characters without a weight gets 1 pt, as a path's does.
if !p.is_none() && r.style.stroke_width == 0.0 {
r.style.stroke_width = 1.0;
}
r.style.stroke = p.clone();
}
}
@@ -57,6 +61,14 @@ impl SymbolOverride {
n.appearance.set_fill(p.clone());
}
if let Some(p) = &self.stroke {
// A stroke without paint has no weight; painting it gives it 1 pt.
if !p.is_none()
&& let Some(s) = n.appearance.stroke_mut()
&& s.paint.is_none()
&& s.width == 0.0
{
s.width = 1.0;
}
n.appearance.set_stroke(p.clone());
}
}
@@ -69,6 +81,13 @@ impl SymbolOverride {
}
}
/// Can Direct Selection select `n`, an object of a dynamic symbol's art, and change its fill and
/// stroke for one instance? Paths, compound paths and type can; groups, images and every other
/// object cannot.
pub fn takes_part_paint(n: &Node) -> bool {
matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_))
}
/// An override's path read from a file: at most [`MAX_PATH_DEPTH`] indices, so a compressed file
/// of one endless path stays small once read.
fn short_path<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<u32>, D::Error> {
@@ -180,6 +199,27 @@ mod tests {
assert_eq!(kept.len(), 1);
}
#[test]
fn a_stroke_on_type_without_a_weight_gets_one_point() {
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let style = crate::CharStyle { stroke: Paint::None, stroke_width: 0.0, ..crate::CharStyle::default() };
let text = Node::new(NodeId(2), NodeKind::Text(Box::new(crate::TextObject::point(vectorcraft_geom::Point::ZERO, "Hi", style))));
let mut a = Node::group(NodeId(1), vec![Arc::new(text)]);
apply(&mut a, &[SymbolOverride { path: vec![0], stroke: Some(red.clone()), ..Default::default() }]);
let Some(NodeKind::Text(t)) = part(&a, &[0]).map(|n| &n.kind) else { panic!("type") };
assert!(t.runs.iter().all(|r| r.style.stroke == red && r.style.stroke_width == 1.0), "the stroke draws at 1 pt");
// A path whose stroke has neither paint nor weight gets 1 pt too.
let mut ap = Appearance::default_art();
if let Some(s) = ap.stroke_mut() {
(s.paint, s.width) = (Paint::None, 0.0);
}
let path = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), ap);
let mut a = Node::group(NodeId(1), vec![Arc::new(path)]);
apply(&mut a, &[SymbolOverride { path: vec![0], stroke: Some(red.clone()), ..Default::default() }]);
assert_eq!(part(&a, &[0]).unwrap().appearance.stroke_width(), 1.0);
}
#[test]
fn a_path_deeper_than_the_cap_does_not_read() {
let deep = format!("{{\"path\":{:?}}}", vec![0; MAX_PATH_DEPTH + 1]);
+28 -4
View File
@@ -8,6 +8,7 @@ use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, Li
mod area;
mod char_style;
mod composite;
mod object;
mod para_style;
mod runs;
@@ -17,12 +18,19 @@ mod wrap;
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
use char_style::yes;
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, ScriptMetrics};
pub use composite::{
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart,
CompositeParts,
};
pub use para_style::{
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, LeadingModel, Mojikumi, ParaDirection,
ParaStyle, SingleWordJustify,
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, KinsokuShoriType, LeadingModel,
Mojikumi, ParaDirection, ParaStyle, SingleWordJustify,
};
pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef, TypeAntiAlias};
pub use tabs_lists::{
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign,
TabStop,
};
pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef};
pub use tabs_lists::{Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, NumberStyle, ParaList, TabAlign, TabStop};
pub use wrap::{resolve_wrap, wrap_work};
/// A text object. `runs` split into paragraphs at `\n`.
@@ -78,6 +86,11 @@ pub struct TextObject {
/// Off for new type and for documents from before it, and saved only when on.
#[serde(default, rename = "opticalMarginAlignment", skip_serializing_if = "crate::skip::is_default")]
pub optical_margin: bool,
/// Character panel › Anti-aliasing Method: how the type's edges are drawn as pixels. Each
/// frame of a thread keeps its own method. Sharp for new type and for documents from before it,
/// and saved only when it is another method.
#[serde(default, rename = "antiAlias", skip_serializing_if = "crate::skip::is_default")]
pub anti_alias: TypeAntiAlias,
/// Character panel menu › System Layout, copied from the document: when on, each character
/// that takes space advances by a whole number of points. Off by default, and saved only when
/// on. The document setting is [`crate::DocSetup::system_layout`].
@@ -96,6 +109,11 @@ pub struct TextObject {
/// file saves the count only when it is not 0.
#[serde(default, rename = "listCount", skip_serializing_if = "crate::skip::is_default")]
pub list_count: u32,
/// Threaded text: as [`Self::list_count`], the counts the earlier frames carry into this frame
/// at list levels 2 on, level 2 first ([`ListCounts::from_parts`]). Empty when they are all 0,
/// and the file saves them only when not empty. A file's longer list opens with the first 8.
#[serde(default, rename = "listLevelCounts", skip_serializing_if = "Vec::is_empty", deserialize_with = "tabs_lists::read_level_counts")]
pub list_level_counts: Vec<u32>,
/// Cached layout bounds in text space, filled in by the layout engine (not serialized).
#[serde(skip)]
pub cached_bounds: Option<Rect>,
@@ -103,6 +121,12 @@ pub struct TextObject {
/// vertical column's centre line), filled in with `cached_bounds` (not serialized).
#[serde(skip)]
pub cached_baselines: Vec<(Point, Point)>,
/// Cached ink of the glyphs in text space, underline and strikethrough bars included
/// (`vectorcraft_effects::preview::laid_out_ink`, `None` when nothing draws),
/// with the `cached_bounds` it was measured with: filled in with `cached_bounds` by the engine's
/// text edits, and stale once `cached_bounds` differs ([`Self::ink`]). Not serialized.
#[serde(skip)]
pub cached_ink: Option<(Rect, Option<Rect>)>,
}
/// Conversion from stored character attributes to document-space type controls.
+13 -4
View File
@@ -101,15 +101,24 @@ impl PathEffect {
}
}
/// Type on a Path Options › Align to Path: which height of the type runs along the path.
/// Type on a Path Options › Align to Path: which height of the type runs along the path. Each
/// character is measured by its own font, size and vertical scale, and in vertical type by its own
/// size and horizontal scale. An inline graphic moves as a character of its run would, by its
/// run's vertical scale in vertical type too. These distances are VectorCraft's own values.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum PathAlign {
/// The font's top edge: the type hangs below the path.
/// The top of the font's em box: the type hangs below the path. The em box is the font's
/// ideographic em box (from its `BASE` table, its typographic or `hhea` box, or its
/// ideographs), else an em box centered on the cap height, else a box whose top is 0.88 em
/// above the baseline. In vertical type the characters move half an em.
Ascender,
/// The font's bottom edge: the type stands above the path.
/// The bottom of the font's bounding box, else the font's descent: the type stands above the
/// path. In vertical type the characters move half an em the other way.
Descender,
/// Halfway between the ascender and the descender.
/// A line at half the height of the top of the font's H above the baseline, else at half its
/// cap height, else at the middle of its em box. In vertical type the characters stay on the
/// path.
Center,
/// The baseline (the default).
#[default]
+344
View File
@@ -0,0 +1,344 @@
//! Type › Composite Fonts…: a font made of other fonts, one for each class of character (the
//! Kanji font is the base; kana, punctuation, symbols, Roman letters and numerals each take a font
//! of their own, sized, raised and scaled against it). Type set in a composite font names it as its
//! family; the layout sets each character in its class's font.
//!
//! Behavior reference (public documentation):
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>.
//! Which characters fall in which class, the ranges and the defaults are VectorCraft's own.
use serde::{Deserialize, Serialize};
/// A class of characters a composite font gives a font of its own.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CharClass {
/// The base font: ideographs, full-width letters and digits, and every character no other
/// class takes.
Kanji,
/// Hiragana and katakana, full-width and half-width.
Kana,
/// East Asian and full-width punctuation, and typographic quotes and dashes.
Punctuation,
/// Arrows, math, shapes, enclosed and other symbols.
Symbols,
/// Half-width Roman letters, their punctuation and spaces.
Roman,
/// The half-width digits 0 to 9.
Numerals,
}
impl CharClass {
/// Every class, in the order the Composite Fonts dialog lists them.
pub const ALL: [CharClass; 6] = [Self::Kanji, Self::Kana, Self::Punctuation, Self::Symbols, Self::Roman, Self::Numerals];
/// The name commands and files use (`kanji`, `kana`, …).
pub fn key(self) -> &'static str {
match self {
Self::Kanji => "kanji",
Self::Kana => "kana",
Self::Punctuation => "punctuation",
Self::Symbols => "symbols",
Self::Roman => "roman",
Self::Numerals => "numerals",
}
}
/// The class named `key` ([`Self::key`], any case).
pub fn named(key: &str) -> Option<Self> {
Self::ALL.into_iter().find(|c| c.key().eq_ignore_ascii_case(key))
}
/// Whether the class's characters can be scaled across and up (Kana, Roman and Numerals).
pub fn scales(self) -> bool {
matches!(self, Self::Kana | Self::Roman | Self::Numerals)
}
/// The class of character `c`.
pub fn of(c: char) -> Self {
let u = c as u32;
match u {
0x30..=0x39 => Self::Numerals,
// Basic Latin, Latin-1, Latin Extended, IPA, spacing and combining marks, and Latin
// Extended Additional.
0x00..=0x036F | 0x1E00..=0x1EFF => Self::Roman,
// The other Latin blocks: combining marks extended, phonetic extensions and their
// supplement, combining marks supplement, Latin Extended-C, -D, -E, -F and -G, and the
// Latin ligatures of the alphabetic presentation forms.
0x1AB0..=0x1AFF
| 0x1D00..=0x1DFF
| 0x2C60..=0x2C7F
| 0xA720..=0xA7FF
| 0xAB30..=0xAB6F
| 0xFB00..=0xFB06
| 0x10780..=0x107BF
| 0x1DF00..=0x1DFFF => Self::Roman,
// ・ and ゠ sit in the katakana block but are punctuation.
0x30A0 | 0x30FB => Self::Punctuation,
// Hiragana, katakana, katakana phonetic extensions, half-width katakana (with its
// prolonged sound and voicing marks) and the kana supplements.
0x3041..=0x309F | 0x30A1..=0x30FF | 0x31F0..=0x31FF | 0xFF66..=0xFF9F | 0x1B000..=0x1B16F => Self::Kana,
// CJK symbols: 〄 〒 〓 〠 〶; ideographic space, 々 〆 〇 and the like stay with the base.
0x3004 | 0x3012 | 0x3013 | 0x3020 | 0x3036 => Self::Symbols,
0x3000 | 0x3005..=0x3007 | 0x3021..=0x302F | 0x3031..=0x3035 | 0x3038..=0x303C => Self::Kanji,
0x3001..=0x303F => Self::Punctuation,
// ※ is a symbol; the rest of General Punctuation (dashes, quotes, leaders) punctuation.
0x203B => Self::Symbols,
0x2010..=0x205E => Self::Punctuation,
// Letterlike symbols, number forms, arrows, math, technical, enclosed alphanumerics, box
// drawing, shapes, miscellaneous symbols and dingbats; enclosed CJK and CJK
// compatibility; full-width signs.
0x2100..=0x2BFF | 0x3200..=0x33FF | 0xFFE0..=0xFFEE => Self::Symbols,
// Full-width forms of the ASCII signs.
0xFF03..=0xFF06 | 0xFF0A | 0xFF0B | 0xFF1C..=0xFF1E | 0xFF20 | 0xFF3C | 0xFF3E | 0xFF5C | 0xFF5E => Self::Symbols,
// Full-width forms of the other ASCII punctuation, and the half-width CJK punctuation.
0xFF01..=0xFF0F | 0xFF1A..=0xFF1F | 0xFF3B..=0xFF40 | 0xFF5B..=0xFF65 => Self::Punctuation,
_ => Self::Kanji,
}
}
}
/// The font a composite font sets one class of characters in, and how.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CompositePart {
/// The font family and style.
pub font: String,
#[serde(default = "regular")]
pub style: String,
/// The size, in percent of the type's size.
#[serde(default = "hundred")]
pub size: f64,
/// How far the characters are raised from the baseline, in percent of the type's size
/// (negative lowers them).
#[serde(default)]
pub baseline: f64,
/// Horizontal and vertical scale, in percent (Kana, Roman and Numerals only).
#[serde(default = "hundred")]
pub h_scale: f64,
#[serde(default = "hundred")]
pub v_scale: f64,
/// Kana only: the characters are scaled from the center of the em box rather than from the
/// baseline.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub scale_at_center: bool,
}
fn hundred() -> f64 {
100.0
}
fn regular() -> String {
"Regular".into()
}
impl CompositePart {
/// The part a new composite font gives every class: `font` in `style` at full size, on the
/// baseline, unscaled.
pub fn new(font: impl Into<String>, style: impl Into<String>) -> Self {
Self { font: font.into(), style: style.into(), size: 100.0, baseline: 0.0, h_scale: 100.0, v_scale: 100.0, scale_at_center: false }
}
}
/// The six parts of a composite font, one per [`CharClass`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CompositeParts {
pub kanji: CompositePart,
pub kana: CompositePart,
pub punctuation: CompositePart,
pub symbols: CompositePart,
pub roman: CompositePart,
pub numerals: CompositePart,
}
impl CompositeParts {
/// Every class set in `part`.
pub fn all(part: CompositePart) -> Self {
Self { kanji: part.clone(), kana: part.clone(), punctuation: part.clone(), symbols: part.clone(), roman: part.clone(), numerals: part }
}
pub fn get(&self, class: CharClass) -> &CompositePart {
match class {
CharClass::Kanji => &self.kanji,
CharClass::Kana => &self.kana,
CharClass::Punctuation => &self.punctuation,
CharClass::Symbols => &self.symbols,
CharClass::Roman => &self.roman,
CharClass::Numerals => &self.numerals,
}
}
pub fn get_mut(&mut self, class: CharClass) -> &mut CompositePart {
match class {
CharClass::Kanji => &mut self.kanji,
CharClass::Kana => &mut self.kana,
CharClass::Punctuation => &mut self.punctuation,
CharClass::Symbols => &mut self.symbols,
CharClass::Roman => &mut self.roman,
CharClass::Numerals => &mut self.numerals,
}
}
}
/// A composite font (Type › Composite Fonts…), saved with the document. Its name is the family
/// that type set in it names.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CompositeFont {
pub name: String,
pub parts: CompositeParts,
}
/// The size a part can take, in percent of the type's size.
pub const COMPOSITE_SIZE: std::ops::RangeInclusive<f64> = 10.0..=400.0;
/// How far a part can raise or lower its characters, in percent of the type's size.
pub const COMPOSITE_BASELINE: std::ops::RangeInclusive<f64> = -100.0..=100.0;
/// The horizontal and vertical scale a part can take, in percent.
pub const COMPOSITE_SCALE: std::ops::RangeInclusive<f64> = 10.0..=400.0;
/// The longest composite font name, in characters.
pub const COMPOSITE_NAME_MAX: usize = 255;
/// The most composite fonts a document or a file keeps.
pub const COMPOSITE_FONTS_MAX: usize = 256;
impl CompositeFont {
/// A composite font named `name` setting every class in `font` and `style`.
pub fn new(name: impl Into<String>, font: impl Into<String>, style: impl Into<String>) -> Self {
Self { name: name.into(), parts: CompositeParts::all(CompositePart::new(font, style)) }
}
/// Do `a` and `b` name the same composite font: equal in any case?
pub fn same_name(a: &str, b: &str) -> bool {
a == b || a.to_lowercase() == b.to_lowercase()
}
/// The font of `fonts` (a document's composite fonts) named `name`, in any case.
pub fn named<'a>(fonts: &'a [CompositeFont], name: &str) -> Option<&'a CompositeFont> {
fonts.iter().find(|f| Self::same_name(&f.name, name))
}
/// `name` trimmed, when it can name a composite font: not empty, at most
/// [`COMPOSITE_NAME_MAX`] characters and without control characters.
pub fn clean_name(name: &str) -> Option<String> {
let name = name.trim();
let ok = !name.is_empty() && name.chars().count() <= COMPOSITE_NAME_MAX && !name.chars().any(char::is_control);
ok.then(|| name.to_string())
}
/// Why this composite font can't be used, if it can't: a name [`Self::clean_name`] refuses, a
/// part without a font, a value out of its range, or a scale or Scale at Center on a class
/// that has none.
pub fn check(&self) -> Result<(), String> {
if Self::clean_name(&self.name).as_deref() != Some(self.name.as_str()) {
return Err(format!("`{}` can't name a composite font", self.name));
}
for class in CharClass::ALL {
let p = self.parts.get(class);
let k = class.key();
if p.font.trim().is_empty() {
return Err(format!("{k}: give a font"));
}
let within = |v: f64, r: &std::ops::RangeInclusive<f64>| v.is_finite() && r.contains(&v);
if !within(p.size, &COMPOSITE_SIZE) {
return Err(format!("{k}: size must be {} to {}%", COMPOSITE_SIZE.start(), COMPOSITE_SIZE.end()));
}
if !within(p.baseline, &COMPOSITE_BASELINE) {
return Err(format!("{k}: baseline must be {} to {}%", COMPOSITE_BASELINE.start(), COMPOSITE_BASELINE.end()));
}
for v in [p.h_scale, p.v_scale] {
if !within(v, &COMPOSITE_SCALE) {
return Err(format!("{k}: scale must be {} to {}%", COMPOSITE_SCALE.start(), COMPOSITE_SCALE.end()));
}
if v != 100.0 && !class.scales() {
return Err(format!("{k}: only kana, roman and numerals can be scaled"));
}
}
if p.scale_at_center && class != CharClass::Kana {
return Err(format!("{k}: only kana can be scaled at the center"));
}
}
Ok(())
}
/// `fonts` without the ones that can't be used: those [`Self::check`] refuses, a later font
/// sharing an earlier one's name (in any case), a part set in one of the fonts, and those past
/// [`COMPOSITE_FONTS_MAX`]. `None` when every font can be used.
pub fn usable(fonts: &[CompositeFont]) -> Option<Vec<CompositeFont>> {
let mut names = std::collections::HashSet::new();
let mut kept: Vec<CompositeFont> =
fonts.iter().filter(|f| f.check().is_ok() && names.insert(f.name.to_lowercase())).take(COMPOSITE_FONTS_MAX).cloned().collect();
kept.retain(|f| CharClass::ALL.iter().all(|&c| !names.contains(&f.parts.get(c).font.to_lowercase())));
(kept.len() != fonts.len()).then_some(kept)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Each class takes its characters: digits and Latin letters are half-width numerals and
/// Roman, kana both widths, and the punctuation, symbols and full-width forms their own.
#[test]
fn characters_fall_in_their_classes() {
for (s, class) in [
("漢字国一龍〇々", CharClass::Kanji),
("AZa09 ", CharClass::Kanji),
("あをアンーアンー", CharClass::Kana),
("、。「」『』【】〜・!?():", CharClass::Punctuation),
("“”‘’—…", CharClass::Punctuation),
("※→★○〒+=$%①㈱", CharClass::Symbols),
("AZaz é!? ()", CharClass::Roman),
// Latin Extended-C, -D and -E, phonetic extensions and a ligature.
("\u{2C60}\u{A7A0}\u{AB30}\u{1D00}\u{FB01}", CharClass::Roman),
("0123456789", CharClass::Numerals),
] {
for c in s.chars() {
assert_eq!(CharClass::of(c), class, "{c:?} (U+{:04X})", c as u32);
}
}
}
/// A composite font is read and written by its fields' names, and a part's omitted values
/// take the defaults.
#[test]
fn composite_fonts_read_back_with_defaults() {
let mut f = CompositeFont::new("Mixed", "Source Sans 3", "Regular");
f.parts.kana.v_scale = 90.0;
f.parts.kana.scale_at_center = true;
f.parts.roman.baseline = -5.0;
let json = serde_json::to_value(&f).unwrap();
assert_eq!(json["parts"]["kana"]["vScale"], 90.0);
assert_eq!(json["parts"]["kana"]["scaleAtCenter"], true);
assert!(json["parts"]["roman"].get("scaleAtCenter").is_none());
assert_eq!(serde_json::from_value::<CompositeFont>(json).unwrap(), f);
let part: CompositePart = serde_json::from_value(serde_json::json!({"font": "Inter"})).unwrap();
assert_eq!(part, CompositePart::new("Inter", "Regular"));
}
/// Names are trimmed; values out of their ranges, and scales on classes that don't scale, are
/// refused.
#[test]
fn composite_fonts_check_their_values() {
assert_eq!(CompositeFont::clean_name(" Mixed ").as_deref(), Some("Mixed"));
for bad in ["", " ", "a\tb", &"x".repeat(COMPOSITE_NAME_MAX + 1)] {
assert_eq!(CompositeFont::clean_name(bad), None, "{bad:?}");
}
let ok = CompositeFont::new("Mixed", "Inter", "Regular");
assert_eq!(ok.check(), Ok(()));
let with = |f: fn(&mut CompositeParts)| {
let mut c = ok.clone();
f(&mut c.parts);
c.check()
};
assert!(with(|p| p.roman.size = 9.0).is_err());
assert!(with(|p| p.roman.size = f64::NAN).is_err());
assert!(with(|p| p.kana.baseline = 101.0).is_err());
assert!(with(|p| p.kana.h_scale = 401.0).is_err());
assert!(with(|p| p.kanji.v_scale = 90.0).is_err());
assert!(with(|p| p.symbols.h_scale = 90.0).is_err());
assert!(with(|p| p.roman.scale_at_center = true).is_err());
assert!(with(|p| p.numerals.font = " ".into()).is_err());
assert_eq!(with(|p| p.kana.scale_at_center = true), Ok(()));
assert_eq!(with(|p| p.numerals.h_scale = 50.0), Ok(()));
let mut spaced = ok.clone();
spaced.name = " Mixed".into();
assert!(spaced.check().is_err());
}
}
+39 -2
View File
@@ -1,8 +1,8 @@
use super::area::{AreaOptions, PathAlign, PathEffect};
use super::char_style::CharStyle;
use super::para_style::ParaStyle;
use super::runs::{RubySpan, TextKind, TextRun, move_anchors, reverse_from_end};
use super::tabs_lists::ParaList;
use super::runs::{RubySpan, TextKind, TextRun, TypeAntiAlias, move_anchors, reverse_from_end};
use super::tabs_lists::{ListCounts, ParaList};
use super::{Affine, PathData, Point, Rect, TextObject, TextStyleScale, Vec2};
impl TextObject {
@@ -71,6 +71,7 @@ impl TextObject {
self.xf *= Affine::scale_non_uniform(1.0 / sx, 1.0 / sy);
self.cached_bounds = None;
self.cached_baselines.clear();
self.cached_ink = None;
true
}
@@ -90,13 +91,25 @@ impl TextObject {
path_spacing: 0.0,
wrap: Vec::new(),
optical_margin: false,
anti_alias: TypeAntiAlias::Sharp,
system_layout: false,
fractional_widths: true,
list_count: 0,
list_level_counts: Vec::new(),
cached_bounds: None,
cached_baselines: Vec::new(),
cached_ink: None,
}
}
/// The list counts the story's earlier frames carry into this frame at each level
/// ([`Self::list_count`] and [`Self::list_level_counts`]).
pub fn list_counts(&self) -> ListCounts {
ListCounts::from_parts(self.list_count, &self.list_level_counts)
}
/// Set the list counts the story's earlier frames carry into this frame ([`Self::list_counts`]).
pub fn set_list_counts(&mut self, counts: ListCounts) {
(self.list_count, self.list_level_counts) = counts.parts();
}
pub fn plain_text(&self) -> String {
self.runs.iter().map(|r| r.text.as_str()).collect()
}
@@ -277,6 +290,12 @@ impl TextObject {
TextKind::Point => Some(self.xf.transform_rect_bbox(self.cached_bounds.unwrap_or_else(|| self.estimate_bounds()))),
}
}
/// The cached ink of the glyphs in text space ([`Self::cached_ink`]): `Some(None)` when nothing
/// draws, and `None` when it was not measured with the current `cached_bounds`.
pub fn ink(&self) -> Option<Option<Rect>> {
let (bounds, ink) = self.cached_ink?;
(self.cached_bounds == Some(bounds)).then_some(ink)
}
/// How far the characters' strokes paint past their glyphs, in document space: they scale
/// with the type.
pub fn char_stroke_outset(&self) -> f64 {
@@ -348,6 +367,24 @@ impl TextObject {
pub fn move_path_anchors(&mut self, refs: &[(usize, usize)], d: Vec2) -> bool {
matches!(self.kind, TextKind::OnPath { .. }) && self.reshape_local(|path, to_text| move_anchors(path, to_text, refs, d))
}
/// Move the out (`out`) or in direction handle of anchor `ai` of subpath `si` of type on a
/// path's path to `pos` in document space, as a path's anchor takes it
/// ([`vectorcraft_geom::Anchor::set_handle`]; `independent`: that side only, the anchor a
/// corner): a Direct Selection drag of a handle (#3565). The handle is set in document space,
/// so a smooth anchor keeps its other handle's length as drawn; the brackets keep their
/// fractions of the path. False, changing nothing, for other type, when the anchor doesn't
/// exist, a degenerate `xf` or a path that would not be finite.
pub fn set_path_handle(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool) -> bool {
let xf = self.xf;
matches!(self.kind, TextKind::OnPath { .. })
&& self.reshape_local(|path, to_text| {
let Some(a) = path.anchor_mut(si, ai) else { return false };
let mut drawn = a.transform(xf);
drawn.set_handle(out, pos, independent);
*a = drawn.transform(to_text);
true
})
}
/// Edit a copy of the area frame with `f` (given the document → text space map) and keep it
/// when `f` succeeds and the result is finite.
fn reshape_area(&mut self, f: impl FnOnce(&mut PathData, Affine) -> bool) -> bool {
+36 -1
View File
@@ -228,11 +228,15 @@ pub struct ParaStyle {
pub leading_model: LeadingModel,
/// Hanging punctuation (Paragraph panel menu › Burasagari): a comma or full stop ending a line
/// may stand outside the frame. New type takes [`Burasagari::Standard`]; documents from before
/// it and imported text keep [`Burasagari::None`].
/// it and imported text keep [`Burasagari::None`], except legacy `.ai` type with binding
/// punctuation on, which opens with [`Burasagari::Forced`].
pub burasagari: Burasagari,
/// Kinsoku (Paragraph panel › Kinsoku Set): which Japanese characters may not start or end a
/// line.
pub kinsoku: Kinsoku,
/// Kinsoku Shori Type (Paragraph panel menu): how a line keeps those characters off its start
/// and end, by pushing them in onto the line or out to the next one. No effect without kinsoku.
pub kinsoku_type: KinsokuShoriType,
/// Roman Hanging Punctuation (Paragraph panel menu): quotation marks, hyphens, full stops and
/// commas starting or ending a line hang outside the margin, and asterisks, tildes, ellipses,
/// dashes, colons and semicolons hang by half. East Asian punctuation hangs by burasagari.
@@ -257,6 +261,12 @@ impl ParaStyle {
}
}
/// The left indent the layout sets the paragraph at: its left indent, and for a paragraph in a
/// list at a level past the first, [`ParaList::level_indent`] more.
pub fn laid_out_left_indent(&self) -> f64 {
self.left_indent + self.list.map_or(0.0, |l| l.level_indent())
}
/// The leading of characters styled `st` in this paragraph, as the layout sets it: their own
/// leading, or for Auto leading the paragraph's Justification › Auto Leading share of their
/// size (exactly [`CharStyle::effective_leading`] at the default 120%, or when the share is
@@ -315,6 +325,8 @@ struct ParaStyleFile {
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
kinsoku: Kinsoku,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
kinsoku_type: KinsokuShoriType,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
roman_hanging: bool,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
kashida: Kashida,
@@ -346,6 +358,7 @@ impl From<ParaStyle> for ParaStyleFile {
leading_model,
burasagari,
kinsoku,
kinsoku_type,
roman_hanging,
kashida,
..
@@ -370,6 +383,7 @@ impl From<ParaStyle> for ParaStyleFile {
leading_model,
burasagari,
kinsoku,
kinsoku_type,
roman_hanging,
kashida,
}
@@ -398,6 +412,7 @@ impl From<ParaStyleFile> for ParaStyle {
leading_model,
burasagari,
kinsoku,
kinsoku_type,
roman_hanging,
kashida,
..
@@ -421,6 +436,7 @@ impl From<ParaStyleFile> for ParaStyle {
leading_model,
burasagari,
kinsoku,
kinsoku_type,
roman_hanging,
kashida,
}
@@ -485,6 +501,25 @@ pub enum Kinsoku {
Soft,
}
/// How a line keeps the characters [`Kinsoku`] rules out of its start and end (Kinsoku Shori
/// Type). Pushing in sets the characters that would start the next line (or that an opening
/// bracket ending this line would pull with it) on this line, with the line's gaps next to CJK
/// characters closed to make room, each by the same share of the em of the character before it
/// and by at most a tenth of that em; pushing out moves the character before them to the next
/// line.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum KinsokuShoriType {
/// Push in when the line can close up enough, else push out.
PushInFirst,
/// Push out, unless that would leave the line more than an em short (of the character before
/// the break): then push in when the line can close up enough.
PushOutFirst,
/// Always push out; never push in.
#[default]
PushOutOnly,
}
/// Hanging punctuation (burasagari): an East Asian comma or full stop ending a line (、。,.、。)
/// stands outside the line's measure, in the space its punctuation spacing gives it (half width
/// with Line-end Punctuation Half Width). Closing brackets and Latin punctuation don't hang. Shown
Loaded 100 of 1007 files, more files were not shown because too many files have changed in this diff. Show more