Merge upstream/main into perf/web-wasm-simd128-2786

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
vangel76andClaude Sonnet 5.5 committed 2026-11-04 00:18:11 +01:00
commit 7cdd83d3ca
391 files changed
+21293 -1707

No files matched your search

+17 -17
View File
@@ -358,20 +358,20 @@ The shared PDF backend keeps the existing standard-font and CMap features. These
| Crate / file | Author | Source | Licence | SHA-256 | Use |
| --- | --- | --- | --- | --- | --- |
| `hayro-interpret 0.7.0 / assets/FoxitDingbats.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitDingbats.pfb | BSD-3-Clause | `845c752392b6c914fb989c75a08b7792b88f542d2499042ef2889f8c814a16ed` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixed.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixed.pfb | BSD-3-Clause | `b6c8fe53f134b8b6d4578cd2d544df4cee9624c4efa8d51a560fb40ea296101b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixedBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixedBold.pfb | BSD-3-Clause | `f1b7159702973f54fc86254ea38bcf3712b2a736eb3a0995751e9f4bb45ad603` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixedBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfb | BSD-3-Clause | `8a000945843bd31add06aee63bf9fd41b7578b4f3242a4b7cd46349ad9d24d4d` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixedItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixedItalic.pfb | BSD-3-Clause | `5007faf8320fa1fcc08b8894b356ad976f60b992ba29ee5272578bbdebaf3876` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSans.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSans.pfb | BSD-3-Clause | `a02339e95d20db14cbdfc1c6baf359cd36a091d5434925c3a4040f60e1a1af9e` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSansBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSansBold.pfb | BSD-3-Clause | `7bdfa36de1d5757dcfaf8b8a4be95c6e41c40fa70dbed9d78bf979a7b9959054` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSansBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfb | BSD-3-Clause | `555ce45924338e2e4b32821910221ce85da691fd59a9723c4c971a7c5627fc8b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSansItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSansItalic.pfb | BSD-3-Clause | `7751cbefeda351708dae8c4a88db043411bc39ab2ae2097685da845d4d16f307` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerif.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerif.pfb | BSD-3-Clause | `4f57d2b9d884af8f907bf22df6019b52d86cbf6214fdbd02b1ae05472a543f35` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerifBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerifBold.pfb | BSD-3-Clause | `0bdf4b04e964139818d51eda03d566ba999fc3ba2421b1c6c51f9dc969022e80` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerifBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfb | BSD-3-Clause | `a406cac82583bf98175cb62c87ed5e95c45fbb34eece63a10b0a13e793cb2e10` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerifItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb | BSD-3-Clause | `610ae0687198045c4db5d1a6650fd5e92536631706382eb8b72e38df578d0ae9` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSymbol.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSymbol.pfb | BSD-3-Clause | `47967d055530e7357088a08403115425643ec2cdfd6201ba8af0fbd7116c1539` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc | CC0-1.0 | `73e1ba37d2bad5bab2a964f40a9eed96209666efc067c3322626214bbef234a0` | Default CMYK colour conversion (pinned hayro-interpret) |
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-cmap/assets/cmaps.brotli | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged |
| `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged |
| `hayro-interpret 0.7.0 / assets/FoxitDingbats.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitDingbats.pfb | BSD-3-Clause | `845c752392b6c914fb989c75a08b7792b88f542d2499042ef2889f8c814a16ed` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixed.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitFixed.pfb | BSD-3-Clause | `b6c8fe53f134b8b6d4578cd2d544df4cee9624c4efa8d51a560fb40ea296101b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixedBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitFixedBold.pfb | BSD-3-Clause | `f1b7159702973f54fc86254ea38bcf3712b2a736eb3a0995751e9f4bb45ad603` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixedBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfb | BSD-3-Clause | `8a000945843bd31add06aee63bf9fd41b7578b4f3242a4b7cd46349ad9d24d4d` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixedItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitFixedItalic.pfb | BSD-3-Clause | `5007faf8320fa1fcc08b8894b356ad976f60b992ba29ee5272578bbdebaf3876` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSans.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSans.pfb | BSD-3-Clause | `a02339e95d20db14cbdfc1c6baf359cd36a091d5434925c3a4040f60e1a1af9e` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSansBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSansBold.pfb | BSD-3-Clause | `7bdfa36de1d5757dcfaf8b8a4be95c6e41c40fa70dbed9d78bf979a7b9959054` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSansBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfb | BSD-3-Clause | `555ce45924338e2e4b32821910221ce85da691fd59a9723c4c971a7c5627fc8b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSansItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSansItalic.pfb | BSD-3-Clause | `7751cbefeda351708dae8c4a88db043411bc39ab2ae2097685da845d4d16f307` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerif.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSerif.pfb | BSD-3-Clause | `4f57d2b9d884af8f907bf22df6019b52d86cbf6214fdbd02b1ae05472a543f35` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerifBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSerifBold.pfb | BSD-3-Clause | `0bdf4b04e964139818d51eda03d566ba999fc3ba2421b1c6c51f9dc969022e80` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerifBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfb | BSD-3-Clause | `a406cac82583bf98175cb62c87ed5e95c45fbb34eece63a10b0a13e793cb2e10` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerifItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb | BSD-3-Clause | `610ae0687198045c4db5d1a6650fd5e92536631706382eb8b72e38df578d0ae9` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSymbol.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSymbol.pfb | BSD-3-Clause | `47967d055530e7357088a08403115425643ec2cdfd6201ba8af0fbd7116c1539` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc | CC0-1.0 | `73e1ba37d2bad5bab2a964f40a9eed96209666efc067c3322626214bbef234a0` | Default CMYK colour conversion (pinned hayro-interpret) |
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-cmap/assets/cmaps.brotli | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged |
| `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged |
Generated
+53 -51
View File
@@ -970,17 +970,17 @@ dependencies = [
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1003,7 +1003,7 @@ dependencies = [
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
dependencies = [
"egui",
"serde",
@@ -1013,7 +1013,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
dependencies = [
"hayro-interpret",
"hayro-syntax",
@@ -1024,9 +1024,10 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
dependencies = [
"craft-winprint-gdi",
"log",
"miniz_oxide 0.9.1",
"roxmltree 0.21.2",
"tempfile",
@@ -1037,7 +1038,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1095,7 +1096,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
dependencies = [
"egui",
"objc2 0.6.5",
@@ -2205,7 +2206,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
dependencies = [
"brotli",
"hayro-postscript",
@@ -2214,7 +2215,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -2232,7 +2233,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -2250,12 +2251,12 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -2863,7 +2864,7 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=fb08be5fa19eee8d37e624397fcdc96df6035e92#fb08be5fa19eee8d37e624397fcdc96df6035e92"
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
dependencies = [
"base64 0.22.1",
"bumpalo",
@@ -6072,7 +6073,7 @@ dependencies = [
[[package]]
name = "vectorcraft"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"arboard",
"block2 0.6.2",
@@ -6117,7 +6118,7 @@ dependencies = [
[[package]]
name = "vectorcraft-affinity"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"crc32fast",
"flate2",
@@ -6128,7 +6129,7 @@ dependencies = [
[[package]]
name = "vectorcraft-brush"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"kurbo 0.13.1",
"serde",
@@ -6140,7 +6141,7 @@ dependencies = [
[[package]]
name = "vectorcraft-cad"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6156,7 +6157,7 @@ dependencies = [
[[package]]
name = "vectorcraft-cli"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"log",
"objc2-core-foundation",
@@ -6178,7 +6179,7 @@ dependencies = [
[[package]]
name = "vectorcraft-color"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"kurbo 0.13.1",
"moxcms",
@@ -6190,7 +6191,7 @@ dependencies = [
[[package]]
name = "vectorcraft-doc"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"chrono",
"hayro-ccitt",
@@ -6209,7 +6210,7 @@ dependencies = [
[[package]]
name = "vectorcraft-effects"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6225,7 +6226,7 @@ dependencies = [
[[package]]
name = "vectorcraft-engine"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"cfb",
"chrono",
@@ -6267,7 +6268,7 @@ dependencies = [
[[package]]
name = "vectorcraft-eps"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"fax",
"flate2",
@@ -6291,7 +6292,7 @@ dependencies = [
[[package]]
name = "vectorcraft-format"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"craft-vectorcraft-format",
"flate2",
@@ -6307,7 +6308,7 @@ dependencies = [
[[package]]
name = "vectorcraft-geom"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"kurbo 0.13.1",
"proptest",
@@ -6319,7 +6320,7 @@ dependencies = [
[[package]]
name = "vectorcraft-mcp"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"image",
"log",
@@ -6338,7 +6339,7 @@ dependencies = [
[[package]]
name = "vectorcraft-metafile"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6352,7 +6353,7 @@ dependencies = [
[[package]]
name = "vectorcraft-pathops"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"kurbo 0.13.1",
"linesweeper",
@@ -6364,7 +6365,7 @@ dependencies = [
[[package]]
name = "vectorcraft-pdf"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"aes",
"chrono",
@@ -6396,7 +6397,7 @@ dependencies = [
[[package]]
name = "vectorcraft-plugins"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"serde",
"serde_json",
@@ -6410,7 +6411,7 @@ dependencies = [
[[package]]
name = "vectorcraft-render"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"flate2",
"gif 0.14.2",
@@ -6440,14 +6441,14 @@ dependencies = [
[[package]]
name = "vectorcraft-scriptcheck"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"proptest",
]
[[package]]
name = "vectorcraft-svg"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"craft-docpath",
"flate2",
@@ -6457,6 +6458,7 @@ dependencies = [
"resvg",
"serde",
"serde_json",
"simplecss",
"skrifa 0.47.0",
"svgtypes 0.16.1",
"thiserror 2.0.21",
@@ -6472,7 +6474,7 @@ dependencies = [
[[package]]
name = "vectorcraft-testkit"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"fax",
"image",
@@ -6490,7 +6492,7 @@ dependencies = [
[[package]]
name = "vectorcraft-text"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"harfrust 0.13.3",
"icu_segmenter",
@@ -6511,7 +6513,7 @@ dependencies = [
[[package]]
name = "vectorcraft-three-d"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"vectorcraft-geom",
"vectorcraft-pathops",
@@ -6519,7 +6521,7 @@ dependencies = [
[[package]]
name = "vectorcraft-tools"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6536,7 +6538,7 @@ dependencies = [
[[package]]
name = "vectorcraft-trace"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6548,7 +6550,7 @@ dependencies = [
[[package]]
name = "vectorcraft-ui-egui"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"bytemuck",
"craft-keymap",
@@ -6586,7 +6588,7 @@ dependencies = [
[[package]]
name = "vectorcraft-web"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"eframe",
"egui",
@@ -6753,12 +6755,12 @@ dependencies = [
[[package]]
name = "wasm-encoder"
version = "0.262.0"
version = "0.263.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a"
checksum = "0b883a26aea02eaabe2d2c3fba7eb039ef5cdcb5d5201ae5551e73d5e251a81f"
dependencies = [
"leb128fmt",
"wasmparser 0.262.0",
"wasmparser 0.263.0",
]
[[package]]
@@ -6813,9 +6815,9 @@ dependencies = [
[[package]]
name = "wasmparser"
version = "0.262.0"
version = "0.263.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b"
checksum = "4f5fa0a054ae153606df820eb0a84213e28cda41bbe04ba2628e71b6ba100fcb"
dependencies = [
"bitflags 2.13.2",
"indexmap",
@@ -6824,9 +6826,9 @@ dependencies = [
[[package]]
name = "wast"
version = "262.0.0"
version = "263.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30612a0c29249b5f185888a107e8a519d920226b7d07f9d351fd094e9f75eb23"
checksum = "69d90bcf581b501aa1c358bc5dc0faa979cd375796908860ebcb6d1d70b907c7"
dependencies = [
"bumpalo",
"leb128fmt",
@@ -6837,9 +6839,9 @@ dependencies = [
[[package]]
name = "wat"
version = "1.262.0"
version = "1.263.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e228027f2b07bbaf946980ebbe2437fca73be6f54c40c2a8d4f42f277075f8d1"
checksum = "bbc9c5aca783b3f1838be89f3f9937c528b90ec5faa6fb62d809726c16a7d8f7"
dependencies = [
"wast",
]
@@ -7717,7 +7719,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
[[package]]
name = "xtask"
version = "0.20.0"
version = "0.21.0"
dependencies = [
"serde_json",
]
+13 -15
View File
@@ -4,21 +4,21 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
[workspace.package]
version = "0.20.0"
version = "0.21.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
repository = "https://github.com/storytold/vectorcraft"
[workspace.dependencies]
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
# 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 = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", 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 = "14d5dbb50c317b8747a9cf9eb35ab8a22515f137" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
@@ -147,14 +147,12 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
# The PDF writer takes craft-libs#417 (CMYK, gray and spot colors keep their exact inks); the other
# craft-libs crates stay at 92d392cf. craft-pdf's sources are the same at both revisions.
krilla = { git = "https://github.com/storytold/craft-libs", rev = "fb08be5fa19eee8d37e624397fcdc96df6035e92" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
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" }
+2 -2
View File
@@ -72,10 +72,10 @@ Shared PDF backend
The patched hayro-interpret 0.7.0, hayro-syntax 0.7.2, hayro-jbig2 0.3.0, hayro-cmap 0.1.0
and hayro-postscript 0.1.0 are fetched from https://github.com/storytold/craft-libs at revision
92d392cff132eaf53e13afff77f38b5c11b73aa0. Their upstream project is
f8f8829cc7be65d466d687dae381d1ca60e31242. Their upstream project is
https://github.com/LaurenzV/hayro, licensed MIT OR Apache-2.0. The snapshot retains each
crate's upstream licence files. The patch ledger is at
https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/README.craft-reader.md.
https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/README.craft-reader.md.
Assets already bundled through Hayro's default features retain their licences:
- Foxit standard-14 substitutes: Copyright 2014 PDFium Authors. All rights reserved.
+7 -1
View File
@@ -1,5 +1,7 @@
# VectorCraft Roadmap
- 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.
@@ -9,7 +11,7 @@
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Color Effects add-on's Find Nearest Swatch; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (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
@@ -129,6 +131,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
## Progress log
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
- 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923).
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
@@ -137,6 +140,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged.
- 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `<name>_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged.
- 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged.
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged.
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
- 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged.
@@ -214,6 +218,8 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| Date | Change | Summary |
|---|---|---|
| 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. |
| 2026-11-02 | minor | Closed font-family fields accept wheel input for selected text in Character, Properties and Control (#5253); scores and estimates unchanged. |
| 2026-11-01 | minor | Progress log row for the Color Effects add-on's Find Nearest Swatch (#4923); headline numbers unchanged. |
| 2026-11-01 | minor | Progress log row for the Path Precision Tools add-on's Expand Dashes into Paths (#4922); headline numbers unchanged. |
| 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Randomize Opacity (#4925); headline numbers unchanged. |
+4
View File
@@ -157,6 +157,10 @@ fn copied_file(paths: Vec<PathBuf>, mimes: &[&'static str]) -> Option<Flavour> {
None if vectorcraft_engine::file_access::current().is_none() => {}
None => return None,
}
// A device or pipe may never end: only a regular file is read whole.
if !std::fs::metadata(&path).ok()?.is_file() {
return None;
}
let mut head = Vec::with_capacity(FILE_HEAD);
std::fs::File::open(&path).ok()?.take(FILE_HEAD as u64).read_to_end(&mut head).ok()?;
let mime = file_flavour(&path.to_string_lossy(), &head, mimes)?;
+297 -1
View File
@@ -151,6 +151,22 @@ fn reveal_command(path: &str) -> std::process::Command {
c
}
/// Read a whole file. A device or pipe may never end: only a regular file is read.
fn read_file(path: &str) -> Result<Vec<u8>, String> {
if !std::fs::metadata(path).map_err(|e| e.to_string())?.is_file() {
return Err(format!("{path}: not a file"));
}
std::fs::read(path).map_err(|e| e.to_string())
}
#[cfg(test)]
#[test]
fn read_file_refuses_what_is_not_a_regular_file() {
assert!(read_file(&std::env::temp_dir().to_string_lossy()).is_err());
#[cfg(unix)]
assert!(read_file("/dev/zero").is_err());
}
/// Write a file the safe way: a failed write keeps the old file ([`fileio::write_atomic`]).
fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> {
fileio::write_atomic(std::path::Path::new(path), bytes).map_err(|e| e.to_string())
@@ -277,7 +293,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
// Windows reads it from the pen's pointer messages (`windows_stylus`).
#[cfg(windows)]
stylus: Some(windows_stylus::start()),
read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))),
read: Some(Box::new(read_file)),
write: Some(Box::new(write_file)),
exists: Some(Box::new(|p: &str| std::path::Path::new(p).exists())),
// Background Save and Export write from a worker thread.
@@ -300,6 +316,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
reveal: Some(Box::new(reveal)),
// Links panel: Edit Original; Package: Show Package. Relink to Folder and Package pick folders.
open_file: Some(Box::new(open_file)),
// Edit Original of a raster image with Use System Defaults for Edit Original off (#5236).
open_in_photocraft: Some(Box::new(open_in_photocraft)),
pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())),
// Sample Color from Screen: the system's color sampler.
#[cfg(target_os = "macos")]
@@ -334,3 +352,281 @@ fn open_file(path: &str) -> Result<(), String> {
c.arg(path);
c.spawn().map(|_| ()).map_err(|e| format!("can't open {path}: {e}"))
}
/// Edit Original with Preferences › File Handling › Use System Defaults for Edit Original off
/// (#5236): open the raster image `path` in PhotoCraft, found only where it installs
/// ([`find_photocraft`]); `Ok(false)` when it isn't installed. PhotoCraft gets the path as its only
/// argument and is never started through a shell.
fn open_in_photocraft(path: &str) -> Result<bool, String> {
explorer_safe(path)?;
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(std::path::PathBuf::from);
let Some(app) = find_photocraft(home.as_deref(), std::env::var_os("PATH").as_deref()) else { return Ok(false) };
#[cfg(target_os = "macos")]
let mut c = {
let mut c = std::process::Command::new("open");
c.arg("-a").arg(&app).arg(path);
c
};
#[cfg(not(target_os = "macos"))]
let mut c = {
let mut c = std::process::Command::new(&app);
c.arg(path);
c
};
// macOS: `open` returns once Launch Services has the request, so a short wait reports an app
// it can't open (a folder named `.app` that isn't a bundle). The wait is capped so a stalled
// `open` never holds the window: past it, the launch is left to run. Elsewhere the editor
// itself runs: waiting would last until it closes.
#[cfg(target_os = "macos")]
{
const WAIT: std::time::Duration = std::time::Duration::from_secs(2);
let fail = |why: String| format!("can't open {path} in {}: {why}", app.display());
let mut child = c.stderr(std::process::Stdio::piped()).spawn().map_err(|e| fail(e.to_string()))?;
let started = std::time::Instant::now();
loop {
match child.try_wait() {
Ok(Some(status)) if status.success() => return Ok(true),
Ok(Some(status)) => {
let mut why = String::new();
if let Some(mut err) = child.stderr.take() {
// Best effort: without its message the exit status says why.
let _ = std::io::Read::read_to_string(&mut err, &mut why);
}
let why = why.trim().to_string();
return Err(fail(if why.is_empty() { status.to_string() } else { why }));
}
Ok(None) if started.elapsed() < WAIT => std::thread::sleep(std::time::Duration::from_millis(20)),
Ok(None) => {
// Reaped off the UI thread once it ends.
std::thread::spawn(move || {
let _ = child.wait();
});
return Ok(true);
}
Err(e) => return Err(fail(e.to_string())),
}
}
}
#[cfg(not(target_os = "macos"))]
c.spawn().map(|_| true).map_err(|e| format!("can't open {path} in {}: {e}", app.display()))
}
/// PhotoCraft where it is installed: the first of [`photocraft_candidates`] that is an application.
pub(crate) fn find_photocraft(home: Option<&std::path::Path>, path_var: Option<&std::ffi::OsStr>) -> Option<std::path::PathBuf> {
photocraft_candidates(home, path_var).into_iter().find(|p| check_app(p).is_ok())
}
/// Where PhotoCraft may be installed: the Applications folders on macOS; on Windows where its
/// installer puts it ([`windows_candidates`]); else a `photocraft` program on the `PATH`.
pub(crate) fn photocraft_candidates(home: Option<&std::path::Path>, path_var: Option<&std::ffi::OsStr>) -> Vec<std::path::PathBuf> {
if cfg!(target_os = "macos") {
let mut v = vec![std::path::PathBuf::from("/Applications/PhotoCraft.app")];
v.extend(home.map(|h| h.join("Applications/PhotoCraft.app")));
return v;
}
let name = if cfg!(windows) { "photocraft.exe" } else { "photocraft" };
let on_path = path_var.map(|p| std::env::split_paths(p).map(|dir| dir.join(name)).collect()).unwrap_or_default();
if cfg!(windows) {
let folders: Vec<std::path::PathBuf> = [
std::env::var_os("LOCALAPPDATA").map(|d| std::path::PathBuf::from(d).join("Programs")),
std::env::var_os("ProgramW6432").map(std::path::PathBuf::from),
std::env::var_os("ProgramFiles").map(std::path::PathBuf::from),
]
.into_iter()
.flatten()
.collect();
return windows_candidates(registered_photocraft(), &folders, on_path);
}
on_path
}
/// Windows: PhotoCraft's installer puts it in `ArtCraft\PhotoCraft` under a folder of
/// `program_folders` (for the current user `%LOCALAPPDATA%\Programs`, for everyone Program Files)
/// and registers its path under App Paths, which also covers a folder chosen in setup. So: the
/// `registered` paths first, then those folders, then `on_path`.
pub(crate) fn windows_candidates(
registered: Vec<std::path::PathBuf>,
program_folders: &[std::path::PathBuf],
on_path: Vec<std::path::PathBuf>,
) -> Vec<std::path::PathBuf> {
let mut v = registered;
for f in program_folders {
let p = f.join("ArtCraft").join("PhotoCraft").join("photocraft.exe");
if !v.contains(&p) {
v.push(p);
}
}
v.extend(on_path);
v
}
/// The paths PhotoCraft's installer registers under App Paths, for the current user and then for
/// everyone (`reg query`, so no extra dependency; a hidden console window).
#[cfg(windows)]
fn registered_photocraft() -> Vec<std::path::PathBuf> {
use std::os::windows::process::CommandExt as _;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
// reg.exe by its full path, so nothing named `reg` in the app's folder or on PATH runs instead.
let root = std::env::var_os("SystemRoot").map(std::path::PathBuf::from).unwrap_or_else(|| r"C:\Windows".into());
["HKCU", "HKLM"]
.into_iter()
.filter_map(|hive| {
let key = format!(r"{hive}\Software\Microsoft\Windows\CurrentVersion\App Paths\photocraft.exe");
let out = std::process::Command::new(root.join("System32").join("reg.exe"))
.args(["query", &key, "/ve"])
.creation_flags(CREATE_NO_WINDOW)
.output()
.ok()?;
registered_path(&String::from_utf8_lossy(&out.stdout))
})
.collect()
}
#[cfg(not(windows))]
fn registered_photocraft() -> Vec<std::path::PathBuf> {
Vec::new()
}
/// The path in `reg query … /ve` output like
/// ` (Default) REG_SZ C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe`.
#[cfg_attr(not(any(windows, test)), allow(dead_code))]
pub(crate) fn registered_path(text: &str) -> Option<std::path::PathBuf> {
text.lines().find_map(|l| l.split_once("REG_SZ")).map(|(_, v)| v.trim().trim_matches('"')).filter(|v| !v.is_empty()).map(std::path::PathBuf::from)
}
/// Is `app` an application Edit Original may start: an `.app` bundle on macOS, an `.exe` on
/// Windows, an executable file elsewhere? Anything else (a document, a folder, a script on
/// Windows) found where PhotoCraft installs is not taken for it.
pub(crate) fn check_app(app: &std::path::Path) -> Result<(), String> {
let ext = app.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
let ok = if cfg!(target_os = "macos") {
ext == "app" && app.is_dir()
} else if cfg!(windows) {
ext == "exe" && app.is_file()
} else {
executable_file(app)
};
if ok { Ok(()) } else { Err(format!("{} isn't an application Edit Original can open files in", app.display())) }
}
#[cfg(unix)]
fn executable_file(p: &std::path::Path) -> bool {
use std::os::unix::fs::PermissionsExt as _;
std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
}
#[cfg(not(unix))]
fn executable_file(p: &std::path::Path) -> bool {
p.is_file()
}
#[cfg(test)]
mod open_with_tests {
use super::{check_app, find_photocraft, photocraft_candidates, registered_path, windows_candidates};
/// A fresh, empty folder under the system's temporary folder.
fn scratch(name: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("vc-open-with-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
/// #5236: only an application counts as PhotoCraft, never a document, a folder or a missing
/// path.
#[test]
fn only_applications_are_started() {
let d = scratch("check");
let doc = d.join("notes.txt");
std::fs::write(&doc, "hi").unwrap();
assert!(check_app(&doc).is_err(), "a document");
assert!(check_app(&d).is_err(), "a folder");
assert!(check_app(&d.join("Missing.app")).is_err(), "a missing path");
if cfg!(target_os = "macos") {
let app = d.join("Editor.app");
std::fs::create_dir_all(&app).unwrap();
assert!(check_app(&app).is_ok(), "an .app bundle");
}
#[cfg(all(unix, not(target_os = "macos")))]
{
use std::os::unix::fs::PermissionsExt as _;
let tool = d.join("editor");
std::fs::write(&tool, "#!/bin/sh\n").unwrap();
assert!(check_app(&tool).is_err(), "not executable yet");
std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
assert!(check_app(&tool).is_ok(), "an executable file");
}
let _ = std::fs::remove_dir_all(&d);
}
/// PhotoCraft is looked for only where it installs.
#[test]
fn photocraft_is_found_where_it_installs() {
let d = scratch("find");
if cfg!(target_os = "macos") {
let candidates = photocraft_candidates(Some(&d), None);
assert_eq!(candidates.first().map(|p| p.to_string_lossy().into_owned()).as_deref(), Some("/Applications/PhotoCraft.app"));
assert!(candidates.contains(&d.join("Applications/PhotoCraft.app")), "{candidates:?}");
std::fs::create_dir_all(d.join("Applications/PhotoCraft.app")).unwrap();
assert!(find_photocraft(Some(&d), None).unwrap().ends_with("PhotoCraft.app"));
} else {
let bin = d.join("bin");
std::fs::create_dir_all(&bin).unwrap();
let path_var = std::env::join_paths([&bin]).unwrap();
// On Windows an installed PhotoCraft (registered, or in a program folder) comes first, so
// there only the `PATH` candidate is checked.
if !cfg!(windows) {
assert!(find_photocraft(None, Some(&path_var)).is_none(), "not installed");
}
let exe = bin.join(if cfg!(windows) { "photocraft.exe" } else { "photocraft" });
std::fs::write(&exe, "").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
}
if cfg!(windows) {
assert_eq!(photocraft_candidates(None, Some(&path_var)).last(), Some(&exe));
assert!(check_app(&exe).is_ok());
} else {
assert_eq!(find_photocraft(None, Some(&path_var)), Some(exe));
}
}
let _ = std::fs::remove_dir_all(&d);
}
/// #5327 review: on Windows PhotoCraft is looked for where its installer puts it: the path it
/// registers, then `ArtCraft\PhotoCraft` in the per-user and per-machine program folders, then
/// the `PATH`.
#[test]
fn windows_looks_where_the_photocraft_installer_puts_it() {
use std::path::PathBuf;
let registered = vec![PathBuf::from("D:/Tools/PhotoCraft/photocraft.exe")];
let folders = [PathBuf::from("C:/Users/me/AppData/Local/Programs"), PathBuf::from("C:/Program Files"), PathBuf::from("C:/Program Files")];
let on_path = vec![PathBuf::from("C:/bin/photocraft.exe")];
let exe = |f: &str| PathBuf::from(f).join("ArtCraft").join("PhotoCraft").join("photocraft.exe");
assert_eq!(
windows_candidates(registered, &folders, on_path),
[
PathBuf::from("D:/Tools/PhotoCraft/photocraft.exe"),
exe("C:/Users/me/AppData/Local/Programs"),
exe("C:/Program Files"),
PathBuf::from("C:/bin/photocraft.exe"),
]
);
}
/// The registered path is read from `reg query … /ve` output, spaces and quotes included;
/// no value, no path.
#[test]
fn the_registered_path_is_read_from_reg_query() {
let out = "\r\nHKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\photocraft.exe\r\n (Default) REG_SZ C:\\Program Files\\ArtCraft\\PhotoCraft\\photocraft.exe\r\n";
assert_eq!(registered_path(out), Some(std::path::PathBuf::from(r"C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe")));
assert_eq!(
registered_path(" (Standard) REG_SZ \"C:\\A B\\photocraft.exe\""),
Some(std::path::PathBuf::from(r"C:\A B\photocraft.exe"))
);
assert_eq!(registered_path("ERROR: The system was unable to find the specified registry key or value."), None);
assert_eq!(registered_path(" (Default) REG_SZ "), None);
}
}
+14 -5
View File
@@ -96,6 +96,12 @@ fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<Sav
.map_err(|e: zbus::zvariant::Error| e.to_string())?;
let uri = uris.first().ok_or("no file in the portal's answer")?;
let path = file_uri_path(uri).ok_or_else(|| format!("not a local file: {uri}"))?;
// A name that isn't UTF-8 can't be written as picked: replacing its bytes would save over (and
// ask to replace) another file. The dialog ends without a file instead.
let Ok(path) = String::from_utf8(path) else {
log::warn!("the portal's save dialog picked a file name that isn't UTF-8: nothing is saved");
return Ok(None);
};
let filter = results.get("current_filter").and_then(|v| {
let (label, _globs): (String, Vec<(u32, String)>) = v.try_clone().ok()?.try_into().ok()?;
Some(label)
@@ -103,9 +109,9 @@ fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<Sav
Ok(Some(Saved { path, filter }))
}
/// `file:///home/me/A%20b.svg` → `/home/me/A b.svg`; `None` for a file elsewhere (`file://host/`)
/// or another scheme.
fn file_uri_path(uri: &str) -> Option<String> {
/// `file:///home/me/A%20b.svg` → `/home/me/A b.svg` (its bytes); `None` for a file elsewhere
/// (`file://host/`) or another scheme.
fn file_uri_path(uri: &str) -> Option<Vec<u8>> {
let rest = uri.strip_prefix("file://")?;
let rest = rest.strip_prefix("localhost").unwrap_or(rest);
if !rest.starts_with('/') {
@@ -126,8 +132,7 @@ fn file_uri_path(uri: &str) -> Option<String> {
}
}
}
// `show_dialog` makes rfd's path a string with `to_string_lossy` too.
Some(String::from_utf8_lossy(&out).into_owned())
Some(out)
}
/// `saved` as the answer of the save dialog for `request`: the path, then the first extension of
@@ -406,6 +411,7 @@ mod tests {
#[test]
fn file_uris_become_local_paths() {
let file_uri_path = |uri: &str| super::file_uri_path(uri).map(|b| String::from_utf8(b).unwrap());
assert_eq!(file_uri_path("file:///home/me/Untitled-1.vectorcraft").as_deref(), Some("/home/me/Untitled-1.vectorcraft"));
assert_eq!(file_uri_path("file:///home/me/A%20b%C3%A9.svg").as_deref(), Some("/home/me/A bé.svg"));
assert_eq!(file_uri_path("file://localhost/tmp/x.pdf").as_deref(), Some("/tmp/x.pdf"));
@@ -413,6 +419,9 @@ mod tests {
assert_eq!(file_uri_path("file:///tmp/100%+1%2").as_deref(), Some("/tmp/100%+1%2"));
assert_eq!(file_uri_path("file://host/x.svg"), None);
assert_eq!(file_uri_path("sftp://host/x.svg"), None);
// Not UTF-8: the bytes as they are, which `answer` refuses rather than changing them.
assert_eq!(super::file_uri_path("file:///tmp/a%FF.svg"), Some(b"/tmp/a\xff.svg".to_vec()));
assert!(matches!(answer(0, &results("file:///tmp/a%FF.svg", None)), Ok(None)));
}
#[test]
+21 -1
View File
@@ -62,7 +62,12 @@ pub(crate) fn keep_prefs_copy(path: &std::path::Path, bytes: &[u8], stem: &str)
use std::io::Write as _;
for n in 1..100u32 {
let name = if n == 1 { format!("{stem}.json") } else { format!("{stem}-{n}.json") };
match std::fs::OpenOptions::new().write(true).create_new(true).open(path.with_file_name(name)) {
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
// The preferences hold recent document paths: the copy is owner-only, whatever the umask.
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
match options.open(path.with_file_name(name)) {
Ok(mut file) => {
if file.write_all(bytes).is_ok() {
return;
@@ -312,6 +317,8 @@ pub(crate) fn prefs_bytes(app: &VectorcraftApp) -> serde_json::Result<Vec<u8>> {
/// [`prefs_bytes`] as JSON.
fn prefs_value(app: &VectorcraftApp) -> serde_json::Result<serde_json::Value> {
let mut ui = app.ui.clone();
// An open dialog is never restored, and its fields can hold passwords (PDF import and save).
ui.dialog = None;
ui.engine_prefs = app.session.prefs.to_json();
serde_json::to_value(&ui)
}
@@ -324,6 +331,19 @@ mod tests {
/// Two windows open at once (#4625): the one that saves last keeps the other's changes and
/// adds its own, instead of putting back the preferences it started from.
#[cfg(unix)]
#[test]
fn a_kept_preferences_copy_is_owner_only() {
use std::os::unix::fs::PermissionsExt as _;
let dir = std::env::temp_dir().join(format!("vc-prefs-copy-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
super::keep_prefs_copy(&dir.join("ui.json"), b"{}", "ui.unreadable");
let mode = std::fs::metadata(dir.join("ui.unreadable.json")).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_window_saves_only_what_it_changed_over_another_windows_save() {
let base = json!({"workspace": "Essentials", "toolbar": true, "engine_prefs": {"uiAccent": "blue", "uiScaling": 1.0}});
+30 -1
View File
@@ -149,6 +149,15 @@ fn copy_dir(from: &Path, to: &Path) -> Result<(), String> {
}
}
/// Make folder `dir`, owner-only on Unix.
fn private_dir(dir: &Path) -> std::io::Result<()> {
let mut builder = std::fs::DirBuilder::new();
builder.recursive(true);
#[cfg(unix)]
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
builder.create(dir)
}
fn copy_dir_into(from: &Path, to: &Path, skip: &mut impl FnMut(String)) {
let entries = match std::fs::read_dir(from) {
Ok(entries) => entries,
@@ -165,7 +174,12 @@ fn copy_dir_into(from: &Path, to: &Path, skip: &mut impl FnMut(String)) {
let (src, dst) = (entry.path(), to.join(entry.file_name()));
// A symbolic link is copied as what it points to, or skipped when that is a folder.
let copied = match entry.file_type() {
Ok(kind) if kind.is_dir() => std::fs::create_dir_all(&dst).map(|()| copy_dir_into(&src, &dst, skip)),
// The copy keeps the folder's permissions (a private recovery folder stays private):
// owner-only while it fills, then the source's.
Ok(kind) if kind.is_dir() => private_dir(&dst).and_then(|()| {
copy_dir_into(&src, &dst, skip);
std::fs::set_permissions(&dst, std::fs::metadata(&src)?.permissions())
}),
Ok(_) => std::fs::copy(&src, &dst).map(|_| ()),
Err(e) => Err(e),
};
@@ -387,4 +401,19 @@ mod tests {
let _ = std::fs::remove_dir_all(&from);
let _ = std::fs::remove_dir_all(&to);
}
#[cfg(unix)]
#[test]
fn a_copied_folder_keeps_its_permissions() {
use std::os::unix::fs::PermissionsExt as _;
let from = temp("copy-mode-from");
let to = temp("copy-mode-to");
std::fs::create_dir_all(from.join("recovery")).unwrap();
std::fs::write(from.join("recovery/copy.vectorcraft"), b"unsaved").unwrap();
std::fs::set_permissions(from.join("recovery"), std::fs::Permissions::from_mode(0o700)).unwrap();
copy_dir(&from, &to).unwrap();
assert_eq!(std::fs::metadata(to.join("recovery")).unwrap().permissions().mode() & 0o777, 0o700);
let _ = std::fs::remove_dir_all(&from);
let _ = std::fs::remove_dir_all(&to);
}
}
+4
View File
@@ -189,3 +189,7 @@ sync_github_name = false
[people.WadahBadawi]
display_name = "Wadah Badawi"
sync_github_name = true
[people.JonRC]
real_name = "Jonathan Cardoso"
display_name = "Jonathan Cardoso"
+65 -26
View File
@@ -15,6 +15,13 @@ const DOCUMENT_KIND: &[u8; 4] = b"nsrP";
/// A save appends one table; real files have one to a few hundred.
const MAX_TABLES: usize = 4096;
/// Allocation records read over the whole table chain. Each save lists every entry again, so a
/// document with a few hundred saves of a few thousand entries stays far below; tables whose
/// record regions overlap (or a table chain of thousands of huge tables) can't multiply the work.
const MAX_INDEX_RECORDS: usize = 1 << 22;
/// Bytes of entry names kept by the index (after lossy UTF-8 decoding, which can triple a name).
/// Real names (`doc.dat`, `d/12`) are a few bytes each.
const MAX_INDEX_NAME_BYTES: usize = 16 << 20;
/// zstd window ceiling: real documents use a few MiB; this stops a header from reserving gigabytes.
const MAX_ZSTD_WINDOW: u64 = 64 << 20;
@@ -75,6 +82,9 @@ pub struct Archive<'a> {
pub revisions: usize,
extracted: usize,
limits: Limits,
/// Entries whose extraction failed after their size was charged: asked again, they fail
/// again without being decompressed again.
failed: HashMap<String, Error>,
}
pub(crate) struct Cursor<'a> {
@@ -157,7 +167,15 @@ pub fn header(bytes: &[u8]) -> Result<Header, Error> {
impl<'a> Archive<'a> {
pub fn open(bytes: &'a [u8], limits: Limits) -> Result<Self, Error> {
Self::open_within(bytes, limits, MAX_INDEX_RECORDS, MAX_INDEX_NAME_BYTES)
}
/// [`Archive::open`] reading at most `max_records` allocation records and keeping at most
/// `max_name_bytes` bytes of entry names, both over the whole table chain.
pub(crate) fn open_within(bytes: &'a [u8], limits: Limits, max_records: usize, max_name_bytes: usize) -> Result<Self, Error> {
let header = header(bytes)?;
let mut records_left = max_records;
let mut name_bytes_left = max_name_bytes;
// Newest record per id: (table date, table index, record).
let mut latest: HashMap<u32, (u64, usize, Option<Entry>)> = HashMap::new();
let mut names: HashMap<u32, String> = HashMap::new();
@@ -189,6 +207,7 @@ impl<'a> Archive<'a> {
let dirs = c.u16()?;
c.take(1)?;
for _ in 0..files {
records_left = records_left.checked_sub(1).ok_or(Error::Limit("too many archive entries"))?;
let id = c.u32()?;
let flag = c.u8()?;
let mut record = None;
@@ -224,8 +243,13 @@ impl<'a> Archive<'a> {
}
if flag == 0 {
let len = usize::from(c.u16()?);
let name = String::from_utf8_lossy(c.take(len)?).into_owned();
names.entry(id).or_insert(name);
let raw = c.take(len)?;
// Only the first name of an id is kept: later ones are not even decoded.
if let std::collections::hash_map::Entry::Vacant(slot) = names.entry(id) {
let name = String::from_utf8_lossy(raw);
name_bytes_left = name_bytes_left.checked_sub(name.len()).ok_or(Error::Limit("archive entry names too long"))?;
slot.insert(name.into_owned());
}
}
// Equal dates: the first table in the chain (the newest) wins, as in afread.
let replace = latest.get(&id).is_none_or(|(d, _, _)| date > *d);
@@ -234,6 +258,7 @@ impl<'a> Archive<'a> {
}
}
for _ in 0..dirs {
records_left = records_left.checked_sub(1).ok_or(Error::Limit("too many archive entries"))?;
let len = usize::from(c.u16()?);
c.take(10)?;
c.take(len)?;
@@ -241,12 +266,12 @@ impl<'a> Archive<'a> {
}
let mut entries = HashMap::new();
for (id, (_, _, record)) in latest {
if let (Some(mut e), Some(name)) = (record, names.get(&id)) {
e.name = name.clone();
if let (Some(mut e), Some(name)) = (record, names.remove(&id)) {
e.name = name;
entries.insert(e.name.clone(), e);
}
}
Ok(Self { bytes, header, entries, revisions: tables, extracted: 0, limits })
Ok(Self { bytes, header, entries, revisions: tables, extracted: 0, limits, failed: HashMap::new() })
}
pub fn entry(&self, name: &str) -> Option<&Entry> {
@@ -279,7 +304,10 @@ impl<'a> Archive<'a> {
}
pub fn read(&mut self, name: &str) -> Result<Vec<u8>, Error> {
let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?.clone();
if let Some(e) = self.failed.get(name) {
return Err(*e);
}
let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?;
let size = usize::try_from(e.size).map_err(|_| Error::Limit("archive entry too large"))?;
if size > self.limits.max_entry {
return Err(Error::Limit("archive entry too large"));
@@ -288,30 +316,41 @@ impl<'a> Archive<'a> {
if total > self.limits.max_total {
return Err(Error::Limit("document too large"));
}
let mut c = Cursor::new(self.bytes, offset(e.offset)?);
if c.take(4)? != b"#Fil" {
return Err(Error::Malformed("archive entry has no data block"));
}
let method = e.compression & 3;
let stored_len = if matches!(method, 1 | 2) { e.compressed } else { e.size };
let data = c.take(offset(stored_len)?)?;
let mut out = match method {
1 => inflate(data, size)?,
2 => unzstd(data, size)?,
_ => data.to_vec(),
};
if out.len() != size {
return Err(Error::Malformed("archive entry size mismatch"));
}
unpredict(&mut out, e.compression)?;
if crc32fast::hash(&out) != e.crc {
return Err(Error::Malformed("archive entry checksum mismatch"));
}
// Charged before the work, and kept when it fails: an entry that fails its checksum
// can't be decompressed over and over for free.
self.extracted = total;
Ok(out)
let result = extract(self.bytes, e, size);
if let Err(err) = result {
self.failed.insert(name.to_owned(), err);
}
result
}
}
/// Decompress entry `e` of `bytes` (declared `size` bytes), undo its predictor and check its CRC.
fn extract(bytes: &[u8], e: &Entry, size: usize) -> Result<Vec<u8>, Error> {
let mut c = Cursor::new(bytes, offset(e.offset)?);
if c.take(4)? != b"#Fil" {
return Err(Error::Malformed("archive entry has no data block"));
}
let method = e.compression & 3;
let stored_len = if matches!(method, 1 | 2) { e.compressed } else { e.size };
let data = c.take(offset(stored_len)?)?;
let mut out = match method {
1 => inflate(data, size)?,
2 => unzstd(data, size)?,
_ => data.to_vec(),
};
if out.len() != size {
return Err(Error::Malformed("archive entry size mismatch"));
}
unpredict(&mut out, e.compression)?;
if crc32fast::hash(&out) != e.crc {
return Err(Error::Malformed("archive entry checksum mismatch"));
}
Ok(out)
}
/// Read at most `size + 1` bytes so a stream that decodes past its declared size is caught
/// without unbounded allocation.
fn read_bounded(mut r: impl Read, size: usize) -> Result<Vec<u8>, Error> {
+29 -17
View File
@@ -332,7 +332,7 @@ fn pixels(img: &mut Image, o: &Overlay) -> bool {
};
let to_unit = match o.source {
Source::Gradient(g) => match invert(g.transform) {
Some(m) => Some((img.transform.then(m), g)),
Some(m) => Some((img.transform.then(m), g, stop_reach(g))),
None => return false,
},
Source::Solid(_) => None,
@@ -343,9 +343,9 @@ fn pixels(img: &mut Image, o: &Overlay) -> bool {
}
let (s, sa) = match (solid, &to_unit) {
(Some(s), _) => s,
(None, Some((m, g))) => {
(None, Some((m, g, reach))) => {
let q = m.apply(Point { x: (i % width) as f64 + 0.5, y: (i / width) as f64 + 0.5 });
let c = sample(g, q);
let c = sample(g, reach, q);
(rgb(c), c.alpha())
}
(None, None) => continue,
@@ -376,8 +376,22 @@ fn decode(bytes: &[u8], width: u32, height: u32) -> Option<Vec<u8>> {
Some(reader.decode().ok()?.into_rgba8().into_raw())
}
/// The gradient's colour at unit-space point `q`.
fn sample(g: &Gradient, q: Point) -> Color {
/// For each pair of neighbouring stops (`k`, `k + 1`), the largest offset of stops `1..=k + 1`:
/// the first pair whose end offset a `t` doesn't pass is the first whose reach it doesn't pass, and
/// reaches never decrease, so [`sample`] finds it by binary search, sorted stops or not.
fn stop_reach(g: &Gradient) -> Vec<f64> {
g.stops
.iter()
.skip(1)
.scan(f64::NEG_INFINITY, |m, s| {
*m = m.max(s.offset);
Some(*m)
})
.collect()
}
/// The gradient's colour at unit-space point `q` (`reach`: [`stop_reach`] of `g`).
fn sample(g: &Gradient, reach: &[f64], q: Point) -> Color {
let t = match g.kind {
GradientKind::Linear => q.x,
GradientKind::Radial => q.x.hypot(q.y),
@@ -388,18 +402,16 @@ fn sample(g: &Gradient, q: Point) -> Color {
if t <= first.offset {
return first.color;
}
for w in g.stops.windows(2) {
let [a, b] = [&w[0], &w[1]];
if t <= b.offset {
let span = b.offset - a.offset;
let u = if span > 1e-9 { (t - a.offset) / span } else { 1.0 };
// Affinity's midpoint bias (see `Stop::half_point`).
let k = 1.0 + 8.0 * (a.bias - 0.5).abs();
let u = if a.bias >= 0.5 { u.powf(k) } else { 1.0 - (1.0 - u).powf(k) };
let (x, y) = (rgb(a.color), rgb(b.color));
let [r, g, bl] = [0, 1, 2].map(|i| x[i] + (y[i] - x[i]) * u);
return Color::Rgb { r, g, b: bl, a: a.color.alpha() + (b.color.alpha() - a.color.alpha()) * u };
}
let k = reach.partition_point(|r| *r < t);
if let (Some(a), Some(b)) = (g.stops.get(k), g.stops.get(k + 1)) {
let span = b.offset - a.offset;
let u = if span > 1e-9 { (t - a.offset) / span } else { 1.0 };
// Affinity's midpoint bias (see `Stop::half_point`).
let k = 1.0 + 8.0 * (a.bias - 0.5).abs();
let u = if a.bias >= 0.5 { u.powf(k) } else { 1.0 - (1.0 - u).powf(k) };
let (x, y) = (rgb(a.color), rgb(b.color));
let [r, g, bl] = [0, 1, 2].map(|i| x[i] + (y[i] - x[i]) * u);
return Color::Rgb { r, g, b: bl, a: a.color.alpha() + (b.color.alpha() - a.color.alpha()) * u };
}
last.color
}
+6 -6
View File
@@ -13,8 +13,7 @@ const MAX_SIDES: i64 = 10_000;
/// The last value of a tag: a shape changed from one kind to another keeps a stale first block.
fn last<'a>(r: &'a Reader, id: ObjId, tag: &[u8; 4]) -> Option<&'a Value> {
let t = Tag::of(tag);
r.s.object(id)?.fields.iter().rev().find(|(k, _)| *k == t).map(|(_, v)| v)
r.s.object(id)?.get_last(Tag::of(tag))
}
fn num(r: &Reader, id: ObjId, tag: &[u8; 4]) -> Option<f64> {
@@ -51,12 +50,13 @@ pub(crate) fn shape(r: &mut Reader, shape: ObjId, b: [f64; 4], world: Affine) ->
let class = r.s.class(shape)?;
let sub = match &class.0.to_be_bytes() {
b"ShNR" | b"ShRR" => {
let types = match last(r, shape, b"CTyp") {
Some(Value::Array(a)) => a.iter().map(|t| if let Value::Enum { id, .. } = t { Some(*id) } else { None }).collect(),
// Only the four corners' entries can matter: longer arrays are read no further.
let types: Vec<Option<u16>> = match last(r, shape, b"CTyp") {
Some(Value::Array(a)) => a.iter().take(4).map(|t| if let Value::Enum { id, .. } = t { Some(*id) } else { None }).collect(),
_ => Vec::new(),
};
let radii = match last(r, shape, b"ShCR") {
Some(Value::Floats(v)) => v.iter().map(|f| if f.is_finite() && *f > 0.0 { *f } else { 0.0 }).collect(),
let radii: Vec<f64> = match last(r, shape, b"ShCR") {
Some(Value::Floats(v)) => v.iter().take(4).map(|f| if f.is_finite() && *f > 0.0 { *f } else { 0.0 }).collect(),
_ => Vec::new(),
};
// Corners follow the first one (top left) unless they were unlocked; then each has
+91 -6
View File
@@ -73,11 +73,67 @@ pub struct Object {
pub chain: Vec<Tag>,
/// Fields in stream order; positional fields have tag 0.
pub fields: Vec<(Tag, Value)>,
/// For objects with many fields: each tag with the positions of its first and last field,
/// sorted by tag, so a lookup isn't a scan of every field (a shared object is looked up
/// again on every visit). Built by [`Object::index`]; empty for small objects.
index: Vec<(Tag, u32, u32)>,
}
/// Objects with more fields than this get an [`Object::index`]; fewer are scanned.
const INDEXED_FIELDS: usize = 16;
impl Object {
pub fn new(class: Tag, kind: Kind, chain: Vec<Tag>, fields: Vec<(Tag, Value)>) -> Self {
let mut o = Self { class, kind, chain, fields, index: Vec::new() };
o.index();
o
}
/// (Re)build the tag index after `fields` changed.
fn index(&mut self) {
self.index.clear();
if self.fields.len() <= INDEXED_FIELDS {
return;
}
let mut index: Vec<(Tag, u32, u32)> = Vec::new();
if index.try_reserve_exact(self.fields.len()).is_err() {
return;
}
// Fields beyond u32 positions are impossible: a stream holds at most MAX_VALUES values.
index.extend(self.fields.iter().enumerate().filter_map(|(i, (t, _))| u32::try_from(i).ok().map(|i| (*t, i, i))));
// Stable: equal tags stay in stream order, so the run of a tag starts at its first field.
index.sort_by_key(|(t, _, _)| *t);
index.dedup_by(|later, first| {
if later.0 == first.0 {
first.2 = later.2;
true
} else {
false
}
});
index.shrink_to_fit();
self.index = index;
}
fn position(&self, tag: Tag, last: bool) -> Option<usize> {
if self.index.is_empty() {
let mut fields = self.fields.iter().enumerate();
let hit = if last { fields.rev().find(|(_, (t, _))| *t == tag) } else { fields.find(|(_, (t, _))| *t == tag) };
return hit.map(|(i, _)| i);
}
let at = self.index.binary_search_by_key(&tag, |(t, _, _)| *t).ok()?;
let (_, first, end) = self.index.get(at)?;
usize::try_from(if last { *end } else { *first }).ok()
}
/// The first field tagged `tag`.
pub fn get(&self, tag: Tag) -> Option<&Value> {
self.fields.iter().find(|(t, _)| *t == tag).map(|(_, v)| v)
self.fields.get(self.position(tag, false)?).map(|(_, v)| v)
}
/// The last field tagged `tag` (a shape changed from one kind to another keeps a stale first one).
pub fn get_last(&self, tag: Tag) -> Option<&Value> {
self.fields.get(self.position(tag, true)?).map(|(_, v)| v)
}
}
@@ -124,10 +180,11 @@ pub fn parse(bytes: &[u8]) -> Result<Stream, Error> {
c.u32()?;
}
let mut p = Parser { c, objects: Vec::new(), shared: std::collections::HashMap::new(), depth: 0, values: 0 };
let root = p.push(Object { class, kind: Kind::Root, chain: vec![class], fields: Vec::new() })?;
let root = p.push(Object::new(class, Kind::Root, vec![class], Vec::new()))?;
let fields = p.fields(true, class)?;
if let Some(o) = p.objects.get_mut(root) {
o.fields = fields;
o.index();
}
Ok(Stream { root, objects: p.objects })
}
@@ -252,7 +309,7 @@ impl Parser<'_> {
}
0x30 => {
let fields = self.fields(false, class)?;
let id = self.push(Object { class, kind: Kind::Positional, chain: Vec::new(), fields })?;
let id = self.push(Object::new(class, Kind::Positional, Vec::new(), fields))?;
Value::Obj(Some(id))
}
0x31 | 0x32 if !tagged => return Err(Error::Malformed("object without a field tag")),
@@ -354,7 +411,7 @@ impl Parser<'_> {
}
};
let fields = self.fields(true, class)?;
let id = self.push(Object { class, kind: Kind::Inline, chain: vec![class], fields })?;
let id = self.push(Object::new(class, Kind::Inline, vec![class], fields))?;
Ok(Value::Obj(Some(id)))
}
@@ -373,7 +430,7 @@ impl Parser<'_> {
return Err(Error::Malformed("object defined twice"));
}
// Register before the fields: an object's own fields may refer back to it.
let id = self.push(Object { class: Tag(0), kind: Kind::Shared, chain: Vec::new(), fields: Vec::new() })?;
let id = self.push(Object::new(Tag(0), Kind::Shared, Vec::new(), Vec::new()))?;
self.shared.insert(key, id);
let mut chain = Vec::new();
let mut fields = Vec::new();
@@ -399,8 +456,36 @@ impl Parser<'_> {
let class = chain.first().copied().unwrap_or(Tag(0));
fields.extend(self.fields(true, class)?);
if let Some(o) = self.objects.get_mut(id) {
*o = Object { class, kind: Kind::Shared, chain, fields };
*o = Object::new(class, Kind::Shared, chain, fields);
}
Ok(Value::Obj(Some(id)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lookups_in_a_large_object_find_the_first_and_last_fields_of_a_tag() {
let tag = |i: u32| Tag(0x4100_0000 + i);
let mut fields: Vec<(Tag, Value)> = (0..1000).map(|i| (tag(i % 300), Value::UInt(u64::from(i)))).collect();
fields.push((tag(7), Value::Str("last".into())));
let o = Object::new(Tag::of(b"Grup"), Kind::Shared, Vec::new(), fields.clone());
assert!(!o.index.is_empty());
// The index has one entry per distinct tag, not per field.
assert_eq!(o.index.len(), 300);
for t in 0..300 {
let first = fields.iter().find(|(k, _)| *k == tag(t)).map(|(_, v)| v);
let last = fields.iter().rev().find(|(k, _)| *k == tag(t)).map(|(_, v)| v);
assert_eq!(o.get(tag(t)), first);
assert_eq!(o.get_last(tag(t)), last);
}
assert_eq!(o.get(tag(300)), None);
assert_eq!(o.get_last(tag(7)), Some(&Value::Str("last".into())));
let small = Object::new(Tag::of(b"Grup"), Kind::Shared, Vec::new(), vec![(tag(1), Value::Bool(true)), (tag(1), Value::Bool(false))]);
assert!(small.index.is_empty());
assert_eq!(small.get(tag(1)), Some(&Value::Bool(true)));
assert_eq!(small.get_last(tag(1)), Some(&Value::Bool(false)));
}
}
+28
View File
@@ -261,6 +261,34 @@ mod archive {
assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_))));
}
#[test]
fn an_entry_that_fails_its_checksum_is_charged_once_and_not_decompressed_again() {
let d = doc();
let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None);
let mut broken = file.clone();
broken[90] ^= 0x55;
let mut a = Archive::open(&broken, Limits::default()).unwrap();
let first = a.read("doc.dat").unwrap_err();
// The work was done, so it counts against the import even though it failed.
assert_eq!(a.extracted(), d.len());
assert_eq!(a.read("doc.dat").unwrap_err(), first);
assert_eq!(a.extracted(), d.len());
// A budget that only covers one attempt is not exceeded by asking again.
let mut a = Archive::open(&broken, Limits { max_entry: usize::MAX, max_total: d.len() }).unwrap();
assert!(a.read("doc.dat").is_err());
assert_eq!(a.read("doc.dat").unwrap_err(), first);
}
#[test]
fn the_table_index_has_a_budget_for_records_and_names() {
let d = doc();
let long = "n".repeat(300);
let file = synth::container(&[("doc.dat", &d, Method::Stored), (&long, b"tile", Method::Stored)], None);
Archive::open_within(&file, Limits::default(), 2, 307).unwrap();
assert_eq!(Archive::open_within(&file, Limits::default(), 1, 1 << 20).unwrap_err(), Error::Limit("too many archive entries"));
assert_eq!(Archive::open_within(&file, Limits::default(), 2, 306).unwrap_err(), Error::Limit("archive entry names too long"));
}
// Regression test for #1710: ruzstd 0.9.0 let a block decompress to more than its frame's
// window allows (RUSTSEC-2026-0344), so a crafted entry made the decoder produce far more than
// the format permits for a block. 0.9.1 refuses it.
+20 -6
View File
@@ -781,10 +781,9 @@ pub fn unique_name(lib: &[Brush], base: &str) -> String {
return base.to_string();
}
// At most `lib.len()` names are taken, so one of the first `lib.len() + 1` candidates is free.
(2..=lib.len() + 2)
.map(|i| format!("{base} {i}"))
.find(|n| !lib.iter().any(|b| &b.name == n))
.unwrap_or_else(|| format!("{base} {}", lib.len() + 2))
// Each is looked up in a set: scanning the library per candidate is quadratic in its size.
let taken: std::collections::HashSet<&str> = lib.iter().map(|b| b.name.as_str()).collect();
(2..=lib.len() + 2).map(|i| format!("{base} {i}")).find(|n| !taken.contains(n.as_str())).unwrap_or_else(|| format!("{base} {}", lib.len() + 2))
}
// ---------- geometry ----------
@@ -849,9 +848,15 @@ fn draws_brushed(doc: &Document, def: Named<'_>, known: &mut Known) -> bool {
};
// Without recursion, each one looked at once: they may use one another without end.
let (mut seen, mut stack) = (std::collections::HashSet::from([key.clone()]), art(def));
// A brush name the library lacks draws a plain stroke ([`node_pieces`]), which runs no brush.
let mut names: Option<std::collections::HashSet<String>> = None;
let mut resolves = |n: &Node| {
let names = names.get_or_insert_with(|| library(doc).into_iter().map(|b| b.name).collect());
n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.visible && s.brush.as_ref().is_some_and(|b| names.contains(b))))
};
let mut answer = false;
while let Some(n) = stack.pop() {
if has_brush(n) {
if has_brush(n) && resolves(n) {
answer = true;
break;
}
@@ -884,7 +889,16 @@ fn leave_out_brushed(doc: &Document, nodes: &mut Vec<Node>, known: &mut Known) {
walk(doc, Arc::make_mut(c), known);
}
}
if n.extras().mask.is_some()
// A mask's art is drawn too. Its root is filtered like any other node: a symbol instance
// there that draws a brushed stroke would run the brush again from inside the mask, so the
// mask goes, as such an instance goes from the pieces and their children.
let rejected_root = matches!(
n.extras().mask.as_ref().map(|m| &m.art.kind),
Some(NodeKind::SymbolInstance { symbol, .. }) if draws_brushed(doc, (false, symbol.as_str()), known)
);
if rejected_root {
n.extras_mut().mask = None;
} else if n.extras().mask.is_some()
&& let Some(mask) = n.extras_mut().mask.as_mut()
{
walk(doc, Arc::make_mut(&mut mask.art), known);
+41
View File
@@ -1301,6 +1301,7 @@ fn pieces_leave_out_what_draws_a_brushed_stroke_by_name() {
};
let art = Node::group(NodeId(0), [instance("plain"), instance("brushed"), painted("plain"), painted("brushed")].map(std::sync::Arc::new).into());
let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) };
store(&mut doc, std::slice::from_ref(&b));
let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 100.0, 0.0), &stroke(1.0));
assert!(!out.is_empty());
for piece in &out {
@@ -1316,6 +1317,46 @@ fn pieces_leave_out_what_draws_a_brushed_stroke_by_name() {
}
}
/// A symbol instance at the root of an opacity mask is filtered like one among the children: when
/// its symbol draws a brushed stroke the mask goes (it would run the brush again from inside the
/// mask, without end), and a mask whose root symbol is plain stays.
#[test]
fn pieces_leave_out_a_mask_whose_root_draws_a_brushed_stroke() {
use vectorcraft_doc::{OpacityMask, Symbol};
let mut doc = Document::new(100.0, 100.0);
let mut brushed = rect_art(10.0, 4.0);
brushed.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(StrokeLayer { brush: Some("s".into()), ..stroke(1.0) }));
// A brush the library lacks draws a plain stroke: its mask stays.
let mut unresolved = rect_art(10.0, 4.0);
unresolved.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(StrokeLayer { brush: Some("missing".into()), ..stroke(1.0) }));
for (name, art) in [("plain", rect_art(10.0, 4.0)), ("brushed", brushed), ("unresolved", unresolved)] {
doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: std::sync::Arc::new(art) });
}
let instance = |symbol: &str| Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY });
let masked = |symbol: &str| {
let mut n = rect_art(10.0, 4.0);
n.extras_mut().mask = Some(Box::new(OpacityMask::new(instance(symbol), true)));
n
};
let art = Node::group(NodeId(0), [masked("plain"), masked("brushed"), masked("unresolved")].map(std::sync::Arc::new).into());
let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) };
store(&mut doc, std::slice::from_ref(&b));
let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 100.0, 0.0), &stroke(1.0));
assert!(!out.is_empty());
for piece in &out {
let roots: Vec<Option<&str>> = piece
.children()
.unwrap()
.iter()
.map(|c| match c.extras().mask.as_ref().map(|m| &m.art.kind) {
Some(NodeKind::SymbolInstance { symbol, .. }) => Some(symbol.as_str()),
_ => None,
})
.collect();
assert_eq!(roots, [Some("plain"), None, Some("unresolved")], "the plain and unresolved masks stay and the brushed one goes");
}
}
/// Anchors a brushed stroke emitted, which is what the output budget counts.
fn anchors(nodes: &[Node]) -> usize {
nodes
+76 -16
View File
@@ -23,10 +23,19 @@ const PT_PER_MM: f64 = 72.0 / 25.4;
const THINNEST: f64 = 0.25;
/// The most objects an import makes.
const MAX_NODES: usize = 2_000_000;
/// The most block visits (one per insert copy) an import makes, whatever they produce.
const MAX_VISITS: usize = 10_000_000;
/// The most block work an import does, whatever it produces: one per insert copy drawn, and one
/// per item of the block looked at for it (art on hidden layers too).
const MAX_VISITS: usize = if cfg!(test) { 1_000_000 } else { 20_000_000 };
/// The most path elements an import makes (blocks drawn as art are copied for every placement).
const MAX_ELEMENTS: usize = if cfg!(test) { 1_000_000 } else { 4_000_000 };
/// The most dash lengths an import keeps (every dashed path holds its own copy of its pattern).
const MAX_DASH_VALUES: usize = if cfg!(test) { 1_000 } else { 4_000_000 };
/// The most bytes of text, font names and symbol names an import copies into objects (a block's
/// text and name are copied for every placement).
const MAX_TEXT_BYTES: usize = if cfg!(test) { 64 << 10 } else { 64 << 20 };
/// The longest font family a text style may name; a longer one is not a font, and is set in the
/// default.
const MAX_FAMILY_BYTES: usize = 256;
/// How far from the origin art may lie (points): the canvas.
pub(crate) const MAX_EXTENT: f64 = 4.0e6;
@@ -34,6 +43,9 @@ const NESTED: &str = "blocks nested more than 8 deep, or inside themselves, are
const XREFS: &str = "blocks referencing other drawings (external references) are left out";
const TOO_MANY: &str = "the drawing has more than 2,000,000 objects: the rest are left out";
const TOO_MANY_POINTS: &str = "the drawing has more than 4,000,000 path points: the rest are left out";
const TOO_MUCH_BLOCK_WORK: &str = "the drawing's blocks take too much work to place: the rest are left out";
const TOO_MANY_DASHES: &str = "the drawing has more dashed lines than can be kept: the rest are drawn solid";
const TOO_MUCH_TEXT: &str = "the drawing has more than 64 MB of text and block names: the rest are left out";
/// What a block's art takes from the insert that places it: its colour, lineweight, linetype
/// and opacity where the art says "by block", and its layer for art on layer 0.
@@ -71,6 +83,9 @@ pub(crate) struct Build<'d, 'a> {
visits: usize,
/// Path elements made so far.
elements: usize,
/// Dash lengths and text bytes kept so far.
dash_values: usize,
text_bytes: usize,
warnings: Vec<String>,
}
@@ -128,6 +143,8 @@ impl<'d, 'a> Build<'d, 'a> {
nodes: 0,
visits: 0,
elements: 0,
dash_values: 0,
text_bytes: 0,
warnings: vec![],
}
}
@@ -138,6 +155,20 @@ impl<'d, 'a> Build<'d, 'a> {
}
}
/// Take `bytes` of text from [`MAX_TEXT_BYTES`]; false (with a warning) when they don't fit.
fn charge_text(&mut self, bytes: usize) -> bool {
match self.text_bytes.checked_add(bytes).filter(|t| *t <= MAX_TEXT_BYTES) {
Some(t) => {
self.text_bytes = t;
true
}
None => {
self.warn(TOO_MUCH_TEXT);
false
}
}
}
/// Import `layout`; `natural` and `ratio` are points per drawing unit in the drawing's own
/// unit and at the scale asked for (fitting computes its own).
pub fn run(mut self, layout: &LayoutDef, natural: f64, ratio: f64) -> Result<(Document, Vec<String>), String> {
@@ -469,6 +500,9 @@ impl<'d, 'a> Build<'d, 'a> {
super::curve::bounds(&bp)?;
let paint = Paint::solid(rgb_color(self.rgb(p, inh)));
let scale = map.determinant().abs().sqrt();
let path = PathData::from_bezpath(&bp);
// A compound path's loops each keep a copy of its appearance, beside its own.
let copies = if path.subpaths.len() > 1 { path.subpaths.len() + 1 } else { 1 };
let appearance = if fill {
Appearance::basic(paint, Paint::None, 0.0)
} else {
@@ -484,15 +518,20 @@ impl<'d, 'a> Build<'d, 'a> {
if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut()
&& let Some((dash, dots)) = self.dash(&self.linetype(p, inh), p, scale)
{
s.dash = Some(dash);
if dots {
s.cap = LineCap::Round;
match dash.pattern.len().checked_mul(copies).and_then(|v| self.dash_values.checked_add(v)).filter(|n| *n <= MAX_DASH_VALUES) {
Some(n) => {
self.dash_values = n;
s.dash = Some(dash);
if dots {
s.cap = LineCap::Round;
}
}
None => self.warn(TOO_MANY_DASHES),
}
}
ap
};
let rule = if fill { FillRule::EvenOdd } else { FillRule::NonZero };
let path = PathData::from_bezpath(&bp);
let kind = |path: PathData| NodeKind::Path { path, rule, live: None, clipping: false, guide: false };
let mut n = if path.subpaths.len() > 1 {
// Several loops (a hatch with islands) paint as one compound path. Each loop is an
@@ -527,10 +566,15 @@ impl<'d, 'a> Build<'d, 'a> {
if !(s > 1e-12 && s.is_finite()) {
return None;
}
let family = t.family.clone().or_else(|| self.d.styles.get(&t.style).filter(|f| !f.is_empty()).cloned());
let d = self.d;
let family = t.family.as_deref().or_else(|| d.styles.get(&t.style).map(String::as_str).filter(|f| !f.is_empty()));
let family = family.filter(|f| f.len() <= MAX_FAMILY_BYTES);
if !self.charge_text(t.text.len().saturating_add(family.map_or(0, str::len))) {
return None;
}
let default = CharStyle::default();
let style = CharStyle {
font_family: family.unwrap_or(default.font_family.clone()),
font_family: family.map_or_else(|| default.font_family.clone(), str::to_string),
size: t.height / CAP_HEIGHT * s,
h_scale: t.width * 100.0,
leading: t.leading.map(|l| l * s),
@@ -558,6 +602,13 @@ impl<'d, 'a> Build<'d, 'a> {
for cell in &ins.cells {
let node = match &symbol {
Some(name) => {
if self.nodes >= MAX_NODES {
self.warn(TOO_MANY);
break;
}
if !self.charge_text(name.len()) {
break;
}
let xf = map * *cell * self.symbol_map.inverse();
self.nodes += 1;
Some(Node::new(self.doc.alloc_id(), NodeKind::SymbolInstance { symbol: name.clone(), xf }))
@@ -581,14 +632,19 @@ impl<'d, 'a> Build<'d, 'a> {
/// The art of block `name` drawn by `map`, as one object.
fn art(&mut self, name: &str, map: Affine, inh: &Inherit, depth: u32) -> Option<Node> {
self.visits += 1;
if self.visits > MAX_VISITS {
if self.visits == MAX_VISITS + 1 {
self.warn(TOO_MANY);
}
if self.visits >= MAX_VISITS {
self.warn(TOO_MUCH_BLOCK_WORK);
return None;
}
let items = self.block(name)?;
let items = self.block(name);
// Each placement looks at every item of the block, drawn or not (art on a hidden layer
// makes nothing, so the node budget doesn't bound it).
self.visits = self.visits.saturating_add(1 + items.as_ref().map_or(0, |i| i.len()));
if self.visits > MAX_VISITS {
self.warn(TOO_MUCH_BLOCK_WORK);
return None;
}
let items = items?;
if !self.enter(name, depth) {
return None;
}
@@ -618,12 +674,16 @@ impl<'d, 'a> Build<'d, 'a> {
let base = self.d.blocks.get(name).map_or(Point::ZERO, |b| b.base);
let map = self.symbol_map * Affine::translate(-base.to_vec2());
let art = self.art(name, map, &key.1, depth);
let made = art.map(|art| {
let made = art.and_then(|art| {
let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str());
// The symbol keeps its name: text, as its instances' copies of it are.
if !self.charge_text(label.len()) {
return None;
}
let symbol = unique(label, &mut self.next_suffix, &self.symbol_names);
self.symbol_names.insert(symbol.clone());
self.doc.symbols.push(Symbol { dynamic: false, name: symbol.clone(), art: Arc::new(art) });
symbol
Some(symbol)
});
self.symbols.insert(key, made.clone());
made
+171 -1
View File
@@ -814,7 +814,7 @@ fn nested_array_inserts_of_nothing_stop_at_the_work_budget() {
blocks.extend(block("*C", None));
let top = [(0, "INSERT"), (2, "*A"), (10, "0"), (20, "0"), (70, "300"), (44, "1")];
let r = open(&drawing(&[], &[], &blocks, &top), &points());
assert!(r.warnings.iter().any(|w| w.contains("more than")), "{:?}", r.warnings);
assert!(r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings);
}
#[test]
@@ -1177,3 +1177,173 @@ fn many_array_inserts_of_a_missing_block_stay_bounded() {
assert!(total <= 2_000_000 + 3000, "total cells materialised: {total}");
assert!(conv.warnings.iter().any(|w| w.contains("array inserts")), "{:?}", conv.warnings);
}
#[test]
fn dashed_lines_past_the_dash_budget_are_drawn_solid() {
// 600 lines of a two-length linetype: 1,200 dash lengths, past the 1,000 tests import with.
let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")];
let line = [(0, "LINE"), (6, "DASHED"), (10, "0"), (20, "0"), (11, "100"), (21, "0")];
let e: Vec<(i32, &str)> = (0..600).flat_map(|_| line).collect();
let r = open(&drawing(&[], &tables, &[], &e), &points());
let (mut dashed, mut solid, mut kept) = (0, 0, 0);
r.document.walk(|n| {
if let NodeKind::Path { .. } = n.kind {
match n.appearance.stroke().and_then(|s| s.dash.as_ref()) {
Some(d) => {
dashed += 1;
kept += d.pattern.len();
}
None => solid += 1,
}
}
});
assert_eq!(dashed + solid, 600);
assert!(dashed > 0 && solid > 0, "{dashed} dashed, {solid} solid");
assert!(kept <= 1_000, "{kept} dash lengths kept");
assert!(r.warnings.iter().any(|w| w.contains("drawn solid")), "{:?}", r.warnings);
}
/// The bytes of text in the document's text objects.
fn text_bytes(doc: &Document) -> usize {
let mut bytes = 0;
doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
bytes += t.runs.iter().map(|r| r.text.len()).sum::<usize>();
}
});
bytes
}
#[test]
fn text_copied_into_array_cells_stops_at_the_text_budget() {
// 1,000 characters of text in an anonymous block placed 10 × 10: 100 KB of copies, past the
// 64 KB tests import with.
let long = "x".repeat(1000);
let blocks =
[(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0"), (0, "TEXT"), (10, "0"), (20, "0"), (40, "1"), (1, long.as_str()), (0, "ENDBLK")];
let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "10"), (71, "10"), (44, "1"), (45, "1")];
let r = open(&drawing(&[], &[], &blocks, &insert), &points());
let bytes = text_bytes(&r.document);
assert!(bytes > 0, "some copies are kept");
assert!(bytes <= 64 << 10, "{bytes} bytes of text");
assert!(r.warnings.iter().any(|w| w.contains("64 MB of text")), "{:?}", r.warnings);
}
#[test]
fn a_text_style_naming_an_overlong_font_family_takes_the_default() {
let family = "F".repeat(10_000);
let tables = [(0, "TABLE"), (2, "STYLE"), (0, "STYLE"), (2, "Big"), (3, "x.ttf"), (1001, "ACAD"), (1000, family.as_str()), (0, "ENDTAB")];
let e = [(0, "TEXT"), (10, "0"), (20, "0"), (40, "1"), (1, "Hi"), (7, "Big")];
let doc = open(&drawing(&[], &tables, &[], &e), &points()).document;
let mut families = vec![];
doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
families.extend(t.runs.iter().map(|r| r.style.font_family.clone()));
}
});
assert_eq!(families, [vectorcraft_doc::CharStyle::default().font_family]);
}
#[test]
fn symbol_instances_of_a_long_block_name_stop_at_the_text_budget() {
// A 1,000-byte block name placed 10 × 10: each instance keeps its own copy of the name.
let name = "N".repeat(1000);
let blocks = [(0, "BLOCK"), (2, name.as_str()), (10, "0"), (20, "0"), (0, "LINE"), (10, "0"), (20, "0"), (11, "1"), (21, "0"), (0, "ENDBLK")];
let insert = [(0, "INSERT"), (2, name.as_str()), (10, "0"), (20, "0"), (70, "10"), (71, "10"), (44, "2"), (45, "2")];
let r = open(&drawing(&[], &[], &blocks, &insert), &points());
let mut instances = 0;
r.document.walk(|n| {
if let NodeKind::SymbolInstance { .. } = n.kind {
instances += 1;
}
});
assert!(instances > 0 && instances < 100, "{instances} instances");
assert!(r.warnings.iter().any(|w| w.contains("64 MB of text")), "{:?}", r.warnings);
}
#[test]
fn arrays_of_blocks_of_hidden_art_stop_at_the_work_budget() {
// 500 lines on a hidden layer in an anonymous block placed 50 × 50: they make nothing, but
// each placement looks at all of them (1,250,000 items, past the 1,000,000 tests import with).
let tables = [(0, "TABLE"), (2, "LAYER"), (0, "LAYER"), (2, "Off"), (70, "0"), (62, "-1"), (0, "ENDTAB")];
let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")];
for _ in 0..500 {
blocks.extend([(0, "LINE"), (8, "Off"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]);
}
blocks.push((0, "ENDBLK"));
let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "50"), (71, "50"), (44, "1"), (45, "1")];
let r = open(&drawing(&[], &tables, &blocks, &insert), &points());
assert!(r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings);
}
#[test]
fn dashed_compound_paths_charge_every_copy_of_their_pattern() {
// 100 pattern hatches of 9 loops in a two-length linetype: each keeps its dashes on the
// compound path and on each loop, 2,000 dash lengths, past the 1,000 tests import with.
let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")];
let corners = ["0", "10", "20", "30", "40", "50", "60", "70", "80", "90"];
let mut hatch = vec![(0, "HATCH"), (6, "DASHED"), (10, "0"), (20, "0"), (30, "0"), (2, "ANSI31"), (70, "0"), (71, "0"), (91, "9")];
for i in 0..9 {
let (a, b) = (corners[i], corners[i + 1]);
hatch.extend([
(92, "2"),
(72, "0"),
(73, "1"),
(93, "4"),
(10, a),
(20, "0"),
(10, b),
(20, "0"),
(10, b),
(20, "5"),
(10, a),
(20, "5"),
(97, "0"),
]);
}
hatch.extend([(75, "0"), (76, "1"), (98, "0")]);
let e: Vec<(i32, &str)> = (0..100).flat_map(|_| hatch.iter().copied()).collect();
let r = open(&drawing(&[], &tables, &[], &e), &points());
let (mut compounds, mut kept) = (0, 0);
r.document.walk(|n| {
compounds += usize::from(matches!(n.kind, NodeKind::Compound { .. }));
kept += n.appearance.stroke().and_then(|s| s.dash.as_ref()).map_or(0, |d| d.pattern.len());
});
assert_eq!(compounds, 100, "{:?}", r.warnings);
assert!(kept > 0 && kept <= 1_000, "{kept} dash lengths kept");
assert!(r.warnings.iter().any(|w| w.contains("drawn solid")), "{:?}", r.warnings);
}
#[test]
fn symbols_of_a_long_block_name_stop_at_the_text_budget() {
// A 1,000-byte block name inserted in 100 colours its art takes: a symbol per colour, each
// keeping its own copy of the name, past the 64 KB tests import with.
let name = "N".repeat(1000);
let blocks = [
(0, "BLOCK"),
(2, name.as_str()),
(10, "0"),
(20, "0"),
(0, "LINE"),
(8, "0"),
(62, "0"),
(10, "0"),
(20, "0"),
(11, "1"),
(21, "0"),
(0, "ENDBLK"),
];
let colours: Vec<String> = (1..=100).map(|c| c.to_string()).collect();
let inserts: Vec<(i32, &str)> =
colours.iter().flat_map(|c| [(0, "INSERT"), (2, name.as_str()), (62, c.as_str()), (10, "0"), (20, "0")]).collect();
let r = open(&drawing(&[], &[], &blocks, &inserts), &points());
let mut bytes: usize = r.document.symbols.iter().map(|s| s.name.len()).sum();
r.document.walk(|n| {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
bytes += symbol.len();
}
});
assert!(!r.document.symbols.is_empty());
assert!(bytes <= 64 << 10, "{bytes} bytes of symbol names");
assert!(r.warnings.iter().any(|w| w.contains("64 MB of text")), "{:?}", r.warnings);
}
+92 -11
View File
@@ -271,7 +271,11 @@ const MAX_ENTITIES: u32 = 10_000_000;
/// The largest x or y a path may have to be flattened, and the most points its polygons keep.
const MAX_COORD: f64 = 1e9;
const MAX_POINTS: usize = 4_000_000;
const MAX_POINTS: usize = if cfg!(test) { 100_000 } else { 4_000_000 };
/// The most segments flattening one path makes, kept or not (repeats of a point are dropped).
const MAX_FLATTEN_SEGMENTS: usize = 4 * MAX_POINTS;
const SYMBOLS_LEFT_OUT: &str = "symbols placed inside symbols hold too many objects for DXF: the instances past that were left out";
/// Do the dashes of `d` start at the start of their pattern, as a linetype's do? A pattern of
/// odd length repeats twice in its linetype.
@@ -296,14 +300,19 @@ fn polygons(bp: &BezPath) -> Vec<Vec<Point>> {
}
let mut out: Vec<Vec<Point>> = vec![];
let mut cur: Vec<Point> = vec![];
let mut points = 0usize;
let mut push = |p: Point, cur: &mut Vec<Point>| {
if points < MAX_POINTS && cur.last().is_none_or(|q| q.distance(p) > 1e-9) {
points += 1;
// Points kept, and segments made: once either budget is spent, no further curve is flattened.
let points = std::cell::Cell::new(0usize);
let segments = std::cell::Cell::new(0usize);
let push = |p: Point, cur: &mut Vec<Point>| {
segments.set(segments.get() + 1);
if points.get() < MAX_POINTS && cur.last().is_none_or(|q| q.distance(p) > 1e-9) {
points.set(points.get() + 1);
cur.push(p);
}
};
kurbo::flatten(bp.iter(), FLATNESS, |el| match el {
let elements = bp.iter().take_while(|_| points.get() < MAX_POINTS && segments.get() < MAX_FLATTEN_SEGMENTS);
// Each curve is flattened into a bounded number of segments, however large it is.
vectorcraft_geom::flatten(elements, FLATNESS, |el| match el {
PathEl::MoveTo(p) => {
out.push(std::mem::take(&mut cur));
push(p, &mut cur);
@@ -412,6 +421,9 @@ pub(crate) struct Scene<'a> {
opacity: f32,
/// Symbols and brush art being written inside one another.
nest: u32,
/// Objects the symbol instances written held, together
/// ([`vectorcraft_doc::MAX_SYMBOL_NODES`]).
symbol_nodes: u64,
}
impl<'a> Scene<'a> {
@@ -441,6 +453,8 @@ impl<'a> Scene<'a> {
extents: None,
opacity: 1.0,
nest: 0,
// Tests spend all but a million of it up front.
symbol_nodes: if cfg!(test) { vectorcraft_doc::MAX_SYMBOL_NODES - 1_000_000 } else { 0 },
}
}
@@ -542,13 +556,36 @@ impl<'a> Scene<'a> {
NodeKind::Text(t) => self.text(n, t),
NodeKind::Image(im) => self.image(im),
NodeKind::SymbolInstance { symbol, xf } => {
if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol)
let doc = self.doc;
if self.symbol_nodes >= vectorcraft_doc::MAX_SYMBOL_NODES {
// Spent: no more instances are looked at, so what's left costs nothing.
self.warn(SYMBOLS_LEFT_OUT);
} else if let Some(sym) = doc.symbols.iter().find(|s| &s.name == symbol)
&& self.nest < MAX_NEST
&& let Some(art) = self.doc.place_symbol_art_unclipped(symbol, &vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n), *xf)
{
self.nest += 1;
self.node(&art, true);
self.nest -= 1;
// Symbols holding instances of symbols are written in full for each instance,
// empty or not: every instance's art counts against one budget for the export.
let art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n);
let count = art.count_with_masks() as u64;
// Counted as `place_symbol_art_unclipped` places it: no clip groups.
let most = doc.symbol_slice_map(symbol, *xf).map_or(count, |m| m.most_placed_unclipped(&art, doc));
let placed = vectorcraft_doc::charge_symbol_art(&mut self.symbol_nodes, most, || {
let placed = doc.place_symbol_art_unclipped(symbol, &art, *xf);
let n = placed.as_ref().map_or(0, |a| a.count_with_masks() as u64);
(placed, n)
});
match placed {
Some(Some(art)) => {
self.nest += 1;
self.node(&art, true);
self.nest -= 1;
}
Some(None) => {}
None => {
self.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES;
self.warn(SYMBOLS_LEFT_OUT);
}
}
}
}
// Live blends, envelopes, meshes and repeats are written as their evaluated art.
@@ -1262,3 +1299,47 @@ fn first_solid(n: &Node) -> Option<vectorcraft_color::Color> {
});
own.or_else(|| n.children().into_iter().flatten().find_map(|c| first_solid(c)))
}
#[cfg(test)]
mod budget_tests {
use super::*;
#[test]
fn flattening_a_path_of_huge_curves_stops_at_its_budget() {
// Each curve, a hundred million points across, flattens to thousands of segments at
// FLATNESS; a small square after them is past the budget and left out.
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
for i in 0..20_000 {
let y = if i % 2 == 0 { 1e8 } else { -1e8 };
bp.curve_to((1e8, y), (-1e8, y), (0.0, 0.0));
}
bp.move_to((10.0, 10.0));
bp.line_to((20.0, 10.0));
bp.line_to((20.0, 20.0));
bp.close_path();
let polys = polygons(&bp);
let points: usize = polys.iter().map(Vec::len).sum();
assert!(points <= MAX_POINTS, "{points} points");
assert!(!polys.iter().any(|p| p.contains(&Point::new(20.0, 20.0))), "the square past the budget is left out");
}
#[test]
fn flattening_a_path_of_repeated_points_stops_at_its_segment_budget() {
// Repeats of a point are dropped, so these keep one point but still count as segments:
// the segment budget, not the point budget, leaves out the square after them.
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
for _ in 0..MAX_FLATTEN_SEGMENTS {
bp.line_to((0.0, 0.0));
}
bp.move_to((10.0, 10.0));
bp.line_to((20.0, 10.0));
bp.line_to((20.0, 20.0));
bp.close_path();
let polys = polygons(&bp);
let points: usize = polys.iter().map(Vec::len).sum();
assert!(points < MAX_POINTS, "{points} points");
assert!(!polys.iter().any(|p| p.contains(&Point::new(20.0, 20.0))), "the square past the budget is left out");
}
}
+19
View File
@@ -1007,3 +1007,22 @@ fn crop_keeps_an_instance_whose_art_reaches_the_region() {
let o = DxfOptions { crop: true, ..opts(&d) };
assert!(!kinds(&export(&d, &o).unwrap()).is_empty());
}
#[test]
fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() {
// Five levels of 100 instances of the level below, ending in an empty symbol: 10^10 empty
// instances, which write no entities, past the million objects tests export with.
let mut d = doc_with(|d| vec![Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "L5".into(), xf: Affine::IDENTITY })]);
let empty = Node::group(d.alloc_id(), vec![]);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "L0".into(), art: Arc::new(empty) });
for level in 1..=5 {
let below = format!("L{}", level - 1);
let children =
(0..100).map(|_| Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: below.clone(), xf: Affine::IDENTITY }))).collect();
let art = Node::group(d.alloc_id(), children);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("L{level}"), art: Arc::new(art) });
}
let out = export(&d, &opts(&d)).unwrap();
assert!(entities(&out).is_empty());
assert!(out.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", out.warnings);
}
+23
View File
@@ -106,6 +106,12 @@ impl IccProfile {
if !localized_text_fits(bytes) {
return Err(CmsError::BadProfile(format!("its localized names take more than {} KB", MAX_LOCALIZED_TEXT >> 10)));
}
if let Some(tag) = repeated_tag(bytes) {
return Err(CmsError::BadProfile(format!(
"its tag table lists the `{}` tag more than once",
String::from_utf8_lossy(&tag.to_be_bytes())
)));
}
let p = ColorProfile::new_from_slice(bytes).map_err(|e| CmsError::BadProfile(format!("{e:?}")))?;
Ok(Self { source: bytes.to_vec(), ..Self::from_profile(name, p)? })
}
@@ -417,6 +423,23 @@ pub(super) fn gray_profile(name: &str) -> ColorProfile {
labelled(p, name)
}
/// The first tag signature the tag table of ICC `bytes` lists twice, which the ICC
/// specification forbids. moxcms parses every entry of the table, so a profile listing one
/// description, copyright or table tag thousands of times, each pointing at the same large data,
/// would decode and copy that data once per entry. A table it can't read is left to moxcms.
pub(crate) fn repeated_tag(bytes: &[u8]) -> Option<u32> {
let be32 = |at: usize| bytes.get(at..at.checked_add(4)?).map(|v| u32::from_be_bytes([v[0], v[1], v[2], v[3]]));
let tags = be32(128)? as usize;
let mut seen = std::collections::HashSet::new();
for i in 0..tags {
let sig = be32(i.checked_mul(12)?.checked_add(132)?)?;
if !seen.insert(sig) {
return Some(sig);
}
}
None
}
/// Most bytes of UTF-16 the localized names (`mluc` tags) of a profile may take together.
const MAX_LOCALIZED_TEXT: usize = 1 << 20;
+26
View File
@@ -181,6 +181,32 @@ fn aliased_localized_names_are_refused() {
assert!(!super::icc::localized_text_fits(&profile(4096, 64 << 10)));
}
/// A tag table that lists one tag many times, every entry pointing at the same long text, is
/// refused before moxcms decodes the text once per entry; distinct tags pass.
#[test]
fn repeated_tags_are_refused() {
let profile = |sigs: &[&[u8; 4]], text: usize| {
let mut b = vec![0u8; 128];
b.extend((sigs.len() as u32).to_be_bytes());
let tag_at = 128 + 4 + 12 * sigs.len();
let size = 8 + text;
for sig in sigs {
b.extend(*sig);
b.extend((tag_at as u32).to_be_bytes());
b.extend((size as u32).to_be_bytes());
}
b.extend(b"text");
b.extend([0; 4]);
b.extend(vec![b'a'; text]);
b
};
assert_eq!(super::icc::repeated_tag(&profile(&[b"desc", b"cprt", b"dmdd"], 64)), None);
let many: Vec<&[u8; 4]> = std::iter::repeat_n(b"desc", 4096).collect();
let bytes = profile(&many, 256 << 10);
assert_eq!(super::icc::repeated_tag(&bytes), Some(u32::from_be_bytes(*b"desc")));
assert!(matches!(super::icc::IccProfile::from_bytes(None, &bytes), Err(super::CmsError::BadProfile(_))));
}
/// Reloading an RGB profile under the name it had (a new file for "My RGB") changes what CMYK
/// converts to in it: the direct CMYK → RGB transform isn't kept from the old file.
#[test]
+51 -3
View File
@@ -175,6 +175,40 @@ fn between(a: &GradientStop, b: &GradientStop, t: f32, mix: &impl Fn(&Color, &Co
(mix(&a.color, &b.color, v), a.opacity + (b.opacity - a.opacity) * v)
}
/// For each pair of neighbouring stops (`k`, `k + 1`), the largest offset among stops `1..=k + 1`.
/// [`Gradient::sample_with`] picks the first pair whose end offset `t` doesn't pass; that is the
/// first pair whose reach `t` doesn't pass, and the reaches never decrease, so the pair is found by
/// binary search whether or not the stops are in order.
struct StopReach(Vec<f32>);
impl StopReach {
fn new(stops: &[GradientStop]) -> Self {
// `f32::max` skips a NaN offset, which `t <= offset` never chooses either.
let reach = stops.iter().skip(1).scan(f32::NEG_INFINITY, |m, s| {
*m = m.max(s.offset);
Some(*m)
});
Self(reach.collect())
}
/// What [`Gradient::sample_with`] gives at `t` for `stops`, the stops this was built from.
fn sample_with(&self, stops: &[GradientStop], t: f32, mix: &impl Fn(&Color, &Color, f32) -> Color) -> (Color, f32) {
let Some(first) = stops.first() else { return (Color::BLACK, 1.0) };
if t <= first.offset {
return (first.color, first.opacity);
}
let last = || stops.last().map_or((Color::BLACK, 1.0), |l| (l.color, l.opacity));
if t.is_nan() {
return last();
}
let k = self.0.partition_point(|r| *r < t);
match (stops.get(k), stops.get(k + 1)) {
(Some(a), Some(b)) => between(a, b, t, mix),
_ => last(),
}
}
}
fn one() -> f32 {
1.0
}
@@ -211,6 +245,12 @@ impl Gradient {
pub fn sample(&self, t: f32) -> (Color, f32) {
self.sample_with(t, |a, b, v| self.method.mix(a, b, v))
}
/// [`Self::sample`] for many points in no order (a gradient drawn pixel by pixel): the stops
/// are prepared once, so each sample costs a binary search rather than a scan of the stops.
pub fn sampler(&self) -> impl Fn(f32) -> (Color, f32) + '_ {
let reach = StopReach::new(&self.stops);
move |t| reach.sample_with(&self.stops, t, &|a, b, v| self.method.mix(a, b, v))
}
/// [`Self::sample`], a Classic gradient's neighbouring stop colours of one model mixed in it
/// (CMYK stays CMYK; [`Color::lerp_keep_model`]) rather than in display RGB, a Perceptual
/// gradient's as [`Self::sample`] mixes them.
@@ -245,9 +285,11 @@ impl Gradient {
/// the one before it stopped, so the work is the samples plus the stops, not their product.
pub fn sample_increasing_with(&self, ts: impl IntoIterator<Item = f32>, mix: impl Fn(&Color, &Color, f32) -> Color) -> Vec<(Color, f32)> {
let stops = &self.stops;
// The shared index assumes ordered stops; others (a file's, unsorted) sample one by one.
// The shared cursor assumes ordered stops; others (a file's, unsorted) look each sample up
// in a [`StopReach`], so they cost a binary search each rather than a scan of the stops.
if stops.windows(2).any(|w| w[1].offset < w[0].offset) {
return ts.into_iter().map(|t| self.sample_with(t, &mix)).collect();
let reach = StopReach::new(stops);
return ts.into_iter().map(|t| reach.sample_with(stops, t, &mix)).collect();
}
let mut j = 0;
ts.into_iter()
@@ -284,6 +326,9 @@ impl Gradient {
fn expanded_with_stops(&self) -> impl Iterator<Item = (f32, Color, f32, Option<f32>, Option<usize>)> + '_ {
// Direct interpolation matches `sample` only for strictly increasing offsets.
let increasing = self.stops.windows(2).all(|w| w[0].offset < w[1].offset);
// Otherwise (repeated or unsorted offsets) each midpoint is looked up as `sample` would
// find it, but by binary search: a scan of all the stops per midpoint cost their square.
let reach = if increasing || !self.method.is_classic() { None } else { Some(StopReach::new(&self.stops)) };
self.stops.iter().enumerate().flat_map(move |(i, s)| {
let next = self.stops.get(i + 1);
let off_centre = (s.midpoint - 0.5).abs() > 1e-3;
@@ -293,7 +338,10 @@ impl Gradient {
// Mixed from the two stops it lies between, as `sample` would: searching all the
// stops again for each midpoint made many stops cost their square.
let mix = |a: &Color, b: &Color, v| self.method.mix(a, b, v);
let (c, o) = if increasing { between(s, n, t, &mix) } else { self.sample_with(t, mix) };
let (c, o) = match &reach {
Some(reach) => reach.sample_with(&self.stops, t, &mix),
None => between(s, n, t, &mix),
};
(t, c, o, Some(s.midpoint), None)
});
// Perceptual: stops along the mix (`v`) where a straight line would stray from it, the
+58
View File
@@ -23,6 +23,64 @@ fn increasing_samples_match_single_samples() {
assert_eq!(g.sample_increasing_with(ts, Color::lerp_keep_model), one_by_one);
}
/// The prepared sampler gives what sampling each position alone does, out-of-order stops included.
#[test]
fn the_sampler_matches_single_samples() {
let stop = |offset: f32, hex: &str| GradientStop::new(offset, Color::from_hex(hex).unwrap());
let g = Gradient::new(
GradientKind::Linear,
vec![stop(0.1, "#ff0000"), stop(0.4, "#00ff00"), stop(0.4, "#0000ff"), stop(0.2, "#ffff00"), stop(0.9, "#000000")],
);
let sample = g.sampler();
for k in (0..=40).rev() {
let t = k as f32 / 40.0;
assert_eq!(sample(t), g.sample(t), "{t}");
}
}
/// Looking stops up by their reach finds what scanning them does, for any order of offsets,
/// repeated, out-of-order and NaN ones included, and for positions outside and between them.
#[test]
fn stop_reach_matches_scanning_the_stops() {
let colors = ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#00ffff", "#000000"];
let offsets: [&[f32]; 5] = [
&[0.1, 0.4, 0.4, 0.2, 0.9, 0.5],
&[0.5, 0.5, 0.5, 0.5],
&[0.9, 0.1, 0.8, 0.2, 0.7, 0.3],
&[0.2, f32::NAN, 0.6, 0.1, f32::NAN, 1.0],
&[f32::NAN, 0.3, 0.3, 0.8],
];
for offsets in offsets {
let stops: Vec<GradientStop> = offsets
.iter()
.zip(colors.iter().cycle())
.map(|(&o, hex)| GradientStop { midpoint: 0.3, ..GradientStop::new(o, Color::from_hex(hex).unwrap()) })
.collect();
let g = Gradient::new(GradientKind::Linear, stops);
let reach = StopReach::new(&g.stops);
for t in (-4..=44).map(|k| k as f32 / 40.0).chain([f32::NAN, f32::INFINITY, f32::NEG_INFINITY]) {
// Compared as printed: a NaN offset mixes NaN colours, which are equal only so.
let (got, want) = (reach.sample_with(&g.stops, t, &Color::lerp_keep_model), g.sample_with(t, Color::lerp_keep_model));
assert_eq!(format!("{got:?}"), format!("{want:?}"), "{offsets:?} at {t}");
}
}
}
/// Repeated offsets turn off the direct midpoint mix, and the midpoints still come out as
/// `sample` gives them, with work that stays near linear in the stops (thousands of stops at one
/// offset used to scan them all for each midpoint).
#[test]
fn expanded_with_repeated_offsets_samples_midpoints() {
let stop = |offset: f32, hex: &str| GradientStop { midpoint: 0.25, ..GradientStop::new(offset, Color::from_hex(hex).unwrap()) };
let g = Gradient::new(GradientKind::Linear, vec![stop(0.0, "#ff0000"), stop(0.5, "#00ff00"), stop(0.5, "#0000ff"), stop(1.0, "#000000")]);
for (t, c, o, mid) in g.expanded().filter(|e| e.3.is_some()) {
assert_eq!(mid, Some(0.25));
assert_eq!((c, o), g.sample(t), "midpoint at {t}");
}
let many = Gradient::new(GradientKind::Linear, (0..200_000).map(|i| stop(if i == 0 { 0.0 } else { 0.5 }, "#808080")).collect());
assert_eq!(many.expanded().count(), 2 * 200_000 - 1);
}
#[test]
fn midpoint_shifts() {
let mut g = Gradient::default();
+10 -1
View File
@@ -433,10 +433,11 @@ pub fn cluster(colors: &[Color], weights: &[f32], n: usize) -> Vec<Vec<usize>> {
.collect();
let w = |i: usize| weights.get(i).copied().unwrap_or(1.0).max(1e-6);
let d2 = |a: &[f32; 3], b: &[f32; 3]| (a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2);
let n = n.max(1);
if pts.is_empty() {
return vec![];
}
// No more rows than colours: each colour seeds one at most.
let n = n.clamp(1, pts.len());
// Seeds: the heaviest colour, then each time the one farthest from every seed so far.
let first = (0..pts.len()).fold(0, |best, i| if w(i) > w(best) { i } else { best });
let mut centres = vec![pts[first]];
@@ -447,6 +448,8 @@ pub fn cluster(colors: &[Color], weights: &[f32], n: usize) -> Vec<Vec<usize>> {
break;
}
centres.push(pts[i]);
// Picked: a colour whose distances aren't finite (an infinite coordinate) stays farthest.
near[i] = 0.0;
for (j, p) in pts.iter().enumerate() {
near[j] = near[j].min(d2(p, &pts[i]));
}
@@ -670,6 +673,12 @@ mod tests {
assert!(matches!(shaded(lab[0], 0.5), Color::Lab { .. }));
}
#[test]
fn clustering_seeds_each_colour_once_even_unbounded() {
let colors = [Color::lab(f32::INFINITY, 0.0, 0.0), Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)];
assert!(cluster(&colors, &[], usize::MAX).len() <= colors.len());
}
#[test]
fn clustering_reduces_to_n_rows_of_similar_colours() {
let colors =
+46
View File
@@ -862,6 +862,52 @@ impl Spine {
pub fn anchor_length(&self, i: usize) -> Option<f64> {
self.anchors.get(i).copied()
}
/// Arc length of the point of the spine nearest `p`. An open spine's end segments run on past
/// its ends as lines, so the result is below 0 before the start and above [`Spine::length`]
/// beyond the end. With `from`, the arc length of an earlier point a drag followed, each point
/// counts as farther by half its distance along the spine from there, so a pointer passing
/// near another part of the spine stays on the part it follows. Where two points count as
/// near as each other, the one earlier along the spine counts.
pub fn length_near(&self, p: Point, from: Option<f64>) -> f64 {
self.nearest(p, from).map_or(0.0, |(_, s)| s)
}
/// [`Spine::length_near`] with how near the point counts: its distance from `p`, plus half its
/// distance along the spine from `from`. `None` for a point that is not finite.
pub fn nearest(&self, p: Point, from: Option<f64>) -> Option<(f64, f64)> {
if !p.x.is_finite() || !p.y.is_finite() {
return None;
}
let last = self.pts.len().saturating_sub(2);
let mut best: Option<(f64, f64)> = None;
for (i, (w, c)) in self.pts.windows(2).zip(&self.cum).enumerate() {
let [a, b] = [w[0], w[1]];
let d = b - a;
let l2 = d.dot(d);
if !l2.is_finite() || l2 <= 0.0 {
continue;
}
let t = (p - a).dot(d) / l2;
let t = match (self.closed, i == 0, i == last) {
(false, true, true) => t,
(false, true, false) => t.min(1.0),
(false, false, true) => t.max(0.0),
_ => t.clamp(0.0, 1.0),
};
let s = c + t * l2.sqrt();
let dist = p.distance(a + d * t) + from.filter(|f| f.is_finite()).map_or(0.0, |f| self.apart(s, f) / 2.0);
if dist.is_finite() && best.is_none_or(|(b, _)| dist < b) {
best = Some((dist, s));
}
}
best
}
/// How far apart arc lengths `s` and `f` are along the spine: the shorter way round a closed
/// spine, across its first anchor.
pub fn apart(&self, s: f64, f: f64) -> f64 {
let len = self.length();
let d = (s - f).abs();
if self.closed && len > 0.0 { d.rem_euclid(len).min(len - d.rem_euclid(len)) } else { d }
}
/// Point and tangent angle (radians) at arc-length fraction `f` (0..1).
pub fn at(&self, f: f64) -> (Point, f64) {
self.at_length(f.clamp(0.0, 1.0) * self.length())
+35 -10
View File
@@ -107,15 +107,21 @@ fn nested_deeper(now: &[Arc<Node>], depth: usize) -> bool {
/// an opacity mask too deep are left out); what it held stays hidden or locked as it was. Returns
/// whether anything changed. Recurses no deeper than the cap.
fn limit(nodes: &mut Vec<Arc<Node>>, depth: usize) -> bool {
let mut changed = false;
let mut i = 0;
while let Some(n) = nodes.get_mut(i) {
if !nested_deeper(std::slice::from_ref(n), depth) {
i += 1;
if !nested_deeper(nodes, depth) {
return false;
}
// The list is rebuilt in order rather than spliced in place: replacing one container of many
// by what it holds would move all the siblings after it each time.
let mut out = Vec::with_capacity(nodes.len());
// What is left to look at, the next one last.
let mut left: Vec<Arc<Node>> = std::mem::take(nodes);
left.reverse();
while let Some(mut a) = left.pop() {
if !nested_deeper(std::slice::from_ref(&a), depth) {
out.push(a);
continue;
}
changed = true;
let n = Arc::make_mut(n);
let n = Arc::make_mut(&mut a);
if n.extras().mask.as_ref().is_some_and(|m| nested_deeper(std::slice::from_ref(&m.art), depth + 1)) {
n.extras_mut().mask = None;
}
@@ -123,7 +129,7 @@ fn limit(nodes: &mut Vec<Arc<Node>>, depth: usize) -> bool {
if let Some(ch) = n.children_mut() {
limit(ch, depth + 1);
}
i += 1;
out.push(a);
continue;
}
let clip = matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. });
@@ -140,9 +146,10 @@ fn limit(nodes: &mut Vec<Arc<Node>>, depth: usize) -> bool {
}
}
// What it held takes its place, and is looked at in its turn.
nodes.splice(i..=i, held);
left.extend(held.into_iter().rev());
}
changed
*nodes = out;
true
}
/// A symbol (`false`) or a pattern (`true`) of the document, by name: what art draws by name, an
@@ -439,6 +446,24 @@ mod tests {
}
}
#[test]
fn many_containers_at_the_cap_are_merged_in_order() {
// A group just above the cap holding many groups of two paths each: every group is
// replaced by its two paths, in order (in time linear in their number).
const PAIRS: u64 = 50_000;
let path = |id| Arc::new(Node::path(NodeId(id), Default::default(), Default::default()));
let pairs = (0..PAIRS).map(|i| Arc::new(Node::group(NodeId(1_000_000 + i), vec![path(2 * i + 1), path(2 * i + 2)]))).collect();
let mut art = Arc::new(Node::group(NodeId(500_000), pairs));
for i in 0..MAX_DEPTH - 3 {
art = Arc::new(Node::group(NodeId(600_000 + i as u64), vec![art]));
}
let mut d = doc(art);
assert!(d.limit_depth());
assert!(!d.too_deep(None));
let holder = d.node(NodeId(500_000)).and_then(Node::children).map(|c| c.iter().map(|c| c.id.0).collect::<Vec<_>>());
assert_eq!(holder, Some((1..=2 * PAIRS).collect()));
}
#[test]
fn a_clipping_path_and_a_mask_too_deep_are_left_out_and_hidden_art_stays_hidden() {
let mut inner = Node::new(NodeId(9000), NodeKind::Group { children: vec![nested(0), nested(0)], clip: true });
+108 -2
View File
@@ -2,8 +2,8 @@ use super::graphic_style::GraphicStyle;
use super::limits::MAX_NEXT_ID;
use super::records::{ImageBlob, SavedSelection, SavedView};
use super::{
Arc, Document, ImageObject, Node, NodeKind, SYMBOL_EXPORT_TYPE, SYMBOL_NINE_SLICE, SYMBOL_REGISTRATION, SymbolExportType, SymbolNineSlice,
SymbolRegistration,
Arc, Document, EnvelopeKind, ImageObject, LiveShape, Node, NodeKind, Point, SYMBOL_EXPORT_TYPE, SYMBOL_NINE_SLICE, SYMBOL_REGISTRATION,
SymbolExportType, SymbolNineSlice, SymbolRegistration, placed_document,
};
impl Document {
@@ -120,6 +120,112 @@ impl Document {
d.drop_edit_modes();
std::borrow::Cow::Owned(d)
}
/// 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
/// edited included), opacity masks and the brushes kept as foreign data. Colors, transforms,
/// opacity, live shapes' own sizes, meshes and type (its frames and paths included) are left
/// as they are.
pub fn round_geometry(&mut self, decimals: u8) {
let scale = 10f64.powi(i32::from(decimals));
let round = |v: f64| {
let r = (v * scale).round() / scale;
if !r.is_finite() {
v
} else if r == 0.0 {
// `-0.0` is written as `0.0`.
0.0
} else {
r
}
};
let round_path = |path: &mut vectorcraft_geom::PathData| {
for a in path.subpaths.iter_mut().flat_map(|s| s.anchors.iter_mut()) {
for p in [&mut a.p, &mut a.h_in, &mut a.h_out] {
*p = Point::new(round(p.x), round(p.y));
}
}
};
let mut fix = |n: &mut Node| {
match &mut n.kind {
NodeKind::Path { path, live, .. } => {
round_path(path);
// Live Corners' uncut outline.
if let Some(LiveShape::Path { base, .. }) = live.as_deref_mut() {
round_path(base);
}
}
NodeKind::Blend { spec, .. } => {
if let Some(spine) = &mut spec.spine {
round_path(spine);
}
}
NodeKind::Envelope { kind, .. } => {
if let EnvelopeKind::TopObject { path } = kind.as_mut() {
round_path(path);
}
}
_ => {}
}
if let Some(e) = n.extras_if_any() {
for area in e.intertwine.as_deref_mut().into_iter().chain(e.intertwine_tiers.iter_mut()) {
round_path(area);
}
}
};
let roots = self
.layers
.iter_mut()
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
for root in roots {
placed_document::each_mut(Arc::make_mut(root), &mut fix);
}
if self.unknown.contains_key("brushes")
&& let Some(brushes) = self.unknown.get_mut("brushes")
{
round_json_paths(brushes, &round);
}
}
}
/// 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.
fn round_json_paths(v: &mut serde_json::Value, round: &impl Fn(f64) -> f64) {
use serde_json::Value;
match v {
Value::Object(o) => {
if o.get("type").and_then(Value::as_str) == Some("text") {
return;
}
if let Some(subpaths) = o.get_mut("subpaths").and_then(Value::as_array_mut) {
let anchors = subpaths.iter_mut().filter_map(|s| s.get_mut("anchors").and_then(Value::as_array_mut)).flatten();
for a in anchors.filter_map(Value::as_object_mut) {
let points = a.iter_mut().filter(|(k, _)| matches!(k.as_str(), "p" | "in" | "out")).filter_map(|(_, v)| v.as_array_mut());
for xy in points {
for n in xy.iter_mut().filter(|n| n.is_f64()) {
if let Some(r) = n.as_f64().and_then(|x| serde_json::Number::from_f64(round(x))) {
*n = Value::Number(r);
}
}
}
}
}
for c in o.values_mut() {
round_json_paths(c, round);
}
}
Value::Array(a) => {
for c in a {
round_json_paths(c, round);
}
}
_ => {}
}
}
/// Graphic styles.
+77 -16
View File
@@ -577,7 +577,41 @@ fn may_hit(parent: &Node, i: usize, c: &Node, p: Point, opt: HitOptions, symbols
// (An envelope's content sits where it was, not where the envelope draws it.)
edits_contents(c)
|| c.extras().shaper.is_some() && source_of(c, opt.scope)
|| c.reach_bounds_with(symbols).is_none_or(|b| b.inflate(opt.tol, opt.tol).contains(p))
|| cull_reach(c, symbols).is_none_or(|b| b.inflate(opt.tol, opt.tol).contains(p))
}
/// A box round everything `c` can paint, for culling clicks: [`Node::reach_bounds_with`], except
/// that paths and compound paths are measured by their control points ([`PathData::control_bounds`],
/// which hold the curves) instead of along their curves, which a compound path of thousands of
/// members takes milliseconds to do on every click and hover. The box only rules points out, and it
/// is at least as large, so the same objects are hit.
///
/// [`PathData::control_bounds`]: vectorcraft_geom::PathData::control_bounds
fn cull_reach(c: &Node, symbols: &SymbolBoxes) -> Option<Rect> {
let control = match &c.kind {
NodeKind::Path { path, .. } => path.control_bounds(),
NodeKind::Compound { children, .. } if children.iter().all(|m| m.path_data().is_some()) => {
children.iter().filter_map(|m| m.path_data().and_then(vectorcraft_geom::PathData::control_bounds)).reduce(|a, b| a.union(b))
}
_ => return c.reach_bounds_with(symbols),
};
let o = c.appearance.outset();
control.map(|b| b.inflate(o, o))
}
/// The members of compound path `children` that a click at `p` within `tol` can touch, as one
/// path: those whose control points' box, grown by `tol`, holds `p` (edges included). A member
/// outside that box is farther than `tol` from `p` and winds zero times round it, so this path's
/// outline and fill answer a click as the whole compound path's do, without assembling it.
fn compound_members_near(children: &[std::sync::Arc<Node>], p: Point, tol: f64) -> vectorcraft_geom::BezPath {
let near = |b: Rect| b.x0 - tol <= p.x && p.x <= b.x1 + tol && b.y0 - tol <= p.y && p.y <= b.y1 + tol;
let mut bp = vectorcraft_geom::BezPath::new();
for pd in children.iter().filter_map(|m| m.path_data()) {
if pd.control_bounds().is_some_and(near) {
bp.extend(pd.to_bezpath());
}
}
bp
}
/// Is the first child of `n` the isolated container `scope`?
@@ -710,12 +744,23 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
}
None
}
NodeKind::Compound { rule, .. } => {
let bp = n.stroke_path()?;
if let Some(k) = hit_stroke(n, &bp, *rule, p, opt) {
return Some(k);
NodeKind::Compound { children, rule } => {
// Painted strokes follow the whole compound path (alignment, dashes, width profiles):
// they are measured along all of it, as before.
if !opt.outline && n.appearance.painted_strokes().next().is_some() {
let bp = n.stroke_path()?;
if n.appearance.stroke_hit(&bp, *rule, p, opt.tol) {
return Some(HitKind::Stroke);
}
}
(!opt.outline && !opt.path_only && fill_contains(&bp, *rule, p)).then_some(HitKind::Fill)
// The outline and the fill only need the members near `p`. (Measured without
// `stroke_contains`'s box check: the box of the members near `p` is smaller than the
// whole path's, and its far edges would turn away points exactly `tol` away.)
let near = compound_members_near(children, p, opt.tol);
if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol {
return Some(HitKind::Outline);
}
(!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill)
}
// The type path lies within the bounds: they rule out the rest before it is measured.
NodeKind::Text(t) if opt.type_path_only => {
@@ -835,6 +880,16 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
/// clipping mask counts only when the marquee meets the region its clipping path clips to, and then
/// only within that region's bounds.
pub fn marquee(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool) -> Vec<NodeId> {
marquee_with(doc, r, scope, leaves, false)
}
/// Candidates for whole-object enclosure by a loop bounded by `r`. Eligibility and group
/// traversal follow [`marquee`]; compounds contribute the complete path they paint.
pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option<NodeId>) -> Vec<NodeId> {
marquee_with(doc, r, scope, true, true)
}
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool) -> Vec<NodeId> {
let mut out = Vec::new();
// `tops` pairs each object with the part of `r` in which the marquee can touch it.
let tops: Vec<(&std::sync::Arc<Node>, Rect)> = match scope.and_then(|s| doc.node(s)) {
@@ -879,13 +934,19 @@ pub fn marquee(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool) ->
/// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched
/// by the copies it draws, as clicks hit them. Objects of every other kind except paths,
/// compound paths, layers and groups are touched by their box.
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>) -> bool {
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool) -> bool {
match &n.kind {
NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r),
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => marquee_in(n, r)
.is_some_and(|r| children.iter().enumerate().any(|(i, c)| c.visible && !shaper_hides(n, i, scope) && touches(c, s, r, scope))),
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope)),
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope)),
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
marquee_in(n, r).is_some_and(|r| {
children.iter().enumerate().any(|(i, c)| c.visible && !shaper_hides(n, i, scope) && touches(c, s, r, scope, whole_compounds))
})
}
NodeKind::Compound { children, .. } if whole_compounds => {
children.iter().filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r))
}
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds)),
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds)),
// A box with no width or no height (an instance of a symbol that draws a straight
// line) is touched where the marquee crosses it.
_ => n.geometric_bounds_with(s).is_some_and(|b| {
@@ -894,18 +955,18 @@ pub fn marquee(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool) ->
}),
}
}
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, out: &mut Vec<NodeId>) {
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, out: &mut Vec<NodeId>) {
match &n.kind {
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
let Some(r) = marquee_in(n, r) else { return };
for (i, c) in children.iter().enumerate() {
if c.visible && !c.locked && !shaper_hides(n, i, scope) {
collect_leaves(c, s, r, scope, out);
collect_leaves(c, s, r, scope, whole_compounds, out);
}
}
}
_ => {
if touches(n, s, r, scope) {
if touches(n, s, r, scope, whole_compounds) {
out.push(n.id);
}
}
@@ -918,8 +979,8 @@ pub fn marquee(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool) ->
continue;
}
if leaves {
collect_leaves(t, &symbols, r, scope, &mut out);
} else if touches(t, &symbols, r, scope) {
collect_leaves(t, &symbols, r, scope, whole_compounds, &mut out);
} else if touches(t, &symbols, r, scope, whole_compounds) {
out.push(t.id);
}
}
+220
View File
@@ -1120,3 +1120,223 @@ fn visible_sampling_reads_locked_art_and_layers_but_excludes_hidden_art() {
d.node_mut(l).unwrap().visible = false;
assert!(hit_test_visible(&d, p, HitOptions::default()).is_none());
}
/// Deterministic xorshift in 0..1.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> f64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
(self.0 % 1_000_000) as f64 / 1_000_000.0
}
}
/// A closed blob of `n` smooth anchors round `c` (radius about `r`), turning either way, with
/// handles long enough that its control points reach past its curves.
fn blob(rng: &mut Rng, c: Point, r: f64, n: usize, clockwise: bool) -> vectorcraft_geom::SubPath {
use vectorcraft_geom::{Anchor, Vec2};
let anchors = (0..n)
.map(|i| {
let k = if clockwise { i as f64 } else { (n - i) as f64 };
let a = k / n as f64 * std::f64::consts::TAU;
let rr = r * (0.6 + 0.8 * rng.next());
let p = c + Vec2::new(a.cos(), a.sin()) * rr;
let t = Vec2::new(-a.sin(), a.cos()) * (if clockwise { 1.0 } else { -1.0 }) * rr * (0.2 + 1.3 * rng.next());
Anchor::smooth(p, p + t)
})
.collect();
vectorcraft_geom::SubPath::new(anchors, true)
}
/// A document with one compound path of `members` blobs (some of them holes), its id and the
/// members' paths.
fn compound_doc(members: usize, rule: vectorcraft_geom::FillRule, appearance: Appearance) -> (Document, NodeId, Vec<vectorcraft_geom::PathData>) {
let mut d = Document::new(800.0, 800.0);
let l = d.layers[0].id;
let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
let mut paths = vec![];
let mut children = vec![];
for i in 0..members {
let c = Point::new(20.0 + rng.next() * 600.0, 20.0 + rng.next() * 600.0);
let r = 3.0 + rng.next() * 9.0;
let pd = vectorcraft_geom::PathData::single(blob(&mut rng, c, r, 3 + i % 4, i % 3 != 0));
children.push(Arc::new(Node::path(d.alloc_id(), pd.clone(), Appearance::default())));
paths.push(pd);
}
let id = d.alloc_id();
let mut compound = Node::new(id, NodeKind::Compound { children, rule });
compound.appearance = appearance.into();
d.insert(Some(l), 0, compound).unwrap();
(d, id, paths)
}
/// What a click on compound path `n` gave before compound paths were culled by their control
/// points and their members near the click: the whole path assembled (`full`), culled by its
/// reach measured along the curves.
fn compound_hit_before(n: &Node, full: &vectorcraft_geom::BezPath, p: Point, opt: HitOptions) -> Option<HitKind> {
let NodeKind::Compound { rule, .. } = &n.kind else { return None };
if !n.reach_bounds().is_none_or(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
return None;
}
if !opt.outline && n.appearance.stroke_hit(full, *rule, p, opt.tol) {
return Some(HitKind::Stroke);
}
if stroke_contains(full, 0.0, opt.tol, p) {
return Some(HitKind::Outline);
}
(!opt.outline && !opt.path_only && fill_contains(full, *rule, p)).then_some(HitKind::Fill)
}
/// The points a test clicks for `paths`: random ones over them and past them, and, for some
/// members, their anchors, points just over the tolerance from them, and the corners and edge
/// midpoints of their control and curve boxes, on them and grown by the tolerance.
fn probe_points(paths: &[vectorcraft_geom::PathData], tol: f64, random: usize, every: usize) -> Vec<Point> {
let all = paths.iter().filter_map(vectorcraft_geom::PathData::control_bounds).reduce(|a, b| a.union(b)).unwrap().inflate(30.0, 30.0);
let mut rng = Rng(7);
let mut pts: Vec<Point> = (0..random).map(|_| Point::new(all.x0 + rng.next() * all.width(), all.y0 + rng.next() * all.height())).collect();
for pd in paths.iter().step_by(every) {
for a in pd.subpaths.iter().flat_map(|sp| &sp.anchors) {
pts.extend([a.p, Point::new(a.p.x + tol, a.p.y), Point::new(a.p.x, a.p.y - tol), Point::new(a.p.x + tol * 1.0001, a.p.y)]);
}
for b in [pd.control_bounds().unwrap(), pd.bounds().unwrap()] {
for b in [b, b.inflate(tol, tol)] {
let (cx, cy) = (b.center().x, b.center().y);
pts.extend(
[(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1), (cx, b.y0), (cx, b.y1), (b.x0, cy), (b.x1, cy)]
.map(|(x, y)| Point::new(x, y)),
);
}
}
}
pts
}
/// A compound path of thousands of members hits exactly as it did when it was assembled
/// whole for every click: at random points, on and next to anchors, and on the edges of the
/// members' boxes (control points' and curves', with and without the tolerance), for both fill
/// rules, in outline mode and with Object Selection by Path Only.
#[test]
fn culled_compound_hits_as_the_whole_path() {
use vectorcraft_geom::FillRule;
for (rule, opt) in [
(FillRule::NonZero, HitOptions::default()),
(FillRule::EvenOdd, HitOptions { tol: 0.5, ..Default::default() }),
(FillRule::NonZero, HitOptions { outline: true, tol: 1.0, ..Default::default() }),
(FillRule::EvenOdd, HitOptions { path_only: true, ..Default::default() }),
] {
let (d, id, paths) = compound_doc(2000, rule, Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
let n = d.node(id).unwrap();
let full = n.stroke_path().unwrap();
// The whole path's box grown by the tolerance. Before, a point on its far edges (right
// and bottom: `Rect::contains` leaves them out) never hit, even exactly `tol` from the
// outline; now it hits there as on the near edges. Those points are clicked too, and
// checked against the distance alone.
let far = vectorcraft_geom::Shape::bounding_box(&full).inflate(opt.tol, opt.tol);
let mut pts = probe_points(&paths, opt.tol, 200, 120);
let rightmost = paths.iter().filter_map(vectorcraft_geom::PathData::bounds).max_by(|a, b| a.x1.total_cmp(&b.x1)).unwrap();
pts.push(Point::new(far.x1, rightmost.center().y));
let (mut hits, mut kinds) = (0, HashSet::new());
for p in pts {
let before = compound_hit_before(n, &full, p, opt);
let now = hit_test(&d, p, opt);
if p.x == far.x1 || p.y == far.y1 {
let outline = vectorcraft_geom::hit::distance_to_outline(&full, p) <= opt.tol;
assert_eq!(now.is_some(), outline || before.is_some(), "{rule:?} {opt:?} on the far edge at {p:?}");
continue;
}
assert_eq!(now.as_ref().map(|h| (h.leaf, h.kind)), before.map(|k| (id, k)), "{rule:?} {opt:?} at {p:?}");
hits += usize::from(before.is_some());
kinds.extend(before.map(|k| format!("{k:?}")));
}
// The points reach both hits and misses, and the outline as well as the fill.
assert!(hits > 100, "{rule:?} {opt:?}: {hits} hits");
assert!(kinds.contains("Outline"), "{rule:?} {opt:?}: {kinds:?}");
}
}
/// A wide stroke paints far past a path's control points: clicks on it there still hit, for a
/// path and for a compound path (whose strokes are measured along all of it), exactly as when
/// they were culled by their reach measured along the curves.
#[test]
fn wide_strokes_hit_past_the_control_points() {
use vectorcraft_geom::{Anchor, PathData, SubPath};
let mut d = Document::new(400.0, 400.0);
let l = d.layers[0].id;
let stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 40.0);
// A zigzag 10 pt high whose 40 pt stroke reaches 20 pt (more at its mitred turns) past it.
let zig = PathData::single(SubPath::new(
[(100.0, 100.0), (110.0, 110.0), (120.0, 100.0), (130.0, 110.0)].map(|(x, y)| Anchor::corner(Point::new(x, y))).to_vec(),
false,
));
let path = d.alloc_id();
d.insert(Some(l), 0, Node::path(path, zig.clone(), stroke.clone())).unwrap();
// A compound path of two small rings with the same stroke, further along.
let mut rng = Rng(3);
let members: Vec<Arc<Node>> = [Point::new(250.0, 250.0), Point::new(262.0, 250.0)]
.into_iter()
.map(|c| Arc::new(Node::path(d.alloc_id(), PathData::single(blob(&mut rng, c, 4.0, 4, true)), Appearance::default())))
.collect();
let compound = d.alloc_id();
let mut node = Node::new(compound, NodeKind::Compound { children: members, rule: vectorcraft_geom::FillRule::NonZero });
node.appearance = stroke.into();
d.insert(Some(l), 9, node).unwrap();
let symbols = d.symbol_boxes();
let opt = HitOptions::default();
for id in [path, compound] {
let n = d.node(id).unwrap();
let full = n.stroke_path().unwrap();
let control = match &n.kind {
NodeKind::Path { path, .. } => path.control_bounds().unwrap(),
_ => n.children().unwrap().iter().filter_map(|m| m.path_data()?.control_bounds()).reduce(|a, b| a.union(b)).unwrap(),
};
let (mut outside, mut checked) = (0, 0);
let area = control.inflate(40.0, 40.0);
for i in 0..=80 {
for j in 0..=80 {
let p = Point::new(area.x0 + area.width() * f64::from(i) / 80.0, area.y0 + area.height() * f64::from(j) / 80.0);
let before = match &n.kind {
NodeKind::Path { .. } => n
.reach_bounds_with(&symbols)
.is_none_or(|b| b.inflate(opt.tol, opt.tol).contains(p))
.then(|| hit_leaf(n, p, opt, &symbols))
.flatten(),
_ => compound_hit_before(n, &full, p, opt),
};
let now = hit_test(&d, p, opt).filter(|h| h.leaf == id).map(|h| h.kind);
assert_eq!(now, before, "{id:?} at {p:?}");
checked += 1;
outside += usize::from(before == Some(HitKind::Stroke) && !control.contains(p));
}
}
assert!(outside > 50, "{id:?}: {outside} of {checked} points hit the stroke outside the control points' box");
}
}
/// The box a click is culled by holds the object's reach for paths and compound paths (it is
/// measured by their control points, which hold their curves, and grown by the same stroke reach),
/// so culling by it never turns away a click the reach let through. (Up to rounding: where a curve's
/// extreme is an anchor, the two boxes measure the same point in different ways.)
#[test]
fn cull_box_holds_the_reach_of_paths_and_compound_paths() {
const E: f64 = 1e-9;
let holds =
|outer: Rect, inner: Rect| outer.x0 - E <= inner.x0 && outer.y0 - E <= inner.y0 && inner.x1 <= outer.x1 + E && inner.y1 <= outer.y1 + E;
let stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 12.0);
let (mut d, id, _) = compound_doc(200, vectorcraft_geom::FillRule::NonZero, stroke.clone());
let path_id = d.alloc_id();
let symbols = d.symbol_boxes();
let n = d.node(id).unwrap();
let mut checked = 0;
for node in std::iter::once(n).chain(n.children().unwrap().iter().map(|m| &**m)) {
let (cull, reach) = (cull_reach(node, &symbols).unwrap(), node.reach_bounds_with(&symbols).unwrap());
assert!(holds(cull, reach), "{:?}: {cull:?} does not hold {reach:?}", node.id);
checked += 1;
}
// A stroked plain path, its handles reaching past its curves.
let mut rng = Rng(11);
let path = Node::path(path_id, vectorcraft_geom::PathData::single(blob(&mut rng, Point::new(50.0, 50.0), 20.0, 5, true)), stroke);
let (cull, reach) = (cull_reach(&path, &symbols).unwrap(), path.reach_bounds_with(&symbols).unwrap());
assert!(holds(cull, reach), "{cull:?} does not hold {reach:?}");
assert_eq!(checked, 201);
}
+4 -1
View File
@@ -29,7 +29,10 @@ mod symbol_registration;
pub use inline::{SYMBOL_HALF, SYMBOL_SIZES};
pub use shared::Shared;
pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType};
pub use symbol_nine_slice::{MAX_SLICE_GROWTH, NineSliceMap, PAINTED_EFFECTS, SYMBOL_NINE_SLICE, SymbolNineSlice, charge_symbol_art};
pub use symbol_nine_slice::{
EditedNineSlice, MAX_SLICE_GROWTH, MIN_CENTER_BAND, NineSliceGuide, NineSliceMap, PAINTED_EFFECTS, SYMBOL_NINE_SLICE, SymbolNineSlice,
charge_symbol_art,
};
pub use symbol_overrides::SymbolOverride;
pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration};
pub mod links;
+23 -8
View File
@@ -185,8 +185,13 @@ impl Node {
match &self.kind {
NodeKind::Path { path, .. } => Some(path.to_bezpath()),
NodeKind::Compound { children, .. } => {
let mut bp = vectorcraft_geom::BezPath::new();
children.iter().filter_map(|c| c.path_data()).for_each(|pd| bp.extend(pd.to_bezpath()));
// Sized up front: grown by doubling, the path of a compound path of hundreds of
// thousands of anchors is copied into ever larger buffers, up to tens of MB, on
// every call.
let subpaths = || children.iter().filter_map(|c| c.path_data()).flat_map(|pd| &pd.subpaths);
let elements = subpaths().filter(|sp| !sp.anchors.is_empty()).map(|sp| 1 + sp.segment_count() + usize::from(sp.closed)).sum();
let mut bp = vectorcraft_geom::BezPath::from_vec(Vec::with_capacity(elements));
subpaths().for_each(|sp| sp.to_bezpath_into(&mut bp));
Some(bp)
}
_ => None,
@@ -393,6 +398,12 @@ impl Node {
self.transform_scaled(a, &scaling.into());
}
/// The path of the child an Objects on Path group's objects are attached to.
fn on_path_data(&self) -> Option<&PathData> {
let r = self.extras().objects_on_path.as_deref()?;
self.children()?.iter().find(|c| c.id == r.path)?.path_data()
}
fn transform_scaled(&mut self, a: Affine, sc: &Scaling) {
// A dimension's measurement moves with it.
if let Some(e) = self.extras_if_any()
@@ -400,12 +411,8 @@ impl Node {
{
dimension.transform(a);
}
// The frames of the objects attached to a path move with them.
if let Some(e) = self.extras_if_any()
&& let Some(on_path) = &mut e.objects_on_path
{
on_path.transform(a);
}
// The path the objects are attached to, before it is transformed.
let on_path_before = self.on_path_data().cloned();
if !self.is_layer() {
self.bbox_angle = crate::orient::transformed_angle(self.bbox_angle, a);
}
@@ -496,6 +503,14 @@ impl Node {
NodeKind::Mesh(m) => m.transform(a),
NodeKind::Repeat(r) => r.transform(a, *sc),
}
// The frames of the objects attached to a path move with them, and the distances along the
// path follow the path as it is now (a live shape's path is regenerated).
let on_path_after = on_path_before.as_ref().and_then(|_| self.on_path_data().cloned());
if let Some(e) = self.extras_if_any()
&& let Some(on_path) = &mut e.objects_on_path
{
on_path.transform(a, on_path_before.as_ref().zip(on_path_after.as_ref()));
}
if let Some(m) = self.extras_if_any().and_then(|e| e.mask.as_mut())
&& m.linked
{
+48
View File
@@ -241,6 +241,34 @@ fn uneven_scales_keep_live_corners_circular() {
assert_round_corners(&n, Affine::IDENTITY, 40.0);
}
/// Objects attached to a rounded rectangle that keeps its corners when scaled stay where the scale
/// takes them on the regenerated path, which is not twice as long when twice the size.
#[test]
fn objects_on_a_live_rectangle_follow_its_regenerated_path() {
use crate::objects_on_path::{CENTER, ObjectsOnPath, stops};
let path = live_rect(100.0, 100.0, 20.0, Affine::IDENTITY);
let objects: Vec<Node> =
(2..5).map(|i| Node::path(NodeId(i), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Default::default())).collect();
let members: Vec<&Node> = objects.iter().collect();
let rec = ObjectsOnPath { spacing: Some(20.0), start: 10.0, ..ObjectsOnPath::new(NodeId(1), &members, CENTER, 0.0) };
let mut children = vec![Arc::new(path)];
children.extend(objects.iter().cloned().map(Arc::new));
let mut g = Node::new(NodeId(9), NodeKind::Group { children, clip: false });
g.extras_mut().objects_on_path = Some(Box::new(rec));
let path_of = |g: &Node| g.children().and_then(|c| c.first()).and_then(|p| p.path_data().cloned()).unwrap();
let rec_of = |g: &Node| g.extras().objects_on_path.as_deref().cloned().unwrap();
let r = rec_of(&g);
let before = stops(&path_of(&g), 3, r.spacing, r.start).unwrap();
let a = Affine::scale(2.0);
g.transform(a, KEEP_CORNERS);
assert_round_corners(&g.children().unwrap()[0], Affine::IDENTITY, 20.0);
let r = rec_of(&g);
let after = stops(&path_of(&g), 3, r.spacing, r.start).unwrap();
for ((p, _), (q, _)) in before.iter().zip(&after) {
assert!((a * *p).distance(*q) < 1e-6, "{p:?} went to {q:?}: {r:?}");
}
}
#[test]
fn rotated_and_reflected_live_rectangles_scale_along_their_own_sides() {
let place = Affine::translate((200.0, 100.0)) * Affine::rotate(30f64.to_radians());
@@ -518,3 +546,23 @@ fn fields_before_the_type_are_buffered_within_the_value_budget() {
assert!(with_buffered_value_budget(0, || read(&written)).is_ok(), "a saved object buffers nothing: {written}");
assert!(read(reordered).is_ok(), "no budget outside a read");
}
/// A compound path's path is its members' paths one after another, open and closed, empty
/// members and single anchors included.
#[test]
fn compound_stroke_path_is_its_members_in_order() {
use vectorcraft_geom::{Anchor, PathData, SubPath};
let open = PathData::single(SubPath::new([(0.0, 0.0), (5.0, 1.0), (9.0, 7.0)].map(|(x, y)| Anchor::corner(Point::new(x, y))).to_vec(), false));
let lone = PathData::single(SubPath::new(vec![Anchor::corner(Point::new(3.0, 3.0))], false));
let members =
[shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), open, PathData::default(), lone, shapes::ellipse(Rect::new(10.0, 10.0, 20.0, 16.0))];
let mut expected = vectorcraft_geom::BezPath::new();
for pd in &members {
expected.extend(pd.to_bezpath());
}
let children = members.iter().enumerate().map(|(i, pd)| Arc::new(Node::path(NodeId(i as u64 + 1), pd.clone(), Appearance::default()))).collect();
let n = Node::new(NodeId(99), NodeKind::Compound { children, rule: vectorcraft_geom::FillRule::EvenOdd });
let bp = n.stroke_path().unwrap();
assert_eq!(bp.elements(), expected.elements());
assert!(!bp.elements().is_empty());
}
+318 -22
View File
@@ -5,8 +5,9 @@
//! the other children are the attached objects, kept where they are drawn: the group draws, hits,
//! saves and exports as a group. The record lists the objects in their order along the path, each
//! with the frame it is drawn in and the angle that frame is turned by. [`place`] spreads them
//! evenly along the path from its first anchor (the first object sits on that anchor, and the last
//! one sits on the end of an open path), puts the attachment point of each one
//! along the path ([`stops`]): evenly from its first anchor by default (the first object sits on
//! that anchor, and the last one sits on the end of an open path), or [`ObjectsOnPath::spacing`]
//! apart from [`ObjectsOnPath::start`]. It puts the attachment point of each one
//! ([`ObjectsOnPath::pivot`]) on the path, and turns its frame to the path's direction there,
//! tilted by [`ObjectsOnPath::rotate`].
//!
@@ -45,6 +46,14 @@ pub struct ObjectsOnPath {
/// upright object has its frame's x axis along the path's direction at its attachment point.
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub rotate: f64,
/// Space: the distance along the path (points) from each object's attachment point to the
/// next one's. `None` (Auto) spreads the objects evenly ([`layout`]).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub spacing: Option<f64>,
/// The distance along the path (points) from its first anchor to the first object's
/// attachment point.
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub start: f64,
}
/// An object attached to the path of an Objects on Path group.
@@ -95,19 +104,38 @@ impl ObjectsOnPath {
/// in its frame as drawn ([`upright_frame`]).
pub fn new(path: NodeId, members: &[&Node], pivot: u8, rotate: f64) -> Self {
let members = members.iter().map(|n| Member::new(n)).collect();
Self { path, members, pivot: pivot.min(8), rotate: if rotate.is_finite() { rotate } else { 0.0 } }
Self { path, members, pivot: pivot.min(8), rotate: if rotate.is_finite() { rotate } else { 0.0 }, spacing: None, start: 0.0 }
}
/// The frames go with the group, and each frame's angle becomes the transformed path's
/// direction at the object plus the tilt, so that [`place`] keeps each object's scale, shear
/// and reflection when it spreads the objects along the transformed path again. A reflection
/// also reverses Rotate: the objects keep the mirrored tilt to the mirrored path.
pub fn transform(&mut self, a: Affine) {
/// also reverses Rotate: the objects keep the mirrored tilt to the mirrored path. With `paths`,
/// the group's path before the transform and as it is after it, the start and a Space value
/// keep the first and last objects where the transform takes them on the path; a value that
/// cannot be followed that way scales by how much the path's length changed. Without `paths`,
/// they scale by the transform's average scale (the square root of its area scale). A
/// value that would not be finite once scaled stays as it is.
pub fn transform(&mut self, a: Affine, paths: Option<(&PathData, &PathData)>) {
let before = tilt(self.rotate);
let [a0, a1, a2, a3, _, _] = a.as_coeffs();
if a.determinant() < 0.0 && self.rotate != 0.0 {
self.rotate = -self.rotate;
}
let along = paths.and_then(|(old, new)| {
let s = path_length(new)?.0 / path_length(old)?.0;
(s.is_finite() && s > 0.0).then_some(s)
});
let scale = along.unwrap_or_else(|| a.determinant().abs().sqrt());
// A move leaves the distances along the path as they are.
let moves = a0 == 1.0 && a1 == 0.0 && a2 == 0.0 && a3 == 1.0;
if !moves && scale.is_finite() && scale > 0.0 {
let scaled = |v: f64| Some(v * scale).filter(|s| s.is_finite()).unwrap_or(v);
let moved = paths.and_then(|(old, new)| self.moved_along(a, old, new, scale));
let (spacing, start) = moved.unwrap_or((None, None));
self.spacing = self.spacing.map(|g| spacing.unwrap_or_else(|| scaled(g)));
self.start = start.unwrap_or_else(|| scaled(self.start));
}
let after = tilt(self.rotate);
let [a0, a1, a2, a3, _, _] = a.as_coeffs();
for m in &mut self.members {
m.frame = a * m.frame;
let (sin, cos) = (m.angle - before).sin_cos();
@@ -117,6 +145,41 @@ impl ObjectsOnPath {
}
}
}
/// The start and Space value on `new`, the path `old` after the transform `a` (regenerated, for
/// a live shape), that keep the first object and the last one where `a` takes them: each one's
/// point on `old`, mapped by `a`, measured along `new` near `scale` times its distance along
/// `old`. Either one is `None` when it cannot be followed that way: a start before or beyond the
/// ends of an open path, or a Space value of 0, one the path has no room for, or one with fewer
/// than two objects. `None` for a path without length or a start that is not finite.
fn moved_along(&self, a: Affine, old: &PathData, new: &PathData, scale: f64) -> Option<(Option<f64>, Option<f64>)> {
let (was, is) = (Spine::new(old)?, Spine::new(new)?);
let (len, closed) = path_length(old)?;
let (new_len, _) = path_length(new)?;
if !self.start.is_finite() {
return None;
}
let n = self.members.len();
let (s0, gap) = layout(len, closed, n, self.spacing, self.start);
let follow = |s: f64| -> Option<f64> {
let (p, _) = was.at_length(s);
let t = is.nearest(a * p, Some(s * scale))?.1;
t.is_finite().then_some(if closed { wrap(t, new_len) } else { t.clamp(0.0, new_len) })
};
let t0 = follow(s0)?;
// On a closed path the start keeps the number of times it goes round, when that stays finite.
let start =
if closed { Some(t0 + ((self.start - s0) / len).round() * new_len).filter(|s| s.is_finite()) } else { (s0 == self.start).then_some(t0) };
let spacing = self.spacing.filter(|g| n > 1 && g.is_finite() && *g > 0.0 && *g <= gap).and_then(|g| {
let t1 = follow(nth_length(len, closed, s0, gap, n - 1))?;
let steps = (n - 1) as f64;
// Round a closed path, the span nearest the scaled one.
let expected = steps * g * scale;
let span = if closed { wrap(t1 - t0 - expected + new_len / 2.0, new_len) - new_len / 2.0 + expected } else { t1 - t0 };
let g = span / steps;
(g.is_finite() && g >= 0.0).then_some(g)
});
Some((spacing, start))
}
/// The children given new ids (a copy of the group): the path and the objects by their new ids.
pub fn rename(&mut self, ids: &HashMap<NodeId, NodeId>) {
let to = |id: NodeId| ids.get(&id).copied().unwrap_or(id);
@@ -210,19 +273,75 @@ pub fn upright_frame(n: &Node) -> Affine {
}
}
/// Where `n` objects attach along `path` (its first subpath): the point and the direction there
/// (radians, as `atan2` gives in the document's axes). They are spread evenly by length from the
/// first anchor: on an open path the last one is at its end, on a closed path the gaps go all the way
/// around. `None` for a path without length.
pub fn stops(path: &PathData, n: usize) -> Option<Vec<(Point, f64)>> {
let spine = Spine::new(path)?;
let len = spine.length();
if !len.is_finite() || len <= 1e-9 {
return None;
}
/// The length of `path`'s first subpath and whether it is closed. `None` for a path without
/// length.
pub fn path_length(path: &PathData) -> Option<(f64, bool)> {
let len = Spine::new(path)?.length();
let closed = path.subpaths.first().is_some_and(|s| s.closed);
let gaps = if closed { n } else { n.saturating_sub(1) }.max(1);
Some((0..n).map(|i| spine.at_length(len * i as f64 / gaps as f64)).collect())
(len.is_finite() && len > 1e-9).then_some((len, closed))
}
/// Where the first of `n` objects attaches along a path of length `len` (closed or not), and the
/// distance from each object's attachment point to the next one's, both along the path (points),
/// for Space `spacing` (`None`: Auto) from `start`:
/// - The first object is `start` from the first anchor: on an open path no further than its end,
/// and on a closed path less than once around.
/// - Auto spreads the objects evenly from there: on an open path the last one is at its end, and on
/// a closed path the gaps go all the way around.
/// - A Space value is kept to what the path has room for, so a shorter path draws the objects
/// closer while the value stays: on an open path the last object reaches its end at most, and on
/// a closed path the last one stops at least a gap short of the first.
///
/// A Space value that is negative or not finite counts as Auto, and a `start` that is not finite as 0.
pub fn layout(len: f64, closed: bool, n: usize, spacing: Option<f64>, start: f64) -> (f64, f64) {
let start = match (start.is_finite(), closed) {
(false, _) => 0.0,
(true, true) => wrap(start, len),
(true, false) => start.clamp(0.0, len.max(0.0)),
};
let room = if closed {
len / n.max(1) as f64
} else if n > 1 {
(len - start) / (n - 1) as f64
} else {
0.0
};
let room = if room.is_finite() { room.max(0.0) } else { 0.0 };
match spacing.filter(|g| g.is_finite() && *g >= 0.0) {
Some(g) => (start, g.min(room)),
None => (start, room),
}
}
/// `s` taken round a closed path of length `len`: 0 or more, and less than `len`.
fn wrap(s: f64, len: f64) -> f64 {
let w = s.rem_euclid(len);
if w.is_finite() && w < len { w } else { 0.0 }
}
/// Where `n` objects attach along `path` (its first subpath): the point and the direction there
/// (radians, as `atan2` gives in the document's axes). They go along it as [`layout`] spaces them
/// for Space `spacing` (`None`: Auto) from `start`. `None` for a path without length.
pub fn stops(path: &PathData, n: usize, spacing: Option<f64>, start: f64) -> Option<Vec<(Point, f64)>> {
let spine = Spine::new(path)?;
let (len, closed) = path_length(path)?;
let (start, gap) = layout(len, closed, n, spacing, start);
Some((0..n).map(|i| spine.at_length(nth_length(len, closed, start, gap, i))).collect())
}
/// Where object `i` of `n` attaches along `path`, as [`stops`] places it, without the others.
pub fn stop(path: &PathData, n: usize, spacing: Option<f64>, start: f64, i: usize) -> Option<(Point, f64)> {
let spine = Spine::new(path)?;
let (len, closed) = path_length(path)?;
let (start, gap) = layout(len, closed, n, spacing, start);
(i < n).then(|| spine.at_length(nth_length(len, closed, start, gap, i)))
}
/// The distance along a path of length `len` (closed or not) to object `i`, from `start` and
/// `gap` apart as [`layout`] gives them.
pub fn nth_length(len: f64, closed: bool, start: f64, gap: f64, i: usize) -> f64 {
let s = start + gap * i as f64;
if closed { wrap(s, len) } else { s.min(len) }
}
/// The tilt Rotate gives (radians, the document's axes, where y points down): `rotate` degrees
@@ -277,7 +396,7 @@ pub fn place(g: &mut Node, symbols: &SymbolBoxes) -> bool {
}
}
let mut moved = false;
if let Some(stops) = path.and_then(|p| stops(&p, rec.members.len())) {
if let Some(stops) = path.and_then(|p| stops(&p, rec.members.len(), rec.spacing, rec.start)) {
let turn = tilt(rec.rotate);
for (m, (p, dir)) in rec.members.iter_mut().zip(stops) {
let Some(c) = at.get(&m.id).and_then(|i| children.get_mut(*i)) else { continue };
@@ -309,15 +428,192 @@ mod tests {
#[test]
fn stops_spread_from_the_first_anchor() {
let open = shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0));
let s = stops(&open, 4).unwrap();
let s = stops(&open, 4, None, 0.0).unwrap();
let xs: Vec<f64> = s.iter().map(|(p, _)| p.x.round()).collect();
assert_eq!(xs, [0.0, 100.0, 200.0, 300.0], "first at the start, last at the end of an open path");
let closed = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0));
let s = stops(&closed, 4).unwrap();
let s = stops(&closed, 4, None, 0.0).unwrap();
let mut pts: Vec<(i64, i64)> = s.iter().map(|(p, _)| (p.x.round() as i64, p.y.round() as i64)).collect();
pts.sort();
assert_eq!(pts, [(0, 0), (0, 100), (100, 0), (100, 100)], "a closed path spreads them all the way round");
assert!(stops(&shapes::line(Point::ZERO, Point::ZERO), 2).is_none());
assert!(stops(&shapes::line(Point::ZERO, Point::ZERO), 2, None, 0.0).is_none());
}
/// The x of each stop on the `len` pt line from (0, 0) to the right, to 1/1000 pt.
fn xs_on_line(len: f64, n: usize, spacing: Option<f64>, start: f64) -> Vec<f64> {
let open = shapes::line(Point::new(0.0, 0.0), Point::new(len, 0.0));
stops(&open, n, spacing, start).unwrap().iter().map(|(p, _)| (p.x * 1000.0).round() / 1000.0).collect()
}
#[test]
fn space_sets_the_distance_between_the_stops() {
assert_eq!(xs_on_line(300.0, 4, Some(60.0), 0.0), [0.0, 60.0, 120.0, 180.0], "the first stays on the first anchor");
assert_eq!(xs_on_line(300.0, 4, Some(60.0), 60.0), [60.0, 120.0, 180.0, 240.0], "centered on the path");
assert_eq!(xs_on_line(300.0, 4, Some(0.0), 0.0), [0.0; 4], "no space stacks them");
// More than the path has room for: the last one reaches the end.
assert_eq!(xs_on_line(300.0, 4, Some(500.0), 0.0), [0.0, 100.0, 200.0, 300.0]);
assert_eq!(xs_on_line(300.0, 4, Some(500.0), 150.0), [150.0, 200.0, 250.0, 300.0]);
// A shorter path draws them closer, while the Space value stays to come back with the length.
assert_eq!(xs_on_line(90.0, 4, Some(60.0), 0.0), [0.0, 30.0, 60.0, 90.0]);
assert_eq!(layout(90.0, false, 4, Some(60.0), 0.0), (0.0, 30.0));
assert_eq!(layout(300.0, false, 4, Some(60.0), 0.0), (0.0, 60.0));
// Values that are not usable count as Auto, and a start beyond the end stops at it.
assert_eq!(xs_on_line(300.0, 4, Some(f64::NAN), f64::INFINITY), [0.0, 100.0, 200.0, 300.0]);
assert_eq!(xs_on_line(300.0, 4, Some(-5.0), 0.0), [0.0, 100.0, 200.0, 300.0]);
assert_eq!(xs_on_line(300.0, 2, Some(10.0), 400.0), [300.0, 300.0]);
assert_eq!(xs_on_line(300.0, 1, Some(10.0), 20.0), [20.0], "one object has no space to set");
assert_eq!(xs_on_line(300.0, 0, Some(10.0), 0.0), Vec::<f64>::new());
// One stop on its own is where the stops put it.
let open = shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0));
let all = stops(&open, 4, Some(60.0), 60.0).unwrap();
for (i, s) in all.iter().enumerate() {
assert_eq!(stop(&open, 4, Some(60.0), 60.0, i), Some(*s));
}
assert_eq!(stop(&open, 4, Some(60.0), 60.0, 4), None);
}
#[test]
fn space_on_a_closed_path_wraps_at_the_first_anchor_and_stops_short_of_the_first_object() {
// The square's outline is 400 pt round, from (0, 0) to the right and on clockwise.
let closed = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0));
let pts = |spacing, start| -> Vec<(i64, i64)> {
stops(&closed, 4, spacing, start).unwrap().iter().map(|(p, _)| (p.x.round() as i64, p.y.round() as i64)).collect()
};
assert_eq!(pts(Some(50.0), 0.0), [(0, 0), (50, 0), (100, 0), (100, 50)]);
// Centered on the first anchor: the span goes back past it.
assert_eq!(pts(Some(50.0), -75.0), [(0, 75), (0, 25), (25, 0), (75, 0)]);
// At most a quarter of the way round each: no two objects meet at the first anchor.
assert_eq!(pts(Some(300.0), 0.0), [(0, 0), (100, 0), (100, 100), (0, 100)]);
assert_eq!(layout(400.0, true, 4, Some(300.0), 400.0), (0.0, 100.0));
}
#[test]
fn a_group_saved_without_space_reads_as_auto() {
let a = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0));
let rec = ObjectsOnPath::new(NodeId(1), &[&a], CENTER, 0.0);
let v = serde_json::to_value(&rec).unwrap();
assert!(v.get("spacing").is_none() && v.get("start").is_none(), "Auto is not written: {v}");
let back: ObjectsOnPath = serde_json::from_value(v).unwrap();
assert_eq!((back.spacing, back.start), (None, 0.0));
let set = ObjectsOnPath { spacing: Some(60.0), start: 12.5, ..rec };
let back: ObjectsOnPath = serde_json::from_value(serde_json::to_value(&set).unwrap()).unwrap();
assert_eq!(back, set);
}
#[test]
fn transforming_the_group_scales_its_space() {
let a = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0));
let mut rec = ObjectsOnPath { spacing: Some(60.0), start: 12.5, ..ObjectsOnPath::new(NodeId(1), &[&a], CENTER, 30.0) };
rec.transform(Affine::new([-2.0, 0.0, 0.0, 2.0, 5.0, 5.0]), None);
assert_eq!((rec.spacing, rec.start, rec.rotate), (Some(120.0), 25.0, -30.0));
rec.transform(Affine::translate((40.0, 0.0)) * Affine::rotate(0.7), None);
assert!((rec.spacing.unwrap() - 120.0).abs() < 1e-9 && (rec.start - 25.0).abs() < 1e-9, "{rec:?}");
// Twice as wide and no higher: a level path is stretched twice along its length.
let level = shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0));
let stretch = Affine::new([2.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
rec.transform(stretch, Some((&level, &level.transformed(stretch))));
assert!((rec.spacing.unwrap() - 240.0).abs() < 1e-9 && (rec.start - 50.0).abs() < 1e-9, "{rec:?}");
let mut auto = ObjectsOnPath::new(NodeId(1), &[&a], CENTER, 0.0);
auto.transform(Affine::scale(3.0), None);
assert_eq!((auto.spacing, auto.start), (None, 0.0), "Auto stays Auto");
let mut huge = ObjectsOnPath { spacing: Some(1e308), start: -1e308, ..auto };
huge.transform(Affine::scale(2.0), None);
assert_eq!((huge.spacing, huge.start), (Some(1e308), -1e308), "kept finite");
}
/// Stretching a path that turns a corner keeps the first and last objects where the stretch
/// takes them, not where the whole path's change in length would.
#[test]
fn a_stretch_keeps_the_first_and_last_objects_where_it_takes_them() {
// 100 pt to the right, then 100 pt down; twice as wide, the first part is 200 pt long.
let points = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0)];
let corner = PathData::single(vectorcraft_geom::SubPath::polyline(&points, false));
let stretch = Affine::scale_non_uniform(2.0, 1.0);
let wide = corner.transformed(stretch);
let (a, b) = (rect(2, Rect::new(0.0, 0.0, 10.0, 10.0)), rect(3, Rect::new(20.0, 0.0, 30.0, 10.0)));
let mut rec = ObjectsOnPath { spacing: Some(40.0), start: 50.0, ..ObjectsOnPath::new(NodeId(1), &[&a, &b], CENTER, 0.0) };
rec.transform(stretch, Some((&corner, &wide)));
assert!((rec.start - 100.0).abs() < 1e-9 && (rec.spacing.unwrap() - 80.0).abs() < 1e-9, "{rec:?}");
// Round a closed path, from before its first anchor: the start goes round as many times.
let square = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0));
let wide = square.transformed(stretch);
let mut rec = ObjectsOnPath { spacing: Some(50.0), start: -75.0, ..ObjectsOnPath::new(NodeId(1), &[&a, &b], CENTER, 0.0) };
let before = stops(&square, 2, rec.spacing, rec.start).unwrap();
rec.transform(stretch, Some((&square, &wide)));
let after = stops(&wide, 2, rec.spacing, rec.start).unwrap();
for ((p, _), (q, _)) in before.iter().zip(&after) {
assert!((stretch * *p).distance(*q) < 1e-9, "{p:?} went to {q:?}: {rec:?}");
}
assert!(rec.start < 0.0, "{rec:?}");
}
/// A start round a closed path so many times that scaling it would not be finite stays as it is.
#[test]
fn a_closed_path_start_too_large_to_scale_stays_finite() {
let square = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0));
let grow = Affine::scale(2.0);
let a = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0));
let mut rec = ObjectsOnPath { start: 1e308, ..ObjectsOnPath::new(NodeId(1), &[&a], CENTER, 0.0) };
rec.transform(grow, Some((&square, &square.transformed(grow))));
assert_eq!(rec.start, 1e308, "{rec:?}");
}
/// Stretching the group across its level path only keeps the objects where the stretch takes
/// them: twice as far apart.
#[test]
fn a_group_stretched_along_its_path_keeps_the_objects_in_proportion() {
let line = Node::path(NodeId(1), shapes::line(Point::new(0.0, 100.0), Point::new(300.0, 100.0)), Default::default());
let (a, b) = (rect(2, Rect::new(0.0, 0.0, 10.0, 10.0)), rect(3, Rect::new(20.0, 0.0, 30.0, 10.0)));
let mut g = Node::new(NodeId(4), NodeKind::Group { children: vec![Arc::new(line), Arc::new(a.clone()), Arc::new(b.clone())], clip: false });
let rec = ObjectsOnPath { spacing: Some(20.0), start: 10.0, ..ObjectsOnPath::new(NodeId(1), &[&a, &b], CENTER, 0.0) };
g.extras_mut().objects_on_path = Some(Box::new(rec));
let empty = crate::Document::new(1.0, 1.0);
let symbols = empty.symbol_boxes();
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));
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)));
}
#[test]
fn length_near_measures_along_the_path_and_past_its_ends() {
// An L: 400 pt to the right, then 300 pt up.
let points = [Point::new(0.0, 300.0), Point::new(400.0, 300.0), Point::new(400.0, 0.0)];
let l = PathData::single(vectorcraft_geom::SubPath::polyline(&points, false));
let spine = Spine::new(&l).unwrap();
assert!((spine.length_near(Point::new(300.0, 320.0), None) - 300.0).abs() < 1e-9);
assert!((spine.length_near(Point::new(420.0, 100.0), None) - 600.0).abs() < 1e-9);
assert!((spine.length_near(Point::new(400.0, -26.0), None) - 726.0).abs() < 1e-9, "beyond the end");
assert!((spine.length_near(Point::new(-50.0, 300.0), None) + 50.0).abs() < 1e-9, "before the start");
// A path that turns back near its start: beyond its end, the pointer is nearer the first
// segment than the last one, but on the line of the last one.
let hook = [Point::new(0.0, 0.0), Point::new(200.0, 0.0), Point::new(200.0, 10.0), Point::new(100.0, 10.0)];
let hook = Spine::new(&PathData::single(vectorcraft_geom::SubPath::polyline(&hook, false))).unwrap();
assert!((hook.length_near(Point::new(80.0, 10.0), None) - 330.0).abs() < 1e-9);
assert!((hook.length_near(Point::new(50.0, 10.0), None) - 360.0).abs() < 1e-9);
let closed = Spine::new(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0))).unwrap();
assert!((closed.length_near(Point::new(-30.0, -30.0), None)).abs() < 1e-9, "a closed path has no ends");
}
#[test]
fn length_near_a_point_followed_stays_on_that_part_of_the_path() {
// A narrow U, open on the left: its ends are 20 pt apart, 620 pt from each other along it.
let u = [Point::new(0.0, 0.0), Point::new(300.0, 0.0), Point::new(300.0, 20.0), Point::new(0.0, 20.0)];
let u = Spine::new(&PathData::single(vectorcraft_geom::SubPath::polyline(&u, false))).unwrap();
assert!((u.length_near(Point::new(-26.0, 20.0), None) - 646.0).abs() < 1e-9, "beyond the end");
// Nearer the first segment's line, the pointer stays beyond the end it was following.
assert!((u.length_near(Point::new(-26.0, 8.0), None) + 26.0).abs() < 1e-9);
assert!((u.length_near(Point::new(-26.0, 8.0), Some(646.0)) - 646.0).abs() < 1e-9);
// Following the path round, it goes on from where it was.
assert!((u.length_near(Point::new(305.0, 10.0), Some(312.0)) - 310.0).abs() < 1e-9);
// Round a closed path's first anchor: from 10 pt short of it to 20 pt past it.
let square = Spine::new(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0))).unwrap();
let (at, _) = square.at_length(390.0);
assert!((square.length_near(at, None) - 390.0).abs() < 1e-9);
assert!((square.length_near(Point::new(20.0, -5.0), Some(390.0)) - 20.0).abs() < 1e-9);
}
#[test]
+83 -19
View File
@@ -522,7 +522,28 @@ pub struct RepeatSpec {
/// many as one 500 × 500 grid, the budget [`PatternDef::offsets_covering`] also keeps.
const MAX_REPEAT_INSTANCES: usize = 250_000;
/// Counts the instances Repeats make in all, following symbol instances into their symbol's art
/// Most nodes and anchors a Repeat copies in all, those of the Repeats nested in its source and
/// of the opacity masks in it included: each instance copies the whole source, so a large source
/// keeps fewer instances than [`MAX_REPEAT_INSTANCES`] allows (a 500 × 500 grid of a shape of up
/// to 39 anchors keeps them all).
const MAX_REPEAT_COPIES: usize = 10_000_000;
/// What the Repeats in some art make in all ([`NestedCount::nodes`]).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct Cost {
/// Instances the Repeats make (0 when there are none).
instances: usize,
/// Nodes and path anchors drawn, each Repeat's source counted once per instance it keeps.
copies: usize,
}
impl Cost {
fn plus(self, o: Cost) -> Cost {
Cost { instances: self.instances.saturating_add(o.instances), copies: self.copies.saturating_add(o.copies) }
}
}
/// Counts the instances Repeats make, and the nodes they copy, in all, following symbol instances into their symbol's art
/// in `doc`: each symbol's art is counted once, and a missing symbol, or an instance of a symbol
/// inside its own art, counts as none.
///
@@ -549,21 +570,27 @@ impl<'a> NestedCount<'a> {
}
let Some(sym) = self.doc.and_then(|d| d.symbols.iter().find(|s| s.name == name)) else { return 0 };
self.symbols.borrow_mut().insert(name.to_owned(), None);
let n = self.nodes(std::slice::from_ref(&sym.art));
let n = self.nodes(std::slice::from_ref(&sym.art)).instances;
self.symbols.borrow_mut().insert(name.to_owned(), Some(n));
n
}
/// Instances the Repeats in `nodes` make in all (0 when there are none).
fn nodes(&self, nodes: &[Arc<Node>]) -> usize {
let mut sum = 0usize;
/// What the Repeats in `nodes` make in all, in the art of their enabled opacity masks too
/// (drawn again with each copy of the object they mask).
fn nodes(&self, nodes: &[Arc<Node>]) -> Cost {
let mut sum = Cost::default();
for n in nodes {
sum = sum.saturating_add(match (&n.kind, n.children()) {
(NodeKind::Repeat(r), _) => r.instances_in_all(self),
(NodeKind::SymbolInstance { symbol, .. }, _) => self.symbol(symbol),
(_, Some(c)) => self.nodes(c),
_ => 0,
});
let own = match (&n.kind, n.children()) {
(NodeKind::Repeat(r), _) => r.in_all(self),
(NodeKind::SymbolInstance { symbol, .. }, _) => Cost { instances: self.symbol(symbol), copies: 1 },
(NodeKind::Path { path, .. }, _) => Cost { instances: 0, copies: path.anchor_count().saturating_add(1) },
(_, Some(c)) => self.nodes(c).plus(Cost { instances: 0, copies: 1 }),
_ => Cost { instances: 0, copies: 1 },
};
sum = sum.plus(own);
if let Some(m) = n.extras().mask.as_ref().filter(|m| !m.disabled) {
sum = sum.plus(self.nodes(std::slice::from_ref(&m.art)));
}
}
sum
}
@@ -643,21 +670,22 @@ impl RepeatSpec {
v.truncate(self.kept(NestedCount::new(doc).nodes(&self.source)));
v
}
/// How many of its instances this Repeat keeps when each makes `nested` instances of the
/// Repeats in its source: as many as fit in [`MAX_REPEAT_INSTANCES`], at least one.
fn kept(&self, nested: usize) -> usize {
self.kind.count().min(MAX_REPEAT_INSTANCES / nested.max(1)).max(1)
/// How many of its instances this Repeat keeps when its source costs `nested`: as many as fit
/// in [`MAX_REPEAT_INSTANCES`] and [`MAX_REPEAT_COPIES`], at least one.
fn kept(&self, nested: Cost) -> usize {
self.kind.count().min(MAX_REPEAT_INSTANCES / nested.instances.max(1)).min(MAX_REPEAT_COPIES / nested.copies.max(1)).max(1)
}
/// How many instances this Repeat draws ([`Self::transforms`] for `doc`): as many as its
/// options make, fewer when the Repeats in its source would take it past
/// [`MAX_REPEAT_INSTANCES`].
/// [`MAX_REPEAT_INSTANCES`], or the copies of its source past [`MAX_REPEAT_COPIES`].
pub fn instances(&self, doc: Option<&Document>) -> usize {
self.kept(NestedCount::new(doc).nodes(&self.source))
}
/// Instances made in all, those of the Repeats nested in the source included.
fn instances_in_all(&self, count: &NestedCount) -> usize {
/// Instances made and nodes copied in all, those of the Repeats nested in the source included.
fn in_all(&self, count: &NestedCount) -> Cost {
let nested = count.nodes(&self.source);
self.kept(nested).saturating_mul(nested.max(1))
let kept = self.kept(nested);
Cost { instances: kept.saturating_mul(nested.instances.max(1)), copies: kept.saturating_mul(nested.copies).saturating_add(1) }
}
/// Evaluated instances: one group of the (transformed) source per instance (ids 0), as many
/// as [`Self::transforms`] keeps for `doc`.
@@ -1005,6 +1033,42 @@ mod tests {
assert_eq!(made(&small), 18);
}
#[test]
fn repeats_in_opacity_masks_share_the_instance_budget() {
let grid = |source: Arc<Node>| {
let mut g = RepeatSpec::grid(vec![source], 0.0, 0.0);
if let RepeatKind::Grid { rows, cols, .. } = &mut g.kind {
*rows = 500;
*cols = 500;
}
g
};
// A shape masked by a 500 × 500 grid draws the grid again for each copy.
let inner = Node::new(NodeId(3), NodeKind::Repeat(grid(sq(0.0, 0.0, 1.0))));
let mut masked = (*sq(0.0, 0.0, 1.0)).clone();
masked.extras_mut().mask = Some(Box::new(crate::node::OpacityMask::new(inner, true)));
let outer = grid(Arc::new(masked.clone()));
assert_eq!(outer.transforms(None).len(), 1);
// A disabled mask is not drawn, so it costs nothing.
if let Some(m) = &mut masked.extras_mut().mask {
m.disabled = true;
}
assert_eq!(grid(Arc::new(masked)).transforms(None).len(), 250_000);
}
#[test]
fn a_large_source_keeps_fewer_copies() {
let mut g = RepeatSpec::grid((0..1000).map(|i| sq(i as f64, 0.0, 1.0)).collect(), 0.0, 0.0);
if let RepeatKind::Grid { rows, cols, .. } = &mut g.kind {
*rows = 500;
*cols = 500;
}
// Each copy is 1000 paths of 4 anchors: far fewer than 250 000 of them fit.
let kept = g.transforms(None).len();
assert!(kept.saturating_mul(5000) <= MAX_REPEAT_COPIES, "{kept} copies kept");
assert!(kept > 1);
}
#[test]
fn serde_roundtrip() {
let mut def = PatternDef::new("Dots", vec![sq(0.0, 0.0, 10.0)]);
+3
View File
@@ -559,6 +559,9 @@ impl Document {
reads += usize::from(read_full && depth > 0);
let full = if read_full { full_bytes(&p, &blob) } else { None };
if full.and_then(|b| read(&p, &b)).is_none() {
// A full read cached for another caller (one allowed to read the file) must not
// stand in for the one refused or not tried here: the preview shows instead.
cache().entries.remove(&(p.key.clone(), false));
let preview = if blob.is_proxy() { Some(blob.bytes.clone()) } else { blob.proxy.clone() };
if let Some(bytes) = preview {
read_preview(&p, &bytes);
+41 -5
View File
@@ -17,7 +17,9 @@ pub fn parse_range(s: &str, count: usize) -> Result<Vec<usize>, String> {
.ok_or_else(|| format!("range `{s}`: `{t}` is not a number from 1 to {count}"))
};
let mut out = vec![];
let mut seen = std::collections::HashSet::new();
// Past each run of indices picked so far, the index after it: an interval skips the runs it
// overlaps instead of walking them again, so repeating `1-` costs no more than writing it once.
let mut next = std::collections::HashMap::new();
for part in s.split(',').map(str::trim).filter(|p| !p.is_empty()) {
let (a, b) = match part.replace('\u{2013}', "-").split_once('-') {
Some((a, b)) if a.trim().is_empty() && b.trim().is_empty() => return Err(format!("range `{s}`: `{part}` names no number")),
@@ -30,10 +32,11 @@ pub fn parse_range(s: &str, count: usize) -> Result<Vec<usize>, String> {
if a > b {
return Err(format!("range `{s}`: `{part}` runs backwards"));
}
for i in a - 1..b {
if seen.insert(i) {
out.push(i);
}
let mut i = unpicked(&mut next, a - 1);
while i < b {
out.push(i);
next.insert(i, i + 1);
i = unpicked(&mut next, i + 1);
}
}
if out.is_empty() {
@@ -42,6 +45,23 @@ pub fn parse_range(s: &str, count: usize) -> Result<Vec<usize>, String> {
Ok(out)
}
/// The first index from `i` on not picked yet, `next` linking each picked index onward (the links
/// followed are then pointed straight at it).
fn unpicked(next: &mut std::collections::HashMap<usize, usize>, i: usize) -> usize {
let mut end = i;
while let Some(&j) = next.get(&end) {
end = j;
}
let mut at = i;
while at != end {
match next.insert(at, end) {
Some(j) => at = j,
None => break,
}
}
end
}
#[cfg(test)]
mod tests {
use super::parse_range;
@@ -53,4 +73,20 @@ mod tests {
assert!(parse_range("-+2", 5).is_err());
assert_eq!(parse_range("1-3, 5", 5), Ok(vec![0, 1, 2, 4]));
}
#[test]
fn repeats_and_overlaps_are_dropped_in_order() {
assert_eq!(parse_range("3-5, 1-4, 2, 6-, -1", 7), Ok(vec![2, 3, 4, 0, 1, 5, 6]));
assert_eq!(parse_range("2,2,1-2", 4), Ok(vec![1, 0]));
assert_eq!(parse_range("4, 2, 1-", 5), Ok(vec![3, 1, 0, 2, 4]));
}
#[test]
fn a_range_repeated_many_times_is_read_once() {
// 100 000 pages named 50 000 times: walking the pages for each would take billions of steps.
let s = "1-,".repeat(50_000);
let pages = parse_range(&s, 100_000).unwrap();
assert_eq!(pages.len(), 100_000);
assert!(pages.iter().enumerate().all(|(i, p)| i == *p));
}
}
+25 -2
View File
@@ -110,8 +110,9 @@ impl Document {
/// Visit every color that can link to a swatch (solid paints and gradient stops of fills,
/// strokes and text runs) in the art (opacity masks included), symbol definitions, graph
/// designs, pattern tiles and the tile that pattern editing's Cancel puts back, graphic styles
/// and the swatches themselves (tint swatches, gradient swatches' stops).
/// designs, pattern tiles and the tile that pattern editing's Cancel puts back, graphic styles,
/// character styles' fill and stroke and the swatches themselves (tint swatches, gradient
/// swatches' stops).
/// `f(colour, link, tint)` may change them and returns true when it did
/// ([`Paint::map_links`]). Only nodes holding a changed paint (and the paths to them) are
/// copied. Returns the number of changed paints.
@@ -134,6 +135,11 @@ impl Document {
for w in self.swatches_iter_mut() {
n += usize::from(w.paint.map_links(f));
}
for def in &mut self.char_styles {
for key in ["fill", "stroke"] {
n += usize::from(map_style_paint(&mut def.attrs, key, f));
}
}
n
}
@@ -198,6 +204,23 @@ pub fn color_name(c: Color) -> String {
/// true when it changed them.
pub type LinkFn<'a> = dyn FnMut(&mut Color, &mut Option<String>, &mut f32) -> bool + 'a;
/// Apply `f` to the paint a character style's attribute `key` holds, as [`Paint::map_links`]
/// does, and store the result in the attribute. True when it changed.
fn map_style_paint(attrs: &mut serde_json::Map<String, serde_json::Value>, key: &str, f: &mut LinkFn) -> bool {
let Some(value) = attrs.get_mut(key) else { return false };
let Ok(mut paint) = serde_json::from_value::<Paint>(value.clone()) else { return false };
if !paint.map_links(f) {
return false;
}
match serde_json::to_value(&paint) {
Ok(changed) => {
*value = changed;
true
}
Err(_) => false,
}
}
/// 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.
pub fn node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) {
+173 -4
View File
@@ -71,6 +71,79 @@ impl SymbolNineSlice {
}
}
/// One of the four 9-slice guides.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NineSliceGuide {
Left,
Top,
Right,
Bottom,
}
impl NineSliceGuide {
pub const ALL: [Self; 4] = [Self::Left, Self::Top, Self::Right, Self::Bottom];
}
/// The narrowest center band a guide dragged toward the opposite guide leaves, as a fraction of
/// the art's width or height (VectorCraft's own rule).
pub const MIN_CENTER_BAND: f64 = 0.001;
/// The 9-slice guides of the symbol edited in symbol editing mode, over its art on the editing
/// layer ([`Document::edited_nine_slice`]).
#[derive(Clone, Debug, PartialEq)]
pub struct EditedNineSlice {
/// The symbol's name.
pub symbol: String,
pub guides: SymbolNineSlice,
/// The art's geometric box at its natural size.
art: Rect,
/// The art at its natural size → the document.
to_doc: Affine,
}
impl EditedNineSlice {
/// Guide `g` as a line across the art's box, from one edge to the other, in the document.
pub fn line(&self, g: NineSliceGuide) -> (Point, Point) {
let (b, s) = (self.art, self.guides);
let (a, c) = match g {
NineSliceGuide::Left | NineSliceGuide::Right => {
let x = if g == NineSliceGuide::Left { b.x0 + s.left * b.width() } else { b.x1 - s.right * b.width() };
(Point::new(x, b.y0), Point::new(x, b.y1))
}
NineSliceGuide::Top | NineSliceGuide::Bottom => {
let y = if g == NineSliceGuide::Top { b.y0 + s.top * b.height() } else { b.y1 - s.bottom * b.height() };
(Point::new(b.x0, y), Point::new(b.x1, y))
}
};
(self.to_doc * a, self.to_doc * c)
}
/// The four guides' lines: left, top, right, bottom.
pub fn lines(&self) -> [(NineSliceGuide, Point, Point); 4] {
NineSliceGuide::ALL.map(|g| {
let (a, b) = self.line(g);
(g, a, b)
})
}
/// The guides with guide `g` moved across its axis to document point `p`. The guide stays
/// within the art's box, and [`MIN_CENTER_BAND`] short of the opposite guide, or where it is
/// when the guides are already closer than that. A point that is not finite leaves the guides
/// as they are.
pub fn moved(&self, g: NineSliceGuide, p: Point) -> SymbolNineSlice {
let (b, mut out) = (self.art, self.guides);
let q = self.to_doc.inverse() * p;
let fit = |v: f64, other: f64, now: f64| if v.is_finite() { v.clamp(0.0, (1.0 - other - MIN_CENTER_BAND).max(now)) } else { now };
match g {
NineSliceGuide::Left => out.left = fit((q.x - b.x0) / b.width(), out.right, out.left),
NineSliceGuide::Right => out.right = fit((b.x1 - q.x) / b.width(), out.left, out.right),
NineSliceGuide::Top => out.top = fit((q.y - b.y0) / b.height(), out.bottom, out.top),
NineSliceGuide::Bottom => out.bottom = fit((b.y1 - q.y) / b.height(), out.top, out.bottom),
}
out
}
}
/// The most objects [`NineSliceMap::place`] makes for each object of the art it places: an
/// object drawn in nine cells becomes a group of nine clip groups, each a clip path and a copy.
pub const MAX_SLICE_GROWTH: u64 = 28;
@@ -364,6 +437,11 @@ impl NineSliceMap {
self.most_at(art, &boxes, 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)
}
/// [`Self::most_placed`] for `n` at nesting depth `depth`, following [`Self::place_at`].
fn most_at(&self, n: &Node, boxes: &SymbolBoxes, depth: u32) -> u64 {
let whole = n.count_with_masks() as u64;
@@ -638,14 +716,30 @@ impl Document {
}
}
/// The 9-slice guides of the symbol being edited in symbol editing mode, over its art on the
/// editing layer: `None` outside the mode, when the symbol has no guides, or when its art has
/// no width or height.
pub fn edited_nine_slice(&self) -> Option<EditedNineSlice> {
let se = self.symbol_edit.as_ref()?;
let guides = self.symbol_nine_slice(&se.symbol)?;
let sym = self.symbols.iter().find(|s| s.name == se.symbol)?;
let art = self.symbol_boxes().quick().art_bounds(&se.symbol).or_else(|| sym.art.geometric_bounds())?;
let natural = self.symbol_natural_xf(&se.symbol);
let b = natural.transform_rect_bbox(art);
if !finite(b) || b.width() <= 1e-9 || b.height() <= 1e-9 || natural.determinant().abs() < 1e-18 {
return None;
}
let to_doc = se.xf * natural.inverse();
let det = to_doc.determinant();
let usable = to_doc.as_coeffs().into_iter().all(f64::is_finite) && det.is_finite() && det.abs() > 1e-18;
usable.then(|| EditedNineSlice { symbol: se.symbol.clone(), guides, art: b, to_doc })
}
/// [`Self::place_symbol_art`] for writers that do not apply clipping
/// ([`NineSliceMap::place_unclipped`]).
pub fn place_symbol_art_unclipped(&self, name: &str, art: &Node, xf: Affine) -> Option<Node> {
match self.symbol_slice_map(name, xf) {
Some(m) => {
let m = NineSliceMap { clips: false, ..m };
(m.most_placed(art, self) <= MAX_SYMBOL_NODES).then(|| m.place(art, self))
}
Some(m) => (m.most_placed_unclipped(art, self) <= MAX_SYMBOL_NODES).then(|| m.place_unclipped(art, self)),
None => Some(transformed(art, xf)),
}
}
@@ -1072,6 +1166,9 @@ mod tests {
let bar = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 40.0, 100.0, 60.0)), Appearance::basic(gradient, Paint::None, 0.0));
assert_eq!(m.most_placed(&bar, &d), 10);
assert_eq!(m.place(&bar, &d).count(), 10);
// Unclipped, as DXF writes it, the bar is cut at the guides and stays one path.
assert_eq!(m.most_placed_unclipped(&bar, &d), 1);
assert_eq!(m.place_unclipped(&bar, &d).count(), 1);
// Art nested past the depth limit, clipped in all nine cells.
let mut deep = square(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0);
for _ in 0..=MAX_SLICE_DEPTH {
@@ -1279,4 +1376,76 @@ mod tests {
let v = inst.visual_bounds_with(&d.symbol_boxes());
assert!(v.is_some_and(|b| near(b, whole)), "{v:?}");
}
/// Symbol "S" of [`markers`] edited in symbol editing mode, its art placed by `xf`.
fn editing(guides: Option<SymbolNineSlice>, xf: Affine) -> Document {
let mut d = markers(guides);
let layer = d.layers[0].id;
d.symbol_edit = Some(crate::SymbolEdit {
symbol: "S".into(),
layer,
instance: None,
xf,
group: true,
changed: false,
back_isolation: None,
back_layer: None,
});
d
}
fn near_point(a: Point, b: Point) -> bool {
(a - b).hypot() < 1e-9
}
/// While a symbol with guides is edited, its four guides cross its art's box from edge to edge
/// where the art shows on the editing layer: here at 25 % in, the art doubled and moved.
#[test]
fn the_edited_symbols_guides_cross_its_art_where_the_editing_layer_shows_it() {
let xf = Affine::translate((10.0, 20.0)) * Affine::scale(2.0);
let e = editing(Some(SymbolNineSlice::default()), xf).edited_nine_slice().unwrap();
assert_eq!(e.symbol, "S");
let want = [
(NineSliceGuide::Left, Point::new(60.0, 20.0), Point::new(60.0, 220.0)),
(NineSliceGuide::Top, Point::new(10.0, 70.0), Point::new(210.0, 70.0)),
(NineSliceGuide::Right, Point::new(160.0, 20.0), Point::new(160.0, 220.0)),
(NineSliceGuide::Bottom, Point::new(10.0, 170.0), Point::new(210.0, 170.0)),
];
for ((g, a, b), (wg, wa, wb)) in e.lines().into_iter().zip(want) {
assert!(g == wg && near_point(a, wa) && near_point(b, wb), "{g:?} {a:?} {b:?}");
}
// Outside the mode, without guides, or for a symbol that is gone: no guides.
assert!(markers(Some(SymbolNineSlice::default())).edited_nine_slice().is_none());
assert!(editing(None, xf).edited_nine_slice().is_none());
let mut d = editing(Some(SymbolNineSlice::default()), xf);
d.symbols.clear();
assert!(d.edited_nine_slice().is_none());
}
/// Moving a guide changes that guide alone, follows the pointer across its axis only, stays
/// within the art's box and stops short of the opposite guide.
#[test]
fn a_moved_guide_stays_in_the_art_and_short_of_the_opposite_guide() {
let xf = Affine::translate((10.0, 20.0)) * Affine::scale(2.0);
let e = editing(Some(SymbolNineSlice::default()), xf).edited_nine_slice().unwrap();
let q = SymbolNineSlice { left: 0.25, top: 0.25, right: 0.25, bottom: 0.25 };
assert_eq!(e.moved(NineSliceGuide::Left, Point::new(30.0, 999.0)), SymbolNineSlice { left: 0.1, ..q });
assert_eq!(e.moved(NineSliceGuide::Bottom, Point::new(-50.0, 180.0)), SymbolNineSlice { bottom: 0.2, ..q });
assert_eq!(e.moved(NineSliceGuide::Top, Point::new(0.0, -500.0)), SymbolNineSlice { top: 0.0, ..q });
assert_eq!(e.moved(NineSliceGuide::Right, Point::new(1e6, 0.0)), SymbolNineSlice { right: 0.0, ..q });
let crossed = e.moved(NineSliceGuide::Left, Point::new(200.0, 50.0));
assert!((crossed.left - (0.75 - MIN_CENTER_BAND)).abs() < 1e-12, "{crossed:?}");
assert!(SymbolNineSlice::new(crossed.left, crossed.top, crossed.right, crossed.bottom).is_some());
assert_eq!(e.moved(NineSliceGuide::Top, Point::new(f64::NAN, f64::NAN)), q);
// Saved guides closer than the minimum center band keep their place when a drag does not
// move them closer.
let narrow = SymbolNineSlice::new(0.00005, 0.25, 0.9999, 0.25).unwrap();
let e = editing(Some(narrow), xf).edited_nine_slice().unwrap();
assert_eq!(e.moved(NineSliceGuide::Left, Point::new(200.0, 50.0)), narrow);
assert_eq!(e.moved(NineSliceGuide::Left, Point::new(0.0, 50.0)), SymbolNineSlice { left: 0.0, ..narrow });
// A mirrored placement measures along the symbol's own axes.
let e = editing(Some(SymbolNineSlice::default()), Affine::scale_non_uniform(-1.0, 1.0)).edited_nine_slice().unwrap();
assert!(near_point(e.line(NineSliceGuide::Left).0, Point::new(-25.0, 0.0)));
assert_eq!(e.moved(NineSliceGuide::Left, Point::new(-10.0, 0.0)), SymbolNineSlice { left: 0.1, ..q });
}
}
+5
View File
@@ -93,6 +93,10 @@ pub struct CharStyle {
/// them.
#[serde(default, rename = "charDirection", skip_serializing_if = "Option::is_none")]
pub char_direction: Option<ParaDirection>,
/// Character panel menu › Kashidas: whether these characters may receive a kashida when
/// their paragraph is justified with Insert Kashidas. On by default, including old documents.
#[serde(default = "crate::yes", skip_serializing_if = "crate::skip::is_true")]
pub kashidas: bool,
/// Proportional Metrics (Character panel menu, East Asian options): full-width glyphs take the
/// font's own proportional widths, OpenType `palt` (#966); in vertical type upright glyphs take
/// its proportional heights, `vpal`.
@@ -405,6 +409,7 @@ impl Default for CharStyle {
position: CharPosition::Normal,
char_align: CharAlign::RomanBaseline,
char_direction: None,
kashidas: true,
proportional_metrics: false,
tate_chu_yoko: false,
tcy_up_down: 0.0,
+4
View File
@@ -435,12 +435,16 @@ impl crate::Document {
st.h_scale = num("h_scale").unwrap_or(st.h_scale);
st.v_scale = num("v_scale").unwrap_or(st.v_scale);
st.baseline_shift = num("baseline_shift").unwrap_or(st.baseline_shift);
st.tcy_up_down = num("tcyUpDown").unwrap_or(st.tcy_up_down);
st.tcy_left_right = num("tcyLeftRight").unwrap_or(st.tcy_left_right);
st.keep_dimensions_in_range();
let kept = [
("size", Some(st.size)),
("h_scale", Some(st.h_scale)),
("v_scale", Some(st.v_scale)),
("baseline_shift", Some(st.baseline_shift)),
("tcyUpDown", Some(st.tcy_up_down)),
("tcyLeftRight", Some(st.tcy_left_right)),
("leading", st.leading),
];
for (k, v) in kept {
+17
View File
@@ -103,6 +103,23 @@ fn shape_modes_follow_the_pathfinder_panel() {
assert_eq!(div.len(), 3);
}
/// Divide and Outline draw no piece of a member without fill or stroke, the same as when such
/// pieces are left out.
#[test]
fn divide_and_outline_draw_nothing_for_unpainted_members() {
let unpainted =
Arc::new(Node::path(NodeId(2), shapes::rectangle(Rect::new(5.0, 0.0, 15.0, 10.0)), Appearance::basic(Paint::None, Paint::None, 0.0)));
for effect in ["pathfinder.divide", "pathfinder.outline"] {
let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), unpainted.clone()]);
g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({}), visible: true });
let out = pathfinder_children(&g, None).unwrap();
assert!(out.iter().any(|n| n.id == NodeId(1)) && out.iter().any(|n| n.id == NodeId(2)), "{effect}: {out:#?}");
for n in out.iter().filter(|n| n.id == NodeId(2)) {
assert!(n.appearance.items.iter().all(|i| i.paint().is_none()), "{effect}: {n:#?}");
}
}
}
/// Returns an "H" in blue type at 100 pt on a baseline at y = 80, with its stems on either
/// side of x = 100.
fn type_h() -> Node {
+4
View File
@@ -57,6 +57,10 @@ pub fn dash(bp: &BezPath, d: &Dash) -> Option<Dashed> {
pat.extend_from_within(..);
}
let period: f64 = pat.iter().sum();
// Finite entries can still sum to infinity, which would never leave the phase loop below.
if !period.is_finite() {
return None;
}
let plans: Vec<Plan> = subpaths(bp)
.into_iter()
.map(|(r, closed)| {
+5
View File
@@ -21,6 +21,11 @@ fn stroke(width: f64, f: impl FnOnce(&mut StrokeLayer)) -> StrokeLayer {
st
}
#[test]
fn dash_period_overflowing_to_infinity_is_solid() {
assert!(dash(&line(0.0, 60.0), &dashed(&[f64::MAX, f64::MAX], -1.0)).is_none());
}
fn dashed(pattern: &[f64], offset: f64) -> Dash {
Dash { pattern: pattern.to_vec(), offset, align_corners: false }
}
+20
View File
@@ -611,6 +611,26 @@ pub(crate) fn unique_name(base: &str, taken: impl Fn(&str) -> bool) -> String {
(2..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_else(|| base.to_string())
}
/// [`unique_name`] for names given one after another (an import): `next` keeps, per base (in
/// any case), the number after the last one tried, so a run of one name doesn't count up from 2
/// again for each copy. Names only become taken meanwhile, so the result is the same.
pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<String, usize>, taken: impl Fn(&str) -> bool) -> String {
if !taken(base) {
return base.to_string();
}
let i = next.entry(base.to_lowercase()).or_insert(2);
loop {
let n = format!("{base} {i}");
*i += 1;
if !taken(&n) {
return n;
}
}
}
/// The most presets one presets file imports: each is looked up among the saved ones.
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use edit::{settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
pub(crate) use vectorcraft_doc::range::parse_range;
+2
View File
@@ -7,6 +7,7 @@ mod color;
mod document;
mod pathtools;
mod pen;
mod typetools;
use super::CommandSpec;
@@ -18,5 +19,6 @@ pub fn specs() -> Vec<CommandSpec> {
v.extend(document::specs());
v.extend(pathtools::specs());
v.extend(pen::specs());
v.extend(typetools::specs());
v
}
+165
View File
@@ -0,0 +1,165 @@
//! Type Tools (`addon.type.*`), a built-in add-on: Text Tweaker gives one character attribute to
//! the selected characters letter by letter, from a start value to an end value along a shape
//! (straight, eased, a bow, a spike, or at random), while the text stays live. Values are set as
//! the Character panel sets them (`text.setRangeStyle`), in its units and ranges
//! (<https://helpx.adobe.com/illustrator/using/formatting-type.html>). Its submenu
//! (Object › Plug-ins › Type Tools) and dialog are the UI's.
#[cfg(test)]
mod tests;
use serde_json::{Value, json};
use vectorcraft_color::recolor::Rng;
use vectorcraft_doc::{NodeId, TextRun};
use vectorcraft_text::edit;
use super::super::menucmds::whole_or;
use super::super::object::choice;
use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges};
use super::super::typecmd::refresh_bounds;
use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or};
use crate::{EngineError, Result, Session};
/// An attribute Text Tweaker sets: its `text.setRangeStyle` param, the values it takes and its
/// default start and end.
type Attribute = (&'static str, (f64, f64), (f64, f64));
/// The attributes Text Tweaker sets.
pub const ATTRIBUTES: [Attribute; 8] = [
("size", (0.1, 1296.0), (12.0, 36.0)),
("baselineShift", (-1296.0, 1296.0), (0.0, 12.0)),
("rotation", (-360.0, 360.0), (0.0, 30.0)),
("hScale", (1.0, 10000.0), (100.0, 150.0)),
("vScale", (1.0, 10000.0), (100.0, 150.0)),
("tracking", (-1000.0, 10000.0), (0.0, 200.0)),
("leading", (0.1, 5000.0), (12.0, 36.0)),
("strokeWidth", (0.0, 1000.0), (0.0, 2.0)),
];
/// The shapes the values follow from the first character to the last.
pub const SHAPES: [&str; 5] = ["straight", "ease", "bow", "spike", "random"];
/// The most characters one run changes.
const MAX_CHARS: usize = 100_000;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.type.textTweaker",
"Text Tweaker",
["Object", "Plug-ins", "Type Tools"],
None,
"{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}",
has_selection,
text_tweaker
)]
}
/// Where along `shape` (0 at `from`, 1 at `to`) character `i` of `n` lands; `random` for the
/// random shape.
fn amount(shape: &str, i: usize, n: usize, random: f64) -> f64 {
let t = if n > 1 { i as f64 / (n - 1) as f64 } else { 0.0 };
match shape {
"ease" => t * t * (3.0 - 2.0 * t),
"bow" => (std::f64::consts::PI * t).sin(),
"spike" => 1.0 - (2.0 * t - 1.0).abs(),
"random" => random,
_ => t,
}
}
/// A random number from 0 to 1.
fn unit(rng: &mut Rng) -> f64 {
(rng.next_u64() >> 11) as f64 / (1u64 << 53) as f64
}
fn text_tweaker(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.type.textTweaker";
let attribute = choice(p, C, "attribute", &ATTRIBUTES.map(|a| a.0))?.unwrap_or("size");
let Some(&(key, (lo, hi), (from0, to0))) = ATTRIBUTES.iter().find(|a| a.0 == attribute) else {
return Err(bad(C, format!("unknown attribute `{attribute}`")));
};
let mut ends = [0.0; 2];
for (end, (k, default)) in ends.iter_mut().zip([("from", from0), ("to", to0)]) {
let v = number_or(p, k, default, C)?;
if !(lo..=hi).contains(&v) {
return Err(bad(C, format!("`{k}` must be from {lo} to {hi} for {key}")));
}
*end = v;
}
let [from, to] = ends;
let shape = choice(p, C, "shape", &SHAPES)?.unwrap_or("straight");
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
let skip = switch_or(p, "skipSpaces", true, C)?;
let setup = s.doc()?.doc.setup.clone();
// At a caret, all of the object's text.
let ranges = type_ranges(s, p, C, |text, _| Some((0, text.len())))?;
// Each object's changed characters: (byte, its change), worked out before the edit.
let mut plans: Vec<(NodeId, Vec<(usize, CharChange)>)> = vec![];
let mut count = 0;
for (id, a, b, _) in ranges {
let t = text_ref(s, id)?;
let text = t.plain_text();
let chars: Vec<usize> =
text.char_indices().filter(|&(i, c)| (a..b).contains(&i) && !(skip && (c.is_whitespace() || c.is_control()))).map(|(i, _)| i).collect();
count += chars.len();
if count > MAX_CHARS {
return Err(bad(C, format!("too many characters: at most {MAX_CHARS}")));
}
let n = chars.len();
let mut changes = Vec::with_capacity(n);
for (i, at) in chars.into_iter().enumerate() {
let random = if shape == "random" { unit(&mut rng) } else { 0.0 };
let value = from + (to - from) * amount(shape, i, n, random);
let mut change = CharChange::parse(&json!({ key: value }), C, &setup)?;
change.localize(&t, C)?;
changes.push((at, change));
}
if !changes.is_empty() {
plans.push((id, changes));
}
}
if plans.is_empty() {
return Ok(json!({ "count": 0, "ids": [] }));
}
let ids: Vec<u64> = plans.iter().map(|(id, _)| id.0).collect();
s.edit("Text Tweaker", |d, _| {
for (id, changes) in &plans {
let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?;
t.runs = tweak(std::mem::take(&mut t.runs), changes);
refresh_bounds(t);
}
Ok(())
})?;
Ok(json!({ "count": count, "ids": ids }))
}
/// `runs` with each character at a byte of `changes` (in order) changed: its run split into
/// characters, the changes applied, and runs that came out alike merged again.
fn tweak(runs: Vec<TextRun>, changes: &[(usize, CharChange)]) -> Vec<TextRun> {
let mut out = Vec::with_capacity(runs.len() + changes.len() * 2);
let mut next = changes.iter().peekable();
let mut off = 0;
for r in runs {
let end = off + r.text.len();
if r.inline.is_some() || next.peek().is_none_or(|(at, _)| *at >= end) {
// An inline graphic is one character: its style changes whole.
if let Some((_, change)) = next.next_if(|(at, _)| (off..end).contains(at)) {
let mut r = r;
change.apply(&mut r.style);
out.push(r);
} else {
out.push(r);
}
off = end;
continue;
}
for (i, c) in r.text.char_indices() {
let mut piece = TextRun::new(c.to_string(), r.style.clone());
if let Some((_, change)) = next.next_if(|(at, _)| *at == off + i) {
change.apply(&mut piece.style);
}
out.push(piece);
}
off = end;
}
edit::normalize(&mut out);
out
}
@@ -0,0 +1,195 @@
//! Text Tweaker: the values each shape gives each character, what it skips and changes, one undo
//! step, and bad params refused without a change.
use serde_json::json;
use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextObject};
use super::amount;
use crate::Session;
const C: &str = "addon.type.textTweaker";
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
s
}
fn text(s: &mut Session, words: &str) -> NodeId {
NodeId(s.execute("text.create", &json!({"x": 40, "y": 100, "text": words, "size": 20})).unwrap()["id"].as_u64().unwrap())
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.select(|_, sel| sel.set(ids.iter().copied())).unwrap();
}
fn obj(s: &Session, id: NodeId) -> TextObject {
match &s.doc().unwrap().doc.node(id).unwrap().kind {
NodeKind::Text(t) => (**t).clone(),
_ => panic!("not text"),
}
}
/// Each character of `id` with its style.
fn styles(s: &Session, id: NodeId) -> Vec<(char, CharStyle)> {
obj(s, id).runs.iter().flat_map(|r| r.text.chars().map(|c| (c, r.style.clone())).collect::<Vec<_>>()).collect()
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn near(a: &[f64], b: &[f64]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9)
}
#[test]
fn the_shapes_run_from_the_start_value_to_the_end_value() {
let at = |shape, n| (0..n).map(|i| amount(shape, i, n, 0.5)).collect::<Vec<_>>();
assert!(near(&at("straight", 5), &[0.0, 0.25, 0.5, 0.75, 1.0]));
assert!(near(&at("ease", 5), &[0.0, 0.15625, 0.5, 0.84375, 1.0]), "slow at both ends");
let bow = at("bow", 5);
assert!(near(&[bow[0], bow[2], bow[4]], &[0.0, 1.0, 0.0]) && (bow[1] - 0.5f64.sqrt()).abs() < 1e-9, "a smooth arc");
assert!(near(&at("spike", 5), &[0.0, 0.5, 1.0, 0.5, 0.0]), "straight up and down");
assert!(near(&at("random", 3), &[0.5; 3]));
assert!(near(&at("straight", 1), &[0.0]), "one character takes the start value");
}
#[test]
fn a_straight_ramp_sizes_each_letter_and_skips_spaces() {
let mut s = session();
let id = text(&mut s, "ab cd");
select(&mut s, &[id]);
let n = steps(&s);
let out = s.execute(C, &json!({"attribute": "size", "from": 10, "to": 40})).unwrap();
assert_eq!(out, json!({"count": 4, "ids": [id.0]}));
assert_eq!(steps(&s), n + 1, "one undo step");
let sizes: Vec<(char, f64)> = styles(&s, id).into_iter().map(|(c, st)| (c, st.size)).collect();
assert_eq!(sizes, [('a', 10.0), ('b', 20.0), (' ', 20.0), ('c', 30.0), ('d', 40.0)], "the space keeps its size");
assert_eq!(obj(&s, id).plain_text(), "ab cd", "the text stays live");
s.execute("edit.undo", &json!({})).unwrap();
assert!(styles(&s, id).iter().all(|(_, st)| st.size == 20.0), "undone");
}
#[test]
fn spaces_can_count_too() {
let mut s = session();
let id = text(&mut s, "a b");
select(&mut s, &[id]);
s.execute(C, &json!({"attribute": "baselineShift", "from": 0, "to": 10, "skipSpaces": false})).unwrap();
let shifts: Vec<f64> = styles(&s, id).iter().map(|(_, st)| st.baseline_shift).collect();
assert_eq!(shifts, [0.0, 5.0, 10.0]);
}
#[test]
fn every_attribute_is_set_as_the_character_panel_sets_it() {
let mut s = session();
for (attribute, get) in [
("size", (|st: &CharStyle| st.size) as fn(&CharStyle) -> f64),
("baselineShift", |st| st.baseline_shift),
("rotation", |st| st.rotation),
("hScale", |st| st.h_scale),
("vScale", |st| st.v_scale),
("tracking", |st| st.tracking),
("leading", |st| st.leading.unwrap_or(-1.0)),
("strokeWidth", |st| st.stroke_width),
] {
let id = text(&mut s, "xyz");
select(&mut s, &[id]);
s.execute(C, &json!({"attribute": attribute, "from": 2, "to": 6})).unwrap();
let got: Vec<f64> = styles(&s, id).iter().map(|(_, st)| get(st)).collect();
assert!(near(&got, &[2.0, 4.0, 6.0]), "{attribute}: {got:?}");
}
}
#[test]
fn each_object_gets_its_own_ramp() {
let mut s = session();
let (a, b) = (text(&mut s, "abc"), text(&mut s, "de"));
select(&mut s, &[a, b]);
let out = s.execute(C, &json!({"attribute": "rotation", "from": 0, "to": 30})).unwrap();
assert_eq!(out["count"], json!(5));
let turns = |id| styles(&s, id).iter().map(|(_, st)| st.rotation).collect::<Vec<_>>();
assert_eq!((turns(a), turns(b)), (vec![0.0, 15.0, 30.0], vec![0.0, 30.0]));
}
#[test]
fn a_range_changes_only_its_characters() {
let mut s = session();
let id = text(&mut s, "abcde");
s.execute(C, &json!({"id": id.0, "start": 1, "end": 4, "attribute": "tracking", "from": 100, "to": 300})).unwrap();
let tracking: Vec<f64> = styles(&s, id).iter().map(|(_, st)| st.tracking).collect();
assert_eq!(tracking, [0.0, 100.0, 200.0, 300.0, 0.0]);
}
#[test]
fn random_values_stay_in_range_and_repeat_with_the_seed() {
let mut s = session();
let id = text(&mut s, "randomness");
select(&mut s, &[id]);
let run = |s: &mut Session, seed| {
s.execute(C, &json!({"attribute": "vScale", "from": 50, "to": 150, "shape": "random", "seed": seed})).unwrap();
styles(s, id).iter().map(|(_, st)| st.v_scale).collect::<Vec<_>>()
};
let first = run(&mut s, 7);
assert!(first.iter().all(|v| (50.0..=150.0).contains(v)), "{first:?}");
assert!(first.windows(2).any(|w| w[0] != w[1]), "values vary");
assert_eq!(run(&mut s, 7), first, "same seed, same values");
assert_ne!(run(&mut s, 8), first, "another seed, other values");
}
#[test]
fn values_follow_the_text_transform_as_the_character_panel_does() {
let mut s = session();
let id = text(&mut s, "ab");
select(&mut s, &[id]);
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
s.execute(C, &json!({"attribute": "size", "from": 20, "to": 40})).unwrap();
let sizes: Vec<f64> = styles(&s, id).iter().map(|(_, st)| st.size).collect();
// Shown sizes are the asked ones: stored sizes are half, the text being scaled twice.
let scale = obj(&s, id).style_scale().unwrap().points;
assert!(near(&sizes.iter().map(|v| v * scale).collect::<Vec<_>>(), &[20.0, 40.0]), "{sizes:?} at {scale}");
}
#[test]
fn empty_text_and_only_spaces_change_nothing() {
let mut s = session();
let id = text(&mut s, " ");
select(&mut s, &[id]);
let n = steps(&s);
assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"count": 0, "ids": []}));
assert_eq!(steps(&s), n, "no step");
}
#[test]
fn bad_params_are_refused_without_a_change() {
let mut s = session();
let id = text(&mut s, "abc");
select(&mut s, &[id]);
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
for p in [
json!({"attribute": "colour"}),
json!({"attribute": 3}),
json!({"shape": "zigzag"}),
json!({"attribute": "size", "from": 0}),
json!({"attribute": "size", "to": 5000}),
json!({"attribute": "hScale", "from": -1}),
json!({"from": "big"}),
json!({"to": f64::MAX}),
json!({"seed": -1}),
json!({"skipSpaces": "yes"}),
json!({"ids": [999_999]}),
] {
assert!(s.execute(C, &p).is_err(), "{p}");
assert_eq!(s.doc().unwrap().doc, before, "{p}");
assert_eq!(steps(&s), n, "{p}");
}
}
#[test]
fn it_needs_a_selection() {
let mut s = session();
text(&mut s, "abc");
select(&mut s, &[]);
assert!(s.execute(C, &json!({})).is_err());
}
+8 -3
View File
@@ -107,10 +107,14 @@ impl BrushLibrary {
/// `name`: the brushes and every resource their art uses.
pub fn from_document(src: &Document, names: &[String], name: String) -> std::result::Result<Self, String> {
let all = brush::library(src);
if let Some(n) = names.iter().find(|n| !all.iter().any(|b| b.name == **n)) {
// Names looked up in sets: scanning the lists for each brush made a library of N brushes
// cost N² comparisons.
let have: HashSet<&str> = all.iter().map(|b| b.name.as_str()).collect();
if let Some(n) = names.iter().find(|n| !have.contains(n.as_str())) {
return Err(format!("no brush `{n}`"));
}
let picked = all.iter().filter(|b| names.is_empty() || names.contains(&b.name));
let wanted: HashSet<&str> = names.iter().map(String::as_str).collect();
let picked = all.iter().filter(|b| names.is_empty() || wanted.contains(b.name.as_str()));
let clip = Clipboard::gather(src, picked.map(|b| stroke(&b.name)).collect());
let mut doc = clip.to_document();
for l in &mut doc.layers {
@@ -120,7 +124,8 @@ impl BrushLibrary {
}
// The brushes picked and those their art paints with, in the panel order of the document
// they came from.
let brushes: Vec<Brush> = all.into_iter().filter(|b| clip.brushes.iter().any(|c| c.name == b.name)).collect();
let kept: HashSet<&str> = clip.brushes.iter().map(|c| c.name.as_str()).collect();
let brushes: Vec<Brush> = all.iter().filter(|b| kept.contains(b.name.as_str())).cloned().collect();
brush::store(&mut doc, &brushes);
doc.title = name.clone();
Ok(Self { name, brushes, doc })
+11 -2
View File
@@ -161,10 +161,19 @@ impl Clipboard {
d.para_styles = self.para_styles.clone().into();
if !self.brushes.is_empty() {
let mut lib = vectorcraft_brush::library(&d);
// Each brush's place in the library by name: finding it by scanning the growing list
// made a library of N brushes cost N² comparisons.
let mut at: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
for (i, b) in lib.iter().enumerate() {
at.entry(b.name.clone()).or_insert(i);
}
for b in &self.brushes {
match lib.iter_mut().find(|x| x.name == b.name) {
match at.get(&b.name).and_then(|&i| lib.get_mut(i)) {
Some(x) => *x = b.clone(),
None => lib.push(b.clone()),
None => {
at.insert(b.name.clone(), lib.len());
lib.push(b.clone());
}
}
}
vectorcraft_brush::store(&mut d, &lib);
+25 -7
View File
@@ -125,6 +125,10 @@ pub struct Flavour {
/// Longest side (px) of the PNG Copy offers: larger art is scaled down to fit.
const COPY_PNG_SIDE: f64 = 4096.0;
/// The smallest scale (pixels a point) the PNG encoder renders at.
const MIN_COPY_PNG_SCALE: f64 = 0.01;
/// What Copy says when the art is too large for its PNG.
const TOO_LARGE_FOR_PNG: &str = "The art is too large to copy as a picture: other apps get no PNG of it";
/// Most bytes of text `clipboard.importText` takes.
const MAX_TEXT: usize = 1 << 20;
/// Most bytes of images the SVG markup may embed and still go out as plain text. A paste reads the
@@ -288,12 +292,24 @@ impl Clipboard {
let text = (svg && self.image_bytes() <= COPY_TEXT_IMAGE_BYTES) || self.nodes.iter().all(type_only);
// Art without an area (a lone guide-like line) has no page or picture.
let area = self.bounds().is_some_and(|b| b.width() > 0.0 && b.height() > 0.0);
[(TEXT, text), (SVG, svg), (PDF, pdf && area), (PNG, area)].into_iter().filter_map(|(m, on)| on.then_some(m)).collect()
[(TEXT, text), (SVG, svg), (PDF, pdf && area), (PNG, area && self.png_scale().is_some())]
.into_iter()
.filter_map(|(m, on)| on.then_some(m))
.collect()
}
/// The scale (pixels a point) of the PNG Copy offers: at most [`COPY_PNG_SIDE`] pixels a side,
/// and `None` when even [`MIN_COPY_PNG_SCALE`], the encoder's smallest, can't bring it that small
/// (rather than a PNG of up to a gigabyte of pixels).
fn png_scale(&self) -> Option<f64> {
let side = self.bounds().map_or(1.0, |b| b.width().max(b.height()));
Some((COPY_PNG_SIDE / side).min(1.0)).filter(|s| *s >= MIN_COPY_PNG_SCALE)
}
/// What Copy offers other apps, best first, with Include SVG Code (`svg`) and On Copy: PDF
/// (`pdf`) as given (see `clipboard.flavours`). A [`Flavour`] that can't be made (art too large
/// to render) is left out; the PNG is scaled down to at most [`COPY_PNG_SIDE`] pixels a side.
/// to render) is left out; the PNG is scaled down to at most [`COPY_PNG_SIDE`] pixels a side, and
/// left out when even [`MIN_COPY_PNG_SCALE`] can't bring it that small.
pub fn flavours(&self, svg: bool, pdf: bool) -> Vec<Flavour> {
self.flavours_with_warnings(svg, pdf).0
}
@@ -305,6 +321,9 @@ impl Clipboard {
let svg = types.contains(&SVG).then(|| self.svg()).flatten();
let mut out = vec![];
let mut warnings: Vec<String> = vec![];
if !self.is_empty() && self.png_scale().is_none() {
warnings.push(TOO_LARGE_FOR_PNG.to_string());
}
let mut keep = |(bytes, notes): (Vec<u8>, Vec<String>)| {
for w in notes {
if !warnings.contains(&w) {
@@ -318,11 +337,10 @@ impl Clipboard {
TEXT => self.text().or_else(|| svg.clone()).map(String::into_bytes),
SVG => svg.clone().map(String::into_bytes),
PDF => self.pdf().inspect_err(|e| log::warn!("clipboard PDF: {e}")).ok().flatten().map(&mut keep),
_ => {
let side = self.bounds().map_or(1.0, |b| b.width().max(b.height()));
let scale = (COPY_PNG_SIDE / side).clamp(0.01, 1.0);
self.png(scale).inspect_err(|e| log::warn!("clipboard PNG: {e}")).ok().flatten().map(|(png, _, _, notes)| keep((png, notes)))
}
_ => self
.png_scale()
.and_then(|scale| self.png(scale).inspect_err(|e| log::warn!("clipboard PNG: {e}")).ok().flatten())
.map(|(png, _, _, notes)| keep((png, notes))),
};
out.extend(data.map(|data| Flavour { mime, data }));
}
+56 -12
View File
@@ -14,7 +14,7 @@
//! uses its resources as they are now.
use std::cell::OnceCell;
use std::collections::{BTreeMap, BTreeSet};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::sync::Arc;
use serde_json::{Map, Value, json};
@@ -149,6 +149,39 @@ struct Defs<'a> {
char_styles: &'a [TextStyleDef],
para_styles: &'a [TextStyleDef],
brushes: Brushes<'a>,
/// Where each name is defined, built the first time a kind is followed.
index: DefIndex,
}
/// The positions of a kind's definitions by name.
type NameIndex = HashMap<String, Vec<usize>>;
/// [`Defs`]' definitions by name (graphic styles by id), each kind indexed the first time a
/// reference to it is followed: finding a name's definitions by scanning them all made a
/// document or library of N definitions that use each other cost N² comparisons.
#[derive(Default)]
struct DefIndex {
swatches: OnceCell<NameIndex>,
symbols: OnceCell<NameIndex>,
patterns: OnceCell<NameIndex>,
styles: OnceCell<HashMap<u32, Vec<usize>>>,
char_styles: OnceCell<NameIndex>,
para_styles: OnceCell<NameIndex>,
brushes: OnceCell<NameIndex>,
}
/// The items of `list` named `name`, in order, `index` holding their positions (built from
/// `list` the first time).
fn named<'l, T>(index: &OnceCell<NameIndex>, list: &'l [T], name_of: impl Fn(&T) -> &str, name: &str) -> impl Iterator<Item = &'l T> {
let index = index.get_or_init(|| {
let mut by: NameIndex = HashMap::new();
for (i, item) in list.iter().enumerate() {
by.entry(name_of(item).to_string()).or_default().push(i);
}
by
});
let at: &[usize] = index.get(name).map_or(&[], Vec::as_slice);
at.iter().filter_map(move |&i| list.get(i))
}
/// The brushes references lead to: a document's library, read the first time a brush is used
@@ -178,6 +211,7 @@ impl<'a> Defs<'a> {
char_styles: &d.char_styles,
para_styles: &d.para_styles,
brushes: Brushes::Lazy(d, brushes),
index: DefIndex::default(),
}
}
}
@@ -219,8 +253,16 @@ impl Used {
fn note<'a>(&mut self, defs: &Defs<'a>, r: Ref<'_>, todo: &mut Vec<Source<'a>>) {
let (res, name) = match r {
Ref::Style(id) => {
if self.styles.insert(id) {
todo.extend(defs.styles.iter().filter(|g| g.id != 0 && g.id == id).map(|g| Source::Appearance(&g.appearance)));
if self.styles.insert(id) && id != 0 {
let index = defs.index.styles.get_or_init(|| {
let mut by: HashMap<u32, Vec<usize>> = HashMap::new();
for (i, g) in defs.styles.iter().enumerate() {
by.entry(g.id).or_default().push(i);
}
by
});
let at = index.get(&id).map_or(&[][..], Vec::as_slice);
todo.extend(at.iter().filter_map(|&i| defs.styles.get(i)).map(|g| Source::Appearance(&g.appearance)));
}
return;
}
@@ -237,15 +279,16 @@ impl Used {
return;
}
set.insert(name.to_string());
let ix = &defs.index;
match res {
// A tint swatch's base, a gradient swatch's linked stops.
Res::Swatch => todo.extend(defs.swatches.iter().filter(|w| w.name == name).map(|w| Source::Paint(&w.paint))),
Res::Symbol => todo.extend(defs.symbols.iter().filter(|s| s.name == name).map(|s| Source::Node(&s.art))),
Res::Pattern => todo.extend(defs.patterns.iter().filter(|p| p.name == name).flat_map(|p| p.art.iter().map(|a| Source::Node(a)))),
Res::CharStyle => todo.extend(defs.char_styles.iter().filter(|s| s.name == name).map(|s| Source::Attrs(&s.attrs))),
Res::ParaStyle => todo.extend(defs.para_styles.iter().filter(|s| s.name == name).map(|s| Source::Attrs(&s.attrs))),
Res::Swatch => todo.extend(named(&ix.swatches, &defs.swatches, |w| &w.name, name).map(|w| Source::Paint(&w.paint))),
Res::Symbol => todo.extend(named(&ix.symbols, defs.symbols, |s| &s.name, name).map(|s| Source::Node(&s.art))),
Res::Pattern => todo.extend(named(&ix.patterns, defs.patterns, |p| &p.name, name).flat_map(|p| p.art.iter().map(|a| Source::Node(a)))),
Res::CharStyle => todo.extend(named(&ix.char_styles, defs.char_styles, |s| &s.name, name).map(|s| Source::Attrs(&s.attrs))),
Res::ParaStyle => todo.extend(named(&ix.para_styles, defs.para_styles, |s| &s.name, name).map(|s| Source::Attrs(&s.attrs))),
// A scatter or art brush's art, a pattern brush's tiles.
Res::Brush => todo.extend(defs.brushes.get().iter().filter(|b| b.name == name).flat_map(|b| b.art().into_iter().map(Source::Node))),
Res::Brush => todo.extend(named(&ix.brushes, defs.brushes.get(), |b| &b.name, name).flat_map(|b| b.art().into_iter().map(Source::Node))),
_ => {}
}
}
@@ -649,6 +692,7 @@ impl Clipboard {
char_styles: &self.char_styles,
para_styles: &self.para_styles,
brushes: Brushes::Ready(&self.brushes),
index: DefIndex::default(),
};
Used::of(&defs, &self.nodes)
}
@@ -671,7 +715,7 @@ impl Clipboard {
self.import_swatches(d, &used, choices, same_doc, &mut out);
// Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art
// they may brush; the others once those are in.
let mut added_brushes = self.import_brushes(d, &used, same_doc, false, &mut out);
let mut added_brushes: HashSet<String> = self.import_brushes(d, &used, same_doc, false, &mut out).into_iter().collect();
// Character and paragraph styles (their colours relinked first).
for (r, mine, theirs) in [(Res::CharStyle, &self.char_styles, &mut d.char_styles), (Res::ParaStyle, &self.para_styles, &mut d.para_styles)] {
for def in mine.iter().filter(|s| used.has(r, &s.name)) {
@@ -683,14 +727,14 @@ impl Clipboard {
}
// Symbols and patterns, compared once relinked. Those added are relinked at the end, when
// every new name and graphic style id is known.
let mut added_symbols = vec![];
let mut added_symbols = HashSet::new();
for def in self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)) {
let r = &out.relink;
let p = place(&mut d.symbols, def, same_doc, |a, b| same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art)));
added_symbols.extend(p.new_name(&def.name));
out.placed(Res::Symbol, &def.name, &p);
}
let mut added_patterns = vec![];
let mut added_patterns = HashSet::new();
for def in self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)) {
// Tile options alike, and the art once relinked.
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
+77 -3
View File
@@ -1,7 +1,7 @@
//! Document Info panel data, its categories and the text report (Document Info › Save…, File →
//! Package), and Object → Make Pixel Perfect.
use std::collections::{BTreeMap, BTreeSet};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use serde_json::{Value, json};
use vectorcraft_color::Paint;
@@ -293,8 +293,14 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
// `repeats` and `repeat_rows` hold the `repeatObjects` entries and the rows of the Repeat objects that the walk visits, in walk order.
let mut repeats: Vec<Value> = vec![];
let mut repeat_rows: Vec<(String, String)> = vec![];
// The objects the walk has visited: a selection can hold a group and objects inside it, and each object counts once.
// The set holds each object's address, so two objects that share an id (as a damaged file can hold) count as two.
let mut seen: HashSet<*const Node> = HashSet::new();
for r in roots {
r.walk(&mut |n| {
if !seen.insert(std::ptr::from_ref(n)) {
return;
}
let k = match &n.kind {
NodeKind::Layer { .. } => None,
NodeKind::Group { clip: true, .. } => Some("clipGroups"),
@@ -337,13 +343,15 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(k) = k {
*counts.entry(k).or_default() += 1;
}
// The paint kinds this object's fills and strokes use, each once.
let mut kinds = BTreeSet::new();
for item in &n.appearance.items {
let paint = match item {
vectorcraft_doc::AppearanceItem::Fill(f) => &f.paint,
vectorcraft_doc::AppearanceItem::Stroke(s) => &s.paint,
};
if let Some(k) = paint_kind(paint) {
*counts.entry(k).or_default() += 1;
kinds.insert(k);
}
if let Paint::Pattern { pattern, .. } = paint {
patterns.insert(pattern.clone());
@@ -354,6 +362,9 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
spot.insert(name.clone());
}
}
for k in kinds {
*counts.entry(k).or_default() += 1;
}
if n.extras().mask.is_some() {
*counts.entry("opacityMasks").or_default() += 1;
}
@@ -552,7 +563,7 @@ mod tests {
/// Document Info › Repeat Objects lists each Repeat object by name with its kind and the number
/// of instances it makes (for a grid, its rows and columns, followed by the number it draws when
/// that is fewer), one in a group included. With Selection Only it lists the Repeat objects in
/// the selection.
/// the selection, each once when the selection holds a group and a Repeat object inside it.
#[test]
fn info_lists_the_repeat_objects() {
let mut s = Session::new();
@@ -590,6 +601,11 @@ mod tests {
};
s.execute("select.set", &json!({"ids": [grid, group]})).unwrap();
assert_eq!(names(&mut s), ["Tiles", "<Mirror Repeat>"]);
// A selection that holds the group and the Repeat object inside it lists that object once.
for ids in [json!([group, mirror]), json!([mirror, group])] {
s.execute("select.set", &json!({"ids": ids})).unwrap();
assert_eq!(names(&mut s), ["<Mirror Repeat>"], "{ids}");
}
s.execute("select.set", &json!({"ids": [radial]})).unwrap();
assert_eq!(names(&mut s), ["<Radial Repeat>"]);
s.execute("select.set", &json!({"ids": [d]})).unwrap();
@@ -618,6 +634,64 @@ mod tests {
assert_eq!(i["sections"][0]["rows"][0], json!(["<Grid Repeat>", "Grid Repeat, 500 rows × 500 columns, 125000 instances"]));
}
/// Document Info › Objects counts an object with a gradient or a pattern on both its fill and
/// its stroke once, and with Selection Only a selection that holds a group and an object inside
/// it counts that object once.
#[test]
fn info_counts_each_object_once() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let square =
|s: &mut Session, x: f64| s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
let tile = square(&mut s, 0.0);
s.execute("object.pattern.make", &json!({"ids": [tile], "name": "Dots", "edit": false})).unwrap();
let (g, p) = (square(&mut s, 100.0), square(&mut s, 200.0));
let gradient = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]});
s.execute("paint.setFill", &json!({"ids": [g], "gradient": gradient})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [g], "gradient": gradient})).unwrap();
s.execute("paint.setFill", &json!({"ids": [p], "swatch": "Dots"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [p], "swatch": "Dots"})).unwrap();
let i = s.execute("document.info", &json!({})).unwrap();
assert_eq!((i["objects"]["gradients"].as_u64(), i["objects"]["patterns"].as_u64()), (Some(1), Some(1)), "{}", i["objects"]);
// A group of the two squares, selected together with one of them.
s.execute("select.set", &json!({"ids": [g, p]})).unwrap();
let group = s.execute("object.group", &json!({})).unwrap()["id"].clone();
for ids in [json!([group, p]), json!([p, group])] {
s.execute("select.set", &json!({"ids": ids})).unwrap();
let i = s.execute("document.info", &json!({"selectionOnly": true})).unwrap();
let o = &i["objects"];
assert_eq!(
(o["paths"].as_u64(), o["groups"].as_u64(), o["gradients"].as_u64(), o["patterns"].as_u64()),
(Some(2), Some(1), Some(1), Some(1)),
"{ids}: {o}"
);
assert!((i["pathLength"].as_f64().unwrap() - 80.0).abs() < 1e-6, "{ids}: {}", i["pathLength"]);
}
}
/// Document Info › Objects counts two objects that share an id (as a damaged file can hold) as
/// two, in the whole document and in a selected group that holds both.
#[test]
fn info_counts_objects_that_share_an_id() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let square = |s: &mut Session, x: f64| {
s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()
};
let (a, b) = (square(&mut s, 0.0), square(&mut s, 100.0));
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let group = s.execute("object.group", &json!({})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [group]})).unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
d.node_mut(NodeId(b)).unwrap().id = NodeId(a);
for p in [json!({}), json!({"selectionOnly": true})] {
let i = s.execute("document.info", &p).unwrap();
let o = &i["objects"];
assert_eq!((o["paths"].as_u64(), o["groups"].as_u64()), (Some(2), Some(1)), "{p}: {o}");
assert!((i["pathLength"].as_f64().unwrap() - 80.0).abs() < 1e-6, "{p}: {}", i["pathLength"]);
}
}
#[test]
fn embedding_permissions_read_from_fs_type() {
assert_eq!(embedding_label(0), "embedding allowed");
+10 -1
View File
@@ -66,6 +66,15 @@ pub fn specs() -> Vec<CommandSpec> {
"select.same.textStrokeColor",
|a, b| a.stroke == b.stroke
)),
cmd!(
"select.same.textFillAndStrokeColor",
"Text Fill & Stroke Color",
["Select", "Same"],
None,
"{} select the type objects with characters whose fill and stroke both match the first character of the first selected type → {count}",
has_selection,
|s, _| same_text(s, "select.same.textFillAndStrokeColor", |a, b| a.fill == b.fill && a.stroke == b.stroke)
),
cmd!(
"select.object.directionHandles",
"Direction Handles",
@@ -316,7 +325,7 @@ fn first_text_style(s: &Session) -> Option<CharStyle> {
fn same_text(s: &mut Session, cmd: &str, eq: fn(&CharStyle, &CharStyle) -> bool) -> Result<Value> {
let r = first_text_style(s).ok_or_else(|| bad(cmd, "select a text object"))?;
let ids = candidates(s, |n| match &n.kind {
NodeKind::Text(t) => t.runs.iter().any(|run| eq(&run.style, &r)),
NodeKind::Text(t) => t.runs.iter().any(|run| !run.text.is_empty() && eq(&run.style, &r)),
_ => false,
})?;
finish_same(s, cmd, ids)
@@ -1,7 +1,8 @@
use super::nodes::MAX_DEPTH;
use super::{Kind, af};
/// What copying a subtree takes: its nodes, characters and table cells (`work`), and its pixels.
/// What copying a subtree takes: its nodes, characters, table cells and path segments (`work`),
/// and its pixels.
#[derive(Clone, Copy, Debug, Default)]
pub(super) struct CopyCost {
pub(super) work: u64,
@@ -40,8 +41,58 @@ pub(super) fn copy_cost(n: &af::Node, depth: usize) -> CopyCost {
let own = match &n.kind {
Kind::Text(t) => CopyCost { work: 1 + len(&t.runs), pixels: 0 },
Kind::Table(t) => CopyCost { work: 1 + t.cells.iter().map(|c| 1 + len(&c.runs)).sum::<u64>(), pixels: 0 },
Kind::Image(img) => CopyCost { work: 1, pixels: u64::from(img.width) * u64::from(img.height) },
Kind::Image(img) => CopyCost { work: 1, pixels: pixels(img) },
// Each copy builds its own path: a curve of many segments costs them all.
Kind::Shape { path, .. } | Kind::Artboard { path, .. } => CopyCost { work: 1 + segments(path), pixels: 0 },
_ => CopyCost { work: 1, pixels: 0 },
};
n.children.iter().fold(own, |c, ch| c.plus(copy_cost(ch, depth + 1)))
// A vector mask is a path of its own, and a pixel mask an image of its own, in every copy.
let mask =
CopyCost { work: n.mask.as_ref().map_or(0, segments) + u64::from(n.pixel_mask.is_some()), pixels: n.pixel_mask.as_ref().map_or(0, pixels) };
n.children.iter().fold(own.plus(mask), |c, ch| c.plus(copy_cost(ch, depth + 1)))
}
/// The subpaths and segments of `p`.
fn segments(p: &af::Path) -> u64 {
p.subpaths.iter().map(|s| 1 + s.segments.len() as u64).sum()
}
fn pixels(img: &af::Image) -> u64 {
u64::from(img.width) * u64::from(img.height)
}
#[cfg(test)]
mod tests {
use super::*;
fn node(kind: Kind, mask: Option<af::Path>) -> af::Node {
af::Node {
class: vectorcraft_affinity::stream::Tag::of(b"ShpN"),
name: String::new(),
visible: true,
locked: false,
opacity: 1.0,
blend: af::Blend::Normal,
kind,
mask,
pixel_mask: None,
effects: vec![],
children: vec![],
}
}
fn path(n: usize) -> af::Path {
let p = af::Point { x: 0.0, y: 0.0 };
af::Path { subpaths: vec![af::SubPath { start: p, segments: vec![[p; 3]; n], closed: false }] }
}
/// A curve, and a vector mask, cost every segment each copy rebuilds: a shape of a million
/// segments shown on many pages can't pass as one object.
#[test]
fn paths_and_masks_cost_their_segments() {
let shape = |n| Kind::Shape { path: path(n), fills: vec![], strokes: vec![], even_odd: false };
assert!(copy_cost(&node(shape(1_000_000), None), 0).work > 1_000_000);
assert!(copy_cost(&node(Kind::Group, Some(path(1_000_000))), 0).work > 1_000_000);
assert!(copy_cost(&node(shape(3), None), 0).work < 10);
}
}
@@ -11,6 +11,15 @@ pub(super) fn affine(a: af::Affine) -> Affine {
Affine::new(a.0)
}
/// Are all of `p`'s points, mapped by `to_doc`, finite and within `MAX_COORD` of the origin?
pub(super) fn path_in_range(p: &af::Path, to_doc: Affine) -> bool {
let ok = |q: &af::Point| {
let d = to_doc * kurbo::Point::new(q.x, q.y);
[d.x, d.y].iter().all(|v| v.is_finite() && v.abs() <= crate::MAX_COORD)
};
p.subpaths.iter().all(|s| ok(&s.start) && s.segments.iter().flatten().all(ok))
}
impl Builder {
pub(super) fn layer_with(&mut self, name: Option<&str>, children: Vec<Arc<Node>>) -> Arc<Node> {
let id = self.doc.alloc_id();
@@ -107,6 +116,12 @@ impl Builder {
return None;
}
}
// So must its vector mask, which becomes a clipping path: every control point, not just
// the finite ones a bounding box takes.
if n.mask.as_ref().is_some_and(|m| !path_in_range(m, to_doc)) {
self.warn("objects beyond the document range VectorCraft supports (left out)");
return None;
}
let n = &*self.overlaid(n);
// Register before descending so nested artboards keep their document order. Inside an
// embedded document an artboard is just its content's frame.
@@ -252,3 +267,25 @@ impl Builder {
Some(Arc::new(out))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn path(points: &[(f64, f64)]) -> af::Path {
let p = |&(x, y): &(f64, f64)| af::Point { x, y };
let start = p(&points[0]);
let segments = points[1..].iter().map(|q| [start, p(q), p(q)]).collect();
af::Path { subpaths: vec![af::SubPath { start, segments, closed: true }] }
}
/// A mask's control points are checked as mapped into the document, NaN ones included.
#[test]
fn mask_paths_must_stay_in_the_document_range() {
let k = Affine::scale(0.75);
assert!(path_in_range(&path(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)]), k));
assert!(!path_in_range(&path(&[(0.0, 0.0), (1.0e7, 0.0)]), k));
assert!(!path_in_range(&path(&[(0.0, 0.0), (f64::NAN, 0.0)]), k));
assert!(!path_in_range(&path(&[(0.0, 0.0), (1.0, 1.0)]), Affine::scale(1.0e9)));
}
}
+14 -2
View File
@@ -70,9 +70,11 @@ pub fn render(template: &str, p: &NameParts<'_>) -> String {
let mut out = String::with_capacity(t.len() + 16);
let mut rest = t;
while let Some(c) = rest.chars().next() {
// Bracketed tokens; an unknown one stays as written, with `-` for its brackets.
// Bracketed tokens; an unknown one stays as written, with `-` for its brackets. A token's
// name has no `<`, so the search for its `>` stops at the next `<`: each part of the
// pattern is searched once, not once for every `<` before it.
if c == '<'
&& let Some(end) = rest.find('>')
&& let Some(end) = rest.get(1..).and_then(|r| r.find(['<', '>'])).map(|i| i + 1).filter(|&i| rest.as_bytes().get(i) == Some(&b'>'))
&& let Some(value) = rest.get(1..end).and_then(|name| token(name, p))
{
out.push_str(&value);
@@ -155,6 +157,16 @@ mod tests {
assert_eq!(render("#", &NameParts { counter: 12345, ..parts() }), "12345");
}
/// Many `<` without a `>`, or before one far away, are each looked at once.
#[test]
fn unmatched_brackets_are_read_in_one_pass() {
let p = parts();
let n = 200_000;
assert_eq!(render(&"<".repeat(n), &p), "-".repeat(n));
assert_eq!(render(&format!("{}<name>", "<".repeat(n)), &p), format!("{}Dark", "-".repeat(n)));
assert_eq!(render("<a<name>>", &p), "-aDark-");
}
#[test]
fn dates_are_strict_about_hyphens_and_days() {
for bad in ["2026-1-011", "2-0-2-6-1-0-1-6", "2026--10--16", "2026-02-31", "2026-10-16-", "202610-16"] {
+46 -4
View File
@@ -35,6 +35,12 @@ pub const OPTIONS: &[FormatOption] = &[
default: "false",
description: "embed a PNG preview of the first artboard (at most 256 pixels on its longer side) for file browsers",
},
FormatOption {
name: "precision",
ty: "integer",
default: "null",
description: "round path anchors and handles to this many decimal places, 0 to 9 (a smaller file; colors, transforms and type are kept exactly); null writes them exactly. Only the save that gives it rounds",
},
SEPARATE_ARTBOARDS,
SEPARATE_RANGE,
INCLUDE_LINKED,
@@ -131,6 +137,7 @@ struct NativeOptions {
compress: Option<bool>,
version: Option<u32>,
preview: bool,
precision: Option<Value>,
include_linked: bool,
embed_profiles: Option<bool>,
pdf_compatible: bool,
@@ -151,6 +158,7 @@ pub(super) fn save_options(cmd: &str, f: &Format, doc: &Document, p: &Value) ->
compress: o.compress.unwrap_or(false),
version: o.version.unwrap_or(vectorcraft_format::VERSION),
include_linked: o.include_linked,
precision: o.precision.map(|v| precision(cmd, &v)).transpose()?,
..SaveOptions::default()
};
if o.embed_profiles.unwrap_or(true) {
@@ -160,6 +168,20 @@ pub(super) fn save_options(cmd: &str, f: &Format, doc: &Document, p: &Value) ->
Ok((so, Extras { preview: o.preview, pdf: o.pdf_compatible }))
}
/// The `precision` option `v`: a whole number of decimal places, 0 to
/// [`vectorcraft_format::MAX_PRECISION`]. Any other value, a string included, gets the range message.
fn precision(cmd: &str, v: &Value) -> Result<u8> {
let (key, min, max) = ("precision", 0u8, vectorcraft_format::MAX_PRECISION);
if let Some(x) = v.as_f64()
&& x.fract() == 0.0
&& (f64::from(min)..=f64::from(max)).contains(&x)
{
return Ok(x as u8);
}
let x = v.as_f64().map_or_else(|| v.to_string(), |x| x.to_string());
Err(bad(cmd, format!("`{key}` must be a whole number between {min} and {max} (got {x})")))
}
/// The `.vectorcraft` file of `doc` with the options in `p`.
pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<Vec<u8>> {
let mut out = Vec::new();
@@ -177,13 +199,19 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp
} else {
std::borrow::Cow::Borrowed(doc)
};
// With a precision, the preview and PDF show the rounded art the file holds.
let drawn = match so.precision {
Some(decimals) if extras.preview || extras.pdf => Cow::Owned(rounded(&full, so.version, decimals)),
_ => Cow::Borrowed(full.as_ref()),
};
if extras.preview {
so.preview = preview_png(&full)?;
so.preview = preview_png(&drawn)?;
}
if extras.pdf {
// Every artboard as PDF pages (no editing data: the file is the native document).
so.pdf = Some(super::pdf::encode(cmd, &full, &json!({ "range": "all", "preserveEditing": false }))?.0);
so.pdf = Some(super::pdf::encode(cmd, &drawn, &json!({ "range": "all", "preserveEditing": false }))?.0);
}
drop(drawn);
let native = match full {
Cow::Owned(full) if so.include_linked && so.version >= vectorcraft_format::VERSION => {
// Include available bytes without replacing missing, relinkable placed objects.
@@ -197,6 +225,20 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp
vectorcraft_format::save_to(&native, &so, w).map_err(|e| bad(cmd, e.to_string()))
}
/// `doc` with its path geometry rounded to `decimals` places, as [`vectorcraft_format::save_to`]
/// writes it for `version`: placed documents become groups of their art for older versions.
fn rounded(doc: &Document, version: u32, decimals: u8) -> Document {
let mut d = if version < vectorcraft_format::VERSION && doc.has_placed() {
let mut d = doc.with_placed_art().into_owned();
d.placed_as_groups();
d
} else {
doc.clone()
};
d.round_geometry(decimals.min(vectorcraft_format::MAX_PRECISION));
d
}
/// The ICC files of the profiles `doc` is tagged with that were loaded from files (the built-in
/// ones are there wherever VectorCraft runs).
fn embedded_profiles(doc: &Document) -> BTreeMap<String, Vec<u8>> {
@@ -230,8 +272,8 @@ pub(super) fn ai_options(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Re
let mut q = p.clone();
if let Some(o) = q.as_object_mut() {
// AI carries the current native format without a separate preview. Its compression
// and PDF-content flags are still validated as booleans.
o.retain(|k, _| !matches!(k.as_str(), "version" | "preview"));
// and PDF-content flags are still validated as booleans. Its coordinates are written exactly.
o.retain(|k, _| !matches!(k.as_str(), "version" | "preview" | "precision"));
if o.get("pdfCompatible").is_some_and(Value::is_null) {
o.remove("pdfCompatible");
}
+19 -9
View File
@@ -134,8 +134,9 @@ pub fn templates_folder(prefs: &Prefs) -> Option<String> {
pub fn templates_dialog_folder(prefs: &Prefs) -> Option<String> {
let folder = std::path::PathBuf::from(templates_folder(prefs)?);
if !folder.is_dir() {
// Best effort: a folder that can't be made leaves the nearest one that exists.
let _ = std::fs::create_dir_all(&folder);
// Best effort: a folder that can't be made (or automation may not write) leaves the
// nearest one that exists.
let _ = super::create_dir(&folder.to_string_lossy());
}
folder.ancestors().find(|a| a.is_dir()).map(|a| a.to_string_lossy().into_owned()).or_else(home_folder)
}
@@ -265,7 +266,7 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
given = svg;
} else {
// So do PDF options (as the Save PDF dialog and document.exportPdf name them) and the
// native ones (compress, version, preview).
// native ones (compress, version, preview, precision).
if let Some(o) = p.as_object() {
given.extend(
o.iter().filter(|(k, v)| !v.is_null() && k.as_str() != "path" && reads_option(format, k)).map(|(k, v)| (k.clone(), v.clone())),
@@ -296,7 +297,7 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
}
/// The native save options, which a save also takes beside the path.
const NATIVE_OPTIONS: [&str; 3] = ["compress", "version", "preview"];
const NATIVE_OPTIONS: [&str; 4] = ["compress", "version", "preview", "precision"];
/// The first option `p` gives both beside the path and in `options` with different values, as
/// `(key, top-level value, options value)`. For an SVG save (`svg`), an SVG option's value on
@@ -839,6 +840,8 @@ impl SaveJob {
st.path = Some(path);
st.format = self.plan.format.id;
st.save_options = self.plan.options;
// A later save rounds only when it gives `precision` too.
st.save_options.remove("precision");
st.save_artboards = self.snapshot.artboards.iter().map(|a| a.id).collect();
st.converted = false;
st.recovered = false;
@@ -869,7 +872,7 @@ impl SaveJob {
let saved = self.plan.retargets() && self.plan.path.is_some();
if saved && self.plan.format.id == "vectorcraft" {
let mut last = self.plan.options.clone();
last.retain(|k, _| !ARTBOARD_PARAMS.contains(&k.as_str()) && !matches!(k.as_str(), "separateArtboards" | "compress"));
last.retain(|k, _| !ARTBOARD_PARAMS.contains(&k.as_str()) && !matches!(k.as_str(), "separateArtboards" | "compress" | "precision"));
s.prefs.native_save_options = last;
}
// The other open documents that place this one show the new version.
@@ -964,7 +967,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Save Document",
[],
None,
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version or preview given flat), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: false for native (also carry a PDF of every artboard) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly; separateArtboards writes more files, one per artboard. EPS saves the chosen artboard (first by default), retaining its page margins and the whole editable document; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified",
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: false for native (also carry a PDF of every artboard) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly; separateArtboards writes more files, one per artboard. EPS saves the chosen artboard (first by default), retaining its page margins and the whole editable document; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified",
has_doc,
|s, p| save(s, SaveMode::Save, p)
),
@@ -973,7 +976,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Save As…",
["File"],
Some("Cmd+Shift+S"),
"{…as document.save} {path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own; ait, a .ait template, is written by file.saveAsTemplate), options?, svg?, modified?} the document takes on the new path, name and format (except a template, which is always a copy) → {path, format, bytes, warnings}; no path → {dataBase64, format, name, folder?, warnings}",
"{…as document.save} {path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own; ait, a .ait template, is written by file.saveAsTemplate), options?, svg?, precision?, modified?} the document takes on the new path, name and format (except a template, which is always a copy) → {path, format, bytes, warnings}; no path → {dataBase64, format, name, folder?, warnings}",
has_doc,
|s, p| save(s, SaveMode::SaveAs, p)
),
@@ -982,7 +985,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Save a Copy…",
["File"],
Some("Cmd+Alt+S"),
"{…as document.save} {path?, format?, options?} write a copy; the document keeps its path, title and modified state → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \"<name> copy.<ext>\", folder?, warnings}",
"{…as document.save} {path?, format?, options?, precision?} write a copy; the document keeps its path, title and modified state → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \"<name> copy.<ext>\", folder?, warnings}",
has_doc,
|s, p| save(s, SaveMode::Copy, p)
),
@@ -991,7 +994,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Save as Template…",
["File"],
None,
"{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \"<name> template.<ext>\", folder: the Templates folder (preference templatesFolder), warnings}",
"{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?, precision?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \"<name> template.<ext>\", folder: the Templates folder (preference templatesFolder), warnings}",
has_doc,
|s, p| save(s, SaveMode::Template, p)
),
@@ -1072,6 +1075,13 @@ mod tests_folders {
std::fs::write(base.join("blocked"), b"x").unwrap();
prefs.templates_folder = base.join("blocked").join("Templates").to_string_lossy().into_owned();
assert_eq!(super::templates_dialog_folder(&prefs).map(PathBuf::from), Some(base.clone()));
// Automation that may not write there makes no folder.
let outside = base.join("Outside").join("Templates");
prefs.templates_folder = outside.to_string_lossy().into_owned();
std::fs::create_dir_all(base.join("Allowed")).unwrap();
let roots = crate::file_access::AutomationRoots::new(&[&base], &[&base.join("Allowed")]).unwrap().unwrap();
crate::file_access::confine(Some(&roots), || super::templates_dialog_folder(&prefs));
assert!(!outside.exists(), "not made");
let _ = std::fs::remove_dir_all(&base);
}
}
+108 -3
View File
@@ -521,6 +521,11 @@ struct Output {
folders: std::collections::HashMap<String, String>,
/// Sub-folders already made, by their [`fold`]ed names.
made: HashSet<String>,
/// For each [`fold`]ed name asked for, the number to try next: many files given one name
/// would otherwise try `-2`, `-3`… from the start each time.
next: std::collections::HashMap<String, u64>,
/// Each [`fold`]ed name asked for with the file (`key`) that got a name from it.
claimed: HashSet<(String, String)>,
/// `(relative name, bytes)` kept to return or zip (empty when written to a folder).
kept: Vec<(String, Vec<u8>)>,
/// The paths written.
@@ -540,8 +545,14 @@ impl Output {
}
None => name.to_string(),
};
let asked = (fold(&name), key.to_string());
// The same file under the same name again: it has its name already.
if self.claimed.contains(&asked) {
return None;
}
let (base, ext) = name.rsplit_once('.').map_or((name.as_str(), ""), |(b, e)| (b, e));
for n in 1.. {
let start = self.next.get(&asked.0).copied().unwrap_or(1);
for n in start.. {
let candidate = if n == 1 {
name.to_string()
} else if ext.is_empty() {
@@ -554,6 +565,8 @@ impl Output {
Some(_) => continue,
None => {
self.taken.insert(fold(&candidate), key.to_string());
self.next.insert(asked.0.clone(), n + 1);
self.claimed.insert(asked);
return Some(candidate);
}
}
@@ -685,6 +698,8 @@ fn preset_settings(s: &Session, cmd: &str, given: &Map<String, Value>) -> Result
// Refuse what an export would refuse, now rather than when the preset is used.
check_settings(s, &Value::Object(settings.clone())).map_err(|e| bad(cmd, e.to_string()))?;
Folders::of(&ScreenParams::of(&Value::Object(settings.clone()))?).map_err(|e| bad(cmd, e.to_string()))?;
let mut settings = settings;
remove_passwords(&mut settings);
Ok(settings)
}
@@ -912,6 +927,7 @@ pub(crate) fn with_export_preset(s: &Session, cmd: &str, settings: &mut Map<Stri
/// so do different files that would share a name, with or without the `name` pattern. The reply's
/// `warnings` lists every warning the encoders give for the files, each once.
pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
check_passwords(p)?;
let o = ScreenParams::of(p)?;
let rows = rows_of(s, p, o.preset.as_deref())?;
o.one_source()?;
@@ -1262,9 +1278,61 @@ fn remember(s: &mut Session, p: &Value) {
let _ = store_settings(s, settings);
}
/// The PDF passwords an export may be given (`security` of a PDF row or of `settings.pdf`).
const PASSWORD_KEYS: [&str; 2] = ["openPassword", "permissionsPassword"];
/// Left where [`remove_passwords`] took a password out: an export of these settings is refused
/// until a password is given again ([`check_passwords`]), rather than written unprotected.
const PASSWORD_REQUIRED: &str = "passwordRequired";
/// `settings` without the PDF passwords anywhere in them: settings kept in the document (which
/// native saves write) or in the preferences hold the export's choices, never its secrets, as
/// the PDF settings themselves are saved without them. Where one was given, [`PASSWORD_REQUIRED`]
/// says so.
fn remove_passwords(settings: &mut Map<String, Value>) {
let mut removed = false;
for key in PASSWORD_KEYS {
removed |= settings.remove(key).is_some_and(|v| v.as_str().is_none_or(|p| !p.is_empty()));
}
if removed {
settings.insert(PASSWORD_REQUIRED.into(), Value::Bool(true));
}
for v in settings.values_mut() {
remove_passwords_in(v);
}
}
/// Refuse export params `v` that hold settings whose PDF passwords were left out
/// ([`PASSWORD_REQUIRED`]) without a password given again.
fn check_passwords(v: &Value) -> Result<()> {
match v {
Value::Object(m) => {
let given = PASSWORD_KEYS.iter().any(|k| m.get(*k).and_then(Value::as_str).is_some_and(|p| !p.is_empty()));
if m.get(PASSWORD_REQUIRED) == Some(&Value::Bool(true)) && !given {
return Err(bad(
C,
"the PDF security settings were saved without their passwords: give openPassword or permissionsPassword again, or security without passwordRequired to export unprotected",
));
}
m.values().try_for_each(check_passwords)
}
Value::Array(items) => items.iter().try_for_each(check_passwords),
_ => Ok(()),
}
}
fn remove_passwords_in(v: &mut Value) {
match v {
Value::Object(m) => remove_passwords(m),
Value::Array(items) => items.iter_mut().for_each(remove_passwords_in),
_ => {}
}
}
/// Make `settings` the document's export settings. Not an undo step (like the settings of any
/// export); the document has changed only if they differ.
pub(crate) fn store_settings(s: &mut Session, settings: Map<String, Value>) -> Result<()> {
pub(crate) fn store_settings(s: &mut Session, mut settings: Map<String, Value>) -> Result<()> {
remove_passwords(&mut settings);
let st = s.doc_mut()?;
if st.doc.export_settings != settings {
Arc::make_mut(&mut st.doc).export_settings = settings;
@@ -1280,7 +1348,26 @@ pub(super) fn export_settings(s: &mut Session, _: &Value) -> Result<Value> {
#[cfg(test)]
mod tests {
use super::{ScreenSize, safe_file_name};
use super::{Output, ScreenSize, safe_file_name};
/// Files given one name are numbered in turn, each numbering going on from the last one (so
/// thousands of them don't each try every number used before), and a file asking again for
/// the name it got is told it has it.
#[test]
fn taken_names_are_numbered_from_the_last_number() {
let mut out = Output::default();
assert_eq!(out.claim("a.png", "1").as_deref(), Some("a.png"));
assert_eq!(out.claim("A.png", "2").as_deref(), Some("A-2.png"));
assert_eq!(out.claim("a-3.png", "x").as_deref(), Some("a-3.png"));
assert_eq!(out.claim("a.png", "3").as_deref(), Some("a-4.png"));
assert_eq!(out.claim("a.png", "2"), None);
assert_eq!(out.claim("a.png", "1"), None);
assert_eq!(out.claim("sub/a.png", "1").as_deref(), Some("sub/a.png"));
for k in 0..20_000 {
assert!(out.claim("same.png", &k.to_string()).is_some());
}
assert_eq!(out.claim("same.png", "last").as_deref(), Some("same-20001.png"));
}
#[test]
fn size_parse_refuses_signs_and_exponents() {
@@ -1302,4 +1389,22 @@ mod tests {
assert_eq!(safe_file_name("lpt9 .png"), "lpt9-.png");
assert_eq!(safe_file_name("My CON .png"), "My CON .png");
}
/// The settings an export leaves in the document keep its PDF security choices but not its
/// passwords, in a row or in `settings.pdf`.
#[test]
fn stored_settings_leave_out_pdf_passwords() {
let mut s = crate::Session::new();
s.execute("file.new", &serde_json::json!({"width": 100, "height": 100})).unwrap();
let given = serde_json::json!({
"formats": [{"format": "pdf", "security": {"openPassword": "open sesame", "permissionsPassword": "owner", "printing": "low"}}],
"settings": {"pdf": {"security": {"openPassword": "open sesame", "copy": false}}},
});
super::store_settings(&mut s, given.as_object().unwrap().clone()).unwrap();
let kept = serde_json::Value::Object(s.doc().unwrap().doc.export_settings.clone());
assert!(!kept.to_string().contains("Password"), "{kept}");
assert_eq!(kept["formats"][0]["security"]["printing"], "low");
assert_eq!(kept["settings"]["pdf"]["security"]["copy"], false);
assert_eq!(kept["formats"][0]["security"]["passwordRequired"], true);
}
}
+12 -2
View File
@@ -704,8 +704,8 @@ fn a_native_save_streams_the_bytes_the_encoder_makes() {
}
/// An option given beside the path (an SVG option flat or in `svg`) and in `options` with different
/// values is refused before anything is written; `compress`, `version` or `preview` beside the path of a format that doesn't
/// read it is named in the warnings.
/// values is refused before anything is written; `compress`, `version`, `preview` or `precision` beside the path of a format
/// that doesn't read it is named in the warnings.
#[test]
fn a_save_refuses_disagreeing_options_and_names_unread_native_ones() {
let d = tmp_dir("save-options");
@@ -752,6 +752,16 @@ fn a_save_refuses_disagreeing_options_and_names_unread_native_ones() {
let r = s.execute("file.saveCopy", &json!({"path": d.join("a.ai").to_string_lossy(), "compress": false, "version": 3})).unwrap();
let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
assert!(w.iter().any(|w| w.starts_with("`version` was not used")) && !w.iter().any(|w| w.starts_with("`compress`")), "{w:?}");
// `precision` is read by native files and templates only.
for name in ["p.svg", "p.pdf", "p.ai", "p.eps"] {
let r = s.execute("file.saveCopy", &json!({"path": d.join(name).to_string_lossy(), "precision": 2})).unwrap();
let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
assert!(w.iter().any(|w| w.starts_with("`precision` was not used:")), "{name}: {w:?}");
}
for name in ["p.vectorcraft", "p.vctemplate"] {
let r = s.execute("file.saveCopy", &json!({"path": d.join(name).to_string_lossy(), "precision": 2})).unwrap();
assert_eq!(r["warnings"], json!([]), "{name}: {r}");
}
let _ = std::fs::remove_dir_all(&d);
}
+157 -14
View File
@@ -112,8 +112,16 @@ pub(super) fn reach(n: &Node) -> Option<Rect> {
Some(b.inflate(fx + 1.0, fx + 1.0))
}
/// Indices of `bounds` grouped by overlap (transitively), each group in index order.
pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Vec<Vec<usize>> {
/// Indices of `bounds` grouped by overlap (transitively), each group in index order. Boxes that
/// only touch overlap; a box with a coordinate that isn't finite overlaps none.
///
/// A sweep left to right keeps the boxes still open at the current left edge in a tree by their
/// tops that knows the lowest bottom below each of its branches, so each box meets only the open
/// boxes it overlaps, not every open one (many objects stacked in a column, sharing their
/// horizontal extent, would otherwise compare every pair). An open box inside a later box of
/// its group, ending no further right, is closed early: whatever overlaps it overlaps that box.
/// Fails only when cancelled ([`vectorcraft_doc::cancel`]).
pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, vectorcraft_doc::cancel::Cancelled> {
fn find(p: &mut [usize], mut i: usize) -> usize {
while p[i] != i {
p[i] = p[p[i]];
@@ -122,19 +130,75 @@ pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Vec<Vec<usize>> {
i
}
let mut parent: Vec<usize> = (0..bounds.len()).collect();
let mut order: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.map(|b| (i, b))).collect();
order.sort_by(|a, b| a.1.x0.total_cmp(&b.1.x0));
// Sweep left to right, comparing each box with those still open at its left edge.
let mut open: Vec<(usize, Rect)> = vec![];
for (i, b) in order {
open.retain(|(_, o)| o.x1 >= b.x0);
for (j, o) in &open {
if o.y0 <= b.y1 && b.y0 <= o.y1 {
let (a, c) = (find(&mut parent, i), find(&mut parent, *j));
parent[a.max(c)] = a.min(c);
let finite = |b: &Rect| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && b.x0 <= b.x1 && b.y0 <= b.y1;
let boxes: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.filter(finite).map(|b| (i, b))).collect();
let n = boxes.len();
// Each box's place in the tree: by top (then index).
let mut by_top: Vec<usize> = (0..n).collect();
by_top.sort_by(|&a, &b| boxes[a].1.y0.total_cmp(&boxes[b].1.y0).then(a.cmp(&b)));
let tops: Vec<f64> = by_top.iter().map(|&k| boxes[k].1.y0).collect();
let mut leaf = vec![0usize; n];
for (pos, &k) in by_top.iter().enumerate() {
leaf[k] = pos;
}
// The lowest bottom of the open boxes below each node (−∞: none open).
let size = n.next_power_of_two().max(1);
let mut low = vec![f64::NEG_INFINITY; 2 * size];
let set = |low: &mut [f64], pos: usize, v: f64| {
let mut i = pos + size;
low[i] = v;
while i > 1 {
i /= 2;
low[i] = low[2 * i].max(low[2 * i + 1]);
}
};
let mut by_left: Vec<usize> = (0..n).collect();
by_left.sort_by(|&a, &b| boxes[a].1.x0.total_cmp(&boxes[b].1.x0));
let mut by_right: Vec<usize> = (0..n).collect();
by_right.sort_by(|&a, &b| boxes[a].1.x1.total_cmp(&boxes[b].1.x1));
let mut closing = 0;
let mut stack: Vec<(usize, usize, usize)> = vec![];
let mut met = vec![];
let mut work = 0usize;
for &k in &by_left {
let b = boxes[k].1;
// Close the boxes that end left of this one.
while let Some(&c) = by_right.get(closing)
&& boxes[c].1.x1 < b.x0
{
set(&mut low, leaf[c], f64::NEG_INFINITY);
closing += 1;
}
// The open boxes with their top at most this bottom and their bottom at least this top.
let below = tops.partition_point(|t| *t <= b.y1);
met.clear();
stack.clear();
stack.push((1, 0, size));
while let Some((node, lo, hi)) = stack.pop() {
work += 1;
if work.is_multiple_of(4096) {
vectorcraft_doc::cancel::check()?;
}
if lo >= below || low[node] < b.y0 {
continue;
}
if hi - lo == 1 {
met.push(by_top[lo]);
continue;
}
let mid = (lo + hi) / 2;
stack.push((2 * node + 1, mid, hi));
stack.push((2 * node, lo, mid));
}
for &o in &met {
let (a, c) = (find(&mut parent, boxes[k].0), find(&mut parent, boxes[o].0));
parent[a.max(c)] = a.min(c);
let ob = boxes[o].1;
if ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 {
set(&mut low, leaf[o], f64::NEG_INFINITY);
}
}
open.push((i, b));
set(&mut low, leaf[k], b.y1);
}
let mut groups: Vec<Vec<usize>> = vec![];
let mut slot: Vec<Option<usize>> = vec![None; bounds.len()];
@@ -148,5 +212,84 @@ pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Vec<Vec<usize>> {
}
}
}
groups
Ok(groups)
}
#[cfg(test)]
mod tests {
use super::*;
/// What [`overlapping`] gives, comparing every pair.
fn every_pair(bounds: &[Option<Rect>]) -> Vec<Vec<usize>> {
let n = bounds.len();
let mut group: Vec<usize> = (0..n).collect();
let hit = |a: &Rect, b: &Rect| a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1;
loop {
let mut changed = false;
for i in 0..n {
for j in 0..n {
if let (Some(a), Some(b)) = (bounds[i], bounds[j])
&& hit(&a, &b)
&& group[j] < group[i]
{
group[i] = group[j];
changed = true;
}
}
}
if !changed {
break;
}
}
let mut out: Vec<Vec<usize>> = vec![];
let mut seen = std::collections::HashMap::new();
for (i, &root) in group.iter().enumerate() {
let g = *seen.entry(root).or_insert_with(|| {
out.push(vec![]);
out.len() - 1
});
out[g].push(i);
}
out
}
/// Boxes of many sizes, nested, touching and apart, group as comparing every pair groups them.
#[test]
fn groups_match_comparing_every_pair() {
let mut seed = 0x2545_f491_4f6c_dd1du64;
let mut next = |m: f64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % 1000) as f64 / 1000.0 * m
};
for round in 0..40 {
let n = 5 + round * 4;
let bounds: Vec<Option<Rect>> = (0..n)
.map(|i| {
if i % 11 == 3 {
return None;
}
let (x, y) = (next(100.0).round(), next(100.0).round());
Some(Rect::new(x, y, x + next(30.0).round(), y + next(30.0).round()))
})
.collect();
assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}");
}
}
/// A column of many boxes sharing their horizontal extent: each one meets only its
/// neighbours, so they group (here, touching in pairs) without comparing every pair.
#[test]
fn a_tall_column_groups_by_its_neighbours() {
let n = 200_000;
let bounds: Vec<Option<Rect>> =
(0..n).map(|i| Some(Rect::new(0.0, 3.0 * f64::from(i), 100.0, 3.0 * f64::from(i) + if i % 2 == 0 { 3.0 } else { 1.0 }))).collect();
let groups = overlapping(&bounds).unwrap();
assert_eq!(groups.len(), n as usize / 2);
assert!(groups.iter().enumerate().all(|(g, ids)| ids == &[2 * g, 2 * g + 1]));
// Boxes that aren't finite overlap nothing.
let odd = [Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(f64::NAN, 0.0, 10.0, 10.0)), Some(Rect::new(5.0, 5.0, 20.0, 20.0))];
assert_eq!(overlapping(&odd).unwrap(), vec![vec![0, 2], vec![1]]);
}
}
+55 -3
View File
@@ -26,6 +26,40 @@ pub(super) struct Flat {
/// Where its image goes, and the image (once rendered).
pub(super) area: Option<Area>,
raster: Option<Raster>,
/// When the group is one block of type over several lines: its lines, to group the regions by.
lines: Option<Lines>,
}
/// The lines of a block of type: document space → its line space, where each line spans a band
/// across the lines (its ascent above the baseline to its descent below).
struct Lines {
to_lines: Affine,
bands: Vec<(f64, f64)>,
}
impl Lines {
/// The lines of `n` when it is type laid out in two lines or more (not on a path).
fn of(n: &Node) -> Option<Lines> {
let NodeKind::Text(t) = &n.kind else { return None };
if t.xf.determinant().abs() < 1e-12 {
return None;
}
let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
if layout.on_path {
return None;
}
let bands: Vec<(f64, f64)> = layout.lines.iter().filter(|l| l.x1 > l.x0).map(|l| (l.baseline - l.ascent, l.baseline + l.descent)).collect();
let to_lines = if layout.vertical { layout.line_xf.inverse() * t.xf.inverse() } else { t.xf.inverse() };
(bands.len() > 1).then_some(Lines { to_lines, bands })
}
/// The line nearest to the middle of `path`.
fn line_of(&self, path: &PathData) -> usize {
let Some(b) = path.bounds() else { return 0 };
let y = (self.to_lines * b.center()).y;
let away = |&(lo, hi): &(f64, f64)| if y < lo { lo - y } else { (y - hi).max(0.0) };
self.bands.iter().enumerate().min_by(|a, b| away(a.1).total_cmp(&away(b.1))).map_or(0, |(i, _)| i)
}
}
/// Where a group's image goes.
@@ -79,7 +113,7 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render:
let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() };
// Baking above stopped early when cancelled; each group is a place to stop (a plan changes nothing).
vectorcraft_doc::cancel::check()?;
for g in overlapping(&reaches) {
for g in overlapping(&reaches)? {
vectorcraft_doc::cancel::check()?;
let ids: Vec<NodeId> = g.iter().map(|&i| roots[i]).collect();
let group = g.iter().any(|&i| see_through[i]).then(|| {
@@ -97,7 +131,11 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render:
}
None => None,
};
out.flat.push(Flat { roots: ids, regions, area, raster });
let lines = match g.as_slice() {
[i] => Lines::of(&art[*i]),
_ => None,
};
out.flat.push(Flat { roots: ids, regions, area, raster, lines });
}
Ok(out)
}
@@ -366,7 +404,10 @@ pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan
children.push(Arc::new(raster_node(d, r)));
rasterized += 1;
}
// Type over several lines gives a group per line.
let mut by_line: Vec<Vec<Arc<Node>>> = f.lines.as_ref().map_or(vec![], |l| vec![vec![]; l.bands.len()]);
for (path, fill) in f.regions {
let line = f.lines.as_ref().map(|l| l.line_of(&path));
let mut n = shape_node(d, path, None);
n.appearance = Appearance {
items: vec![AppearanceItem::Fill(FillLayer { overprint: fill.overprint, ..FillLayer::new(fill.paint) })],
@@ -374,9 +415,20 @@ pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan
}
.into();
n.opacity = fill.alpha.min(1.0);
children.push(Arc::new(n));
match line.and_then(|i| by_line.get_mut(i)) {
Some(l) => l.push(Arc::new(n)),
None => children.push(Arc::new(n)),
}
vector += 1;
}
by_line.retain(|l| !l.is_empty());
if by_line.len() > 1 {
for l in by_line {
children.push(Arc::new(Node::group(d.alloc_id(), l)));
}
} else {
children.extend(by_line.into_iter().flatten());
}
let g = Node::group(d.alloc_id(), children);
ids.push(g.id);
if one_pass {
+117 -37
View File
@@ -29,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Replace Font",
[],
None,
"{from: {family, style?}, to: {family (any of its names; stored as the font's own family name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); the type in the art of the symbols in scope changes too (all of the document's, or those the selected instances show, so every instance of them follows); text that is hidden or locked, in a hidden or locked group or layer (or group of a symbol's art), or on a locked artboard keeps its font → {runs, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}",
"{from: {family, style?}, to: {family (any of its names; stored as the font's own family name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); the type in the art of the symbols in scope changes too (all of the document's, or those the selected instances show, so every instance of them follows); text that is hidden or locked, in a hidden or locked group or layer (or group of a symbol's art), or on a locked artboard keeps its font; when no run changes (text already set in the new font, or none to change), the document and its undo history stay as they are → {runs: the runs changed, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}",
has_doc,
replace
),
@@ -549,6 +549,16 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
let matches = |st: &vectorcraft_doc::CharStyle| {
st.font_family.eq_ignore_ascii_case(&ff) && fs.as_ref().is_none_or(|x| st.font_style.eq_ignore_ascii_case(x))
};
// The style a matching run is set in after the change, or `None` when the run doesn't match or
// is already set in that family and style with no version or Variable Font settings.
let new_style = |st: &vectorcraft_doc::CharStyle| {
if !matches(st) {
return None;
}
// An explicit style, else the closest the new family has to the old one.
let style = ts.clone().or_else(|| db.face(&tf, &st.font_style).map(|f| f.style.clone())).unwrap_or_else(|| st.font_style.clone());
(st.font_family != tf || st.font_style != style || st.font_version.is_some() || !st.font_axes.is_empty()).then_some(style)
};
// Only text the Selection tool can reach changes: not hidden or locked, in a hidden or locked
// group or layer, or on a locked artboard. The text left in the font is counted. The type in
// the art of the symbols in scope (all of them, or those the selection shows) changes too,
@@ -564,54 +574,59 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
(None, BTreeSet::new())
};
let uses = |t: &TextObject| t.runs.iter().any(|r| matches(&r.style));
let (ids, skipped) = {
// Whether a run of `t` changes.
let changes = |t: &TextObject| t.runs.iter().any(|r| new_style(&r.style).is_some());
let (ids, skipped, in_symbols) = {
let d = &s.doc()?.doc;
let editable = d.editable();
let (ids, other): (Vec<NodeId>, Vec<NodeId>) = scope(s, selection_only)?.into_iter().partition(|id| editable(*id));
let mut skipped = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).count();
skipped += symbol_texts(d, symbols.as_ref()).into_iter().filter(|(t, open)| !open && uses(t)).count();
let texts = symbol_texts(d, symbols.as_ref());
skipped += texts.iter().filter(|(t, open)| !open && uses(t)).count();
if !closed.is_empty() {
skipped += symbol_texts(d, Some(&closed)).into_iter().filter(|(t, _)| uses(t)).count();
}
(ids, skipped)
// The text that changes: when none does, the document and its undo history stay as they are.
let ids: Vec<NodeId> = ids.into_iter().filter(|id| text(d, *id).is_some_and(changes)).collect();
let in_symbols = texts.iter().any(|(t, open)| *open && changes(t));
(ids, skipped, in_symbols)
};
// The fonts the replaced runs are set in, for the warning.
let mut set = BTreeSet::new();
let n = s.edit("Replace Font", |d, _| {
let mut n = 0;
let mut replace_in = |t: &mut TextObject| {
let mut changed = false;
for r in &mut t.runs {
if matches(&r.style) {
// An explicit style, else the closest the new family has to the old one.
let style = ts
.clone()
.or_else(|| db.face(&tf, &r.style.font_style).map(|f| f.style.clone()))
.unwrap_or_else(|| r.style.font_style.clone());
r.style.font_family = tf.clone();
r.style.font_style = style;
// Another font: none of the old one's versions or Variable Font settings.
r.style.font_version = None;
r.style.font_axes.clear();
set.insert(font_of(&r.style));
changed = true;
n += 1;
let n = if ids.is_empty() && !in_symbols {
0
} else {
s.edit("Replace Font", |d, _| {
let mut n = 0;
let mut replace_in = |t: &mut TextObject| {
let mut changed = false;
for r in &mut t.runs {
if let Some(style) = new_style(&r.style) {
r.style.font_family = tf.clone();
r.style.font_style = style;
// Another font: none of the old one's versions or Variable Font settings.
r.style.font_version = None;
r.style.font_axes.clear();
set.insert(font_of(&r.style));
changed = true;
n += 1;
}
}
if changed {
vectorcraft_text::edit::normalize(&mut t.runs);
refresh_bounds(t);
}
};
for id in &ids {
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
replace_in(t);
}
}
if changed {
vectorcraft_text::edit::normalize(&mut t.runs);
refresh_bounds(t);
}
};
for id in &ids {
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
replace_in(t);
}
}
edit_symbol_texts(d, symbols.as_ref(), &|t, open| open && uses(t), &mut replace_in);
drop(replace_in);
Ok(n)
})?;
edit_symbol_texts(d, symbols.as_ref(), &|t, open| open && changes(t), &mut replace_in);
drop(replace_in);
Ok(n)
})?
};
let mut out = json!({ "runs": n });
let mut warnings = Vec::new();
if skipped > 0 {
@@ -889,6 +904,71 @@ mod tests {
assert_eq!(r, json!({"runs": 2}));
}
/// Replace Font adds no undo step when no run changes: only locked text uses the font, no text
/// uses it, or the text is already set in the new font and style.
#[test]
fn replace_font_that_changes_nothing_adds_no_undo_step() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let serif = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Serif", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap();
let sans = s.execute("text.create", &json!({"x": 10, "y": 60, "text": "Sans", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [serif]})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let before = steps(&s);
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}})).unwrap();
assert_eq!(r, json!({"runs": 0, "skipped": 1, "warning": REPLACE_SKIPPED}));
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Nothing Uses This"}, "to": {"family": "Source Sans 3"}})).unwrap();
assert_eq!(r, json!({"runs": 0}));
let style = text(&s.doc().unwrap().doc, NodeId(sans)).unwrap().runs[0].style.font_style.clone();
let r =
s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Source Sans 3", "style": style}})).unwrap();
assert_eq!(r, json!({"runs": 0}));
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Source Sans 3"}})).unwrap();
assert_eq!(r, json!({"runs": 0}));
assert_eq!(steps(&s), before);
// A change is still one step.
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}})).unwrap();
assert_eq!(r, json!({"runs": 1}));
assert_eq!(steps(&s), before + 1);
assert_eq!(text_family(&s, sans), "Inter");
}
/// Change and Change All add no undo step when the type in a symbol's art already has the new
/// font, and a change to that type is still one step.
#[test]
fn replace_font_in_symbols_that_changes_nothing_adds_no_undo_step() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Sans", "font": "Source Sans 3"})).unwrap()["id"].clone();
s.execute("symbol.new", &json!({"name": "Mark", "ids": [id]})).unwrap();
let mut on_layers = 0;
s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_))));
assert_eq!(on_layers, 0, "the type is only in the symbol");
let family = |s: &Session| symbol_texts(&s.doc().unwrap().doc, None)[0].0.runs[0].style.font_family.clone();
let style = symbol_texts(&s.doc().unwrap().doc, None)[0].0.runs[0].style.font_style.clone();
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let before = steps(&s);
// New Symbol selects the instance: Change (the selection) and Change All.
for selection_only in [true, false] {
for to in [json!({"family": "Source Sans 3"}), json!({"family": "Source Sans 3", "style": style})] {
let p = json!({"from": {"family": "Source Sans 3"}, "to": to, "selectionOnly": selection_only});
assert_eq!(s.execute("text.replaceFont", &p).unwrap(), json!({"runs": 0}), "{p}");
}
}
assert_eq!(steps(&s), before);
// A change is still one step, with the instance selected and without.
let r =
s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}, "selectionOnly": true})).unwrap();
assert_eq!(r, json!({"runs": 1}));
assert_eq!(steps(&s), before + 1);
assert_eq!(family(&s), "Inter");
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Inter"}, "to": {"family": "Source Serif 4"}})).unwrap();
assert_eq!(r, json!({"runs": 1}));
assert_eq!(steps(&s), before + 2);
assert_eq!(family(&s), "Source Serif 4");
}
/// The fonts of the symbols' art: Find Font lists them, and Change All replaces them, leaving
/// hidden or locked type in the art as it is.
#[test]
+55 -5
View File
@@ -59,8 +59,15 @@
//! opacity, blending, fills and effects). When the model group gains or loses objects, or one of
//! them becomes another kind of object, each member takes the model's objects at that level
//! whole, keeping its own ids in order. At most [`MAX_MEMBERS`] objects are taken, so that a huge
//! document can't stall the start or every edit. Rotated copies and excluding a member with a
//! Shift-click are not covered.
//! document can't stall the start or every edit.
//!
//! In the how-to above, a Shift-click on one of the found objects takes it out of the edit. Here a
//! Shift-click (not a Shift-drag) with the Selection tool on a highlighted member, or on an object
//! inside it, leaves that member out (`select.globalEditExclude`): it is no longer highlighted,
//! and later edits leave it as it is.
//! The object the edit started from can't be left out (a Shift-click on it selects it or
//! deselects it as before), Global Edit ends when fewer than two members are left, and leaving
//! one out is not an undo step. Rotated copies are not covered.
use serde::Serialize;
use serde_json::{Value, json};
@@ -68,10 +75,11 @@ use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, Nod
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, Shape};
use super::wand::{fill_of, stroke_of};
use super::{CommandSpec, Result, Session, bad, bool_or, cmd, has_doc};
use super::{CommandSpec, Result, Session, bad, bool_or, checked_id, cmd, has_doc};
const C: &str = "select.globalEdit";
const OPTIONS: &str = "select.globalEditOptions";
const EXCLUDE: &str = "select.globalEditExclude";
/// The most objects a Global Edit takes, the selected one included.
pub const MAX_MEMBERS: usize = 10_000;
const UNSUPPORTED: &str = "Global Edit works on paths, compound paths, symbol instances and groups of them";
@@ -96,6 +104,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
set_options
),
cmd!(
"select.globalEditExclude",
"Leave Out of Global Edit",
[],
None,
"{id} while Global Edit is on: leave the object `id` of the Global Edit (not the one it started from) out of it, as a Shift-click on it with the Selection tool does: it is no longer highlighted and later edits leave it as it is; with fewer than two objects left, Global Edit ends; not an undo step → {active, count, ids} (the objects left in it; none once it has ended)",
is_on,
exclude
),
]
}
@@ -385,6 +402,35 @@ fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "active": true, "count": ids.len(), "ids": ids }))
}
fn is_on(s: &Session) -> std::result::Result<(), String> {
match s.active() {
None => Err("no document open".into()),
Some(st) if st.global_edit.is_none() => Err("Global Edit is off".into()),
Some(_) => Ok(()),
}
}
/// Leave one object out of the Global Edit (a Shift-click on it): not the object it started from.
fn exclude(s: &mut Session, p: &Value) -> Result<Value> {
let id = checked_id(s, p.get("id").ok_or_else(|| bad(EXCLUDE, "missing id"))?, EXCLUDE)?;
let st = s.doc_mut()?;
let Some(ge) = &mut st.global_edit else { return Err(bad(EXCLUDE, "Global Edit is off")) };
match ge.members.iter().position(|(m, _)| *m == id) {
Some(i) if i > 0 => {
ge.members.remove(i);
}
_ => return Err(bad(EXCLUDE, "only an object of the Global Edit other than the one it started from can be left out")),
}
let ids: Vec<u64> = if ge.members.len() < 2 {
st.global_edit = None;
vec![]
} else {
ge.members.iter().map(|(id, _)| id.0).collect()
};
st.revision += 1;
Ok(json!({ "active": !ids.is_empty(), "count": ids.len(), "ids": ids }))
}
fn set_options(s: &mut Session, p: &Value) -> Result<Value> {
let o = s.global_edit_options.with(p, &s.doc()?.doc, OPTIONS)?;
s.global_edit_options = o.clone();
@@ -674,8 +720,9 @@ pub(crate) fn propagate(before: &Document, d: &mut Document, ge: &GlobalEdit, se
edited
}
/// The outlines of the members of the active document's Global Edit that are not selected, in
/// their layer's colour: the canvas highlights them while Global Edit is on.
/// The outlines of the members of the active document's Global Edit that are not selected, hold
/// no selected object and sit inside no selected object, in their layer's colour: the canvas
/// highlights them while Global Edit is on.
pub fn highlights(s: &Session) -> Outlines {
let Some(st) = s.active() else { return vec![] };
let Some(ge) = &st.global_edit else { return vec![] };
@@ -690,6 +737,9 @@ pub fn highlights(s: &Session) -> Outlines {
.iter()
.filter_map(|(id, _)| {
let n = st.doc.node(*id).filter(|n| !holds(n, &st.selection.objects))?;
if st.doc.ancestry(*id).is_some_and(|a| a.iter().any(|p| st.selection.objects.contains(p))) {
return None;
}
let path = match n.stroke_path() {
Some(p) => p,
None => n.geometric_bounds_with(&symbols)?.to_path(0.1),
+34 -13
View File
@@ -312,10 +312,31 @@ pub(crate) fn apply_gradient_edit_in(
bounds: Option<Rect>,
inside: &dyn Fn(Point) -> bool,
) -> std::result::Result<Paint, String> {
let mut gp = match paint {
apply_gradient_edit_in_model(paint, p, bounds, inside, None)
}
/// New implicit stops use the document's model; existing gradients retain their own colors.
fn gradient_for_edit(paint: &Paint, model: Option<vectorcraft_color::cms::Model>) -> GradientPaint {
match paint {
Paint::Gradient(g) => (**g).clone(),
_ => GradientPaint::new(Gradient::default()),
};
_ => {
let mut gradient = Gradient::default();
for stop in &mut gradient.stops {
stop.color = super::paint::stored_color(model, stop.color);
}
GradientPaint::new(gradient)
}
}
}
fn apply_gradient_edit_in_model(
paint: &Paint,
p: &Value,
bounds: Option<Rect>,
inside: &dyn Fn(Point) -> bool,
model: Option<vectorcraft_color::cms::Model>,
) -> std::result::Result<Paint, String> {
let mut gp = gradient_for_edit(paint, model);
let mut switched = false;
if let Some(k) = str_param(p, "kind") {
let kind = parse_kind(k)?;
@@ -414,13 +435,15 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "`dither` applies to gradient fills (stroke: false)"));
}
super::paint::check_keep_model(p, C)?;
let model = super::paint::new_color_model(s, p);
// New RGB stop colors take the document's model; those of the swatches the stops name don't.
let stored = stop_colors(s, p, p);
// Stops naming swatches take their colours from them.
let p = &link_stops(&s.doc()?.doc, p).map_err(|e| bad(C, e))?;
// Validate against the defaults first so bad params fail without touching the document.
let default_paint = if stroke { s.paint.stroke.clone() } else { s.paint.fill.clone() };
let new_default = apply_gradient_edit(&default_paint, &with_stored_stops(p, &default_paint, &stored), None).map_err(|e| bad(C, e))?;
let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(p, &default_paint, &stored), None, &|_| true, model)
.map_err(|e| bad(C, e))?;
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
edit_items(s, &ids, item, C, "Gradient", !stroke, |n, index| {
if index.is_none()
@@ -429,7 +452,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
let lb = t.local_bounds();
for r in &mut t.runs {
let (cur, b) = run_paint_mut(r, stroke, lb);
*cur = apply_gradient_edit(cur, &with_stored_stops(p, cur, &stored), Some(b)).map_err(|e| bad(C, e))?;
*cur = apply_gradient_edit_in_model(cur, &with_stored_stops(p, cur, &stored), Some(b), &|_| true, model).map_err(|e| bad(C, e))?;
}
return Ok(());
}
@@ -441,7 +464,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
None => &|_| true,
};
let old = n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None);
let np = apply_gradient_edit_in(old, &with_stored_stops(p, old, &stored), b, inside).map_err(|e| bad(C, e))?;
let np = apply_gradient_edit_in_model(old, &with_stored_stops(p, old, &stored), b, inside, model).map_err(|e| bad(C, e))?;
n.appearance.set_paint_at(index, !stroke, np);
if let Some(m) = mode
&& let Some(st) = n.appearance.stroke_at_mut(index)
@@ -547,12 +570,9 @@ impl GeomEdit {
/// `cur` with the vector, aspect and focal point of `e` (given in the document). `to_doc` maps
/// the paint's space (text space for type runs) to the document and `bounds` (in that space) fits
/// an unplaced gradient, so what the document shows carries over where `e` keeps it.
fn vector_paint(cur: &Paint, e: &GeomEdit, to_doc: Affine, bounds: Option<Rect>) -> Option<Paint> {
fn vector_paint(cur: &Paint, e: &GeomEdit, to_doc: Affine, bounds: Option<Rect>, model: Option<vectorcraft_color::cms::Model>) -> Option<Paint> {
let from_doc = invert(to_doc)?;
let mut gp = match cur {
Paint::Gradient(g) => (**g).clone(),
_ => GradientPaint::new(Gradient::default()),
};
let mut gp = gradient_for_edit(cur, model);
let kind = gp.gradient.kind;
let map = |mut g: GradientGeom, a: Affine| {
if a != Affine::IDENTITY {
@@ -597,6 +617,7 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
if targets.is_empty() {
return Err(EngineError::Other("nothing selected".into()));
}
let model = super::paint::new_color_model(s, &Value::Null);
edit_items(s, &targets, item, C, "Gradient", !stroke, |n, index| {
if index.is_none()
&& let NodeKind::Text(t) = &mut n.kind
@@ -607,14 +628,14 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
run_stroke_weight(&mut r.style);
}
let (paint, b) = run_paint_mut(r, stroke, lb);
if let Some(np) = vector_paint(paint, &edit, xf, Some(b)) {
if let Some(np) = vector_paint(paint, &edit, xf, Some(b), model) {
*paint = np;
}
}
return Ok(());
}
let b = item_paint_bounds(n, index, !stroke);
if let Some(np) = vector_paint(n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None), &edit, Affine::IDENTITY, b) {
if let Some(np) = vector_paint(n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None), &edit, Affine::IDENTITY, b, model) {
n.appearance.set_paint_at(index, !stroke, np);
}
Ok(())
+2
View File
@@ -145,6 +145,8 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result<Value> {
return Ok(json!({ "id": id.0 }));
}
if let Some(names) = names_param(p, "delete", C)? {
// Each name once: a repeated one would regenerate the graphs using it again.
let names: std::collections::BTreeSet<String> = names.into_iter().collect();
if let Some(n) = names.iter().find(|n| !taken(s, n)) {
return Err(bad(C, format!("no design named `{n}`")));
}
+16
View File
@@ -1304,6 +1304,10 @@ fn graph_designs_are_saved_pasted_and_deleted() {
s.execute("edit.undo", &json!({})).unwrap();
assert!(series_parts(&s, id, 0).iter().skip(1).all(|n| matches!(n.kind, NodeKind::Group { .. })));
assert!(s.execute("graph.design", &json!({"delete": "Nope"})).is_err());
// A name listed many times deletes once (its graphs regenerate once).
s.execute("graph.design", &json!({"delete": vec!["Pill"; 1000]})).unwrap();
assert!(s.doc().unwrap().doc.graph_designs.is_empty());
assert!(series_parts(&s, id, 0).iter().all(|n| matches!(n.kind, NodeKind::Path { .. })));
}
#[test]
@@ -2588,6 +2592,18 @@ fn formatting_the_whole_graphs_text_survives_it_being_drawn_again() {
assert_eq!(spec(&s, id).label_styles, vectorcraft_doc::LabelStyles::default());
}
/// A stroke given to all of a graph's text without a weight is kept at 1 pt, as `paint.setStroke` keeps it.
#[test]
fn a_stroke_given_to_the_whole_graphs_text_is_kept_at_1_pt() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("text.setStyle", &json!({"stroke": "#ff0000"})).unwrap();
let legend = spec(&s, id).label_styles.legend.unwrap();
assert_eq!((legend.stroke.color().map(|c| c.to_hex()), legend.stroke_width), (Some("#ff0000".into()), 1.0));
}
#[test]
fn formatting_one_label_keeps_that_kind_of_label() {
let mut s = Session::new();
+8 -1
View File
@@ -448,6 +448,8 @@ fn clip(name: &mut String) {
fn uniquify<'a>(names: impl Iterator<Item = &'a mut String>, fallback: &str, sep: &str, fold: bool) {
let key = |n: &str| if fold { n.to_lowercase() } else { n.to_string() };
let mut seen = HashSet::new();
// Per repeated name, the number to try next: a run of one name counts on instead of from 2.
let mut next: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
for name in names {
clip(name);
if name.trim().is_empty() {
@@ -455,7 +457,12 @@ fn uniquify<'a>(names: impl Iterator<Item = &'a mut String>, fallback: &str, sep
}
if seen.contains(&key(name)) {
let base = name.clone();
*name = (2..).map(|n| format!("{base}{sep}{n}")).find(|n| !seen.contains(&key(n))).unwrap_or_default();
let n = next.entry(key(&base)).or_insert(2);
while seen.contains(&key(&format!("{base}{sep}{n}"))) {
*n += 1;
}
*name = format!("{base}{sep}{n}");
*n += 1;
}
seen.insert(key(name));
}
+4 -2
View File
@@ -1338,8 +1338,10 @@ fn placement_json(o: PlacementOptions) -> Value {
/// Link Info's fields of the linked file `l` (of object `id` of `st`) into `out`.
fn file_fields(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Value) {
// Within what the caller that opened the document may read, whoever asks.
crate::file_access::confine(st.opened_by.as_ref(), || file_fields_here(st, id, l, out));
// A confined caller reads within its own roots; anyone else within what the caller that
// opened the document may read (never wider than the caller asking now).
let roots = crate::file_access::current().or_else(|| st.opened_by.clone());
crate::file_access::confine(roots.as_ref(), || file_fields_here(st, id, l, out));
}
fn file_fields_here(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Value) {
+25 -3
View File
@@ -7,7 +7,8 @@
//! path column by column from left to right, top to bottom in each column, spread evenly from its
//! first anchor and turned to follow it. Pivot and Rotate come from the command's params, otherwise
//! from the tool's options (Objects on Path Tool Options). `object.objectsOnPath.options` sets the
//! group's Pivot and Rotate, and `object.objectsOnPath.expand` makes it a plain group.
//! group's Pivot, Rotate and Space (the distance between the objects along the path, and where the
//! first one attaches), and `object.objectsOnPath.expand` makes it a plain group.
//!
//! After every edit, [`refresh`] puts the objects of each Objects on Path group that changed back
//! on its path: editing the path moves them, an object moved on its own goes back to its place,
@@ -48,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Objects on Path Options",
[],
None,
"{ids?: Objects on Path groups or objects in them (default: the selection), pivot?: 0-8 (the reference point of each object that attaches to the path, row by row from the top left; 4: the center), rotate?: degrees counter-clockwise from upright on the path} set how the objects of the groups attach → {ids}",
"{ids?: Objects on Path groups or objects in them (default: the selection), pivot?: 0-8 (the reference point of each object that attaches to the path, row by row from the top left; 4: the center), rotate?: degrees counter-clockwise from upright on the path, spacing?: points along the path from each object's attachment point to the next one's (0 or more, kept to what the path has room for; or \"auto\", the default: spread evenly with the last object at the end of an open path), start?: points along the path from its first anchor to the first object's attachment point (default 0)} set how the objects of the groups attach and are spaced → {ids}",
has_objects_on_path,
options
),
@@ -256,16 +257,37 @@ fn attach(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- Options ----------
/// `spacing` and `start` from `p`, each checked: `spacing` takes points (0 or more) or `"auto"`
/// (`None`), and `start` points along the path.
fn spacing_start(p: &Value, cmd: &str, spacing: Option<f64>, start: f64) -> Result<(Option<f64>, f64)> {
let spacing = match p.get("spacing").filter(|v| !v.is_null()) {
None => spacing,
Some(Value::String(a)) if a == "auto" => None,
Some(v) => Some(
v.as_f64()
.filter(|g| g.is_finite() && *g >= 0.0)
.ok_or_else(|| bad(cmd, "`spacing` must be a number of points, 0 or more, or \"auto\""))?,
),
};
let start = match p.get("start").filter(|v| !v.is_null()) {
None => start,
Some(v) => v.as_f64().filter(|s| s.is_finite()).ok_or_else(|| bad(cmd, "`start` must be a finite number"))?,
};
Ok((spacing, start))
}
fn options(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.objectsOnPath.options";
let groups = target_groups(s, p, C)?;
pivot_rotate(p, C, CENTER, 0.0)?;
spacing_start(p, C, None, 0.0)?;
s.edit("Objects on Path Options", |d, _| {
for g in &groups {
let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?;
let Some(rec) = n.extras().objects_on_path.as_deref().cloned() else { continue };
let (pivot, rotate) = pivot_rotate(p, C, rec.pivot, rec.rotate)?;
n.extras_mut().objects_on_path = Some(Box::new(ObjectsOnPath { pivot, rotate, ..rec }));
let (spacing, start) = spacing_start(p, C, rec.spacing, rec.start)?;
n.extras_mut().objects_on_path = Some(Box::new(ObjectsOnPath { pivot, rotate, spacing, start, ..rec }));
}
Ok(())
})?;
+3 -3
View File
@@ -303,7 +303,7 @@ pub(crate) fn check_keep_model(p: &Value, cmd: &str) -> Result<()> {
/// The model RGB colours given in `p` are stored in: the document's in a CMYK document (`None` in
/// an RGB one, or with `keepModel`).
fn new_color_model(s: &Session, p: &Value) -> Option<vectorcraft_color::cms::Model> {
pub(super) fn new_color_model(s: &Session, p: &Value) -> Option<vectorcraft_color::cms::Model> {
let mode = s.active()?.doc.color_mode;
(mode != vectorcraft_doc::ColorMode::Rgb && !bool_or(p, "keepModel", false)).then(|| mode.model())
}
@@ -697,8 +697,8 @@ fn black_or_white(c: &Color) -> bool {
}
}
/// The points the active tool has picked (its `meshPoints` option: the Mesh tool's or Direct
/// Selection's) on the gradient meshes among `ids`, in range, each mesh with its points.
/// The points the active tool has picked (its `meshPoints` option: the Mesh tool's, Direct
/// Selection's or the Lasso's) on the gradient meshes among `ids`, in range, each mesh with its points.
fn picked_mesh_points(s: &Session, ids: &[NodeId]) -> Vec<(NodeId, Vec<usize>)> {
let o = s.tool_options();
let (Some(picked), Ok(st)) = (o.get("meshPoints").and_then(Value::as_array), s.doc()) else { return vec![] };
+6 -1
View File
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character / Paragraph",
[],
None,
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightR Line truncated
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system ev Line truncated
has_doc,
set_format
),
@@ -328,6 +328,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
"tateChuYoko",
"standardVerticalRoman",
"noBreak",
"kashidas",
"hyphenate",
"hyphenateCapitalized",
"romanHangingPunctuation",
@@ -384,6 +385,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
"leadingModel",
"charAlign",
"charDirection",
"kashidas",
"proportionalMetrics",
"tateChuYoko",
"tcyUpDown",
@@ -571,6 +573,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(v) = flag("noBreak") {
st.no_break = v;
}
if let Some(v) = flag("kashidas") {
st.kashidas = v;
}
if let Some(v) = &font_axes {
super::textedit::change_font_axes(st, v);
}
+6 -2
View File
@@ -8,7 +8,7 @@ use serde_json::{Value, json};
use vectorcraft_pdf::{PdfPreset, builtin_preset, builtin_presets};
use super::fileio::pdf::{find_preset, resolve};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, str_param, unique_name};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, str_param};
/// The `format` of a PDF presets file, also its extension.
pub const PRESET_FORMAT: &str = "vcpdfpresets";
@@ -196,8 +196,12 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
for q in &file.presets {
q.settings.check_values().map_err(|e| bad(C, format!("`{}`: {e}", q.name)))?;
}
if file.presets.len() > super::MAX_IMPORTED_PRESETS {
return Err(bad(C, format!("a PDF presets file with over {} presets", super::MAX_IMPORTED_PRESETS)));
}
let replace = bool_or(p, "replace", false);
let mut imported = vec![];
let mut next = std::collections::HashMap::new();
for mut preset in file.presets {
preset.settings.clear_passwords();
let base = Some(preset.name.trim()).filter(|n| !n.is_empty()).unwrap_or("PDF Preset").to_string();
@@ -211,7 +215,7 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
}
}
None => {
preset.name = unique_name(&base, |n| s.pdf_preset_taken(n, None));
preset.name = super::unique_name_from(&base, &mut next, |n| s.pdf_preset_taken(n, None));
imported.push(preset.name.clone());
s.store_pdf_preset(None, &preset);
s.prefs.pdf_presets.push(preset);
+2
View File
@@ -372,6 +372,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("newArtBasic", "General", "Appearance Panel", "New Art Has Basic Appearance", bool),
// File Handling (continued)
p!("templatesFolder", "File Handling", "Files", "Templates Folder", text),
// Off: raster images open in PhotoCraft where it is installed (#5236).
p!("editOriginalSystemDefaults", "File Handling", "Files", "Use System Defaults for Edit Original", bool),
p!("appendConverted", "File Handling", "Files", "Mark Older Files as [Converted] When Opened", bool),
// Native saves (`document.save {compress}`)
p!("useCompression", "File Handling", "Files", "Use Compression", bool),
+6 -2
View File
@@ -8,7 +8,7 @@ use vectorcraft_pdf::PrintSettings;
use super::fileio::pdf::changed;
use super::print::settings_over;
use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, str_param, unique_name};
use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, str_param};
/// The built-in preset's name.
pub const DEFAULT_PRESET: &str = "[Default]";
@@ -221,8 +221,12 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
for q in &file.presets {
q.settings.check().map_err(|e| bad(C, format!("`{}`: {e}", q.name)))?;
}
if file.presets.len() > super::MAX_IMPORTED_PRESETS {
return Err(bad(C, format!("a print presets file with over {} presets", super::MAX_IMPORTED_PRESETS)));
}
let replace = bool_or(p, "replace", false);
let mut imported = vec![];
let mut next = std::collections::HashMap::new();
for mut preset in file.presets {
// [Default] comes in as a saved copy ("Default 2"…): the built-in one stays.
let name = preset.name.trim().trim_start_matches('[').trim_end_matches(']').trim();
@@ -236,7 +240,7 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
}
}
None => {
preset.name = unique_name(&base, |n| s.print_preset_taken(n, None));
preset.name = super::unique_name_from(&base, &mut next, |n| s.print_preset_taken(n, None));
imported.push(preset.name.clone());
s.prefs.print_presets.push(preset);
}
+20 -6
View File
@@ -308,6 +308,14 @@ impl RecoveryStore for FolderStore {
}
fn read(&self, name: &str) -> std::result::Result<Vec<u8>, String> {
let f = self.file(name)?;
// Entry names come from the copy's metadata: refuse a link (or a folder another account
// owns) that would read a file from outside the store.
if let Some(dir) = f.parent() {
Self::own_area(dir)?;
}
if !std::fs::symlink_metadata(&f).map_err(|e| format!("{}: {e}", f.display()))?.file_type().is_file() {
return Err(format!("{}: not a plain file", f.display()));
}
std::fs::read(&f).map_err(|e| format!("{}: {e}", f.display()))
}
fn write(&self, name: &str, bytes: &[u8]) -> std::result::Result<(), String> {
@@ -693,11 +701,12 @@ impl RecoveryJob {
let meta_bytes = serde_json::to_vec_pretty(&meta).map_err(|e| e.to_string())?;
let area = self.file.split_once('/').map_or("", |(a, _)| a);
let _turn = WRITES.lock().unwrap_or_else(|e| e.into_inner());
let have: BTreeSet<String> = if images.is_empty() { BTreeSet::new() } else { store.list()?.into_iter().collect() };
let mut have: BTreeSet<String> = if images.is_empty() { BTreeSet::new() } else { store.list()?.into_iter().collect() };
let mut image_bytes = 0;
for (blob, data) in images {
let name = format!("{area}/{blob}");
if !have.contains(&name) {
// Images of several keys can share one entry: it is written once.
if have.insert(name.clone()) {
store.write(&name, data)?;
image_bytes += data.len();
}
@@ -1001,16 +1010,21 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
super::threads::mark_continued(&mut doc);
// The images, from the entries of the copy's area.
let from = file.split_once('/').map_or("", |(a, _)| a);
let mut blobs = vec![];
let mut blobs: BTreeMap<String, Arc<Vec<u8>>> = BTreeMap::new();
for (key, r) in &meta.images {
match store.read(&format!("{from}/{}", r.blob)) {
// Keys sharing an entry share its bytes: each entry is read (and written again) once.
let read = match blobs.get(&r.blob) {
Some(data) => Ok(data.clone()),
None => store.read(&format!("{from}/{}", r.blob)).map(Arc::new),
};
match read {
Ok(data) => {
let mut blob = ImageBlob::new(r.mime.clone(), data);
let mut blob = ImageBlob { mime: r.mime.clone(), bytes: data, proxy: None };
// Until the linked file is read, the preview stands in for it.
if r.proxy {
blob.proxy = Some(blob.bytes.clone());
}
blobs.push((r.blob.clone(), blob.bytes.clone()));
blobs.insert(r.blob.clone(), blob.bytes.clone());
doc.images.insert(key.clone(), blob);
}
Err(e) => warnings.push(format!("the image “{key}” of the recovered document couldn't be read: {e}")),
+7 -2
View File
@@ -348,8 +348,13 @@ fn from_guides(s: &mut Session, _: &Value) -> Result<Value> {
v
};
let (xs, ys) = (cuts(true, region.x0, region.x1), cuts(false, region.y0, region.y1));
let rects: Vec<Rect> =
ys.windows(2).flat_map(|y| xs.windows(2).map(move |x| Rect::new(x[0], y[0], x[1], y[1]))).filter(|r| valid_rect(*r)).collect();
// One past the limit tells too many, without making every piece of a huge grid first.
let rects: Vec<Rect> = ys
.windows(2)
.flat_map(|y| xs.windows(2).map(move |x| Rect::new(x[0], y[0], x[1], y[1])))
.filter(|r| valid_rect(*r))
.take(MAX_PIECES + 1)
.collect();
if rects.len() > MAX_PIECES {
return Err(EngineError::Other(format!("Create from Guides: the guides make more than {MAX_PIECES} slices")));
}
+11 -2
View File
@@ -818,7 +818,7 @@ fn swatch_unused(s: &mut Session, _: &Value) -> Result<Value> {
Some(l) if d.swatch(l).is_some() => links.push((l.clone(), tint)),
_ => colors.push(*c),
};
d.visit_paints(&mut |p| match p {
let mut paint = |p: &Paint| match p {
Paint::Solid { color: c, swatch, tint } => color(c, swatch.as_ref(), *tint),
Paint::Gradient(g) => {
g.gradient.stops.iter().for_each(|s| color(&s.color, s.swatch.as_ref(), s.tint));
@@ -827,7 +827,16 @@ fn swatch_unused(s: &mut Session, _: &Value) -> Result<Value> {
}
Paint::Pattern { pattern, .. } => patterns.push(pattern.clone()),
Paint::None => {}
});
};
d.visit_paints(&mut paint);
// A character style's fill and stroke use their swatches even while no text uses the style.
for attrs in d.char_styles.iter().map(|def| &def.attrs) {
for key in ["fill", "stroke"] {
if let Some(p) = attrs.get(key).and_then(|v| serde_json::from_value::<Paint>(v.clone()).ok()) {
paint(&p);
}
}
}
let used = |w: &Swatch| {
gradient_links.contains(&w.name)
|| links.iter().any(|(l, t)| match w.tint_of() {
+38 -5
View File
@@ -7,7 +7,7 @@
//! document VectorCraft opens. `symbol.addFromLibrary` copies symbols into the document;
//! `symbol.saveLibrary` writes the document's.
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, LazyLock};
use serde_json::{Value, json};
@@ -104,10 +104,17 @@ impl SymbolLibrary {
/// `name`: the symbols, the symbols they nest and every other resource they use, with their
/// Symbol Options.
pub fn from_document(src: &Document, names: &[String], name: String) -> std::result::Result<Self, String> {
if let Some(n) = names.iter().find(|n| !src.symbols.iter().any(|s| s.name == **n)) {
// Each name's first place in the panel, looked up rather than scanned for: scanning the
// symbols for each one made a library of N symbols cost N² comparisons.
let mut order: HashMap<&str, usize> = HashMap::new();
for (i, s) in src.symbols.iter().enumerate() {
order.entry(s.name.as_str()).or_insert(i);
}
if let Some(n) = names.iter().find(|n| !order.contains_key(n.as_str())) {
return Err(format!("no symbol `{n}`"));
}
let picked = src.symbols.iter().filter(|s| names.is_empty() || names.contains(&s.name));
let wanted: HashSet<&str> = names.iter().map(String::as_str).collect();
let picked = src.symbols.iter().filter(|s| names.is_empty() || wanted.contains(s.name.as_str()));
let clip = Clipboard::gather(src, picked.map(|s| instance(&s.name)).collect());
let mut doc = clip.to_document();
for l in &mut doc.layers {
@@ -116,8 +123,7 @@ impl SymbolLibrary {
}
}
// The panel order of the document they came from.
let order = |n: &str| src.symbols.iter().position(|s| s.name == n);
doc.symbols.sort_by_key(|s| order(&s.name));
doc.symbols.sort_by_key(|s| order.get(s.name.as_str()).copied());
for s in &doc.symbols.clone() {
copy_options(src, &s.name, &mut doc, &s.name);
}
@@ -344,3 +350,30 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
})?;
Ok(json!({"library": info.id, "name": info.name, "count": lib.len()}))
}
#[cfg(test)]
mod tests {
use super::*;
/// A library made from thousands of symbols holds them all, once each, in the panel order of
/// the document they came from, a name given twice kept at its first place.
#[test]
fn many_symbols_keep_their_panel_order() {
let mut src = Document::new(100.0, 100.0);
let n = 4000;
// Names out of alphabetical order, so the order kept is the panel's.
src.symbols = (0..n)
.map(|i| Symbol { name: format!("s{}", (i * 7919) % n), art: Arc::new(Node::group(NodeId(i as u64 + 1), vec![])), dynamic: false })
.collect();
let lib = SymbolLibrary::from_document(&src, &[], "Many".into()).unwrap();
let names = |d: &Document| d.symbols.iter().map(|s| s.name.clone()).collect::<Vec<_>>();
assert_eq!(names(&lib.doc), names(&src));
let picked = ["s3".to_string(), "s1".to_string()];
let lib = SymbolLibrary::from_document(&src, &picked, "Two".into()).unwrap();
let order = |name: &str| src.symbols.iter().position(|s| s.name == name);
let mut want = vec!["s3", "s1"];
want.sort_by_key(|n| order(n));
assert_eq!(names(&lib.doc), want);
assert!(SymbolLibrary::from_document(&src, &["nope".to_string()], "None".into()).is_err());
}
}
+99 -36
View File
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character",
[],
None,
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
has_doc,
set_range_style
),
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Touch Type",
[],
None,
"{id, start: byte (a character of it), dx?: pt, dy?: pt, hScale?: %, vScale?: %, rotation?: deg} change one character (a ligature, one glyph for several characters, as a whole) as a Touch Type tool drag does, as one undo step: dx moves it along its line in reading order by changing the kerning of the character before it on the line and its own kerning, and the characters after it stay where they are (an error for the first character of a line and for a right-to-left character; limited to what kerning from -1000 to 10000 can give); dy raises it (baseline shift, up from its line whatever its rotation, also for the first character of a line and a right-to-left character); dx and dy are document points; hScale (including the object transform), vScale and rotation set its scales and rotation as text.setRangeStyle does. The kerning of the two characters also keeps the character and the ones after it where they were along the line when the font kerned them with their neighbors; a wider or narrower character moves the ones after it by the change in its width → {id, start, end} (the character's bytes)",
"{id, start: byte (a character of it), dx?: pt, dy?: pt, hScale?: %, vScale?: %, rotation?: deg} change one character (a ligature, one glyph for several characters, as a whole) as a Touch Type tool drag does, as one undo step: dx moves it along its line in reading order by changing the kerning of the character before it on the line and its own kerning, and the characters after it stay where they are (an error for the first logical character of a line or at a reading-direction boundary; supported in either reading direction; limited to what kerning from -1000 to 10000 can give); dy raises it (baseline shift, up from its line whatever its rotation, also for the first character of a line and a right-to-left character); dx and dy are document points; hScale (including the object transform), vScale and rotation set its scales and rotation as text.setRangeStyle does. The kerning of the two characters also keeps the character and the ones after it where they were along the line when the font kerned them with their neighbors; a wider or narrower character moves the ones after it by the change in its width → {id, start, end} (the character's bytes)",
has_doc,
touch_type
),
@@ -154,14 +154,14 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
fn text_mut(d: &mut vectorcraft_doc::Document, id: NodeId) -> Option<&mut TextObject> {
pub(crate) fn text_mut(d: &mut vectorcraft_doc::Document, id: NodeId) -> Option<&mut TextObject> {
match d.node_mut(id).map(|n| &mut n.kind) {
Some(NodeKind::Text(t)) => Some(t),
_ => None,
}
}
fn text_ref(s: &Session, id: NodeId) -> Result<TextObject> {
pub(crate) fn text_ref(s: &Session, id: NodeId) -> Result<TextObject> {
match s.doc()?.doc.node(id).map(|n| &n.kind) {
Some(NodeKind::Text(t)) => Ok((**t).clone()),
Some(_) => Err(EngineError::Other(format!("node {} is not text", id.0))),
@@ -361,6 +361,7 @@ pub(crate) struct CharChange {
small_caps: Option<Option<f64>>,
char_align: Option<vectorcraft_doc::CharAlign>,
char_direction: Option<Option<vectorcraft_doc::ParaDirection>>,
kashidas: Option<bool>,
proportional_metrics: Option<bool>,
tate_chu_yoko: Option<bool>,
/// Tate-chu-yoko Settings › Up/Down and Left/Right, in points.
@@ -600,7 +601,11 @@ impl CharChange {
/// `setup` gives the superscript, subscript and small caps proportions.
pub(crate) fn parse(p: &Value, cmd: &str, setup: &vectorcraft_doc::DocSetup) -> Result<Self> {
check_numbers(p, &["size", "tracking", "baselineShift", "hScale", "vScale", "rotation", "strokeWidth"], cmd)?;
check_switches(p, &["underline", "strikethrough", "allCaps", "proportionalMetrics", "tateChuYoko", "standardVerticalRoman", "noBreak"], cmd)?;
check_switches(
p,
&["underline", "strikethrough", "allCaps", "proportionalMetrics", "tateChuYoko", "standardVerticalRoman", "noBreak", "kashidas"],
cmd,
)?;
let num = |k: &str| p.get(k).and_then(Value::as_f64);
let (position, small_caps) = super::docsetup::script_params(p, setup, cmd)?;
let flag = |k: &str| p.get(k).and_then(Value::as_bool);
@@ -645,6 +650,7 @@ impl CharChange {
small_caps,
char_align: char_align_param(p, cmd)?,
char_direction: char_direction_param(p, cmd)?,
kashidas: flag("kashidas"),
proportional_metrics: flag("proportionalMetrics"),
tate_chu_yoko: flag("tateChuYoko"),
tcy_up_down: tcy_offset_param(p, "tcyUpDown", cmd)?,
@@ -696,6 +702,7 @@ impl CharChange {
&& self.small_caps.is_none()
&& self.char_align.is_none()
&& self.char_direction.is_none()
&& self.kashidas.is_none()
&& self.proportional_metrics.is_none()
&& self.tate_chu_yoko.is_none()
&& self.tcy_up_down.is_none()
@@ -708,7 +715,7 @@ impl CharChange {
&& self.font_height_reference.is_none()
}
fn localize(&mut self, t: &TextObject, cmd: &str) -> Result<()> {
pub(crate) fn localize(&mut self, t: &TextObject, cmd: &str) -> Result<()> {
use super::typecmd::local_type_value;
self.size = self.size.map(|v| local_type_value(t, v, (0.1, 1296.0), false, cmd)).transpose()?;
self.leading = self.leading.map(|v| v.map(|v| local_type_value(t, v, (0.1, 5000.0), false, cmd)).transpose()).transpose()?;
@@ -749,6 +756,9 @@ impl CharChange {
if let Some(v) = self.char_direction {
st.char_direction = v;
}
if let Some(v) = self.kashidas {
st.kashidas = v;
}
if let Some(v) = self.proportional_metrics {
st.proportional_metrics = v;
}
@@ -1007,11 +1017,8 @@ fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
// Document points per text-space point along `v`.
let doc_len = |v: Vec2| linear(t.xf, v).hypot() / v.hypot();
let limit = 1296.0 / points;
if dx != 0.0 && g.rtl {
return Err(bad(C, "a right-to-left character moves only up and down (dy)"));
}
// A list marker's glyphs (length 0) stand for no character.
let prev = lay.glyphs.iter().find(|h| h.line == g.line && h.len > 0 && h.byte + h.len == a);
let prev = lay.glyphs.iter().find(|h| h.line == g.line && h.len > 0 && h.byte + h.len == a && h.rtl == g.rtl);
let pr = prev.map(|h| (h.byte, h.byte + h.len));
let db = vectorcraft_text::FontDb::global();
let em = glyph_em(db, &t, g).ok_or_else(|| bad(C, "the character's size can't be measured"))?;
@@ -1055,8 +1062,10 @@ fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
// to Fit and a path effect such as Skew scale: two layouts with the call's other changes and shifts one step apart, both within the range,
// measure that length. Neither shift is one that a run already has, so the character's run
// splits off alike in both.
let raise = if dy == 0.0 {
0.0
let drawn_move = g.rtl && moved != 0.0;
let up = Vec2::new(d.y, -d.x);
let (mut raise, baseline_step) = if dy == 0.0 && !drawn_move {
(0.0, 0.0)
} else {
let shift = edit::slice_runs(&t.runs, a, b).first().map_or(0.0, |r| r.style.baseline_shift);
let from = shift.clamp(-limit, limit);
@@ -1068,21 +1077,44 @@ fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
// The character's pen with its baseline shift set to `to`.
let pen_at = |to: f64| {
let mut trial = t.clone();
touch(&mut trial, None, None, to - shift);
// Hold kerning fixed: Optical spacing can change along the line as the baseline
// rises, which would make its horizontal drift count as baseline movement.
touch(&mut trial, pr.map(|_| 0.0), Some(0.0), to - shift);
let l = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &trial);
l.glyphs.iter().find(|h| h.byte == a && h.len > 0).map(|h| h.xf * Point::ZERO)
};
let per_step = match (pen_at(from + step), pen_at(from + 2.0 * step)) {
(Some(p), Some(q)) => linear(t.xf, q - p).hypot() / step.abs(),
_ => 0.0,
let (per_step, across) = match (pen_at(from + step), pen_at(from + 2.0 * step)) {
(Some(p), Some(q)) => (linear(t.xf, q - p).hypot() / step.abs(), (q - p).dot(up) / step),
_ => (0.0, 0.0),
};
dy / per_step
(dy / per_step, across)
};
if !raise.is_finite() {
return Err(bad(C, "the character's size can't be measured"));
}
// Where a glyph starts along the line.
let pen = |h: &vectorcraft_text::PositionedGlyph| h.origin.to_vec2().dot(along);
// Along-line RTL movement must measure the drawn glyph: turning off automatic kerning can
// also remove font placement, and Character Rotation turns that placement across the line.
let pen = |h: &vectorcraft_text::PositionedGlyph| {
let at = if drawn_move {
h.xf * Point::ZERO
} else if h.rtl {
h.origin + Vec2::new(h.angle.cos(), h.angle.sin()) * h.width_start
} else {
h.origin
};
at.to_vec2().dot(along)
};
// Scaling or rotation in the same call may intentionally turn the glyph's font placement
// about its pen. Keep that change while compensating placement lost to manual kerning.
let intrinsic_delta = if drawn_move && ["hScale", "vScale", "rotation"].iter().any(|key| p.get(*key).is_some_and(|v| !v.is_null())) {
let mut trial = t.clone();
touch(&mut trial, None, None, 0.0);
let l = vectorcraft_text::layout(db, &trial);
let intrinsic = |h: &vectorcraft_text::PositionedGlyph| h.xf * Point::ZERO - h.xf * h.pivot;
l.glyphs.iter().find(|h| h.byte == a && h.len > 0).map_or(Vec2::ZERO, |h| intrinsic(h) - intrinsic(g))
} else {
Vec2::ZERO
};
// How much further the character's new scales advance it along the line: the character laid
// out alone, in point type of the same orientation, before and after the change.
let grown = {
@@ -1096,10 +1128,27 @@ fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
};
// The character lands `moved` further on, and the character after it on its line keeps its
// distance from it, wider or narrower only by the character's new scales.
let goal = pen(g) + moved;
let goal = pen(g) + moved + intrinsic_delta.dot(along);
let next_goal = lay.glyphs.iter().find(|h| h.byte == b && h.len > 0 && h.line == g.line).map(|h| pen(h) + grown);
// How far the character and the character after it on its line miss their places, along the
// line, with the kerning `k` (before, own) added.
let prev_goal = prev.map(pen);
let mut k = if moved != 0.0 { (em_prev.map(|ep| moved / ep * 1000.0), Some(-moved / em * 1000.0)) } else { (None, None) };
if drawn_move {
if !baseline_step.is_finite() || baseline_step.abs() <= 1e-12 {
return Err(bad(C, "the character's size can't be measured"));
}
let mut trial = t.clone();
touch(&mut trial, k.0, k.1, raise);
let l = vectorcraft_text::layout(db, &trial);
let h = l.glyphs.iter().find(|h| h.byte == a && h.len > 0).ok_or_else(|| bad(C, "the character's size can't be measured"))?;
let across_goal = (g.xf * Point::ZERO).to_vec2().dot(up) + dy / doc_len(up) + intrinsic_delta.dot(up);
raise += (across_goal - (h.xf * Point::ZERO).to_vec2().dot(up)) / baseline_step;
if !raise.is_finite() {
return Err(bad(C, "the character's size can't be measured"));
}
}
// Keep both neighbors: alignment can pin either end of an RTL line, making one neighbor
// insensitive to kerning even though the other one moves. The two spacing values must place
// the selected character and keep every available neighbor in place.
let miss = |k: (Option<f64>, Option<f64>)| {
let mut trial = t.clone();
touch(&mut trial, k.0, k.1, raise);
@@ -1109,30 +1158,40 @@ fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
(Some(n), Some(at)) => pen(n) - at,
_ => 0.0,
};
Some((pen(h) - goal, next))
let previous = match (pr.and_then(|(byte, _)| l.glyphs.iter().find(|n| n.byte == byte && n.len > 0 && n.line == h.line)), prev_goal) {
(Some(n), Some(at)) => pen(n) - at,
_ => 0.0,
};
Some([pen(h) - goal, next, previous])
};
let placed = |m: (f64, f64)| m.0.abs() <= 1e-9 && m.1.abs() <= 1e-9;
let mut k = if moved != 0.0 { (em_prev.map(|ep| moved / ep * 1000.0), Some(-moved / em * 1000.0)) } else { (None, None) };
let placed = |m: [f64; 3]| m.iter().all(|v| v.abs() <= 1e-9);
// A manual kerning value turns off the font's kerning for its character, each style run is
// shaped apart, and centered, right-aligned and justified lines move as their width changes, so
// the first values can miss. Layouts then measure what each kerning value does to the two
// characters, and the values are solved for from that (at most six layouts).
if !g.rtl && miss(k).is_some_and(|m| !placed(m)) {
// characters, and the values are solved for with a bounded set of layouts.
if miss(k).is_some_and(|m| !placed(m)) {
k = (pr.map(|_| k.0.unwrap_or(0.0)), Some(k.1.unwrap_or(0.0)));
if let Some(mut m) = miss(k) {
const STEP: f64 = 10.0;
let column = |dk: (f64, f64)| miss((k.0.map(|v| v + dk.0), k.1.map(|v| v + dk.1))).map(|n| ((n.0 - m.0) / STEP, (n.1 - m.1) / STEP));
let column = |dk: (f64, f64)| miss((k.0.map(|v| v + dk.0), k.1.map(|v| v + dk.1))).map(|n| std::array::from_fn(|i| (n[i] - m[i]) / STEP));
let by_before = if k.0.is_some() { column((STEP, 0.0)) } else { None };
let by_own = column((0.0, STEP));
// The kerning changes that cancel the misses `m`.
let solve = |m: (f64, f64)| match (by_before, by_own) {
(Some(p), Some(q)) if (p.0 * q.1 - q.0 * p.1).abs() > 1e-12 => {
let det = p.0 * q.1 - q.0 * p.1;
((q.0 * m.1 - m.0 * q.1) / det, (m.0 * p.1 - p.0 * m.1) / det)
let solve = |m: [f64; 3]| {
let dot = |a: [f64; 3], b: [f64; 3]| a.into_iter().zip(b).map(|(a, b)| a * b).sum::<f64>();
let (p, q) = (by_before.unwrap_or([0.0; 3]), by_own.unwrap_or([0.0; 3]));
let (pp, pq, qq) = (dot(p, p), dot(p, q), dot(q, q));
let (pm, qm) = (dot(p, m), dot(q, m));
let det = pp * qq - pq * pq;
if det > 1e-12 * pp * qq {
((pq * qm - qq * pm) / det, (pq * pm - pp * qm) / det)
} else if pp >= qq && pp > 1e-24 {
(-pm / pp, 0.0)
} else if qq > 1e-24 {
(0.0, -qm / qq)
} else {
(0.0, 0.0)
}
(Some(p), _) if p.0.abs() > 1e-12 => (-m.0 / p.0, 0.0),
(_, Some(q)) if q.1.abs() > 1e-12 => (0.0, -m.1 / q.1),
_ => (0.0, 0.0),
};
for _ in 0..2 {
if placed(m) {
@@ -1255,7 +1314,7 @@ pub(crate) fn editing_range(s: &mut Session) -> Result<Option<(NodeId, usize, us
/// objects in `ids`, else the text the Type tool has selected, else all the text of every selected
/// type object. At a caret, `at_caret` gives the range from the plain text and the caret's byte
/// (None: nothing changes there). Each range comes with whether it came from a caret.
fn type_ranges(
pub(crate) fn type_ranges(
s: &mut Session,
p: &Value,
c: &str,
@@ -1263,6 +1322,10 @@ fn type_ranges(
) -> Result<Vec<(NodeId, usize, usize, bool)>> {
// (text, its range; None: all of it).
let targets: Vec<(NodeId, Option<(usize, usize)>)> = match id_param(p, "id") {
// An object that isn't type is refused as `ids` of it is.
Some(id) if s.doc()?.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Text(_))) => {
return Err(bad(c, "no text objects selected"));
}
Some(id) => vec![(id, Some(range_of(p, edit::runs_len(&text_ref(s, id)?.runs), c)?))],
None => {
let editing = editing_range(s)?.filter(|_| p.get("ids").filter(|v| !v.is_null()).is_none());
+77 -8
View File
@@ -173,6 +173,7 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> {
("small_caps", json!(v.small_caps)),
("charAlign", json!(v.char_align)),
("charDirection", json!(v.char_direction)),
("kashidas", json!(v.kashidas)),
("proportionalMetrics", json!(v.proportional_metrics)),
("tateChuYoko", json!(v.tate_chu_yoko)),
("tcyUpDown", json!(v.tcy_up_down)),
@@ -477,10 +478,12 @@ fn name_param<'a>(p: &'a Value, kind: Kind, verb: &str) -> Result<&'a str> {
str_param(p, "name").ok_or_else(|| bad(&kind.cmd(verb), "missing `name`"))
}
/// The `attrs` of `p`, validated. `kept` holds the style's current attributes (`charStyle.edit`) or
/// the target text's attributes (`charStyle.new`): a language tag that is not in the list, which a
/// file can give a style or a run, stays when `attrs` keeps it.
fn attrs_param(p: &Value, kind: Kind, verb: &str, kept: Option<&Map<String, Value>>) -> Result<Option<Map<String, Value>>> {
/// The `attrs` of `p`, validated. `kept` holds the style's current attributes (`charStyle.edit`,
/// `charStyle.setAttrs`), the target text's attributes (`charStyle.new`) or the attributes of the
/// style being copied (`charStyle.duplicate`): a language tag that is not in the list, a swatch link the document does
/// not have, or an OpenType feature tag the shaper does not know, which a file can give a style or
/// a run, stays when `attrs` keeps it.
fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Map<String, Value>>) -> Result<Option<Map<String, Value>>> {
match p.get("attrs") {
None | Some(Value::Null) => Ok(None),
Some(Value::Object(m)) => {
@@ -490,12 +493,25 @@ fn attrs_param(p: &Value, kind: Kind, verb: &str, kept: Option<&Map<String, Valu
let full = match kind {
Kind::Char => {
let mut st = with_attrs(&CharStyle::default(), m, &c)?;
let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key);
// A language of the list, stored as its tag (as text.setFormat takes it).
if let Some(l) = &st.language
&& kept.and_then(|k| k.get("language")) != m.get("language")
{
st.language = vectorcraft_doc::setup::char_language(l).map_err(|e| bad(&c, e))?.map(str::to_string);
}
for (key, paint) in [("fill", &mut st.fill), ("stroke", &mut st.stroke)] {
if changed(key) {
style_paint(d, paint, key, &c)?;
}
}
let (key, lo, hi) = ("stroke_width", 0.0, vectorcraft_doc::MAX_COORD);
if changed(key) && !(lo..=hi).contains(&st.stroke_width) {
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
}
if changed("features") {
style_features(&st.features, kept, &c)?;
}
char_attrs(&st)
}
Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), m, &c)?),
@@ -506,6 +522,51 @@ fn attrs_param(p: &Value, kind: Kind, verb: &str, kept: Option<&Map<String, Valu
}
}
/// Check a character style's `fill` or `stroke` (`key`): each solid color and gradient stop has a
/// tint from 0 to 1, and a link to a global swatch of `d`, whose color at that tint it takes.
fn style_paint(d: &Document, paint: &mut vectorcraft_color::Paint, key: &str, c: &str) -> Result<()> {
match paint {
vectorcraft_color::Paint::Solid { color, swatch, tint } => style_color(d, color, swatch.as_deref(), *tint, key, c),
vectorcraft_color::Paint::Gradient(g) => {
g.gradient.stops.iter_mut().try_for_each(|stop| style_color(d, &mut stop.color, stop.swatch.as_deref(), stop.tint, key, c))
}
_ => Ok(()),
}
}
/// Check one color of a character style's `key` paint for [`style_paint`].
fn style_color(d: &Document, color: &mut vectorcraft_color::Color, swatch: Option<&str>, tint: f32, key: &str, c: &str) -> Result<()> {
if !(0.0..=1.0).contains(&tint) {
let (key, lo, hi) = (format!("{key}.tint"), 0, 1);
return Err(bad(c, format!("`{key}` must be from {lo} to {hi}")));
}
if let Some(name) = swatch {
if d.swatch(name).is_none() {
return Err(bad(c, format!("no swatch `{name}`")));
}
let base = d.global_color(name).ok_or_else(|| bad(c, format!("`{name}` is a process colour: tints apply to global and spot colours")))?;
*color = base.tinted(tint);
}
Ok(())
}
/// Check a character style's OpenType `features`: at most [`vectorcraft_text::MAX_STYLE_FEATURES`]
/// tags, or no more than the `kept` attributes already list, each one the shaper knows or one the
/// `kept` attributes already list.
fn style_features(features: &[String], kept: Option<&Map<String, Value>>, c: &str) -> Result<()> {
let kept: Vec<&str> = kept.and_then(|k| k.get("features")).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect();
let max = vectorcraft_text::MAX_STYLE_FEATURES;
if features.len() > max.max(kept.len()) {
return Err(bad(c, format!("features lists at most {max} tags")));
}
// One `-` or `+` at most, as the shaper reads a tag.
let known = |t: &str| vectorcraft_text::OtFeatures::known_tag(t) && !t.strip_prefix(['-', '+']).unwrap_or(t).starts_with(['-', '+']);
match features.iter().find(|t| !known(t) && !kept.contains(&t.as_str())) {
Some(t) => Err(bad(c, format!("unknown OpenType feature `{t}`"))),
None => Ok(()),
}
}
/// The attributes of a new style made from nothing (no `attrs`, no text selected): while the
/// interface is in Japanese, new type's em box top-to-top leading (paragraph styles) and em box
/// centre alignment (character styles); else none (the defaults).
@@ -538,9 +599,15 @@ fn list(s: &mut Session, kind: Kind) -> Result<Value> {
}
fn new(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
new_from(s, p, kind, None)
}
/// `charStyle.new`, `paraStyle.new`: `copied` holds the attributes of the style a copy is made of
/// (`charStyle.duplicate`), which `attrs` keeps as [`attrs_param`] keeps the target text's.
fn new_from(s: &mut Session, p: &Value, kind: Kind, copied: Option<&Map<String, Value>>) -> Result<Value> {
let c = kind.cmd("new");
let target = selection_attrs(s, p, kind)?;
let attrs = match attrs_param(p, kind, "new", target.as_ref())? {
let attrs = match attrs_param(&s.doc()?.doc, p, kind, "new", copied.or(target.as_ref()))? {
Some(a) => a,
None => match target {
Some(a) => a,
@@ -668,7 +735,9 @@ fn redefine(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
fn set_attrs(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
let name = name_param(p, kind, "setAttrs")?.to_string();
let attrs = attrs_param(p, kind, "setAttrs", None)?.ok_or_else(|| bad(&kind.cmd("setAttrs"), "missing `attrs`"))?;
let d = &s.doc()?.doc;
let old = kind.attrs(d, &name);
let attrs = attrs_param(d, p, kind, "setAttrs", old.as_ref())?.ok_or_else(|| bad(&kind.cmd("setAttrs"), "missing `attrs`"))?;
redefine_to(s, kind, &name, attrs, "setAttrs")
}
@@ -678,7 +747,7 @@ fn edit_style(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
let to = str_param(p, "to").ok_or_else(|| bad(&c, "missing `to`"))?.trim().to_string();
let d = &s.doc()?.doc;
let old = kind.attrs(d, &name).ok_or_else(|| bad(&c, format!("no style `{name}`")))?;
let attrs = attrs_param(p, kind, "edit", Some(&old))?.ok_or_else(|| bad(&c, "missing `attrs`"))?;
let attrs = attrs_param(d, p, kind, "edit", Some(&old))?.ok_or_else(|| bad(&c, "missing `attrs`"))?;
if name == kind.normal() {
return Err(bad(&c, format!("`{name}` can't be edited this way")));
}
@@ -726,7 +795,7 @@ fn duplicate(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
.map(|i| if i == 1 { format!("{stem} copy") } else { format!("{stem} copy {i}") })
.find(|n| kind.attrs(d, n).is_none())
.unwrap_or_else(|| format!("{stem} copy"));
new(s, &json!({ "name": copy, "attrs": attrs }), kind)
new_from(s, &json!({ "name": copy, "attrs": attrs }), kind, Some(&attrs))
}
fn rename(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
+138
View File
@@ -257,6 +257,144 @@ fn new_character_style_keeps_a_language_tag_from_the_text() {
assert!(error.contains("unknown language"), "{error}");
}
/// The fill of the first run of `id` and its overprint flags, its stroke and stroke weight.
fn run_paints(s: &Session, id: u64) -> (vectorcraft_color::Paint, vectorcraft_color::Paint, f64, bool, bool) {
let st = runs(s, id)[0].style.clone();
(st.fill, st.stroke, st.stroke_width, st.overprint_fill, st.overprint_stroke)
}
#[test]
fn character_style_color_and_features_reach_text_and_follow_swatch_edits() {
let (mut s, id) = session_with_text("Text 1/2");
s.execute("swatch.new", &json!({"name": "Brand", "color": "#2050a0", "global": true})).unwrap();
let brand = s.doc().unwrap().doc.tint_paint("Brand", 1.0).unwrap();
let mut tinted = serde_json::to_value(s.doc().unwrap().doc.tint_paint("Brand", 1.0).unwrap()).unwrap();
// The command takes the color of the link at the tint, whatever color is sent.
tinted["tint"] = json!(0.4);
let attrs = json!({"fill": brand, "stroke": tinted, "stroke_width": 2.0, "overprint_fill": true, "overprint_stroke": false,
"features": ["dlig", "-liga", "tnum", "lnum", "-onum", "-pnum", "ss02", "-ss01"]});
s.execute("charStyle.new", &json!({"name": "Ink", "attrs": attrs})).unwrap();
s.execute("charStyle.apply", &json!({"name": "Ink", "id": id})).unwrap();
let want_stroke = s.doc().unwrap().doc.tint_paint("Brand", 0.4).unwrap();
assert_eq!(run_paints(&s, id), (brand, want_stroke.clone(), 2.0, true, false));
assert_eq!(runs(&s, id)[0].style.features, ["dlig", "-liga", "tnum", "lnum", "-onum", "-pnum", "ss02", "-ss01"]);
let def = |s: &Session| s.doc().unwrap().doc.char_styles.iter().find(|d| d.name == "Ink").unwrap().attrs.clone();
assert_eq!(def(&s)["stroke"], serde_json::to_value(&want_stroke).unwrap());
let saved = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
assert_eq!(saved.char_styles.iter().find(|d| d.name == "Ink").unwrap().attrs, def(&s));
s.execute("swatch.edit", &json!({"name": "Brand", "color": "#a02050"})).unwrap();
let (brand, tint40) = (s.doc().unwrap().doc.tint_paint("Brand", 1.0).unwrap(), s.doc().unwrap().doc.tint_paint("Brand", 0.4).unwrap());
assert_eq!(run_paints(&s, id).0, brand);
assert_eq!(run_paints(&s, id).1, tint40);
assert_eq!(def(&s)["fill"], serde_json::to_value(&brand).unwrap());
assert_eq!(def(&s)["stroke"], serde_json::to_value(&tint40).unwrap());
let later = s.execute("text.create", &json!({"x": 10, "y": 90, "text": "Later"})).unwrap()["id"].as_u64().unwrap();
s.execute("charStyle.apply", &json!({"name": "Ink", "id": later})).unwrap();
assert_eq!(run_paints(&s, later).0, brand);
}
#[test]
fn character_style_color_and_features_are_checked() {
let (mut s, _) = session_with_text("Text");
s.execute("swatch.new", &json!({"name": "Brand", "color": "#2050a0", "global": true})).unwrap();
s.execute("charStyle.new", &json!({"name": "Body", "attrs": {}})).unwrap();
let mut over = serde_json::to_value(s.doc().unwrap().doc.tint_paint("Brand", 1.0).unwrap()).unwrap();
over["tint"] = json!(1.5);
let mut missing = over.clone();
missing["tint"] = json!(0.5);
missing["swatch"] = json!("Gone");
s.execute("swatch.new", &json!({"name": "Local", "color": "#102030"})).unwrap();
let mut local = missing.clone();
local["swatch"] = json!("Local");
let many: Vec<String> = (0..=vectorcraft_text::MAX_STYLE_FEATURES).map(|_| "dlig".to_string()).collect();
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
for (attrs, message) in [
(json!({"fill": over}), "`fill.tint` must be from 0 to 1"),
(json!({"stroke": missing}), "no swatch `Gone`"),
(json!({"stroke": local}), "`Local` is a process colour"),
(json!({"stroke_width": -1.0}), "`stroke_width` must be from 0 to 4000000"),
(json!({"stroke_width": 5.0e6}), "`stroke_width` must be from 0 to 4000000"),
(json!({"features": ["dlig", "zzzz"]}), "unknown OpenType feature `zzzz`"),
(json!({"features": ["--liga"]}), "unknown OpenType feature `--liga`"),
(json!({"features": many}), "features lists at most 256 tags"),
(json!({"fill": {"type": "solid"}}), "missing field"),
] {
for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] {
let p = match cmd {
"charStyle.edit" => json!({"name": "Body", "to": "Body", "attrs": attrs}),
"charStyle.new" => json!({"name": "Other", "attrs": attrs}),
_ => json!({"name": "Body", "attrs": attrs}),
};
let error = s.execute(cmd, &p).unwrap_err().to_string();
assert!(error.contains(message), "{cmd} {attrs}: {error}");
}
}
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
}
#[test]
fn style_paints_count_as_swatch_uses_and_gradient_stops_are_checked() {
let (mut s, _) = session_with_text("Text");
s.execute("swatch.new", &json!({"name": "Brand", "color": "#2050a0", "global": true})).unwrap();
s.execute("swatch.new", &json!({"name": "Spare", "color": "#a02050", "global": true})).unwrap();
let unused = |s: &mut Session| s.execute("swatch.unused", &json!({})).unwrap()["names"].clone();
assert!(unused(&mut s).as_array().unwrap().contains(&json!("Brand")));
let brand = s.doc().unwrap().doc.tint_paint("Brand", 0.5).unwrap();
s.execute("charStyle.new", &json!({"name": "Ink", "attrs": {"stroke": brand}})).unwrap();
let names = unused(&mut s);
assert!(!names.as_array().unwrap().contains(&json!("Brand")), "{names}");
assert!(names.as_array().unwrap().contains(&json!("Spare")), "{names}");
let mut g = vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default());
g.gradient.stops[0].swatch = Some("Brand".into());
g.gradient.stops[0].tint = 0.25;
let fill = serde_json::to_value(vectorcraft_color::Paint::Gradient(Box::new(g.clone()))).unwrap();
s.execute("charStyle.new", &json!({"name": "Fade", "attrs": {"fill": fill}})).unwrap();
let def = s.doc().unwrap().doc.char_styles.iter().find(|d| d.name == "Fade").unwrap().attrs.clone();
let want = s.doc().unwrap().doc.global_color("Brand").unwrap().tinted(0.25);
assert_eq!(def["fill"]["gradient"]["stops"][0]["color"], serde_json::to_value(want).unwrap());
g.gradient.stops[0].swatch = Some("Gone".into());
let gone = serde_json::to_value(vectorcraft_color::Paint::Gradient(Box::new(g))).unwrap();
let error = s.execute("charStyle.new", &json!({"name": "Bad", "attrs": {"fill": gone}})).unwrap_err().to_string();
assert!(error.contains("no swatch `Gone`"), "{error}");
}
#[test]
fn styles_from_files_keep_their_unknown_feature_tags_and_swatch_links() {
let (mut s, _) = session_with_text("Text");
s.execute("charStyle.new", &json!({"name": "Body", "attrs": {}})).unwrap();
let linked = json!({"type": "solid", "color": {"model": "rgb", "r": 1.0, "g": 0.0, "b": 0.0}, "swatch": "Gone"});
if let Some(def) = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).char_styles.iter_mut().find(|d| d.name == "Body") {
def.attrs.insert("features".into(), json!(["zzzz", "dlig"]));
def.attrs.insert("fill".into(), linked.clone());
}
let fill = s.doc().unwrap().doc.char_styles[0].attrs["fill"].clone();
s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {"features": ["zzzz", "-dlig"], "fill": fill}})).unwrap();
let def = s.doc().unwrap().doc.char_styles.iter().find(|d| d.name == "Body").unwrap().attrs.clone();
assert_eq!(def["features"], json!(["zzzz", "-dlig"]));
let mut replaced = def.clone();
replaced.insert("size".into(), json!(14.0));
s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": replaced})).unwrap();
s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": def})).unwrap();
s.execute("charStyle.duplicate", &json!({"name": "Body"})).unwrap();
assert_eq!(s.doc().unwrap().doc.char_styles.iter().find(|d| d.name == "Body copy").unwrap().attrs, def);
// A list longer than a style made here can have stays editable, but does not grow.
let long: Vec<String> = (0..300).map(|i| if i % 2 == 0 { "dlig".to_string() } else { "-dlig".to_string() }).collect();
if let Some(def) = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).char_styles.iter_mut().find(|d| d.name == "Body") {
def.attrs.insert("features".into(), json!(long));
}
let mut shorter = long.clone();
shorter.pop();
s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {"features": shorter}})).unwrap();
let mut longer = shorter.clone();
longer.extend(["swsh".to_string(), "salt".to_string()]);
let error = s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {"features": longer}})).unwrap_err().to_string();
assert!(error.contains("features lists at most 256 tags"), "{error}");
}
#[test]
fn editing_character_style_clears_removed_size_without_losing_local_override() {
let (mut s, id) = session_with_text("One two");
+22 -7
View File
@@ -93,14 +93,29 @@ thread_local! {
/// makes "changed" a pointer comparison). Deleted frames' text flows into the remaining ones; a
/// frame that is now point type leaves its thread with the text it holds.
pub(crate) fn reflow(before: &Document, doc: &mut Document) {
let threads = std::mem::take(&mut doc.text_threads);
// A frame is in one thread, once: a file that lists it again (in its thread or another) would
// copy its text into the story each time, and write the grown story back for the next thread
// to copy again. Only its first place counts.
let mut seen = std::collections::HashSet::new();
// A thread that lost a frame that way is flowed again: its frames' layout was made for the
// thread as listed (a frame left alone must lose its threaded continuation).
let threads: Vec<(Vec<NodeId>, bool)> = std::mem::take(&mut doc.text_threads)
.into_iter()
.map(|t| {
let listed = t.len();
let t: Vec<NodeId> = t.into_iter().filter(|id| seen.insert(*id)).collect();
let lost = t.len() != listed;
(t, lost)
})
.collect();
let mut kept = vec![];
for thread in threads {
let changed = thread.iter().any(|id| match (before.node(*id), doc.node(*id)) {
(Some(a), Some(b)) => !std::ptr::eq(a, b),
(None, None) => false,
_ => true,
});
for (thread, lost) in threads {
let changed = lost
|| thread.iter().any(|id| match (before.node(*id), doc.node(*id)) {
(Some(a), Some(b)) => !std::ptr::eq(a, b),
(None, None) => false,
_ => true,
});
// When no frame changed, the thread keeps its area-type frames and their text is not copied.
if !changed {
let live: Vec<NodeId> = thread.into_iter().filter(|id| text_of(doc, *id).is_some()).collect();
+41
View File
@@ -40,6 +40,47 @@ fn thread_flows_reflows_on_edit_and_survives_delete() {
assert_eq!(s.doc().unwrap().doc.text_threads.len(), 1);
}
/// A file that lists a frame more than once, in its own thread or in another, flows the story
/// through each frame once: repeated places would copy its text again and again.
#[test]
fn frames_listed_twice_flow_the_story_once() {
let (mut s, a, b) = setup();
s.execute("text.thread.create", &json!({})).unwrap();
let mut d = (*s.doc().unwrap().doc).clone();
let (fa, fb) = (NodeId(a), NodeId(b));
d.text_threads = vec![vec![fa, fb, fa, fb, fa], vec![fb, fa], vec![fa, fb]];
reflow(&Document::new(1.0, 1.0), &mut d);
assert_eq!(d.text_threads, vec![vec![fa, fb]]);
let plain = |id: NodeId| match &d.node(id).unwrap().kind {
NodeKind::Text(t) => t.plain_text(),
_ => panic!("not text"),
};
assert_eq!(format!("{}{}", plain(fa), plain(fb)), TEXT.repeat(4));
}
/// A frame left alone when a repeated listing is dropped (`[[a, b], [b, c]]` → `[[a, b], [c]]`)
/// is flowed again as a story of its own, even when no frame changed: it no longer continues a
/// paragraph from the frame before it.
#[test]
fn a_frame_left_alone_by_a_dropped_repeat_stops_continuing() {
let (mut s, a, b) = setup();
s.execute("text.thread.create", &json!({})).unwrap();
let c =
s.execute("text.create", &json!({"x": 400, "y": 10, "text": "Tail", "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
let mut d = (*s.doc().unwrap().doc).clone();
let (fa, fb, fc) = (NodeId(a), NodeId(b), NodeId(c));
d.text_threads = vec![vec![fa, fb], vec![fb, fc]];
if let Some(NodeKind::Text(t)) = d.node_mut(fc).map(|n| &mut n.kind) {
t.first_para_continues = true;
}
let before = d.clone();
reflow(&before, &mut d);
assert_eq!(d.text_threads, vec![vec![fa, fb]]);
let NodeKind::Text(t) = &d.node(fc).unwrap().kind else { panic!("not text") };
assert!(!t.first_para_continues, "an unthreaded frame continues nothing");
assert_eq!(t.plain_text(), "Tail");
}
#[test]
fn edits_copy_only_the_stories_of_threads_whose_frames_changed() {
let (mut s, a, b) = setup();
+38 -5
View File
@@ -123,7 +123,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character",
[],
None,
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour, keepModel?: bool (as paint.setFill), features?: [\"dlig\", \"-liga\", …] OpenType, featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", …] OpenType, featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
has_doc,
set_style
),
@@ -785,11 +785,21 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
None => None,
};
super::paint::check_keep_model(p, C)?;
let fill = match p.get("fill") {
None | Some(Value::Null) => None,
Some(Value::String(n)) if n.eq_ignore_ascii_case("none") => Some(vectorcraft_color::Paint::None),
Some(v) => Some(vectorcraft_color::Paint::solid(super::paint::new_color(s, p, color_value(v).ok_or_else(|| bad(C, "bad fill colour"))?))),
let paint = |k: &str| -> Result<Option<vectorcraft_color::Paint>> {
Ok(match p.get(k) {
None | Some(Value::Null) => None,
Some(Value::String(n)) if n.eq_ignore_ascii_case("none") => Some(vectorcraft_color::Paint::None),
Some(v) => {
Some(vectorcraft_color::Paint::solid(super::paint::new_color(s, p, color_value(v).ok_or_else(|| bad(C, format!("bad {k} colour")))?)))
}
})
};
let fill = paint("fill")?;
let stroke = paint("stroke")?;
check_numbers(p, &["strokeWidth"], C)?;
// The weight of the character stroke.
let mut stroke_weight = super::stroke::StrokeChange::default();
stroke_weight.weight = p.get("strokeWidth").and_then(Value::as_f64).map(|w| w.clamp(0.0, 1000.0));
let features = super::textedit::features_param(p, C)?;
let feature_changes = super::textedit::feature_changes_param(p, C)?;
if font.is_none()
@@ -799,6 +809,8 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
&& tracking.is_none()
&& justify.is_none()
&& fill.is_none()
&& stroke.is_none()
&& stroke_weight.is_empty()
&& features.is_none()
&& feature_changes.is_none()
{
@@ -814,6 +826,8 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
let size = size.map(|v| local_type_value(t, v, (0.1, 1296.0), false, C)).transpose()?;
let leading = leading.map(|v| v.map(|v| local_type_value(t, v, (0.1, 5000.0), false, C)).transpose()).transpose()?;
// The stroke weight is in document points, as stroke.set gives it; the character stroke is drawn in text space.
let k = vectorcraft_doc::Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0);
let before = protect.then(|| t.runs.clone());
style_chars(t, range, |st| {
if let Some(f) = &font {
@@ -843,6 +857,16 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(f) = &fill {
st.fill = f.clone();
}
if let Some(f) = &stroke {
// A painted stroke on a run without a weight gets 1 pt, as with paint.setStroke.
if !f.is_none() {
super::gradient::run_stroke_weight(st);
}
st.stroke = f.clone();
}
if !stroke_weight.is_empty() {
stroke_weight.apply_char_scaled(st, k);
}
if let Some(f) = &features {
st.features = f.clone();
}
@@ -899,6 +923,15 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(f) = &fill {
st.fill = f.clone();
}
if let Some(f) = &stroke {
if !f.is_none() {
super::gradient::run_stroke_weight(st);
}
st.stroke = f.clone();
}
if !stroke_weight.is_empty() {
stroke_weight.apply_char(st);
}
if let Some(f) = &features {
st.features = f.clone();
}
@@ -1148,6 +1148,37 @@ fn character_direction_is_a_character_attribute_saved_only_when_set() {
assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[0].style).get("charDirection"), Some(&serde_json::Value::Null));
}
/// The Character-menu switch is on for new and old text, and changing a selected range leaves
/// its neighbors alone. The paragraph's Insert Kashidas length is a separate setting.
#[test]
fn character_kashidas_default_on_and_round_trip_by_range() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "كتب محمد"})).unwrap()["id"].as_u64().unwrap();
let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => t.runs.clone(),
_ => panic!("text"),
};
assert!(runs(&s)[0].style.kashidas);
let old = serde_json::to_value(&runs(&s)[0].style).unwrap();
assert!(old.get("kashidas").is_none());
assert!(serde_json::from_value::<vectorcraft_doc::CharStyle>(old).unwrap().kashidas);
s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 6, "kashidas": false})).unwrap();
assert_eq!(runs(&s).iter().map(|r| r.style.kashidas).collect::<Vec<_>>(), [true, false, true]);
let err = s.execute("text.setRangeStyle", &json!({"id": id, "kashidas": "off"})).unwrap_err().to_string();
assert!(err.contains("kashidas"));
s.execute("edit.undo", &json!({})).unwrap();
assert!(runs(&s).iter().all(|r| r.style.kashidas));
s.execute("edit.redo", &json!({})).unwrap();
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") };
assert_eq!(t.runs.iter().map(|r| r.style.kashidas).collect::<Vec<_>>(), [true, false, true]);
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("text.setFormat", &json!({"kashidas": true})).unwrap();
assert!(runs(&s).iter().all(|r| r.style.kashidas));
assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[0].style)["kashidas"], true);
}
/// Proportional Metrics (#966): a character attribute, saved only when on.
#[test]
fn proportional_metrics_is_a_character_attribute_saved_only_when_on() {
+7 -7
View File
@@ -4,11 +4,11 @@
//! variable, anything to a `visibility` variable, a linked image to an `image`
//! variable, or a graph root to a `graph` variable (CSV data), put a row of values in
//! each dataset, and `dataset.select` swaps the whole document to that row in one undo
//! step. `dataset.import` / `dataset.export` move those rows as CSV (header: `name`
//! then variable names, which export writes with `#` before a visibility variable and `@`
//! before an image variable); import also reads tab-separated files, files without the
//! `name` column, and header cells that define new variables (`#` for visibility, `@` for
//! image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the
//! step. `dataset.import` / `dataset.export` move those rows as CSV (header: one
//! variable name per column, which export writes with `#` before a visibility variable and `@`
//! before an image variable); import replaces the datasets, names the rows Data Set 1, 2…,
//! also reads tab-separated files, and reads header cells that define new variables (`#` for
//! visibility, `@` for image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the
//! text variables and data sets of a variable library, the XML file of the reference app's Save
//! Variable Library, and `variable.saveLibrary` writes the text variables and data sets as one.
//! Agents reach every command through `run_command`, like all engine commands.
@@ -838,7 +838,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Import Data Sets…",
["Window", "Variables"],
None,
"{path? | data? | dataBase64? | csv?} load datasets from CSV, comma- or tab-separated, in UTF-16 with a byte-order mark, UTF-8 or else Windows-1252 (header: name, then variable names; one row per dataset; without the name column every header is a variable and the rows take the first free names Data Set 1, 2…). A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. Rows whose name already exists are replaced → {imported, updated, names, defined}",
"{path? | data? | dataBase64? | csv?} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 with a byte-order mark, UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}",
has_doc,
dataset_import
),
@@ -847,7 +847,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Data Sets…",
["Window", "Variables"],
None,
"{path?} write every dataset as CSV (header: name, then one column per variable: `#Name` for a visibility variable, `@Name` for an image variable, and the name alone for a text or graph variable, as dataset.import reads them). Refused when the document has more than 1000 data sets or 256 variables, the most dataset.import reads, or when a variable's header is another variable's name (a visibility variable `Show` next to a text variable `#Show`) → {path, datasets, warning?}; without path → {csv, datasets, warning?}. `warning` names the variables whose header or values make a document without them refuse the file (a % header, a # header whose values aren't true or false); otherwise it names the variables such a document doesn't read back with their kind (text variables whose names start with # or @, graph variables)",
"{path?} write every dataset as CSV (header: one column per variable and no dataset names: `#Name` for a visibility variable, `@Name` for an image variable, and the name alone for a text or graph variable, as dataset.import reads them). Refused when the document has more than 1000 data sets or 256 variables, the most dataset.import reads, or when a variable's header is another variable's name (a visibility variable `Show` next to a text variable `#Show`) → {path, datasets, warning?}; without path → {csv, datasets, warning?}. `warning` names the variables whose header or values make a document without them refuse the file (a % header, a # header whose values aren't true or false); otherwise it names the variables such a document doesn't read back with their kind (text variables whose names start with # or @, graph variables)",
has_doc,
dataset_export
),
+54 -73
View File
@@ -102,7 +102,8 @@ fn tab_separated(text: &str) -> bool {
/// by commas, or by tabs when [`tab_separated`] says so. `"` quotes a cell (doubled inside),
/// which may then hold separators and line breaks, as [`csv_escape`] writes them. An unquoted
/// cell is trimmed. A quoted cell keeps what its quotes hold as written, spaces included, and
/// drops white space after the closing quote at the end of the cell. Blank lines are skipped.
/// drops white space after the closing quote at the end of the cell. A line whose cells are all
/// blank and unquoted is skipped; a quoted empty cell keeps its line as a row.
fn parse_datasets_csv(text: &str, cmd: &str) -> Result<Vec<CsvRow>> {
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
let sep = if tab_separated(text) { '\t' } else { ',' };
@@ -132,7 +133,10 @@ fn parse_datasets_csv(text: &str, cmd: &str) -> Result<Vec<CsvRow>> {
Some('\n') | None if !in_quotes => {
quoted.push(closed.is_some());
row.push(end_csv_cell(&mut cur, &mut closed));
if row.iter().any(|c| !c.trim().is_empty()) {
if row.len() > MAX_CSV_COLS {
return Err(bad(cmd, format!("line {line}: more than {MAX_CSV_COLS} columns")));
}
if row.iter().any(|c| !c.trim().is_empty()) || quoted.contains(&true) {
rows.push((start, std::mem::take(&mut row), std::mem::take(&mut quoted)));
// +1 for the header.
if rows.len() > MAX_CSV_ROWS + 1 {
@@ -174,8 +178,10 @@ fn end_csv_cell(cur: &mut String, closed: &mut Option<usize>) -> String {
}
fn csv_escape(s: &str) -> String {
// An empty string is quoted so that it reads back as an empty value, not as a missing one.
if s.is_empty() || s.contains([',', '"', '\n', '\r']) || s != s.trim() { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() }
// An empty string is quoted so that it reads back as an empty value, not as a missing one. A
// tab is quoted so that a header of one variable whose name holds a tab isn't read as
// tab-separated.
if s.is_empty() || s.contains([',', '"', '\n', '\r', '\t']) || s != s.trim() { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() }
}
/// A visibility cell: true/false, 1/0, yes/no (ASCII, case-insensitive). An error names the
@@ -240,8 +246,7 @@ fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) {
for (i, v) in vars.variables.iter().enumerate() {
let header = export_header(v);
let cell = header.trim();
// Column 1 holds the dataset names.
let read = if cell.is_empty() { None } else { header_variable(cell, i + 2, &none, &mut defined, C).ok() };
let read = if cell.is_empty() { None } else { header_variable(cell, i + 1, &none, &mut defined, C).ok() };
// The import refuses a header that names a variable an earlier column named.
let Some((name, kind)) = read.filter(|(name, _)| seen.insert(name.clone())) else {
refused.push(v.name.as_str());
@@ -260,30 +265,36 @@ fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) {
(refused, other)
}
/// Build the CSV of every dataset (header `name` then each variable's [`export_header`] in
/// definition order). Refused when a variable's header is another variable's name, which the
/// import reads as that variable (a visibility variable `Show` next to a text variable `#Show`).
/// Build the CSV of every dataset: a header of each variable's [`export_header`] in definition
/// order, then one row per dataset. The dataset names are not written. Refused when a variable's
/// header is another variable's name, which the import reads as that variable (a visibility
/// variable `Show` next to a text variable `#Show`). A dataset with no value for any variable would
/// be a blank line, which the import skips, so its row gets a quoted empty cell: in the first column
/// whose variable isn't a text variable, where it reads back as no value, or else in the first
/// column, where it reads back as an empty text.
fn datasets_to_csv(vars: &Variables, cmd: &str) -> Result<String> {
let names: BTreeSet<&str> = vars.variables.iter().map(|v| v.name.as_str()).collect();
let mut out = String::from("name");
let mut header = Vec::with_capacity(vars.variables.len());
for v in &vars.variables {
let header = export_header(v);
if header != v.name && names.contains(header.as_str()) {
let (name, other) = (&v.name, &header);
return Err(bad(cmd, format!("the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them")));
let cell = export_header(v);
if cell != v.name && names.contains(cell.as_str()) {
let (name, other) = (&v.name, &cell);
return Err(bad(cmd, format!("the header `{cell}` for `{name}` would read back as the variable `{other}`: rename one of them")));
}
out.push(',');
out.push_str(&csv_escape(&header));
header.push(csv_escape(&cell));
}
let mut out = header.join(",");
out.push('\n');
let keep = vars.variables.iter().position(|v| v.kind != VariableKind::Text).unwrap_or(0);
for ds in &vars.datasets {
out.push_str(&csv_escape(&ds.name));
for v in &vars.variables {
out.push(',');
if let Some(val) = ds.values.get(&v.name) {
out.push_str(&csv_escape(&value_to_cell(val)));
}
let mut row: Vec<String> =
vars.variables.iter().map(|v| ds.values.get(&v.name).map(|val| csv_escape(&value_to_cell(val))).unwrap_or_default()).collect();
if row.iter().all(String::is_empty)
&& let Some(cell) = row.get_mut(keep)
{
*cell = csv_escape("");
}
out.push_str(&row.join(","));
out.push('\n');
}
Ok(out)
@@ -329,12 +340,11 @@ fn header_variable(
}
}
/// Import datasets from CSV. A first header cell `name` makes the first column the dataset
/// names; the other headers name variables, as [`header_variable`] reads them, and the
/// variables the document doesn't define yet are defined, unbound. Without the `name` column,
/// every header names a variable and the rows take the first free names "Data Set 1", "Data
/// Set 2" and so on. Two headers that name one variable are refused. Existing rows of the same
/// name are replaced; new names are appended. One undo step.
/// Import datasets from CSV. Every header cell names a variable, as [`header_variable`] reads it,
/// and the variables the document doesn't define yet are defined, unbound. Two headers that name
/// one variable are refused. The rows replace every dataset of the document and are named "Data
/// Set 1", "Data Set 2" and so on, in file order. The document's variables and their bindings
/// stay. One undo step, and none when the variables and datasets stay as they were.
pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "dataset.import";
let (bytes, given_as_text) = datasets_csv_bytes(p, C)?;
@@ -344,16 +354,10 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
let Some((_, header, _)) = rows.first() else {
return Err(bad(C, "CSV is empty"));
};
let name_column = header.first().is_some_and(|h| h.trim().eq_ignore_ascii_case("name"));
let (kinds, existing_names) = {
let st = s.doc()?;
let kinds: BTreeMap<String, VariableKind> = st.doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind)).collect();
let existing: BTreeSet<String> = st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect();
(kinds, existing)
};
let kinds: BTreeMap<String, VariableKind> = s.doc()?.doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind)).collect();
let mut columns: Vec<(usize, String, VariableKind)> = Vec::new();
let mut defined: Vec<Variable> = Vec::new();
for (i, h) in header.iter().enumerate().skip(usize::from(name_column)) {
for (i, h) in header.iter().enumerate() {
let cell = h.trim();
if cell.is_empty() {
return Err(bad(C, format!("empty header in column {}", i + 1)));
@@ -373,27 +377,8 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "CSV has a header but no data rows"));
}
let mut parsed: Vec<DataSet> = Vec::new();
// The names of the rows read so far, and the last number given to a row without a name.
let (mut seen, mut number) = (BTreeSet::new(), 0usize);
for &(line, ref row, ref quoted) in rows.iter().skip(1) {
let raw_name = if name_column { row.first().map_or("", |c| c.trim()) } else { "" };
let name = if raw_name.is_empty() {
// Same numbering as Capture Data Set when a row leaves the name blank or the file has
// no name column. The search starts after the last number given.
let (n, name) = (number + 1..)
.map(|n| (n, format!("Data Set {n}")))
.find(|(_, n)| !seen.contains(n) && !existing_names.contains(n))
.unwrap_or_else(|| (line, format!("Data Set {line}")));
number = n;
name
} else if raw_name.chars().count() > MAX_NAME {
return Err(bad(C, format!("line {line}: `name` is longer than {MAX_NAME} characters")));
} else {
raw_name.to_string()
};
if !seen.insert(name.clone()) {
return Err(bad(C, format!("line {line}: dataset `{name}` appears twice")));
}
for (n, &(line, ref row, ref quoted)) in rows.iter().skip(1).enumerate() {
let name = format!("Data Set {}", n + 1);
let mut values = BTreeMap::new();
for &(col, ref var, kind) in &columns {
let cell = row.get(col).map(String::as_str).unwrap_or("");
@@ -406,26 +391,23 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
}
let names: Vec<String> = parsed.iter().map(|d| d.name.clone()).collect();
let new_variables: Vec<String> = defined.iter().map(|v| v.name.clone()).collect();
let deleted: Vec<String> = s.doc()?.doc.variables.datasets.iter().map(|d| d.name.clone()).collect();
// The import is one undo step, and an import that leaves the variables and data sets as they
// were adds none.
let (imported, updated) = super::edit_variables(s, "Import Data Sets", |vars| {
vars.variables.extend(defined);
let (mut imported, mut updated) = (0usize, 0usize);
for row in parsed {
if let Some(existing) = vars.datasets.iter_mut().find(|x| x.name == row.name) {
*existing = row;
updated += 1;
} else {
vars.datasets.push(row);
imported += 1;
}
// were adds none, so the active data set stays when nothing changes.
super::edit_variables(s, "Import Data Sets", |vars| {
if defined.is_empty() && vars.datasets == parsed {
return Ok(());
}
Ok((imported, updated))
vars.variables.extend(defined);
vars.datasets = parsed;
vars.active_dataset = None;
Ok(())
})?;
Ok(json!({"imported": imported, "updated": updated, "names": names, "defined": new_variables}))
Ok(json!({"imported": names.len(), "names": names, "defined": new_variables, "deletedDataSets": deleted}))
}
/// Export every dataset as CSV ([`datasets_to_csv`]). With `path`, write the file; else return
/// Export every dataset as CSV ([`datasets_to_csv`]: one column per variable, no dataset names).
/// With `path`, write the file; else return
/// `{csv}`. The reply's `warning` names the variables whose column makes a document without them
/// refuse the file, or else the variables it doesn't read back with their kind
/// ([`kinds_a_new_document_loses`]); the app shows it in its status bar.
@@ -439,7 +421,6 @@ pub(super) fn dataset_export(s: &mut Session, p: &Value) -> Result<Value> {
if st.doc.variables.datasets.len() > MAX_CSV_ROWS {
return Err(bad(C, format!("more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS}")));
}
// The name column comes first, so the import's column cap leaves room for this many variables.
if st.doc.variables.variables.len() > MAX_CSV_COLS {
return Err(bad(C, format!("more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS}")));
}
+4
View File
@@ -52,6 +52,9 @@ pub struct DocState {
pub recalled_selection: RecalledSelection,
/// Process-unique id of this open document (tab indices shift when tabs close).
pub uid: u64,
/// Preferences › User Interface › Open Documents As Tabs when the document opened: cleared,
/// the UI opens it in a floating window of its own.
pub opened_as_tab: bool,
/// View Opacity Mask (Alt-click the mask thumbnail): the masked object whose mask the canvas
/// shows alone, in greyscale, while that mask is edited (see [`DocState::shown_mask`]).
pub mask_view: Option<NodeId>,
@@ -255,6 +258,7 @@ impl DocState {
last_selection_cmd: None,
recalled_selection: RecalledSelection::default(),
uid: NEXT_DOC_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
opened_as_tab: true,
mask_view: None,
transparency_grid,
format: "vectorcraft",
+26 -3
View File
@@ -99,9 +99,14 @@ impl AutomationRoots {
Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {path}")),
};
}
let resolved = resolve(path)?;
if roots.iter().any(|r| inside(&resolved, &r.resolved)) {
return Ok(());
// Resolving a path on another computer connects to it: unless a root is on a network
// share, such a path is refused by its name before anything is looked up.
let remote = cfg!(windows) && network_path(path) && !roots.iter().any(|r| network_path(&r.resolved.to_string_lossy()));
if !remote {
let resolved = resolve(path)?;
if roots.iter().any(|r| inside(&resolved, &r.resolved)) {
return Ok(());
}
}
let shown: Vec<String> = roots.iter().map(|r| r.shown.display().to_string()).collect();
match (shown.as_slice(), access) {
@@ -282,6 +287,14 @@ pub(crate) fn is_device_name(component: &str) -> bool {
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT")
}
/// Is `path` a Windows name of a file on another computer (`\\server\share\…`, `\\?\UNC\…`)?
/// (Judged by name alone, so it can be tested on any platform; `check` applies it on Windows only.)
fn network_path(path: &str) -> bool {
let p = path.replace('/', "\\");
let upper = p.to_ascii_uppercase();
upper.starts_with(r"\\?\UNC\") || upper.starts_with(r"\\.\UNC\") || (p.starts_with(r"\\") && !p.starts_with(r"\\?\") && !p.starts_with(r"\\.\"))
}
/// Why Windows would not take `path` as an ordinary file name, for the first of its components
/// that is a device name, or holds a `:` (a drive letter's own colon belongs to the prefix, not to
/// a name, so only a stream such as `x.svg:evil` has one). (Judged by name alone, so it can be
@@ -315,6 +328,16 @@ mod tests {
p.to_string_lossy().into_owned()
}
#[test]
fn network_paths_are_told_by_name() {
for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] {
assert!(network_path(p), "{p}");
}
for p in [r"C:\art\x.svg", r"\\?\C:\art\x.svg", r"\\.\C:\x", "/home/me/x.svg", "x.svg"] {
assert!(!network_path(p), "{p}");
}
}
#[test]
fn paths_inside_the_roots_pass_and_others_dont() {
let (base, roots) = folders("inside");
+11
View File
@@ -163,6 +163,11 @@ pub struct Session {
/// While [`Session::place_queue_read`] runs `file.place.queue`: the files read for it, which
/// the command loads the place cursor with instead of reading them; `None` otherwise.
pub(crate) queue_hand_off: Option<cmd::place::QueueRead>,
/// The automation roots in force when the place cursor was last loaded (`None`: none were).
/// The cursor places its files later, on a click that may come from the person at the
/// keyboard: those files, and the files they link to, are read under these roots, so a queue
/// an agent loaded never reads beyond what it was given.
pub(crate) place_queue_roots: Option<std::sync::Arc<file_access::AutomationRoots>>,
/// While [`Session::import_image_read`] runs `clipboard.importImage`: the image read for it,
/// which the command loads instead of reading `dataBase64`; `None` otherwise.
pub(crate) image_hand_off: Option<cmd::clipboard::ImageRead>,
@@ -198,6 +203,12 @@ pub struct Session {
/// The pointer button is held: the last pointer event was a press or a drag, not a release or
/// a move ([`Session::pointer_held`]).
pub(crate) pointer_held: bool,
/// The id and persistent options of the tool when the press under way began, which a dropped
/// press puts back ([`Session::drop_tool_press`]).
pub(crate) press_options: Option<(String, serde_json::Map<String, serde_json::Value>)>,
/// The freeform gradient point selected once the tool took the press under way, which a
/// dropped press selects again ([`Session::drop_tool_press`]).
pub(crate) press_point: Option<Option<(usize, cmd::gradient::StopOwner)>>,
/// A guide being dragged out of a ruler ([`Session::ruler_guide`]).
pub(crate) ruler_guide: Option<vectorcraft_tools::rulerguide::NewGuide>,
/// Which selected type overflows its frame, for the ports every tool but the Type tools shows.
+10 -2
View File
@@ -69,6 +69,9 @@ impl Session {
}
let Some(st) = self.active() else { return };
let (uid, files, doc_path) = (st.uid, crate::cmd::links::linked_groups(&st.doc), st.path.clone());
// A confined caller's roots, else what the caller that opened the document may read (the
// desktop frame is unconfined).
let opened_by = st.opened_by.clone();
if files.is_empty() {
return;
}
@@ -76,7 +79,11 @@ impl Session {
let out = slot.clone();
let scope = crate::file_access::ScopeHandle::capture();
let spawned = std::thread::Builder::new().name("link-watch".into()).spawn(move || {
let stamps = scope.run(|| files.into_iter().map(|(p, ids)| (p.clone(), ids, stamp(&p, doc_path.as_deref()))).collect());
let stamps = scope.run(|| {
crate::file_access::confine(crate::file_access::current().or(opened_by).as_ref(), || {
files.into_iter().map(|(p, ids)| (p.clone(), ids, stamp(&p, doc_path.as_deref()))).collect()
})
});
*out.lock().unwrap_or_else(PoisonError::into_inner) = Some((uid, stamps));
});
if spawned.is_ok() {
@@ -141,7 +148,8 @@ impl Session {
let mode = if update { "automatically" } else { self.prefs.update_links.as_str() };
match mode {
"automatically" => {
let r = self.execute("links.update", &json!({"ids": ids}))?;
let roots = crate::file_access::current().or_else(|| self.active().and_then(|d| d.opened_by.clone()));
let r = crate::file_access::confine(roots.as_ref(), || self.execute("links.update", &json!({"ids": ids})))?;
// Not readable yet (still being written): the next look tries again.
let unread: BTreeSet<u64> = r["missing"].as_array().map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default();
for (path, ids) in &changed {
+5
View File
@@ -253,6 +253,10 @@ pub struct Prefs {
// File Handling (continued)
/// Where Save as Template and New from Template start ("" = `Documents/VectorCraft Templates`).
pub templates_folder: String,
/// File Handling → Use System Defaults for Edit Original (#5236): Links panel › Edit Original
/// opens a linked file in the system's default app for it; off, in the app that made it
/// (PhotoCraft for a raster image, where it is installed; the system's app otherwise).
pub edit_original_system_defaults: bool,
/// Open older native files as "<name> [Converted]" so Save asks for a new name.
pub append_converted: bool,
/// File Handling → Use Compression: native saves are gzip-compressed (`document.save
@@ -464,6 +468,7 @@ impl Default for Prefs {
pdf_presets: vec![],
screen_export_presets: vec![],
templates_folder: String::new(),
edit_original_system_defaults: true,
append_converted: true,
use_compression: false,
web_export_presets: vec![],
+5
View File
@@ -79,6 +79,7 @@ impl Session {
batch_steps: None,
place_hand_off: None,
queue_hand_off: None,
place_queue_roots: None,
image_hand_off: None,
trace_hand_off: None,
place_cursor_requests: false,
@@ -91,6 +92,8 @@ impl Session {
liquify_stroke: None,
plane_widget_press: false,
pointer_held: false,
press_options: None,
press_point: None,
ruler_guide: None,
port_marks: Default::default(),
font_search: None,
@@ -206,6 +209,7 @@ impl Session {
self.reset_tool_for_doc_switch();
let mut st = DocState::new(doc, path);
st.history.limit = self.prefs.history_states as usize;
st.opened_as_tab = self.prefs.open_documents_as_tabs;
self.docs.push(st);
let i = self.docs.len() - 1;
self.active = Some(i);
@@ -236,6 +240,7 @@ impl Session {
st.history.limit = old.history.limit;
// Same open document (caches keyed by uid stay valid); a new revision redraws it.
st.uid = old.uid;
st.opened_as_tab = old.opened_as_tab;
st.revision = old.revision + 1;
st.format = old.format;
st.save_options = old.save_options.clone();
+18
View File
@@ -454,3 +454,21 @@ fn collecting_explicit_assets_rejects_invalid_ids_without_adding_anything() {
assert_eq!(run(&mut s, "assets.add", json!({"ids": [b, a]}))["added"], 2);
assert_eq!(assets(&mut s).len(), 2);
}
/// Settings saved without the PDF passwords they were given export only once a password is given
/// again, never as an unprotected PDF; security given without `passwordRequired` exports as given.
#[test]
fn settings_saved_without_their_pdf_passwords_refuse_to_export_until_given_again() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
run(&mut s, "assets.add", json!({"ids": [a]}));
let row = |security: Value| json!({"formats": [{"format": "pdf", "security": security}]});
run(&mut s, "assets.settings.set", row(json!({"openPassword": "open sesame"})));
let err = s.execute("assets.export", &json!({})).unwrap_err().to_string();
assert!(err.contains("without their passwords"), "{err}");
let encrypted = |r: &Value| files(r)[0].1.windows(8).any(|w| w == b"/Encrypt");
let r = run(&mut s, "assets.export", row(json!({"openPassword": "open sesame", "passwordRequired": true})));
assert!(encrypted(&r), "given again: protected");
let r = run(&mut s, "assets.export", row(json!({})));
assert!(!encrypted(&r), "left out on purpose: unprotected");
}
+21
View File
@@ -350,6 +350,27 @@ fn type_only_copies_offer_their_text() {
assert!(run(&mut s, "clipboard.exportText", json!({}))["text"].is_null());
}
/// Art too large to fit the clipboard's PNG side at the encoder's smallest scale gets no PNG,
/// instead of a picture hundreds of megabytes large.
#[test]
fn copy_leaves_out_the_png_of_art_too_large_to_scale_down() {
let mut s = session();
let id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 1_000_000, "height": 1_000_000}))["id"].clone();
run(&mut s, "select.set", json!({"ids": [id]}));
run(&mut s, "edit.copy", json!({}));
assert!(!s.clipboard.flavour_types(false, false).contains(&PNG), "not offered either");
let (flavours, notes) = s.clipboard.flavours_with_warnings(false, false);
assert!(flavours.iter().all(|f| f.mime != PNG));
assert!(notes.iter().any(|n| n.contains("too large to copy as a picture")), "{notes:?}");
// Art that fits at that scale still gets its PNG, at most 4096 pixels a side.
let id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 200_000, "height": 100}))["id"].clone();
run(&mut s, "select.set", json!({"ids": [id]}));
run(&mut s, "edit.copy", json!({}));
let png = s.clipboard.flavours(false, false).into_iter().find(|f| f.mime == PNG).expect("a PNG");
let img = image::load_from_memory(&png.data).unwrap();
assert!(img.width() <= 4096 && img.height() <= 4096, "{}x{}", img.width(), img.height());
}
#[test]
fn copy_offers_flavours_by_the_preferences() {
let mut s = session();
+22
View File
@@ -66,6 +66,28 @@ fn unique_name_appends_the_first_free_number() {
assert_eq!(unique_name("A 2", |n| taken.contains(&n)), "A 2 2");
}
#[test]
fn unique_name_from_counts_on_for_a_run_of_one_name() {
let mut taken = vec!["A".to_string(), "a 3".to_string()];
let mut next = std::collections::HashMap::new();
for want in ["A 2", "A 4", "A 5"] {
let is_taken = |n: &str| taken.iter().any(|t| t.eq_ignore_ascii_case(n));
let n = crate::cmd::unique_name_from("A", &mut next, is_taken);
assert_eq!(n, want);
taken.push(n);
}
assert_eq!(crate::cmd::unique_name_from("B", &mut next, |_| false), "B");
}
#[test]
fn a_presets_file_with_too_many_presets_is_refused() {
let mut s = Session::new();
let presets: Vec<_> = (0..=crate::cmd::MAX_IMPORTED_PRESETS).map(|_| serde_json::json!({"name": "P"})).collect();
let file = serde_json::json!({"format": crate::cmd::printpresets::PRESET_FORMAT, "presets": presets}).to_string();
let e = s.execute("print.presets.import", &serde_json::json!({"data": file})).unwrap_err().to_string();
assert!(e.contains("over"), "{e}");
}
#[test]
fn leaf_targets_expand_groups_and_stop_at_compound_paths() {
let mut s = session();
Loaded 100 of 391 files, more files were not shown because too many files have changed in this diff. Show more