mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 20:46:22 +01:00
Merge remote-tracking branch 'upstream/main' into pencil-redraw-extend
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
223e88ba4e
521 files changed
+37328
-2999
No files matched your search
@@ -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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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
+55
-52
@@ -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=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
|
||||
[[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=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
|
||||
[[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=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
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=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
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=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
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=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
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=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
dependencies = [
|
||||
"craft-fonts-build",
|
||||
"craft-i18n",
|
||||
@@ -1084,7 +1085,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-vectorcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=14d5dbb50c317b8747a9cf9eb35ab8a22515f137#14d5dbb50c317b8747a9cf9eb35ab8a22515f137"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -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=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
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=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
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=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
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=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
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=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
|
||||
[[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=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
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=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
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",
|
||||
@@ -6283,6 +6284,7 @@ dependencies = [
|
||||
"vectorcraft-effects",
|
||||
"vectorcraft-geom",
|
||||
"vectorcraft-metafile",
|
||||
"vectorcraft-pathops",
|
||||
"vectorcraft-pdf",
|
||||
"vectorcraft-render",
|
||||
"vectorcraft-testkit",
|
||||
@@ -6291,7 +6293,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-format"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-vectorcraft-format",
|
||||
"flate2",
|
||||
@@ -6307,7 +6309,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-geom"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"proptest",
|
||||
@@ -6319,7 +6321,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-mcp"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"log",
|
||||
@@ -6338,7 +6340,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-metafile"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6352,7 +6354,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-pathops"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"linesweeper",
|
||||
@@ -6364,7 +6366,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-pdf"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"chrono",
|
||||
@@ -6396,7 +6398,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-plugins"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -6410,7 +6412,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-render"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"gif 0.14.2",
|
||||
@@ -6440,14 +6442,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 +6459,7 @@ dependencies = [
|
||||
"resvg",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"simplecss",
|
||||
"skrifa 0.47.0",
|
||||
"svgtypes 0.16.1",
|
||||
"thiserror 2.0.21",
|
||||
@@ -6472,7 +6475,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-testkit"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"image",
|
||||
@@ -6490,7 +6493,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-text"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"harfrust 0.13.3",
|
||||
"icu_segmenter",
|
||||
@@ -6511,7 +6514,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-three-d"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"vectorcraft-geom",
|
||||
"vectorcraft-pathops",
|
||||
@@ -6519,7 +6522,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-tools"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6536,7 +6539,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-trace"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6548,7 +6551,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-ui-egui"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"craft-keymap",
|
||||
@@ -6586,7 +6589,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-web"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -6753,12 +6756,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 +6816,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 +6827,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 +6840,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 +7720,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
+14
-16
@@ -4,23 +4,23 @@ 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 = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", default-features = false, features = ["interpret", "write"] }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["serde"] }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
|
||||
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] }
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] }
|
||||
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "14d5dbb50c317b8747a9cf9eb35ab8a22515f137" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
|
||||
# internal
|
||||
@@ -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 = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
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" }
|
||||
|
||||
@@ -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
|
||||
9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb. 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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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
@@ -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. |
|
||||
|
||||
@@ -27,6 +27,19 @@ pub(crate) fn kept_from_browser(key: &str, code: &str, modifiers: Modifiers, alt
|
||||
vectorcraft_ui_egui::shortcuts::runs_a_shortcut(key, code, modifiers)
|
||||
}
|
||||
|
||||
/// Leave a paste to its Paste event (#5555). eframe's web runner reports a Cmd+V press both as the
|
||||
/// key press and, with the clipboard's text, as a Paste event (the browser's `paste` comes in the
|
||||
/// same task as the `keydown`, so both are in one frame's input); the app pastes on each, as egui's
|
||||
/// window integration sends only the Paste. With a Paste in `events`, the paste key's press is
|
||||
/// dropped; its release stays, so the paste chord is still followed (`PasteChord`). A Cmd+V without
|
||||
/// a Paste (a clipboard with no text) keeps its press.
|
||||
pub(crate) fn drop_paste_key_presses(events: &mut Vec<egui::Event>) {
|
||||
if !events.iter().any(|e| matches!(e, egui::Event::Paste(_))) {
|
||||
return;
|
||||
}
|
||||
events.retain(|e| !matches!(e, egui::Event::Key { key: Key::V, pressed: true, modifiers, .. } if modifiers.command));
|
||||
}
|
||||
|
||||
/// The modifiers of a key event as eframe reports them to egui (its `modifiers_from_kb_event`).
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn modifiers(e: &web_sys::KeyboardEvent) -> Modifiers {
|
||||
@@ -115,4 +128,31 @@ mod tests {
|
||||
assert!(!kept_from_browser("ż", "KeyZ", ctrl_alt, true));
|
||||
assert!(!kept_from_browser("}", "Digit0", ctrl_alt, true));
|
||||
}
|
||||
|
||||
fn key(key: Key, pressed: bool, modifiers: Modifiers) -> egui::Event {
|
||||
egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paste_chord_pastes_once() {
|
||||
// Cmd+V and Cmd+Shift+V (Paste in Place): the press goes, the Paste and the release stay.
|
||||
for mods in [cmd(), cmd() | Modifiers::SHIFT] {
|
||||
let mut events = vec![key(Key::V, true, mods), egui::Event::Paste("<svg/>".into()), key(Key::V, false, mods)];
|
||||
drop_paste_key_presses(&mut events);
|
||||
assert_eq!(events, vec![egui::Event::Paste("<svg/>".into()), key(Key::V, false, mods)], "{mods:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_without_a_paste_stay() {
|
||||
// No text on the clipboard: no Paste event, so the press is the paste chord's only report.
|
||||
let mut events = vec![key(Key::V, true, cmd()), key(Key::V, false, cmd())];
|
||||
drop_paste_key_presses(&mut events);
|
||||
assert_eq!(events.len(), 2);
|
||||
// Typing V, and other chords, beside a paste.
|
||||
let typed = vec![key(Key::V, true, Modifiers::NONE), key(Key::C, true, cmd()), egui::Event::Paste("a".into())];
|
||||
let mut events = typed.clone();
|
||||
drop_paste_key_presses(&mut events);
|
||||
assert_eq!(events, typed);
|
||||
}
|
||||
}
|
||||
@@ -378,6 +378,8 @@ impl eframe::App for WebShell {
|
||||
/// shared input hook before egui runs.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
raw.events.extend(self.host.pointers.borrow_mut().take());
|
||||
// A Cmd+V comes as its key and as a Paste: one paste (#5555).
|
||||
crate::keys::drop_paste_key_presses(&mut raw.events);
|
||||
if let Some(app) = &mut self.app {
|
||||
app.raw_input_hook(ctx, raw);
|
||||
}
|
||||
|
||||
@@ -56,8 +56,9 @@ pollster = "1"
|
||||
# `GetPointerPenInfo`, which it uses to read the pen's pressure and which end of the pen is down.
|
||||
# Win32_System_Threading has `GetProcessAffinityMask`, which src/windows_cores.rs uses to count the
|
||||
# cores the process may run on. Win32_UI_Input_KeyboardAndMouse has `GetKeyState`, which
|
||||
# src/caps_lock.rs uses to read whether Caps Lock is on.
|
||||
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
|
||||
# src/caps_lock.rs uses to read whether Caps Lock is on. Win32_System_Registry has `RegGetValueW`,
|
||||
# which src/host_services.rs uses to read the path PhotoCraft registers under App Paths.
|
||||
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
|
||||
# The renderer's worker count follows those cores (src/windows_cores.rs).
|
||||
vectorcraft-render = { workspace = true }
|
||||
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
@@ -334,7 +334,9 @@ fn tcp_connection_is_closed_after_junk() {
|
||||
});
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(WAIT)).unwrap();
|
||||
c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n{\"method\":\"y\"}\n").unwrap();
|
||||
// Nothing after the junk line: on Windows, closing a socket with unread input resets the
|
||||
// connection, and the reset can discard the reply before the client reads it.
|
||||
c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n").unwrap();
|
||||
let mut text = String::new();
|
||||
c.read_to_string(&mut text).unwrap(); // returns at EOF: the server closed the connection
|
||||
server.join().unwrap();
|
||||
|
||||
@@ -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,314 @@ 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.
|
||||
#[cfg(windows)]
|
||||
fn registered_photocraft() -> Vec<std::path::PathBuf> {
|
||||
use windows::Win32::System::Registry::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};
|
||||
[HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE]
|
||||
.into_iter()
|
||||
.filter_map(|hive| registry_default_path(hive, r"Software\Microsoft\Windows\CurrentVersion\App Paths\photocraft.exe"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn registered_photocraft() -> Vec<std::path::PathBuf> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// The default `REG_SZ` value of `subkey` under `hive` as a path ([`registered_path`]), or `None`
|
||||
/// when the key or the value is missing. The value is read as UTF-16, so a folder name in any
|
||||
/// script comes back as stored.
|
||||
#[cfg(windows)]
|
||||
#[allow(unsafe_code)]
|
||||
fn registry_default_path(hive: windows::Win32::System::Registry::HKEY, subkey: &str) -> Option<std::path::PathBuf> {
|
||||
use windows::Win32::System::Registry::{RRF_RT_REG_SZ, RegGetValueW};
|
||||
use windows::core::PCWSTR;
|
||||
let subkey: Vec<u16> = subkey.encode_utf16().chain([0]).collect();
|
||||
let mut size = 0u32;
|
||||
// SAFETY: `subkey` is a NUL-terminated UTF-16 string that outlives the call, a null value name
|
||||
// reads the default value, and with no buffer the call only writes the value's size to `size`.
|
||||
unsafe { RegGetValueW(hive, PCWSTR(subkey.as_ptr()), PCWSTR::null(), RRF_RT_REG_SZ, None, None, Some(&mut size)) }.ok().ok()?;
|
||||
let mut value = vec![0u16; (size as usize).div_ceil(2)];
|
||||
let mut size = u32::try_from(value.len() * 2).ok()?;
|
||||
// SAFETY: as above, and `value` holds the `size` bytes the call may write.
|
||||
unsafe { RegGetValueW(hive, PCWSTR(subkey.as_ptr()), PCWSTR::null(), RRF_RT_REG_SZ, None, Some(value.as_mut_ptr().cast()), Some(&mut size)) }
|
||||
.ok()
|
||||
.ok()?;
|
||||
registered_path(&value)
|
||||
}
|
||||
|
||||
/// The path in a registry string value read as UTF-16, up to its first NUL, without surrounding
|
||||
/// spaces or quotes, like `C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe`.
|
||||
#[cfg_attr(not(any(windows, test)), allow(dead_code))]
|
||||
pub(crate) fn registered_path(value: &[u16]) -> Option<std::path::PathBuf> {
|
||||
let end = value.iter().position(|&c| c == 0).unwrap_or(value.len());
|
||||
let text = String::from_utf16(&value[..end]).ok()?;
|
||||
Some(text.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 the UTF-16 value up to its NUL, spaces, quotes and
|
||||
/// characters outside ASCII included; an empty value or one that is not UTF-16 gives no path.
|
||||
#[test]
|
||||
fn the_registered_path_is_read_from_the_utf16_value() {
|
||||
let wide = |s: &str| s.encode_utf16().chain([0, 0]).collect::<Vec<u16>>();
|
||||
assert_eq!(
|
||||
registered_path(&wide(r"C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe")),
|
||||
Some(std::path::PathBuf::from(r"C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe"))
|
||||
);
|
||||
assert_eq!(
|
||||
registered_path(&wide(" \"C:\\Prögram Fïles\\Тест\\写真\\photocraft.exe\" ")),
|
||||
Some(std::path::PathBuf::from(r"C:\Prögram Fïles\Тест\写真\photocraft.exe"))
|
||||
);
|
||||
assert_eq!(registered_path(&wide("")), None);
|
||||
assert_eq!(registered_path(&[0xD800, 0]), None);
|
||||
}
|
||||
|
||||
/// On Windows a registered path with characters outside the console's code page is read as
|
||||
/// stored, from a scratch key under the current user's hive.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_registered_path_outside_ascii_is_read_as_stored() {
|
||||
let key = format!(r"Software\VectorCraftTest-app-paths-{}", std::process::id());
|
||||
let path = r"C:\Prögram Fïles\Тест\写真\photocraft.exe";
|
||||
let reg = std::env::var_os("SystemRoot").map(std::path::PathBuf::from).unwrap_or_else(|| r"C:\Windows".into()).join(r"System32\reg.exe");
|
||||
let full = format!(r"HKCU\{key}");
|
||||
let added = std::process::Command::new(®).args(["add", &full, "/ve", "/t", "REG_SZ", "/d", path, "/f"]).output().unwrap();
|
||||
assert!(added.status.success(), "{added:?}");
|
||||
let read = super::registry_default_path(windows::Win32::System::Registry::HKEY_CURRENT_USER, &key);
|
||||
let _ = std::process::Command::new(®).args(["delete", &full, "/f"]).output();
|
||||
assert_eq!(read, Some(std::path::PathBuf::from(path)));
|
||||
assert_eq!(super::registry_default_path(windows::Win32::System::Registry::HKEY_CURRENT_USER, &key), None, "deleted");
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -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}});
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -329,10 +329,15 @@ mod tests {
|
||||
#[test]
|
||||
fn a_stale_endpoint_file_is_ignored_and_replaced() {
|
||||
let (path, dir, file) = folder("stale");
|
||||
// No listener on the recorded port any more.
|
||||
let port = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap().local_addr().unwrap().port();
|
||||
// The recorded app is gone: whatever holds the port closes without a greeting. (A freed
|
||||
// port can be taken by another test's listener meanwhile, which would then accept this
|
||||
// connection in place of its own client's.)
|
||||
let gone = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let port = gone.local_addr().unwrap().port();
|
||||
write_endpoint(&path, &json!({ "port": port, "token": "t", "hello": "h" })).unwrap();
|
||||
let closed = std::thread::spawn(move || drop(gone.accept()));
|
||||
assert!(forward(&path, std::slice::from_ref(&file)).is_err());
|
||||
closed.join().unwrap();
|
||||
// A listener that doesn't know the greeting gets neither the token nor the paths.
|
||||
let impostor = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let port = impostor.local_addr().unwrap().port();
|
||||
|
||||
@@ -189,3 +189,15 @@ sync_github_name = false
|
||||
[people.WadahBadawi]
|
||||
display_name = "Wadah Badawi"
|
||||
sync_github_name = true
|
||||
|
||||
[people.JonRC]
|
||||
real_name = "Jonathan Cardoso"
|
||||
display_name = "Jonathan Cardoso"
|
||||
|
||||
[people.vangel76]
|
||||
real_name = "Valentin Klein"
|
||||
display_name = "vangel76"
|
||||
sync_github_name = false
|
||||
|
||||
[people.FrancoJacquet]
|
||||
real_name = "Franco Jacquet"
|
||||
@@ -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> {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)));
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -236,7 +236,8 @@ pub fn tracks(bp: &BezPath, tol: f64) -> Vec<Track> {
|
||||
return out;
|
||||
}
|
||||
let mut els = vec![];
|
||||
kurbo::flatten(bp.iter(), tol.max(1e-4), |el| {
|
||||
// Guarded: kurbo works out every subdivision of a curve even when the callback drops them.
|
||||
vectorcraft_geom::flatten(bp.iter(), tol.max(1e-4), |el| {
|
||||
if els.len() < MAX_FLATTENED {
|
||||
els.push(el);
|
||||
}
|
||||
|
||||
@@ -103,7 +103,7 @@ fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option<Vec<Point>> {
|
||||
let mut bp = BezPath::new();
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
let mut pts = vec![];
|
||||
kurbo::flatten(bp.iter(), flat_tol.max(1e-4), |e| {
|
||||
vectorcraft_geom::flatten(bp.iter(), flat_tol.max(1e-4), |e| {
|
||||
if let PathEl::MoveTo(q) | PathEl::LineTo(q) = e {
|
||||
pts.push(q);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
+198
-26
@@ -1,7 +1,7 @@
|
||||
//! The document walk: each visible object becomes DXF entities on its layer's DXF layer, in paint
|
||||
//! order. Fills are their outlines then solid hatches (the outlines alone in R12), strokes
|
||||
//! polylines and cubic splines with a lineweight and dashes, or filled outlines where the look
|
||||
//! needs them.
|
||||
//! polylines (with bulges for circular arcs) and cubic splines with a lineweight and dashes, or
|
||||
//! filled outlines where the look needs them.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::Cursor;
|
||||
@@ -66,6 +66,8 @@ struct CircularSub {
|
||||
centre: Point,
|
||||
radius: f64,
|
||||
samples: Vec<Point>,
|
||||
/// The signed angle (radians) the curve turns through about `centre` in document space.
|
||||
turn: f64,
|
||||
}
|
||||
|
||||
fn cubic_point(p0: Point, p1: Point, p2: Point, p3: Point, t: f64) -> Point {
|
||||
@@ -122,7 +124,12 @@ fn circular_subpath(sub: &Sub) -> Option<CircularSub> {
|
||||
if !centre.x.is_finite() || !centre.y.is_finite() || !radius.is_finite() || radius <= 1e-9 {
|
||||
return None;
|
||||
}
|
||||
let tolerance = (radius * 5e-4).max(1e-6);
|
||||
// The tolerance is a fraction of the smaller of the radius and the curve's extent, so the large
|
||||
// radius of a shallow curve does not loosen it.
|
||||
let (lo, hi) = samples
|
||||
.iter()
|
||||
.fold((samples[0], samples[0]), |(lo, hi), p| (Point::new(lo.x.min(p.x), lo.y.min(p.y)), Point::new(hi.x.max(p.x), hi.y.max(p.y))));
|
||||
let tolerance = (radius.min(lo.distance(hi)) * 5e-4).max(1e-6);
|
||||
if samples.iter().any(|p| (centre.distance(*p) - radius).abs() > tolerance) {
|
||||
return None;
|
||||
}
|
||||
@@ -181,7 +188,76 @@ fn circular_subpath(sub: &Sub) -> Option<CircularSub> {
|
||||
} else if total_turn.abs() < 1e-6 || total_turn.abs() >= std::f64::consts::TAU - 1e-3 {
|
||||
return None;
|
||||
}
|
||||
Some(CircularSub { centre, radius, samples })
|
||||
Some(CircularSub { centre, radius, samples, turn: total_turn })
|
||||
}
|
||||
|
||||
/// The points of the circle about `centre` of `radius` furthest left, right, up and down that lie on
|
||||
/// its arc from `from` through `turn` radians, for the drawing extents.
|
||||
fn arc_extrema(centre: Point, radius: f64, from: Point, turn: f64) -> Vec<Point> {
|
||||
let start = (from.y - centre.y).atan2(from.x - centre.x);
|
||||
(0..4)
|
||||
.map(|k| f64::from(k) * std::f64::consts::FRAC_PI_2)
|
||||
.filter(|a| ((a - start) * turn.signum()).rem_euclid(std::f64::consts::TAU) <= turn.abs())
|
||||
.map(|a| Point::new(centre.x + radius * a.cos(), centre.y + radius * a.sin()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The most cubics one bulge arc is fitted to; the cubics after them start the next arc.
|
||||
const MAX_ARC_RUN: usize = 64;
|
||||
|
||||
/// A subpath of straight segments and circular arcs as polyline vertices, in document space.
|
||||
struct BulgedSub {
|
||||
/// The anchors, without a closed subpath's repeated start.
|
||||
pts: Vec<Point>,
|
||||
/// For each anchor, the angle (radians, document space) the segment that starts there turns
|
||||
/// through: 0 for a straight segment.
|
||||
turns: Vec<f64>,
|
||||
/// The arcs' extreme points ([`arc_extrema`]), for the drawing extents.
|
||||
extrema: Vec<Point>,
|
||||
}
|
||||
|
||||
/// Fit a subpath with curves to straight segments and circular arcs: each run of cubics on one
|
||||
/// circle, turning one way and less than a whole turn, becomes one arc ([`circular_subpath`]'s
|
||||
/// tolerance). `None` when the subpath has no curves or a curve that is not a circular arc.
|
||||
fn bulged_subpath(sub: &Sub) -> Option<BulgedSub> {
|
||||
if !sub.segs.iter().any(|s| matches!(s, Seg::Cubic(..))) {
|
||||
return None;
|
||||
}
|
||||
let mut pts = vec![sub.start];
|
||||
let mut turns = vec![];
|
||||
let mut extrema = vec![];
|
||||
let mut from = sub.start;
|
||||
let mut i = 0;
|
||||
while let Some(seg) = sub.segs.get(i) {
|
||||
if let Seg::Line(p) = *seg {
|
||||
turns.push(0.0);
|
||||
pts.push(p);
|
||||
from = p;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let mut best = None;
|
||||
let mut j = i;
|
||||
while j < sub.segs.len() && j - i < MAX_ARC_RUN && matches!(sub.segs[j], Seg::Cubic(..)) {
|
||||
let run = Sub { start: from, segs: sub.segs[i..=j].to_vec(), closed: false };
|
||||
let Some(arc) = circular_subpath(&run) else { break };
|
||||
best = Some((j, arc));
|
||||
j += 1;
|
||||
}
|
||||
let (j, arc) = best?;
|
||||
turns.push(arc.turn);
|
||||
extrema.extend(arc_extrema(arc.centre, arc.radius, from, arc.turn));
|
||||
from = sub.segs[j].end();
|
||||
pts.push(from);
|
||||
i = j + 1;
|
||||
}
|
||||
if sub.closed && pts.last().is_some_and(|p| p.distance(sub.start) <= 1e-9) {
|
||||
pts.pop();
|
||||
} else {
|
||||
// The segment from the last anchor: the straight closing edge, or none for an open subpath.
|
||||
turns.push(0.0);
|
||||
}
|
||||
(pts.len() >= 2).then_some(BulgedSub { pts, turns, extrema })
|
||||
}
|
||||
|
||||
/// A closed subpath that is the four-cubic circle under an affine map: an ellipse, or a circle
|
||||
@@ -271,7 +347,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 +376,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 +497,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 +529,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 +632,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.
|
||||
@@ -809,7 +922,9 @@ impl<'a> Scene<'a> {
|
||||
}
|
||||
|
||||
/// Path `bp` as lines: a line for an open subpath of one straight segment, polylines for
|
||||
/// other straight subpaths (and for curves in R12, flattened), cubic splines for curved ones.
|
||||
/// other straight subpaths, circles, arcs and ellipses where the curves are one, polylines
|
||||
/// with bulges for subpaths of straight segments and circular arcs, and cubic splines for
|
||||
/// other curved ones (flattened polylines in R12).
|
||||
/// `width`: the stroke weight, which DXF before 2000 gives polylines as a width.
|
||||
fn lines(&mut self, bp: &BezPath, style: &EntityStyle, width: f64) {
|
||||
let v = self.o.version;
|
||||
@@ -826,7 +941,7 @@ impl<'a> Scene<'a> {
|
||||
// A LINE has no width, so a stroke before 2000 keeps its polyline width.
|
||||
match (sub.closed, width, pts.as_slice()) {
|
||||
(false, None, &[a, b]) => self.line(a, b, style),
|
||||
_ => self.polyline(&pts, sub.closed, style, width),
|
||||
_ => self.polyline(&pts, &[], sub.closed, style, width),
|
||||
}
|
||||
} else if (v.handles() || width.is_none()) && self.circular(&sub, style) {
|
||||
// Native circles/arcs are preferred by CAD/CAM software. In R12, however, a
|
||||
@@ -834,6 +949,12 @@ impl<'a> Scene<'a> {
|
||||
// its width. Non-circular curves continue through the existing fallback.
|
||||
} else if v.handles() && self.elliptical(&sub, style) {
|
||||
// R13 and later write an ellipse as a native ELLIPSE.
|
||||
} else if let Some(b) = bulged_subpath(&sub) {
|
||||
// Straight segments and circular arcs: one polyline whose bulges draw the arcs.
|
||||
b.extrema.iter().for_each(|p| _ = self.pt(*p));
|
||||
let flip = if self.to_dxf.determinant() < 0.0 { -1.0 } else { 1.0 };
|
||||
let bulges: Vec<f64> = b.turns.iter().map(|t| flip * (t / 4.0).tan()).collect();
|
||||
self.polyline(&b.pts, &bulges, sub.closed, style, width);
|
||||
} else if v.handles() {
|
||||
self.spline(&sub, style);
|
||||
} else {
|
||||
@@ -846,7 +967,7 @@ impl<'a> Scene<'a> {
|
||||
}
|
||||
}
|
||||
for pts in polygons(&path) {
|
||||
self.polyline(&pts, sub.closed, style, width);
|
||||
self.polyline(&pts, &[], sub.closed, style, width);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -863,8 +984,9 @@ impl<'a> Scene<'a> {
|
||||
}
|
||||
|
||||
/// A polyline through `pts` (document space): lightweight from R14, else a polyline with a
|
||||
/// vertex entity per point.
|
||||
fn polyline(&mut self, pts: &[Point], closed: bool, style: &EntityStyle, width: Option<f64>) {
|
||||
/// vertex entity per point. `bulges`: the bulge (group 42) of the segment that starts at each
|
||||
/// point, in drawing space; empty for straight segments only.
|
||||
fn polyline(&mut self, pts: &[Point], bulges: &[f64], closed: bool, style: &EntityStyle, width: Option<f64>) {
|
||||
if pts.len() < 2 {
|
||||
return;
|
||||
}
|
||||
@@ -880,8 +1002,11 @@ impl<'a> Scene<'a> {
|
||||
if let Some(w) = width {
|
||||
self.e.num(43, w);
|
||||
}
|
||||
for p in &pts {
|
||||
for (i, p) in pts.iter().enumerate() {
|
||||
self.e.xy(10, p.x, p.y);
|
||||
if let Some(&b) = bulges.get(i).filter(|b| **b != 0.0) {
|
||||
self.e.num(42, b);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -893,13 +1018,16 @@ impl<'a> Scene<'a> {
|
||||
self.e.num(40, w);
|
||||
self.e.num(41, w);
|
||||
}
|
||||
for p in &pts {
|
||||
for (i, p) in pts.iter().enumerate() {
|
||||
let vh = self.handle();
|
||||
self.e.entity("VERTEX", vh, h, &layer, style, "AcDbVertex");
|
||||
if self.o.version.handles() {
|
||||
self.e.raw(100, "AcDb2dVertex");
|
||||
}
|
||||
self.e.xyz(10, p.x, p.y);
|
||||
if let Some(&b) = bulges.get(i).filter(|b| **b != 0.0) {
|
||||
self.e.num(42, b);
|
||||
}
|
||||
}
|
||||
let end = self.handle();
|
||||
self.e.entity("SEQEND", end, h, &layer, style, "");
|
||||
@@ -923,8 +1051,8 @@ impl<'a> Scene<'a> {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Count sampled points in the drawing extents. For a full circle include all cardinal
|
||||
// points exactly; for an arc, the dense samples conservatively cover its visible span.
|
||||
// Count the curve's extreme points in the drawing extents: all four cardinal points of a
|
||||
// full circle; an arc's ends and the cardinal points on it.
|
||||
if sub.closed {
|
||||
let r = circle.radius;
|
||||
for p in [
|
||||
@@ -936,8 +1064,8 @@ impl<'a> Scene<'a> {
|
||||
self.pt(p);
|
||||
}
|
||||
} else {
|
||||
for p in &circle.samples {
|
||||
self.pt(*p);
|
||||
for p in [sub.start, last].into_iter().chain(arc_extrema(circle.centre, circle.radius, sub.start, circle.turn)) {
|
||||
self.pt(p);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1262,3 +1390,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");
|
||||
}
|
||||
}
|
||||
+223
-4
@@ -275,6 +275,197 @@ fn circles_and_circular_arcs_are_native_dxf_entities() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cubic arc about `c` of radius `r` from `deg0` to `deg1` (degrees, y down), from the current
|
||||
/// point, which is the arc's start.
|
||||
fn arc_cubic(b: &mut vectorcraft_geom::BezPath, c: Point, r: f64, deg0: f64, deg1: f64) {
|
||||
let (a0, a1) = (deg0.to_radians(), deg1.to_radians());
|
||||
let k = 4.0 / 3.0 * ((a1 - a0) / 4.0).tan() * r;
|
||||
let (p0, p3) = (Point::new(c.x + r * a0.cos(), c.y + r * a0.sin()), Point::new(c.x + r * a1.cos(), c.y + r * a1.sin()));
|
||||
b.curve_to(Point::new(p0.x - k * a0.sin(), p0.y + k * a0.cos()), Point::new(p3.x + k * a1.sin(), p3.y - k * a1.cos()), p3);
|
||||
}
|
||||
|
||||
/// A slot (two lines, two half circles) about y = 50, a D shape (a half circle closed by its
|
||||
/// diameter) and a rounded rectangle with 10 pt corners.
|
||||
fn lines_and_arcs() -> [PathData; 3] {
|
||||
let mut slot = vectorcraft_geom::BezPath::new();
|
||||
slot.move_to((60.0, 30.0));
|
||||
slot.line_to((140.0, 30.0));
|
||||
arc_cubic(&mut slot, Point::new(140.0, 50.0), 20.0, -90.0, 0.0);
|
||||
arc_cubic(&mut slot, Point::new(140.0, 50.0), 20.0, 0.0, 90.0);
|
||||
slot.line_to((60.0, 70.0));
|
||||
arc_cubic(&mut slot, Point::new(60.0, 50.0), 20.0, 90.0, 180.0);
|
||||
arc_cubic(&mut slot, Point::new(60.0, 50.0), 20.0, 180.0, 270.0);
|
||||
slot.close_path();
|
||||
let mut d = vectorcraft_geom::BezPath::new();
|
||||
d.move_to((150.0, 20.0));
|
||||
arc_cubic(&mut d, Point::new(150.0, 50.0), 30.0, -90.0, 0.0);
|
||||
arc_cubic(&mut d, Point::new(150.0, 50.0), 30.0, 0.0, 90.0);
|
||||
d.close_path();
|
||||
[PathData::from_bezpath(&slot), PathData::from_bezpath(&d), shapes::rounded_rectangle(Rect::new(20.0, 20.0, 100.0, 80.0), 10.0)]
|
||||
}
|
||||
|
||||
/// A polyline entity's vertices as (x, y, bulge): an LWPOLYLINE's, or those of the VERTEX
|
||||
/// entities that follow a POLYLINE at `e[i]`.
|
||||
fn vertices(e: &[Pairs], i: usize) -> Vec<(f64, f64, f64)> {
|
||||
let mut out = vec![];
|
||||
let mut read = |o: &Pairs| {
|
||||
for (code, value) in o {
|
||||
let v: f64 = value.trim().parse().unwrap_or(0.0);
|
||||
match code {
|
||||
10 => out.push((v, 0.0, 0.0)),
|
||||
20 => out.last_mut().expect("x before y").1 = v,
|
||||
42 => out.last_mut().expect("a vertex before its bulge").2 = v,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
};
|
||||
if kind(&e[i]) == "LWPOLYLINE" {
|
||||
read(&e[i]);
|
||||
} else {
|
||||
e[i + 1..].iter().take_while(|o| kind(o) == "VERTEX").for_each(&mut read);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_of_lines_and_circular_arcs_are_polylines_with_bulges() {
|
||||
let [slot, d_shape, rounded] = lines_and_arcs();
|
||||
let d = doc_with(|d| {
|
||||
let black = || Paint::solid(Color::BLACK);
|
||||
let mut open = vectorcraft_geom::BezPath::new();
|
||||
open.move_to((10.0, 90.0));
|
||||
open.line_to((30.0, 90.0));
|
||||
arc_cubic(&mut open, Point::new(30.0, 80.0), 10.0, 90.0, 0.0);
|
||||
vec![
|
||||
path(d, slot, Paint::None, black(), 1.0),
|
||||
path(d, d_shape, Paint::None, black(), 1.0),
|
||||
path(d, rounded, Paint::None, black(), 1.0),
|
||||
path(d, PathData::from_bezpath(&open), Paint::None, black(), 1.0),
|
||||
]
|
||||
});
|
||||
let b = (std::f64::consts::PI / 8.0).tan();
|
||||
for version in DxfVersion::ALL {
|
||||
let out = export(&d, &DxfOptions { version, ..opts(&d) }).unwrap();
|
||||
let e = entities(&out);
|
||||
let polys: Vec<usize> = (0..e.len()).filter(|i| matches!(kind(&e[*i]), "LWPOLYLINE" | "POLYLINE")).collect();
|
||||
let k = kinds(&out);
|
||||
assert_eq!(polys.len(), 4, "{version:?}: {k:?}");
|
||||
assert!(!k.iter().any(|k| matches!(k.as_str(), "SPLINE" | "ARC" | "CIRCLE")), "{version:?}: {k:?}");
|
||||
let want = if version.lwpolyline() { "LWPOLYLINE" } else { "POLYLINE" };
|
||||
assert!(polys.iter().all(|i| kind(&e[*i]) == want), "{version:?}: {k:?}");
|
||||
let flags: Vec<i64> = polys.iter().map(|i| get(&e[*i], 70).unwrap().parse::<i64>().unwrap() & 1).collect();
|
||||
assert_eq!(flags, [1, 1, 1, 0], "{version:?}: closed, closed, closed, open");
|
||||
// The slot's half circles turn clockwise with y up: a bulge of -1 after each long side.
|
||||
assert_eq!(vertices(&e, polys[0]), [(60.0, 70.0, 0.0), (140.0, 70.0, -1.0), (140.0, 30.0, 0.0), (60.0, 30.0, -1.0)], "{version:?}");
|
||||
// The D shape: the half circle, then the straight closing edge.
|
||||
assert_eq!(vertices(&e, polys[1]), [(150.0, 80.0, -1.0), (150.0, 20.0, 0.0)], "{version:?}");
|
||||
// The rounded rectangle: eight anchors, a quarter circle (bulge tan 22.5°) at each corner.
|
||||
let r = vertices(&e, polys[2]);
|
||||
assert_eq!(r.len(), 8, "{version:?}: {r:?}");
|
||||
let bulges: Vec<f64> = r.iter().map(|v| v.2).filter(|b| *b != 0.0).collect();
|
||||
assert!(close_to(&bulges, &[-b; 4], 1e-6), "{version:?}: {r:?}");
|
||||
// An open line then a quarter circle turning counterclockwise with y up.
|
||||
let o = vertices(&e, polys[3]);
|
||||
assert!(
|
||||
close_to(&o.iter().flat_map(|v| [v.0, v.1, v.2]).collect::<Vec<_>>(), &[10.0, 10.0, 0.0, 30.0, 10.0, b, 40.0, 20.0, 0.0], 1e-6),
|
||||
"{version:?}: {o:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polylines_with_bulges_read_back_as_the_same_outline() {
|
||||
for (i, shape) in lines_and_arcs().into_iter().enumerate() {
|
||||
let original = shape.to_bezpath();
|
||||
let d = doc_with(|d| vec![path(d, shape, Paint::None, Paint::solid(Color::BLACK), 1.0)]);
|
||||
let out = export(&d, &opts(&d)).unwrap();
|
||||
assert_eq!(kinds(&out), ["LWPOLYLINE"], "shape {i}");
|
||||
let o = ImportOptions { unit: Some(Unit::Points), scale: Some(1.0), center: false, ..ImportOptions::default() };
|
||||
let back = import(&out.bytes, &o).unwrap().document;
|
||||
let mut paths = vec![];
|
||||
back.walk(|n| {
|
||||
if let NodeKind::Path { path, .. } = &n.kind {
|
||||
paths.push(path.to_bezpath());
|
||||
}
|
||||
});
|
||||
assert_eq!(paths.len(), 1, "shape {i}");
|
||||
assert!(paths[0].elements().last().is_some_and(|el| matches!(el, kurbo::PathEl::ClosePath)), "shape {i} reads back closed");
|
||||
let (a, b) = (original.bounding_box(), paths[0].bounding_box());
|
||||
assert!(close_to(&[a.width(), a.height()], &[b.width(), b.height()], 1e-2), "shape {i}: {a:?} against {b:?}");
|
||||
// Every point read back lies on the original outline, once both are centered.
|
||||
let shift = a.center() - b.center();
|
||||
let outline: Vec<Point> = original.segments().flat_map(|s| (0..=64).map(move |t| s.eval(f64::from(t) / 64.0))).collect();
|
||||
for seg in paths[0].segments() {
|
||||
for t in 0..=16 {
|
||||
let p = seg.eval(f64::from(t) / 16.0) + shift;
|
||||
let near = outline
|
||||
.windows(2)
|
||||
.map(|w| {
|
||||
let (u, v) = (w[1] - w[0], p - w[0]);
|
||||
let s = if u.hypot2() > 0.0 { (v.dot(u) / u.hypot2()).clamp(0.0, 1.0) } else { 0.0 };
|
||||
(v - u * s).hypot()
|
||||
})
|
||||
.fold(f64::INFINITY, f64::min);
|
||||
assert!(near < 1e-2, "shape {i}: {p:?} is {near} pt off the outline");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_with_a_curve_that_is_not_a_circular_arc_stays_a_spline() {
|
||||
// The slot with one end drawn by a longer-handled curve.
|
||||
let mut slot = vectorcraft_geom::BezPath::new();
|
||||
slot.move_to((60.0, 30.0));
|
||||
slot.line_to((140.0, 30.0));
|
||||
slot.curve_to((165.0, 30.0), (165.0, 70.0), (140.0, 70.0));
|
||||
slot.line_to((60.0, 70.0));
|
||||
arc_cubic(&mut slot, Point::new(60.0, 50.0), 20.0, 90.0, 180.0);
|
||||
arc_cubic(&mut slot, Point::new(60.0, 50.0), 20.0, 180.0, 270.0);
|
||||
slot.close_path();
|
||||
let d = doc_with(|d| {
|
||||
vec![
|
||||
path(d, PathData::from_bezpath(&slot), Paint::None, Paint::solid(Color::BLACK), 1.0),
|
||||
path(d, shapes::ellipse(Rect::new(150.0, 20.0, 190.0, 60.0)), Paint::None, Paint::solid(Color::BLACK), 1.0),
|
||||
]
|
||||
});
|
||||
assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["SPLINE", "CIRCLE"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawing_extents_reach_the_extreme_points_of_arcs() {
|
||||
// An arc about (100, 50) of radius 40 from -60° to 30° passes x = 140 at 0°, between the points
|
||||
// along it that recognition samples.
|
||||
let arc = |closed: bool| {
|
||||
let mut b = vectorcraft_geom::BezPath::new();
|
||||
let start = Point::new(100.0 + 40.0 * 60f64.to_radians().cos(), 50.0 - 40.0 * 60f64.to_radians().sin());
|
||||
b.move_to(start);
|
||||
arc_cubic(&mut b, Point::new(100.0, 50.0), 40.0, -60.0, 30.0);
|
||||
if closed {
|
||||
b.close_path();
|
||||
}
|
||||
PathData::from_bezpath(&b)
|
||||
};
|
||||
for (closed, entity) in [(false, "ARC"), (true, "LWPOLYLINE")] {
|
||||
let d = doc_with(|d| vec![path(d, arc(closed), Paint::None, Paint::solid(Color::BLACK), 1.0)]);
|
||||
let out = export(&d, &opts(&d)).unwrap();
|
||||
assert_eq!(kinds(&out), [entity]);
|
||||
let x: f64 = header(&pairs(&out.bytes), "$EXTMAX").unwrap().trim().parse().unwrap();
|
||||
assert!((x - 140.0).abs() < 1e-6, "{entity}: $EXTMAX x {x}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shallow_curve_that_is_not_circular_is_not_an_arc() {
|
||||
// 100 pt across and 1.5 pt deep: the circle through its ends and middle has a radius of about
|
||||
// 834 pt, and the curve is 0.12 pt off it a quarter of the way along.
|
||||
let mut b = vectorcraft_geom::BezPath::new();
|
||||
b.move_to((0.0, 50.0));
|
||||
b.curve_to((20.0, 48.0), (80.0, 48.0), (100.0, 50.0));
|
||||
let d = doc_with(|d| vec![path(d, PathData::from_bezpath(&b), Paint::None, Paint::solid(Color::BLACK), 1.0)]);
|
||||
assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["SPLINE"]);
|
||||
}
|
||||
|
||||
/// The path `p` with `xf` applied.
|
||||
fn transformed(p: &PathData, xf: Affine) -> PathData {
|
||||
PathData::from_bezpath(&(xf * p.to_bezpath()))
|
||||
@@ -391,11 +582,12 @@ fn closed_four_cubic_shapes_that_are_not_writable_ellipses_stay_splines() {
|
||||
vec![
|
||||
path(d, PathData::from_bezpath(&squircle), Paint::None, Paint::solid(Color::BLACK), 1.0),
|
||||
path(d, PathData::from_bezpath(&kurbo::BezPath::from_vec(els)), Paint::None, Paint::solid(Color::BLACK), 1.0),
|
||||
// An ellipse thinner than the smallest ratio DXF readers take (5e-7 against 1e-6).
|
||||
// An ellipse thinner than the smallest ratio DXF readers take (5e-7 against 1e-6). Its
|
||||
// quarters fit shallow circular arcs within the tolerance, so it is a polyline with bulges.
|
||||
path(d, shapes::ellipse(Rect::new(0.0, 90.0, 200.0, 90.0001)), Paint::None, Paint::solid(Color::BLACK), 1.0),
|
||||
]
|
||||
});
|
||||
assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["SPLINE", "SPLINE", "SPLINE"]);
|
||||
assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["SPLINE", "SPLINE", "LWPOLYLINE"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -462,8 +654,12 @@ fn closed_circular_arc_with_a_closing_chord_is_not_a_circle() {
|
||||
vec![path(d, PathData::from_bezpath(&arc), Paint::None, Paint::solid(Color::BLACK), 1.0)]
|
||||
});
|
||||
|
||||
// The three quarters turn counterclockwise with y up (bulge tan 67.5°), then the chord closes it.
|
||||
let modern = export(&d, &opts(&d)).unwrap();
|
||||
assert_eq!(kinds(&modern), ["SPLINE"]);
|
||||
assert_eq!(kinds(&modern), ["LWPOLYLINE"]);
|
||||
let v = vertices(&entities(&modern), 0);
|
||||
let flat: Vec<f64> = v.iter().flat_map(|v| [v.0, v.1, v.2]).collect();
|
||||
assert!(close_to(&flat, &[80.0, 50.0, 67.5f64.to_radians().tan(), 50.0, 20.0, 0.0], 1e-6), "{v:?}");
|
||||
let r12 = export(&d, &DxfOptions { version: DxfVersion::R12, ..opts(&d) }).unwrap();
|
||||
assert!(kinds(&r12).iter().any(|k| k == "POLYLINE"));
|
||||
assert!(!kinds(&r12).iter().any(|k| k == "CIRCLE"));
|
||||
@@ -497,9 +693,13 @@ fn a_closed_sliver_along_a_circle_is_not_a_circle() {
|
||||
vec![path(d, PathData::from_bezpath(&sliver), Paint::None, Paint::solid(Color::BLACK), 1.0)]
|
||||
});
|
||||
|
||||
// Two arcs, out along the circle and back: one polyline with a bulge each way.
|
||||
let modern = export(&d, &opts(&d)).unwrap();
|
||||
assert_ne!(kinds(&modern), ["CIRCLE"]);
|
||||
assert_eq!(kinds(&modern), ["SPLINE"]);
|
||||
assert_eq!(kinds(&modern), ["LWPOLYLINE"]);
|
||||
let bulges: Vec<f64> = vertices(&entities(&modern), 0).iter().map(|v| v.2).collect();
|
||||
let b = 10f64.to_radians().tan();
|
||||
assert!(close_to(&bulges, &[-b, b], 1e-6) || close_to(&bulges, &[b, -b], 1e-6), "{bulges:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1007,3 +1207,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);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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 =
|
||||
|
||||
@@ -34,11 +34,11 @@ impl WidthProfile {
|
||||
if t <= p[0].0 {
|
||||
return (p[0].1, p[0].2);
|
||||
}
|
||||
for w in p.windows(2) {
|
||||
if t <= w[1].0 {
|
||||
let u = (t - w[0].0) / (w[1].0 - w[0].0).max(1e-9);
|
||||
return (w[0].1 + (w[1].1 - w[0].1) * u, w[0].2 + (w[1].2 - w[0].2) * u);
|
||||
}
|
||||
// (Positions go forward; found in log time, so a long profile read from a file is cheap to ask.)
|
||||
let i = p.partition_point(|q| q.0 < t);
|
||||
if let (Some(a), Some(b)) = (i.checked_sub(1).and_then(|j| p.get(j)), p.get(i)) {
|
||||
let u = (t - a.0) / (b.0 - a.0).max(1e-9);
|
||||
return (a.1 + (b.1 - a.1) * u, a.2 + (b.2 - a.2) * u);
|
||||
}
|
||||
p.last().map_or((1.0, 1.0), |l| (l.1, l.2))
|
||||
}
|
||||
@@ -90,10 +90,12 @@ impl WidthProfile {
|
||||
/// discontinuous point (two points at `t`, within `1e-7`).
|
||||
pub fn around(&self, t: f64) -> ((f64, f64), (f64, f64)) {
|
||||
let p = &self.points;
|
||||
if let Some(i) = p.iter().position(|q| (q.0 - t).abs() <= 1e-7) {
|
||||
let j = i + p[i..].iter().take_while(|q| (q.0 - p[i].0).abs() <= 1e-9).count() - 1;
|
||||
// The same distance test below, so a point exactly 1e-7 before `t` is never skipped by rounding.
|
||||
let i = p.partition_point(|q| q.0 < t && (q.0 - t).abs() > 1e-7);
|
||||
if let Some(first) = p.get(i).filter(|q| (q.0 - t).abs() <= 1e-7) {
|
||||
let j = i + p[i..].partition_point(|q| q.0 - first.0 <= 1e-9) - 1;
|
||||
if j > i {
|
||||
return ((p[i].1, p[i].2), (p[j].1, p[j].2));
|
||||
return ((first.1, first.2), (p[j].1, p[j].2));
|
||||
}
|
||||
}
|
||||
let v = self.at(t);
|
||||
@@ -334,3 +336,26 @@ pub struct SavedProfile {
|
||||
pub name: String,
|
||||
pub profile: WidthProfile,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn width_profile_lookups_by_search() {
|
||||
let p = WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (0.5, 0.5, 0.25), (1.0, 0.0, 0.0)] };
|
||||
assert_eq!(p.at(-1.0), (0.0, 0.0));
|
||||
assert_eq!(p.at(0.25), (0.5, 0.5));
|
||||
assert_eq!(p.at(0.75), (0.25, 0.125));
|
||||
assert_eq!(p.at(2.0), (0.0, 0.0));
|
||||
// A step: the widths just before and just after it.
|
||||
assert_eq!(p.around(0.5), ((1.0, 1.0), (0.5, 0.25)));
|
||||
assert_eq!(p.around(0.25), ((0.5, 0.5), (0.5, 0.5)));
|
||||
// Many points at one position are one step, found without a pass over them all.
|
||||
let many = WidthProfile { points: (0..1000).map(|i| (0.5, i as f64, i as f64)).collect() };
|
||||
assert_eq!(many.around(0.5), ((0.0, 0.0), (999.0, 999.0)));
|
||||
// 0.4999999 == 0.5 - 1e-7, yet its distance from 0.5 rounds above 1e-7: it is not part of the step.
|
||||
let near = WidthProfile { points: vec![(0.4999999, 2.0, 2.0), (0.5, 1.0, 1.0), (0.5, 0.5, 0.25)] };
|
||||
assert_eq!(near.around(0.5), ((1.0, 1.0), (0.5, 0.25)));
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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 });
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -314,6 +314,13 @@ pub struct SeriesPaint {
|
||||
/// Stroke weight in points, kept with [`Self::stroke`].
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub stroke_width: Option<f64>,
|
||||
/// Opacity (0..1) of the topmost fill of each path directly in the series group (graph designs keep their own),
|
||||
/// taken from the topmost fill row edited on one of them. Absent: fully opaque.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub fill_opacity: Option<f32>,
|
||||
/// Opacity (0..1) of the topmost stroke of each path directly in the series group, as [`Self::fill_opacity`].
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub stroke_opacity: Option<f32>,
|
||||
}
|
||||
|
||||
/// Graph data and options. `rows` are categories (one per row of the Graph Data window), each
|
||||
|
||||
+77
-16
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -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());
|
||||
@@ -362,10 +390,19 @@ fn a_projection_follows_the_transform_or_is_removed() {
|
||||
let mut n = instance(far);
|
||||
n.transform(Affine::scale(1e150), false);
|
||||
assert_eq!(projection(&n), None);
|
||||
// A transform that is not invertible leaves the projection as it is.
|
||||
// A transform that is not invertible leaves the projection as it is, at any scale.
|
||||
let mut n = instance(far);
|
||||
n.transform(Affine::scale(0.0), false);
|
||||
assert_eq!(projection(&n), Some(far.to_array()));
|
||||
let mut n = instance(far);
|
||||
n.transform(Affine::new([1e-8, 2e-8, 2e-8, 4e-8, 0.0, 0.0]), false);
|
||||
assert_eq!(projection(&n), Some(far.to_array()));
|
||||
// A scale by 1e-8 is invertible: a move by 10 becomes a move by 1e-7.
|
||||
let ten = Homography::from_affine(Affine::translate((10.0, 0.0)));
|
||||
let mut n = instance(ten);
|
||||
n.transform(Affine::scale(1e-8), false);
|
||||
let q = n.projection().unwrap().apply(Point::new(3e-8, 7e-8)).unwrap();
|
||||
assert!(q.distance(Point::new(1.3e-7, 7e-8)) < 1e-20, "{q:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -518,3 +555,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());
|
||||
}
|
||||
@@ -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
@@ -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)]);
|
||||
|
||||
@@ -63,7 +63,7 @@ impl Node {
|
||||
pub(crate) fn transform_projection(&mut self, a: vectorcraft_geom::Affine) {
|
||||
if let Some(p) = self.extras_if_any().and_then(|e| e.perspective.as_deref_mut())
|
||||
&& let Some(h) = p.homography()
|
||||
&& a.determinant().abs() >= 1e-15
|
||||
&& Homography::affine_is_invertible(a)
|
||||
{
|
||||
p.projection = h.conjugated(a).map(|h| h.to_array());
|
||||
}
|
||||
|
||||
@@ -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
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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>)) {
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -200,14 +200,16 @@ impl TextObject {
|
||||
}
|
||||
/// The list that the characters before byte `at` start ([`ParaList::typed`]) with the byte
|
||||
/// where their paragraph starts: when the plain text from the start of the paragraph up to
|
||||
/// `at` is a list's start followed by a space, and the paragraph is in no list. None otherwise.
|
||||
/// `at` is a list's start followed by a space, and the paragraph is in no list. None otherwise,
|
||||
/// and for a first paragraph that continues from the frame before
|
||||
/// ([`TextObject::first_para_continues`]).
|
||||
pub fn typed_list_at(&self, at: usize) -> Option<(usize, ParaList)> {
|
||||
let text = self.plain_text();
|
||||
let before = text.get(..at)?;
|
||||
let start = before.rfind('\n').map_or(0, |i| i + 1);
|
||||
let list = ParaList::typed(before[start..].strip_suffix(' ')?)?;
|
||||
let index = before.bytes().filter(|&b| b == b'\n').count();
|
||||
self.para_at(index).list.is_none().then_some((start, list))
|
||||
(!(index == 0 && self.first_para_continues) && self.para_at(index).list.is_none()).then_some((start, list))
|
||||
}
|
||||
/// Apply `f` to the attributes of paragraphs `range` (indices; None = every paragraph).
|
||||
pub fn edit_paras(&mut self, range: Option<std::ops::Range<usize>>, mut f: impl FnMut(&mut ParaStyle)) {
|
||||
@@ -435,12 +437,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 {
|
||||
|
||||
@@ -239,6 +239,19 @@ fn typed_list_starts_are_found_at_a_paragraphs_start() {
|
||||
assert_eq!(t.typed_list_at(19), Some((16, letters)));
|
||||
}
|
||||
|
||||
/// In a threaded frame whose first paragraph continues from the frame before, the text at the
|
||||
/// frame's start is not the start of a paragraph, so typing a list's start there starts nothing.
|
||||
/// The paragraphs after it still start lists.
|
||||
#[test]
|
||||
fn typed_list_starts_skip_a_continued_paragraph() {
|
||||
let dot = ParaList::bulleted(Bullet::Dot);
|
||||
let mut t = TextObject::point(Point::ZERO, "* Pears\n# ", CharStyle::default());
|
||||
assert_eq!(t.typed_list_at(2), Some((0, dot)));
|
||||
t.first_para_continues = true;
|
||||
assert_eq!(t.typed_list_at(2), None, "a continued paragraph starts no list");
|
||||
assert_eq!(t.typed_list_at(10), Some((8, dot)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn character_controls_reject_collapsed_and_nonfinite_transforms() {
|
||||
let mut t = TextObject::point(Point::ZERO, "Text", CharStyle::default());
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)| {
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
@@ -114,13 +114,16 @@ pub(super) fn split_at(pts: &[Point], corner: &[bool], closed: bool, marks: &[f6
|
||||
let seg_count = if closed { n } else { n.saturating_sub(1) };
|
||||
let mut out = (Vec::with_capacity(n + marks.len()), Vec::with_capacity(n + marks.len()));
|
||||
let mut acc = 0.0;
|
||||
// Sorted once, so each segment finds its marks by search, not by a pass over all of them.
|
||||
let mut marks = marks.to_vec();
|
||||
marks.sort_by(f64::total_cmp);
|
||||
for i in 0..seg_count {
|
||||
let (a, b) = (pts[i], pts[(i + 1) % n]);
|
||||
let len = a.distance(b);
|
||||
out.0.push(a);
|
||||
out.1.push(corner[i]);
|
||||
let mut inner: Vec<f64> = marks.iter().copied().filter(|d| *d > acc + 1e-9 && *d < acc + len - 1e-9).collect();
|
||||
inner.sort_by(f64::total_cmp);
|
||||
let from = marks.partition_point(|d| *d <= acc + 1e-9);
|
||||
let mut inner: Vec<f64> = marks.iter().skip(from).copied().take_while(|d| *d < acc + len - 1e-9).collect();
|
||||
inner.dedup_by(|a, b| (*a - *b).abs() <= 1e-9);
|
||||
for d in inner {
|
||||
out.0.push(a.lerp(b, (d - acc) / len));
|
||||
|
||||
@@ -61,6 +61,8 @@ vectorcraft-testkit = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
# A variable font built in code (no font file is committed).
|
||||
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
|
||||
# How many times an open reads a PDF.
|
||||
vectorcraft-pdf = { workspace = true, features = ["read-count"] }
|
||||
wat = { workspace = true }
|
||||
# Zstandard streams for the Illustrator editing data fuzz tests.
|
||||
ruzstd = { workspace = true }
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
//! 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 seen, mut count) = (0, 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();
|
||||
seen += chars.len();
|
||||
if seen > MAX_CHARS {
|
||||
return Err(bad(C, format!("too many characters: at most {MAX_CHARS}")));
|
||||
}
|
||||
// Each run's end byte, to find the style a character has now.
|
||||
let ends: Vec<usize> = t
|
||||
.runs
|
||||
.iter()
|
||||
.scan(0, |off, r| {
|
||||
*off += r.text.len();
|
||||
Some(*off)
|
||||
})
|
||||
.collect();
|
||||
let n = chars.len();
|
||||
let mut changes = Vec::with_capacity(n);
|
||||
let mut run = 0;
|
||||
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)?;
|
||||
while ends.get(run).is_some_and(|&e| e <= at) {
|
||||
run += 1;
|
||||
}
|
||||
// A character that already has the value is left out, so a run that changes nothing
|
||||
// makes no step.
|
||||
if let Some(r) = t.runs.get(run) {
|
||||
let mut style = r.style.clone();
|
||||
change.apply(&mut style);
|
||||
if style == r.style {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
changes.push((at, change));
|
||||
}
|
||||
count += changes.len();
|
||||
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,213 @@
|
||||
//! 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();
|
||||
// `b` is 20 pt already: three characters change.
|
||||
assert_eq!(out, json!({"count": 3, "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();
|
||||
// Each first character is upright already.
|
||||
assert_eq!(out["count"], json!(3));
|
||||
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 characters_that_already_have_the_value_are_left_out() {
|
||||
let mut s = session();
|
||||
let id = text(&mut s, "abc");
|
||||
select(&mut s, &[id]);
|
||||
let p = json!({"attribute": "rotation", "from": 0, "to": 30});
|
||||
// The first character already has 0°.
|
||||
assert_eq!(s.execute(C, &p).unwrap(), json!({"count": 2, "ids": [id.0]}));
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
assert_eq!(s.execute(C, &p).unwrap(), json!({"count": 0, "ids": []}), "again: nothing to change");
|
||||
assert_eq!((s.doc().unwrap().doc.clone(), steps(&s)), (before, 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]}),
|
||||
json!({"id": id.0, "start": -1}),
|
||||
json!({"id": id.0, "start": 1, "end": 1.5}),
|
||||
json!({"id": id.0, "end": "2"}),
|
||||
] {
|
||||
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());
|
||||
}
|
||||
@@ -178,6 +178,23 @@ pub(crate) struct ActiveItem {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The method returns explicit target parameters and the selected appearance effect list.
|
||||
pub fn appearance_effect_target(&self, params: &Value) -> Option<(Value, &[vectorcraft_doc::Effect])> {
|
||||
let mut ids = appearance_targets(self, params).ok()?;
|
||||
let item = item_target(self, params, "effect.apply").ok()?;
|
||||
let anchor = item.anchor(self, &ids);
|
||||
let node = self.active()?.doc.node(*ids.get(anchor)?)?;
|
||||
let at = item.effects_item(&node.appearance, "effect.apply").ok()?;
|
||||
let effects = node.appearance.effects_at(at)?;
|
||||
ids.swap(0, anchor);
|
||||
let ids: Vec<u64> = ids.into_iter().map(|id| id.0).collect();
|
||||
let aligned = match item {
|
||||
ItemTarget::Item { aligned, .. } => aligned,
|
||||
ItemTarget::Top => aligned(params),
|
||||
};
|
||||
Some((json!({"ids": ids, "item": at, "aligned": aligned}), effects.as_slice()))
|
||||
}
|
||||
|
||||
/// The Appearance panel's active fill/stroke: a paint-order index into the first selected
|
||||
/// object's stack, while the selection it was chosen for is unchanged.
|
||||
pub fn appearance_item(&self) -> Option<usize> {
|
||||
@@ -514,6 +531,7 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
}
|
||||
_ => vec![None; ids.len()],
|
||||
};
|
||||
let before = s.doc()?.doc.clone();
|
||||
let mut inserted = None;
|
||||
// Where the new fill went in on the active item's object, when it went above the active row.
|
||||
let mut above = None;
|
||||
@@ -560,6 +578,7 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
Ok(())
|
||||
})?;
|
||||
// A fill added above the active row becomes the active row; otherwise the rows above the new
|
||||
@@ -578,12 +597,28 @@ fn clear_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
clear(n);
|
||||
}
|
||||
}
|
||||
Ok(count_changed(d, &before, &ids))
|
||||
let kept = super::graph::capture_series_opacity(d, &both_kinds(&ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept))
|
||||
})?;
|
||||
s.active_appearance_item = None;
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Each of `ids` with both kinds of row (fill, then stroke), for [`super::graph::capture_series_opacity`] after an
|
||||
/// edit that replaces whole stacks.
|
||||
fn both_kinds(ids: &[NodeId]) -> Vec<(NodeId, bool)> {
|
||||
ids.iter().flat_map(|id| [(*id, true), (*id, false)]).collect()
|
||||
}
|
||||
|
||||
/// Each of `ids` with each kind of row (fill `true`, stroke `false`) whose topmost row has another opacity in `d` than
|
||||
/// in `before` (no row counts as opaque), for [`super::graph::capture_series_opacity`].
|
||||
fn top_opacity_changed(before: &vectorcraft_doc::Document, d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec<(NodeId, bool)> {
|
||||
let top = |d: &vectorcraft_doc::Document, id: NodeId, fill: bool| {
|
||||
d.node(id).and_then(|n| n.appearance.items.iter().rev().find(|it| it.is_fill() == fill).map(AppearanceItem::opacity)).unwrap_or(1.0)
|
||||
};
|
||||
ids.iter().flat_map(|id| [(*id, true), (*id, false)]).filter(|(id, fill)| top(before, *id, *fill) != top(d, *id, *fill)).collect()
|
||||
}
|
||||
|
||||
/// Clear Appearance on `n`: no fill, no stroke, and the object's Opacity row back to Default. A
|
||||
/// group keeps no fill or stroke rows of its own.
|
||||
fn clear(n: &mut Node) {
|
||||
@@ -619,7 +654,9 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
clear(n);
|
||||
(n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false);
|
||||
}
|
||||
Ok(count_changed(d, &before, &[source, target]))
|
||||
let changed = if copy { vec![target] } else { vec![source, target] };
|
||||
let kept = super::graph::capture_series_opacity(d, &both_kinds(&changed));
|
||||
Ok(count_changed(d, &before, &[source, target]) + usize::from(kept))
|
||||
})?;
|
||||
s.active_appearance_item = None;
|
||||
Ok(json!({ "source": source.0, "target": target.0 }))
|
||||
@@ -672,7 +709,8 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(count_changed(d, &before, &ids))
|
||||
let kept = super::graph::capture_series_opacity(d, &both_kinds(&ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept))
|
||||
})?;
|
||||
s.active_appearance_item = None;
|
||||
ok()
|
||||
@@ -694,9 +732,14 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let before = s.doc()?.doc.clone();
|
||||
let per = items_per_target(&before, &ids, &[idx], aligned(p));
|
||||
super::overprint::edit_counted(s, "Appearance", |d| {
|
||||
let mut edited = Vec::new();
|
||||
for (id, at) in ids.iter().zip(&per) {
|
||||
let Some(&idx) = at.first() else { continue };
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let items = &n.appearance.items;
|
||||
if let Some(fill) = items.get(idx).map(AppearanceItem::is_fill).filter(|f| items.iter().rposition(|it| it.is_fill() == *f) == Some(idx)) {
|
||||
edited.push((*id, fill));
|
||||
}
|
||||
if p.get("weight").is_none()
|
||||
&& let Some(pa) = &paint
|
||||
{
|
||||
@@ -727,7 +770,9 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
*vis = v;
|
||||
}
|
||||
}
|
||||
Ok(count_changed(d, &before, &ids))
|
||||
// The graph keeps an opacity set on the topmost fill or stroke of its series art for when it is drawn again.
|
||||
let kept = p.get("opacity").and_then(Value::as_f64).is_some() && super::graph::capture_series_opacity(d, &edited);
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept))
|
||||
})?;
|
||||
if let Some(pa) = &paint {
|
||||
s.remember_paint(pa);
|
||||
@@ -770,7 +815,8 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(count_changed(d, &before, &ids))
|
||||
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept))
|
||||
})?;
|
||||
s.remap_appearance_item(&ids, |a| (!idx.contains(&a)).then(|| a - idx.iter().filter(|i| **i < a).count()));
|
||||
ok()
|
||||
@@ -796,7 +842,8 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if aligned(p) && to.is_some() && shared_stack(&s.doc()?.doc, &ids).is_some() {
|
||||
return Err(bad(C, "`to` takes the rows of one object's stack, not aligned rows"));
|
||||
}
|
||||
let per = items_per_target(&s.doc()?.doc, &ids, &idx, aligned(p));
|
||||
let before = s.doc()?.doc.clone();
|
||||
let per = items_per_target(&before, &ids, &idx, aligned(p));
|
||||
s.edit("Duplicate Item", |d, _| {
|
||||
let mut any = false;
|
||||
for (id, idx) in ids.iter().zip(&per) {
|
||||
@@ -834,7 +881,11 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if any { Ok(()) } else { Err(bad(C, format!("no item at index {}", idx[0]))) }
|
||||
if !any {
|
||||
return Err(bad(C, format!("no item at index {}", idx[0])));
|
||||
}
|
||||
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
Ok(())
|
||||
})?;
|
||||
// Rows at or above each copy move up by one (by the block, for copies placed at `to`).
|
||||
let m = idx.len();
|
||||
@@ -893,7 +944,8 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
n.appearance.set_contents_at(k);
|
||||
}
|
||||
}
|
||||
Ok(count_changed(d, &before, &ids))
|
||||
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept))
|
||||
})?;
|
||||
// The moved row stays the active one; the rows it passed shift by one.
|
||||
s.remap_appearance_item(&ids, |a| {
|
||||
@@ -936,7 +988,8 @@ fn move_items(s: &mut Session, p: &Value, ids: &[NodeId], to: usize) -> Result<V
|
||||
n.appearance.set_contents_at(k);
|
||||
}
|
||||
}
|
||||
Ok(count_changed(d, &before, ids))
|
||||
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, ids));
|
||||
Ok(count_changed(d, &before, ids) + usize::from(kept))
|
||||
})?;
|
||||
let m = idx.len();
|
||||
let landed = first_landed.unwrap_or(to);
|
||||
@@ -1034,15 +1087,25 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.eyedropper_sample = Some(node);
|
||||
}
|
||||
let range = range.filter(|(id, _, _)| targets.contains(id));
|
||||
// The highlighted characters' type objects and ranges: after Select All in threaded text, all
|
||||
// the text of every frame of the story.
|
||||
let story = super::textedit::editing_story(s);
|
||||
let ranges: Vec<(NodeId, Option<(usize, usize)>)> = match range {
|
||||
Some((id, _, _)) if story.contains(&id) => story.iter().map(|f| (*f, None)).collect(),
|
||||
Some((id, start, end)) => vec![(id, Some((start, end)))],
|
||||
None => vec![],
|
||||
};
|
||||
// Character styles cannot represent object transparency. Refuse before even changing
|
||||
// paint defaults; applying it to the object would also alter the unselected characters.
|
||||
if let Some((id, _, _)) = range.filter(|_| attrs.appearance.transparency) {
|
||||
let target = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
if picked.opacity != 1.0 || picked.blend != BlendMode::Normal || target.opacity != 1.0 || target.blend != BlendMode::Normal {
|
||||
return Err(bad(
|
||||
C,
|
||||
"object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object",
|
||||
));
|
||||
if attrs.appearance.transparency {
|
||||
for (id, _) in &ranges {
|
||||
let target = s.doc()?.doc.node(*id).ok_or(EngineError::NoNode(*id))?;
|
||||
if picked.opacity != 1.0 || picked.blend != BlendMode::Normal || target.opacity != 1.0 || target.blend != BlendMode::Normal {
|
||||
return Err(bad(
|
||||
C,
|
||||
"object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !reverse {
|
||||
@@ -1051,19 +1114,23 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if targets.is_empty() || attrs.is_empty() {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
}
|
||||
if let Some((id, start, end)) = range {
|
||||
if !ranges.is_empty() {
|
||||
let ids: Vec<NodeId> = ranges.iter().map(|(f, _)| *f).collect();
|
||||
let before = s.doc()?.doc.clone();
|
||||
super::overprint::edit_counted(s, "Eyedropper", |d| {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
|
||||
let placed = picked.placed(Some(t.local_bounds()));
|
||||
vectorcraft_text::edit::style_range(&mut t.runs, start, end, |st| picked.run(st, &placed, &attrs));
|
||||
if let Some((_, para)) = picked.text.as_ref().filter(|_| attrs.paragraph) {
|
||||
t.edit_paras(Some(t.paragraphs_in(start, end)), |p| *p = para.clone());
|
||||
for &(id, range) in &ranges {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
|
||||
let (start, end) = range.unwrap_or((0, vectorcraft_text::edit::runs_len(&t.runs)));
|
||||
let placed = picked.placed(Some(t.local_bounds()));
|
||||
vectorcraft_text::edit::style_range(&mut t.runs, start, end, |st| picked.run(st, &placed, &attrs));
|
||||
if let Some((_, para)) = picked.text.as_ref().filter(|_| attrs.paragraph) {
|
||||
t.edit_paras(Some(t.paragraphs_in(start, end)), |p| *p = para.clone());
|
||||
}
|
||||
super::typecmd::refresh_bounds(t);
|
||||
}
|
||||
super::typecmd::refresh_bounds(t);
|
||||
Ok(count_changed(d, &before, &[id]))
|
||||
Ok(count_changed(d, &before, &ids))
|
||||
})?;
|
||||
return Ok(json!({ "ids": [id.0] }));
|
||||
return Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }));
|
||||
}
|
||||
// When every target comes out as it was, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
@@ -1073,7 +1140,8 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
picked.apply(n, &attrs, append);
|
||||
}
|
||||
}
|
||||
Ok(count_changed(d, &before, &targets))
|
||||
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &targets));
|
||||
Ok(count_changed(d, &before, &targets) + usize::from(kept))
|
||||
})?;
|
||||
Ok(json!({ "ids": targets.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
@@ -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 })
|
||||
|
||||
@@ -35,7 +35,9 @@ use brushes::{
|
||||
};
|
||||
use dynamic::{symbol_instance_reset, symbol_instance_set_appearance};
|
||||
use symbols::selected_instances;
|
||||
pub(crate) use symbols::{instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol};
|
||||
pub(crate) use symbols::{
|
||||
expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol,
|
||||
};
|
||||
use symbols::{
|
||||
symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_list, symbol_new, symbol_options, symbol_place, symbol_replace,
|
||||
symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update,
|
||||
@@ -201,7 +203,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Break Link to Symbol",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them → {ids}",
|
||||
"{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them, with the instance's opacity mask → {ids}",
|
||||
has_selection,
|
||||
symbol_break_link
|
||||
),
|
||||
|
||||
@@ -341,7 +341,8 @@ pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// The plain art of instance `inst` in document space (fresh ids), with the instance's own
|
||||
/// appearance changes to a dynamic symbol's art when `own`, placed through its symbol's 9-slice
|
||||
/// guides when it has them.
|
||||
/// guides when it has them. The instance's opacity mask goes on the art, or on a group around it
|
||||
/// when the art has a mask of its own.
|
||||
fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option<Node> {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None };
|
||||
let sym = d.symbols.iter().find(|s| &s.name == symbol)?;
|
||||
@@ -361,13 +362,21 @@ fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option<Node> {
|
||||
art.opacity *= inst.opacity;
|
||||
art.blend = inst.blend;
|
||||
}
|
||||
if let Some(mask) = &inst.extras().mask {
|
||||
if art.extras().mask.is_some() {
|
||||
let id = d.alloc_id();
|
||||
art = Node::group(id, vec![Arc::new(art)]);
|
||||
}
|
||||
art.extras_mut().mask = Some(mask.clone());
|
||||
}
|
||||
Some(art)
|
||||
}
|
||||
|
||||
/// The most objects [`expanded_instance`] makes of instance `inst` in `d` (`own` as there): its
|
||||
/// symbol's object count with the art of its opacity masks, or
|
||||
/// [`vectorcraft_doc::NineSliceMap::most_placed`] when it is placed through 9-slice guides, plus
|
||||
/// the group that opacity or a blending mode adds. 0 for any other object.
|
||||
/// the group that opacity, a blending mode or the instance's opacity mask adds, plus the art of
|
||||
/// the instance's opacity mask. 0 for any other object.
|
||||
fn expanded_bound(d: &Document, inst: &Node, own: bool) -> u64 {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return 0 };
|
||||
let Some(sym) = d.symbols.iter().find(|s| &s.name == symbol) else { return 0 };
|
||||
@@ -378,7 +387,8 @@ fn expanded_bound(d: &Document, inst: &Node, own: bool) -> u64 {
|
||||
None if dynamic => vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst).count_with_masks() as u64,
|
||||
None => sym.art.count_with_masks() as u64,
|
||||
};
|
||||
most.saturating_add(1)
|
||||
let mask = inst.extras().mask.as_ref().map_or(0, |m| m.art.count_with_masks() as u64);
|
||||
most.saturating_add(1).saturating_add(mask)
|
||||
}
|
||||
|
||||
/// Replace instances `ids` with their art ([`expanded_instance`], `own` as there). Returns the
|
||||
@@ -402,7 +412,64 @@ fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result<Vec<NodeId
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// How many objects [`break_links`] may make at once.
|
||||
/// Object › Expand: the symbol instances under `roots` of `d` ([`expandable_instances`]) replaced
|
||||
/// by their art, as Break Link places it, each keeping the instance's id and place. The instances
|
||||
/// that art holds stay instances. A hidden or locked instance's art stays hidden or locked. When
|
||||
/// the instances together would make more than [`MAX_EXPAND_NODES`] objects, all of them stay
|
||||
/// instances. Returns whether any instance was expanded.
|
||||
pub(crate) fn expand_instances_under(d: &mut Document, roots: &[NodeId]) -> Result<bool> {
|
||||
let ids = expandable_instances(d, roots);
|
||||
let total = ids.iter().filter_map(|id| d.node(*id)).fold(0u64, |sum, n| sum.saturating_add(expanded_bound(d, n, true)));
|
||||
if total > MAX_EXPAND_NODES as u64 {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut any = false;
|
||||
for id in ids {
|
||||
let Some(inst) = d.node(id).cloned() else { continue };
|
||||
let Some(mut art) = expanded_instance(d, &inst, true) else { continue };
|
||||
let (par, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
|
||||
art.id = id;
|
||||
art.visible &= inst.visible;
|
||||
art.locked |= inst.locked;
|
||||
d.remove(id)?;
|
||||
d.insert(par, idx, art)?;
|
||||
any = true;
|
||||
}
|
||||
Ok(any)
|
||||
}
|
||||
|
||||
/// The symbol instances under `roots` of `d` that Object › Expand turns into their art: those
|
||||
/// without effects (Expand Appearance bakes the others), with no effects on their fills and
|
||||
/// strokes, not in perspective, and whose symbol `d` holds. The instances in blends, repeats and
|
||||
/// Intertwine groups are left to Expand, which turns those into plain groups.
|
||||
pub(crate) fn expandable_instances(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
fn collect(d: &Document, n: &Node, out: &mut Vec<NodeId>) {
|
||||
match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => {
|
||||
if n.appearance.effects.is_empty()
|
||||
&& n.appearance.items.iter().all(|i| i.effects().is_empty())
|
||||
&& n.projection().is_none()
|
||||
&& d.symbols.iter().any(|s| &s.name == symbol)
|
||||
{
|
||||
out.push(n.id);
|
||||
}
|
||||
}
|
||||
NodeKind::Blend { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => {}
|
||||
_ => {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
collect(d, c, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
for n in roots.iter().filter_map(|r| d.node(*r)) {
|
||||
collect(d, n, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How many objects [`break_links`] and [`expand_instances_under`] may make at once.
|
||||
const MAX_EXPAND_NODES: usize = 1_000_000;
|
||||
|
||||
pub(super) fn selected_instances(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
|
||||
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Live Paint"],
|
||||
Some("Cmd+Alt+X"),
|
||||
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); with a Live Paint group among them, add the others to it as livePaint.merge does → {id, faces, edges}",
|
||||
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with its front-most covering source's fill; with a Live Paint group among them, add the others to it as livePaint.merge does → {id, faces, edges}",
|
||||
has_selection_or_ids,
|
||||
lp_make
|
||||
),
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 }));
|
||||
}
|
||||
|
||||
@@ -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() };
|
||||
|
||||
@@ -138,8 +138,12 @@ fn cut_targets(s: &Session) -> Result<Vec<NodeId>> {
|
||||
/// What a cut does to one object: its new pieces (none deletes it).
|
||||
type Plan = Vec<(NodeId, Vec<PathData>)>;
|
||||
|
||||
/// Run `cut` on every target's geometry (`None`: unchanged) and apply the result as one undo step.
|
||||
fn run_cut(s: &mut Session, cmd: &str, label: &str, cut: &dyn Fn(&PathData, FillRule) -> Option<Vec<PathData>>) -> Result<Value> {
|
||||
/// What a cut makes of one object: its pieces (`None`: unchanged), or the pathops refusal.
|
||||
type Cut = std::result::Result<Option<Vec<PathData>>, po::PathOpsError>;
|
||||
|
||||
/// Run `cut` on every target's geometry (`None`: unchanged) and apply the result as one undo step. A shape the
|
||||
/// booleans refuse (too complex, too far out) fails the command with the art untouched: it is not "nothing on that side".
|
||||
fn run_cut(s: &mut Session, cmd: &str, label: &str, cut: &dyn Fn(&PathData, FillRule) -> Cut) -> Result<Value> {
|
||||
let targets = cut_targets(s)?;
|
||||
if targets.is_empty() {
|
||||
return Err(bad(cmd, "select paths or compound paths"));
|
||||
@@ -151,7 +155,8 @@ fn run_cut(s: &mut Session, cmd: &str, label: &str, cut: &dyn Fn(&PathData, Fill
|
||||
if pd.subpaths.iter().flat_map(|sp| &sp.anchors).any(|a| !(a.p.x.is_finite() && a.p.y.is_finite())) {
|
||||
return Err(bad(cmd, "paths contain invalid coordinates"));
|
||||
}
|
||||
if let Some(pieces) = cut(&pd, rule) {
|
||||
let pieces = cut(&pd, rule).map_err(|e| bad(cmd, format!("the cut cannot be made on this art: {e}")))?;
|
||||
if let Some(pieces) = pieces {
|
||||
plan.push((id, pieces));
|
||||
}
|
||||
}
|
||||
@@ -184,9 +189,9 @@ fn reach(pd: &PathData) -> Rect {
|
||||
}
|
||||
|
||||
/// `pd ∩ region`, dropping slivers.
|
||||
fn intersect(pd: &PathData, rule: FillRule, region: &PathData) -> PathData {
|
||||
let r = po::boolean(pd, rule, region, FillRule::NonZero, BoolOp::Intersect);
|
||||
if po::area(&r, FillRule::NonZero) <= 1e-6 { PathData::default() } else { r }
|
||||
fn intersect(pd: &PathData, rule: FillRule, region: &PathData) -> std::result::Result<PathData, po::PathOpsError> {
|
||||
let r = po::try_boolean(pd, rule, region, FillRule::NonZero, BoolOp::Intersect, po::DEFAULT_PRECISION)?;
|
||||
Ok(if po::try_area(&r, FillRule::NonZero)? <= 1e-6 { PathData::default() } else { r })
|
||||
}
|
||||
|
||||
// ---------- Line Cut ----------
|
||||
@@ -198,24 +203,26 @@ fn line_cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// `pd` split by the line: the pieces on both sides, `None` when the line misses it.
|
||||
fn split_by_line(pd: &PathData, rule: FillRule, axis: &Axis) -> Option<Vec<PathData>> {
|
||||
fn split_by_line(pd: &PathData, rule: FillRule, axis: &Axis) -> Cut {
|
||||
if pd.is_closed() {
|
||||
let around = reach(pd);
|
||||
let a = intersect(pd, rule, &axis.half_plane(1.0, around));
|
||||
let b = intersect(pd, rule, &axis.half_plane(-1.0, around));
|
||||
let a = intersect(pd, rule, &axis.half_plane(1.0, around))?;
|
||||
let b = intersect(pd, rule, &axis.half_plane(-1.0, around))?;
|
||||
if a.is_empty() || b.is_empty() {
|
||||
return None;
|
||||
return Ok(None);
|
||||
}
|
||||
return Some(components(&a).into_iter().chain(components(&b)).collect());
|
||||
return Ok(Some(components(&a).into_iter().chain(components(&b)).collect()));
|
||||
}
|
||||
// Open paths: the parts on each side (each pass removes the other side).
|
||||
let a = erase_outline(pd, f64::INFINITY, &|q| axis.side(q) < 0.0)?;
|
||||
let b = erase_outline(pd, f64::INFINITY, &|q| axis.side(q) >= 0.0)?;
|
||||
Some(if pd.subpaths.len() == 1 {
|
||||
let (Some(a), Some(b)) = (erase_outline(pd, f64::INFINITY, &|q| axis.side(q) < 0.0), erase_outline(pd, f64::INFINITY, &|q| axis.side(q) >= 0.0))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some(if pd.subpaths.len() == 1 {
|
||||
a.into_iter().chain(b).collect()
|
||||
} else {
|
||||
vec![PathData::new(a.into_iter().chain(b).flat_map(|p| p.subpaths).collect())]
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
// ---------- Rectangle Cut ----------
|
||||
@@ -238,25 +245,34 @@ fn rect_cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// `pd` cropped to `rect`: `None` when it lies inside, no pieces when it lies outside.
|
||||
fn crop(pd: &PathData, rule: FillRule, rect: Rect) -> Option<Vec<PathData>> {
|
||||
let b = pd.bounds()?;
|
||||
fn crop(pd: &PathData, rule: FillRule, rect: Rect) -> Cut {
|
||||
let Some(b) = pd.bounds() else { return Ok(None) };
|
||||
if rect.inflate(1e-9, 1e-9).contains_rect(b) {
|
||||
return None;
|
||||
return Ok(None);
|
||||
}
|
||||
if pd.is_closed() {
|
||||
let r =
|
||||
intersect(pd, rule, &polygon(&[rect.origin(), Point::new(rect.x1, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1)]));
|
||||
return Some(if r.is_empty() { vec![] } else { vec![r] });
|
||||
// Wholly outside: nothing is left, whatever the booleans would make of the rectangle's coordinates.
|
||||
if rect.intersect(b).is_zero_area() {
|
||||
return Ok(Some(vec![]));
|
||||
}
|
||||
let r = intersect(
|
||||
pd,
|
||||
rule,
|
||||
&polygon(&[rect.origin(), Point::new(rect.x1, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1)]),
|
||||
)?;
|
||||
return Ok(Some(if r.is_empty() { vec![] } else { vec![r] }));
|
||||
}
|
||||
let inside = rect.inflate(1e-9, 1e-9);
|
||||
// Sampled at least every half of the rectangle's shorter side, so a line through it is found.
|
||||
let step = rect.width().min(rect.height()) / 2.0;
|
||||
let pieces = erase_outline(pd, step, &|q| !(q.x >= inside.x0 && q.x <= inside.x1 && q.y >= inside.y0 && q.y <= inside.y1))?;
|
||||
Some(if pd.subpaths.len() == 1 || pieces.is_empty() {
|
||||
let Some(pieces) = erase_outline(pd, step, &|q| !(q.x >= inside.x0 && q.x <= inside.x1 && q.y >= inside.y0 && q.y <= inside.y1)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some(if pd.subpaths.len() == 1 || pieces.is_empty() {
|
||||
pieces
|
||||
} else {
|
||||
vec![PathData::new(pieces.into_iter().flat_map(|p| p.subpaths).collect())]
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
// ---------- Mirror & Cut ----------
|
||||
@@ -287,7 +303,7 @@ fn mirror_cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
other => return Err(bad(C, format!("unknown axis `{other}` (vertical|horizontal|free)"))),
|
||||
};
|
||||
let sign = keep_sign(&axis, str_param(p, "keep")).map_err(|e| bad(C, e))?;
|
||||
run_cut(s, C, "Mirror & Cut", &|pd, rule| Some(mirror(pd, rule, &axis, sign)))
|
||||
run_cut(s, C, "Mirror & Cut", &|pd, rule| mirror(pd, rule, &axis, sign).map(Some))
|
||||
}
|
||||
|
||||
/// The sign of [`Axis::side`] on the side `keep` names (default: left, or top when the axis runs
|
||||
@@ -309,22 +325,22 @@ fn keep_sign(axis: &Axis, keep: Option<&str>) -> std::result::Result<f64, String
|
||||
}
|
||||
|
||||
/// The kept half of `pd` and its reflection, joined (no pieces when nothing is on the kept side).
|
||||
fn mirror(pd: &PathData, rule: FillRule, axis: &Axis, sign: f64) -> Vec<PathData> {
|
||||
fn mirror(pd: &PathData, rule: FillRule, axis: &Axis, sign: f64) -> std::result::Result<Vec<PathData>, po::PathOpsError> {
|
||||
let m = axis.reflection();
|
||||
if pd.is_closed() {
|
||||
let kept = intersect(pd, rule, &axis.half_plane(sign, reach(pd)));
|
||||
let kept = intersect(pd, rule, &axis.half_plane(sign, reach(pd)))?;
|
||||
if kept.is_empty() {
|
||||
return vec![];
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let joined = po::boolean(&kept, FillRule::NonZero, &kept.transformed(m), FillRule::NonZero, BoolOp::Union);
|
||||
return if joined.is_empty() { vec![] } else { vec![joined] };
|
||||
let joined = po::try_boolean(&kept, FillRule::NonZero, &kept.transformed(m), FillRule::NonZero, BoolOp::Union, po::DEFAULT_PRECISION)?;
|
||||
return Ok(if joined.is_empty() { vec![] } else { vec![joined] });
|
||||
}
|
||||
let kept = match erase_outline(pd, f64::INFINITY, &|q| axis.side(q) * sign < 0.0) {
|
||||
Some(pieces) => pieces.into_iter().flat_map(|p| p.subpaths).collect(),
|
||||
None => pd.subpaths.clone(),
|
||||
};
|
||||
let subs: Vec<SubPath> = kept.iter().flat_map(|sp| mirror_open(sp, axis, m)).collect();
|
||||
if subs.is_empty() { vec![] } else { vec![PathData::new(subs)] }
|
||||
Ok(if subs.is_empty() { vec![] } else { vec![PathData::new(subs)] })
|
||||
}
|
||||
|
||||
/// An open run and its reflection, joined where its ends touch the axis (closed when both do);
|
||||
@@ -399,4 +415,28 @@ mod tests {
|
||||
let out = mirror_open(&sp, &axis, axis.reflection());
|
||||
assert_eq!((out.len(), out[0].closed, out[0].anchors.len()), (1, false, 3));
|
||||
}
|
||||
|
||||
/// A shape the booleans refuse (here: so far from the origin that the sweep tolerance exceeds the precision) is an error,
|
||||
/// not "no pieces": that would make Mirror & Cut delete it and Rectangle Cut crop it to nothing.
|
||||
#[test]
|
||||
fn a_shape_the_booleans_refuse_is_an_error_not_no_pieces() {
|
||||
let far = polygon(&[
|
||||
Point::new(1e15, 1e15),
|
||||
Point::new(1e15 + 100.0, 1e15),
|
||||
Point::new(1e15 + 100.0, 1e15 + 100.0),
|
||||
Point::new(1e15, 1e15 + 100.0),
|
||||
]);
|
||||
let axis = Axis { p: Point::ZERO, d: Vec2::new(0.0, 1.0) };
|
||||
let refused = Some(po::PathOpsError::Degenerate);
|
||||
assert_eq!(mirror(&far, FillRule::NonZero, &axis, 1.0).err(), refused);
|
||||
assert_eq!(split_by_line(&far, FillRule::NonZero, &axis).err(), refused);
|
||||
// A rectangle that far out, against art near the origin, still crops it to nothing.
|
||||
let far_rect = Rect::new(1e15, 1e15, 1e15 + 100.0, 1e15 + 100.0);
|
||||
let near_art = polygon(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)]);
|
||||
assert_eq!(crop(&near_art, FillRule::NonZero, far_rect).unwrap(), Some(vec![]));
|
||||
// Near the origin the same cuts work.
|
||||
let near = polygon(&[Point::new(-50.0, 0.0), Point::new(50.0, 0.0), Point::new(50.0, 100.0), Point::new(-50.0, 100.0)]);
|
||||
assert_eq!(mirror(&near, FillRule::NonZero, &axis, 1.0).unwrap().len(), 1);
|
||||
assert_eq!(split_by_line(&near, FillRule::NonZero, &axis).unwrap().map(|p| p.len()), Some(2));
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -11,7 +11,7 @@ use vectorcraft_geom::Vec2;
|
||||
|
||||
use super::edit::selected_roots;
|
||||
use super::pathops::Beside;
|
||||
use super::select::{is_selectable, selectable_ids, walk_selectable};
|
||||
use super::select::{first_selectable, is_selectable, selectable_ids, walk_selectable};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Point, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, f64_req, has_doc, has_selection, id_param, ok,
|
||||
str_param,
|
||||
@@ -19,14 +19,18 @@ use super::{
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("select.same.symbolInstance", "Symbol Instance", ["Select", "Same"], None, "{} → {count}", has_selection, |s, _| same(
|
||||
s,
|
||||
cmd!(
|
||||
"select.same.symbolInstance",
|
||||
|a, b| match (&a.kind, &b.kind) {
|
||||
"Symbol Instance",
|
||||
["Select", "Same"],
|
||||
None,
|
||||
"{} select the instances of the symbol of the first selected object that can be selected; objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard while nothing is isolated, or outside the isolated group or layer are passed over → {count}",
|
||||
has_selection,
|
||||
|s, _| same(s, "select.same.symbolInstance", |a, b| match (&a.kind, &b.kind) {
|
||||
(NodeKind::SymbolInstance { symbol: x, .. }, NodeKind::SymbolInstance { symbol: y, .. }) => x == y,
|
||||
_ => false,
|
||||
}
|
||||
)),
|
||||
})
|
||||
),
|
||||
cmd!(
|
||||
"select.same.linkBlockSeries",
|
||||
"Link Block Series",
|
||||
@@ -66,6 +70,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",
|
||||
@@ -288,35 +301,30 @@ fn finish_same(s: &mut Session, cmd: &str, ids: Vec<NodeId>) -> Result<Value> {
|
||||
Ok(json!({ "count": st.selection.objects.len() }))
|
||||
}
|
||||
|
||||
/// The objects `eq` matches with the [`first_selectable`] selected object.
|
||||
fn same(s: &mut Session, cmd: &str, eq: fn(&Node, &Node) -> bool) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let r = st.selection.objects.first().and_then(|id| st.doc.node(*id)).cloned().ok_or_else(|| bad(cmd, "nothing selected"))?;
|
||||
let r = first_selectable(s.doc()?).cloned().ok_or_else(|| bad(cmd, "nothing selected"))?;
|
||||
let ids = candidates(s, |n| eq(n, &r))?;
|
||||
finish_same(s, cmd, ids)
|
||||
}
|
||||
|
||||
/// The first character style of the first type object [`each_selected_text`] gives.
|
||||
fn first_text_style(s: &Session) -> Option<CharStyle> {
|
||||
let st = s.active()?;
|
||||
let mut out = None;
|
||||
for id in &st.selection.objects {
|
||||
st.doc.node(*id)?.walk(&mut |n| {
|
||||
if out.is_none()
|
||||
&& let NodeKind::Text(t) = &n.kind
|
||||
{
|
||||
out = Some(t.first_style());
|
||||
}
|
||||
});
|
||||
if out.is_some() {
|
||||
break;
|
||||
each_selected_text(s, |id| {
|
||||
if let Some(NodeKind::Text(t)) = st.doc.node(id).map(|n| &n.kind) {
|
||||
out = Some(t.first_style());
|
||||
}
|
||||
}
|
||||
out.is_none()
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -324,8 +332,9 @@ fn same_text(s: &mut Session, cmd: &str, eq: fn(&CharStyle, &CharStyle) -> bool)
|
||||
|
||||
/// Call `f` with each type object among the selected objects and inside them, in selection order,
|
||||
/// keeping only those [`walk_selectable`] visits: none that is hidden, locked, on a hidden, locked
|
||||
/// or template layer, or outside the isolated group. A type object inside two selected objects is
|
||||
/// given twice. The walk stops when `f` returns false.
|
||||
/// or template layer, or outside the isolated group. A selected layer or sublayer, or a selected
|
||||
/// group that holds the isolated group, gives the type in it that passes the same test. A type
|
||||
/// object inside two selected objects is given twice. The walk stops when `f` returns false.
|
||||
fn each_selected_text(s: &Session, mut f: impl FnMut(NodeId) -> bool) {
|
||||
fn inside(n: &Node, f: &mut impl FnMut(NodeId) -> bool) -> bool {
|
||||
if !n.visible || n.locked {
|
||||
@@ -336,12 +345,23 @@ fn each_selected_text(s: &Session, mut f: impl FnMut(NodeId) -> bool) {
|
||||
}
|
||||
n.children().into_iter().flatten().all(|c| inside(c, f))
|
||||
}
|
||||
fn from(n: &Node, selectable: &impl Fn(NodeId) -> bool, holds_isolated: &[NodeId], f: &mut impl FnMut(NodeId) -> bool) -> bool {
|
||||
if selectable(n.id) {
|
||||
return inside(n, f);
|
||||
}
|
||||
if n.is_layer() || holds_isolated.contains(&n.id) {
|
||||
return n.children().into_iter().flatten().all(|c| from(c, selectable, holds_isolated, f));
|
||||
}
|
||||
true
|
||||
}
|
||||
let Some(st) = s.active() else { return };
|
||||
let locks = st.doc.locked_artboards();
|
||||
let selectable = |id| is_selectable(&st.doc, st.isolation, &locks, id);
|
||||
// The isolated group and the groups and layers that hold it.
|
||||
let holds_isolated = st.isolation.and_then(|i| st.doc.ancestry(i)).unwrap_or_default();
|
||||
for id in &st.selection.objects {
|
||||
if is_selectable(&st.doc, st.isolation, &locks, *id)
|
||||
&& let Some(n) = st.doc.node(*id)
|
||||
&& !inside(n, &mut f)
|
||||
if let Some(n) = st.doc.node(*id)
|
||||
&& !from(n, &selectable, &holds_isolated, &mut f)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Object → Expand: live shapes, type and effects (Object), strokes (Stroke) and gradient and pattern
|
||||
//! fills (Fill) into plain art in one undo step; blends, repeats and Intertwine groups become groups of their steps, of their instances and of what they draw. Placed documents (Object) become editable copies of the
|
||||
//! art they show, their resources joining the document. A linear or radial gradient fill becomes a
|
||||
//! art they show, their resources joining the document. Symbol instances (Object) become their art,
|
||||
//! as Break Link to Symbol places it. A linear or radial gradient fill becomes a
|
||||
//! gradient mesh, or solid strips / concentric ellipses, inside a clip group shaped like the object; a freeform
|
||||
//! gradient becomes a mesh shaped like the object. A pattern fill becomes the tiles it paints inside a clip
|
||||
//! group shaped like the object. Create Gradient Mesh shares the sampling.
|
||||
@@ -40,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Expand…",
|
||||
["Object"],
|
||||
None,
|
||||
"{object?: true (type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step → {ids}",
|
||||
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step → {ids}",
|
||||
has_selection,
|
||||
expand
|
||||
),
|
||||
@@ -49,11 +50,17 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Expand Options",
|
||||
[],
|
||||
None,
|
||||
"{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance} (true: something to expand; gradient: a gradient fill that Fill expands, which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus)",
|
||||
"{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands, which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)",
|
||||
has_selection,
|
||||
|s, _| {
|
||||
let e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?);
|
||||
Ok(json!({"object": e.object(), "fill": e.fill, "stroke": e.stroke, "gradient": e.gradient, "appearance": has_appearance(s)}))
|
||||
let mut info =
|
||||
json!({"object": e.object(), "fill": e.fill, "stroke": e.stroke, "gradient": e.gradient, "appearance": has_appearance(s)});
|
||||
if e.symbols {
|
||||
let [fill, stroke, gradient] = e.symbol_art;
|
||||
info["symbolArt"] = json!({"fill": fill, "stroke": stroke, "gradient": gradient});
|
||||
}
|
||||
Ok(info)
|
||||
}
|
||||
),
|
||||
]
|
||||
@@ -124,45 +131,74 @@ struct Expandable {
|
||||
repeats: bool,
|
||||
/// Intertwine groups (Object expands them into groups of what they draw).
|
||||
intertwines: bool,
|
||||
/// Symbol instances (Object expands them into their art, as Break Link to Symbol does).
|
||||
symbols: bool,
|
||||
/// Fill, stroke and gradient that only the art of those symbol instances holds: Fill and Stroke
|
||||
/// reach them only when Object expands the instances.
|
||||
symbol_art: [bool; 3],
|
||||
}
|
||||
|
||||
impl Expandable {
|
||||
fn of(d: &Document, roots: &[NodeId]) -> Self {
|
||||
let mut e = Self::default();
|
||||
for n in roots.iter().filter_map(|r| d.node(*r)) {
|
||||
n.walk(&mut |c| {
|
||||
let shape = matches!(c.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
|
||||
e.text |= matches!(c.kind, NodeKind::Text(_));
|
||||
e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. });
|
||||
e.effects |= !c.appearance.effects.is_empty();
|
||||
e.envelope |= matches!(c.kind, NodeKind::Envelope { .. });
|
||||
e.blends |= matches!(c.kind, NodeKind::Blend { .. });
|
||||
e.placed |= matches!(c.kind, NodeKind::PlacedDocument(_));
|
||||
e.repeats |= matches!(c.kind, NodeKind::Repeat(_));
|
||||
e.intertwines |= matches!(c.kind, NodeKind::Intertwine { .. });
|
||||
e.stroke |= match &c.kind {
|
||||
// Type's outlines take its characters' stroke (see `type.createOutlines`).
|
||||
NodeKind::Text(t) => t.runs.iter().any(|r| r.style.has_stroke()),
|
||||
_ => shape && !c.appearance.stroke_paint().is_none(),
|
||||
};
|
||||
e.gradient |= match &c.kind {
|
||||
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))),
|
||||
_ => shape && c.appearance.items.iter().any(|i| gradient_fill(i).is_some()),
|
||||
};
|
||||
e.fill |= e.gradient;
|
||||
e.fill |= match &c.kind {
|
||||
NodeKind::Text(t) => {
|
||||
t.runs.iter().any(|r| matches!(&r.style.fill, Paint::Pattern { pattern, .. } if d.pattern(pattern).is_some()))
|
||||
}
|
||||
_ => shape && c.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()),
|
||||
};
|
||||
});
|
||||
e.add(d, n);
|
||||
}
|
||||
let own = [e.fill, e.stroke, e.gradient];
|
||||
// The Fill and Stroke options also reach the art of the symbol instances that Object
|
||||
// expands: a dynamic instance's art with its own changes, and each other symbol's art once.
|
||||
let instances = super::brushsym::expandable_instances(d, roots);
|
||||
e.symbols = !instances.is_empty();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for inst in instances.iter().filter_map(|id| d.node(*id)) {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &inst.kind else { continue };
|
||||
let Some(sym) = d.symbols.iter().find(|s| &s.name == symbol) else { continue };
|
||||
let mut a = Self::default();
|
||||
if !inst.extras().symbol_overrides.is_empty() {
|
||||
a.add(d, &vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst));
|
||||
} else if seen.insert(symbol.clone()) {
|
||||
a.add(d, &sym.art);
|
||||
}
|
||||
e.fill |= a.fill;
|
||||
e.gradient |= a.gradient;
|
||||
e.stroke |= a.stroke;
|
||||
}
|
||||
e.symbol_art = [e.fill && !own[0], e.stroke && !own[1], e.gradient && !own[2]];
|
||||
e
|
||||
}
|
||||
|
||||
/// Adds what `n` and the nodes under it hold.
|
||||
fn add(&mut self, d: &Document, n: &Node) {
|
||||
let e = self;
|
||||
n.walk(&mut |c| {
|
||||
let shape = matches!(c.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
|
||||
e.text |= matches!(c.kind, NodeKind::Text(_));
|
||||
e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. });
|
||||
e.effects |= !c.appearance.effects.is_empty();
|
||||
e.envelope |= matches!(c.kind, NodeKind::Envelope { .. });
|
||||
e.blends |= matches!(c.kind, NodeKind::Blend { .. });
|
||||
e.placed |= matches!(c.kind, NodeKind::PlacedDocument(_));
|
||||
e.repeats |= matches!(c.kind, NodeKind::Repeat(_));
|
||||
e.intertwines |= matches!(c.kind, NodeKind::Intertwine { .. });
|
||||
e.stroke |= match &c.kind {
|
||||
// Type's outlines take its characters' stroke (see `type.createOutlines`).
|
||||
NodeKind::Text(t) => t.runs.iter().any(|r| r.style.has_stroke()),
|
||||
_ => shape && !c.appearance.stroke_paint().is_none(),
|
||||
};
|
||||
e.gradient |= match &c.kind {
|
||||
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))),
|
||||
_ => shape && c.appearance.items.iter().any(|i| gradient_fill(i).is_some()),
|
||||
};
|
||||
e.fill |= e.gradient;
|
||||
e.fill |= match &c.kind {
|
||||
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(&r.style.fill, Paint::Pattern { pattern, .. } if d.pattern(pattern).is_some())),
|
||||
_ => shape && c.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
fn object(&self) -> bool {
|
||||
self.text || self.live || self.effects || self.envelope || self.blends || self.placed || self.repeats || self.intertwines
|
||||
self.text || self.live || self.effects || self.envelope || self.blends || self.placed || self.repeats || self.intertwines || self.symbols
|
||||
}
|
||||
}
|
||||
|
||||
@@ -209,6 +245,30 @@ fn expand_steps(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if object && e.placed {
|
||||
let roots = selected_roots(s)?;
|
||||
s.edit("Expand", |d, _| expand_placed_under(d, &roots))?;
|
||||
e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?);
|
||||
}
|
||||
// Then the symbol instances, those in the placed documents' art included: their art expands
|
||||
// below, and the instances it holds stay instances.
|
||||
if object && e.symbols {
|
||||
let roots = selected_roots(s)?;
|
||||
// An edit that expands no instance (too many objects to make) is undone, and the
|
||||
// instances stay as they are.
|
||||
let mut expanded = None;
|
||||
let r = s.edit("Expand", |d, _| {
|
||||
let any = super::brushsym::expand_instances_under(d, &roots)?;
|
||||
expanded = Some(any);
|
||||
if any { Ok(()) } else { Err(EngineError::Other("Expand: nothing to expand".into())) }
|
||||
});
|
||||
if !matches!((&r, expanded), (Err(_), Some(false))) {
|
||||
r?;
|
||||
}
|
||||
e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?);
|
||||
// The placed documents in the instances' art too.
|
||||
if e.placed {
|
||||
let roots = selected_roots(s)?;
|
||||
s.edit("Expand", |d, _| expand_placed_under(d, &roots))?;
|
||||
e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?);
|
||||
}
|
||||
}
|
||||
// Intertwine groups before what they hold: their objects, and the copies of the parts drawn
|
||||
// over the others, expand below.
|
||||
|
||||
@@ -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)));
|
||||
}
|
||||
}
|
||||
@@ -420,7 +420,10 @@ pub fn encode(doc: &Document, format: &str, p: &Value) -> Result<Vec<u8>> {
|
||||
/// font; PDF, EPS, SVG, EMF, WMF and the raster formats: type that doesn't fit its frame).
|
||||
pub fn encode_with_warnings(doc: &Document, format: &str, p: &Value) -> Result<(Vec<u8>, Vec<String>)> {
|
||||
let f = super::writable(C, Some(format), None)?;
|
||||
encode_all(doc, f.id, p)?.single(f)
|
||||
let enc = encode_all(doc, f.id, p)?;
|
||||
// The error for a version 7 .ai of several artboards names the legacy .ai.
|
||||
let legacy = f.id == "ai" && super::legacy_ai::wanted(C, f, p)?;
|
||||
enc.single(&if legacy { super::legacy_ai::named(f) } else { *f })
|
||||
}
|
||||
|
||||
/// [`encode`], with every file the export writes.
|
||||
|
||||
@@ -41,7 +41,7 @@ use super::super::{Affine, EngineError, NodeId, Result, bad};
|
||||
use super::{ArtboardPick, Encoded, Format};
|
||||
|
||||
/// Does `p` ask a save in `f` for a legacy `.ai` file of version 7 (`aiVersion: "7"`)? An unknown
|
||||
/// version is an error, and so is version 7 for a `.ait` template, which is PDF-compatible only.
|
||||
/// version is an error, and so is version 7 for a `.ait` template, which is never a legacy file.
|
||||
pub(super) fn wanted(cmd: &str, f: &Format, p: &Value) -> Result<bool> {
|
||||
let legacy = match p.get("aiVersion") {
|
||||
None | Some(Value::Null) => false,
|
||||
@@ -51,11 +51,17 @@ pub(super) fn wanted(cmd: &str, f: &Format, p: &Value) -> Result<bool> {
|
||||
Some(v) => return Err(bad(cmd, format!("aiVersion {v}: \"pdf\" (PDF-compatible, the default) or \"7\" (legacy .ai, version 7)"))),
|
||||
};
|
||||
if legacy && f.id == "ait" {
|
||||
return Err(bad(cmd, "aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible"));
|
||||
return Err(bad(cmd, "aiVersion 7 writes legacy .ai files, not .ait templates"));
|
||||
}
|
||||
Ok(legacy)
|
||||
}
|
||||
|
||||
/// `f` (the `.ai` format, whose label names the PDF-compatible file) named, in its errors, as the
|
||||
/// legacy `.ai` file.
|
||||
pub(super) fn named(f: &Format) -> Format {
|
||||
Format { label: "legacy .ai (version 7)", ..*f }
|
||||
}
|
||||
|
||||
/// What a legacy `.ai` does with the images it can't hold (`transparentImages`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum SeeThrough {
|
||||
@@ -109,7 +115,7 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
|
||||
}
|
||||
let mode = see_through(cmd, p)?;
|
||||
let (hidden, outline_text) = (hidden_objects(cmd, p)?, outline_text(cmd, p)?);
|
||||
let picked: ArtboardPick = super::encode::options(f, p)?;
|
||||
let picked: ArtboardPick = super::encode::options(&named(f), p)?;
|
||||
let boards = picked.resolve(n).map_err(|e| bad(cmd, e))?.unwrap_or_else(|| (0..n).collect());
|
||||
let mut enc = Encoded { warnings: vec![FIDELITY.to_string()], ..Encoded::default() };
|
||||
if boards.len() > 1 {
|
||||
|
||||
@@ -165,14 +165,18 @@ pub fn load(name: &str, bytes: &[u8]) -> Result<Loaded> {
|
||||
/// of its art, which it carries: its layers and hidden objects as they were, and the art outside
|
||||
/// its artboard (its PDF part has only what is on the artboards), as an EPS of the editor is read.
|
||||
/// Anything else as it was. `unit`: the size in points of a unit of the PDF part's user space (its
|
||||
/// first page's `UserUnit`) → (document, warnings, whether its layers were read).
|
||||
fn through_editing_data(bytes: &[u8], opts: &LoadOptions, doc: Document, warnings: Vec<String>, unit: f64) -> (Document, Vec<String>, bool) {
|
||||
if opts.pages.is_some() || !opts.layers || !opts.editing_data {
|
||||
return (doc, warnings, false);
|
||||
}
|
||||
let Some(private) = vectorcraft_pdf::illustrator_data(bytes, opts.password.as_deref()) else { return (doc, warnings, false) };
|
||||
/// first page's `UserUnit`) → (document, warnings, whether its layers were read). `private`: the
|
||||
/// editor's copy ([`editing_copy`]).
|
||||
fn through_editing_data(
|
||||
private: Option<&[u8]>,
|
||||
opts: &LoadOptions,
|
||||
doc: Document,
|
||||
warnings: Vec<String>,
|
||||
unit: f64,
|
||||
) -> (Document, Vec<String>, bool) {
|
||||
let Some(private) = private else { return (doc, warnings, false) };
|
||||
let outlined = opts.text_as == vectorcraft_pdf::TextAs::Outlines;
|
||||
let (doc, mut warnings, read) = vectorcraft_eps::layered_ai(&private, doc, warnings, outlined, opts.trust_editing_data, unit);
|
||||
let (doc, mut warnings, read) = vectorcraft_eps::layered_ai(private, doc, warnings, outlined, opts.trust_editing_data, unit);
|
||||
// The layers weren't read (or couldn't be): the notes of reading the PDF part still hold.
|
||||
if !read {
|
||||
return (doc, warnings, false);
|
||||
@@ -189,18 +193,33 @@ fn through_editing_data(bytes: &[u8], opts: &LoadOptions, doc: Document, warning
|
||||
(doc, warnings, true)
|
||||
}
|
||||
|
||||
/// A `.ai` saved without PDF compatibility (its PDF part is a placeholder page) from the editor's
|
||||
/// own copy of its art alone: `None` when the file has none (or pages are picked, or layers or the
|
||||
/// editing data are off), an error when it can't be read.
|
||||
fn from_editing_data_alone(bytes: &[u8], opts: &LoadOptions) -> Option<Result<(Document, Vec<String>)>> {
|
||||
if opts.pages.is_some() || !opts.layers || !opts.editing_data {
|
||||
/// A `.ai` saved without PDF compatibility (its PDF part is a placeholder page), `opened`, from the
|
||||
/// editor's own copy of its art alone: `None` when the file has none (or the pages picked don't
|
||||
/// name every page, or layers or the editing data are off), an error when it can't be read.
|
||||
fn from_editing_data_alone(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option<Result<(Document, Vec<String>)>> {
|
||||
if !every_page(opened.page_count(), opts) || !opts.layers || !opts.editing_data {
|
||||
return None;
|
||||
}
|
||||
let private = vectorcraft_pdf::illustrator_data(bytes, opts.password.as_deref())?;
|
||||
Some(
|
||||
vectorcraft_eps::ai_alone(&private)
|
||||
.map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})"))),
|
||||
)
|
||||
let private = opened.illustrator_data()?;
|
||||
Some(editing_copy_alone(&private))
|
||||
}
|
||||
|
||||
/// [`from_editing_data_alone`] of `private`, the editor's copy already read.
|
||||
fn editing_copy_alone(private: &[u8]) -> Result<(Document, Vec<String>)> {
|
||||
vectorcraft_eps::ai_alone(private)
|
||||
.map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})")))
|
||||
}
|
||||
|
||||
/// Does a file opened with `opts` read the editor's own copy of its art: no pages picked, and
|
||||
/// layers and the editing data on?
|
||||
fn reads_editing_copy(opts: &LoadOptions) -> bool {
|
||||
opts.pages.is_none() && opts.layers && opts.editing_data
|
||||
}
|
||||
|
||||
/// The editor's own copy of its art that `opened` carries (as [`vectorcraft_pdf::illustrator_data`]
|
||||
/// reads it), when `opts` read it ([`reads_editing_copy`]).
|
||||
fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option<Vec<u8>> {
|
||||
reads_editing_copy(opts).then(|| opened.illustrator_data()).flatten()
|
||||
}
|
||||
|
||||
/// A `.ai`, or a PDF saved with the editing data, whose PDF part can't be read (`e`, the import's
|
||||
@@ -266,10 +285,10 @@ pub(crate) fn is_placeholder(e: &EngineError) -> bool {
|
||||
e.to_string() == vectorcraft_pdf::PdfError::PlaceholderOnly.to_string()
|
||||
}
|
||||
|
||||
/// Do `opts` read every page of the PDF `bytes`: no `pages`, or a range that names each one?
|
||||
fn every_page(bytes: &[u8], opts: &LoadOptions) -> bool {
|
||||
/// Do `opts` read every page of a PDF of `count` pages: no `pages`, or a range that names each one?
|
||||
fn every_page(count: usize, opts: &LoadOptions) -> bool {
|
||||
let Some(range) = &opts.pages else { return true };
|
||||
vectorcraft_pdf::info(bytes, opts.password.as_deref()).is_ok_and(|i| parse_range(range, i.pages.len()).is_ok_and(|p| p.len() == i.pages.len()))
|
||||
parse_range(range, count).is_ok_and(|p| p.len() == count)
|
||||
}
|
||||
|
||||
/// Page `page_index` (0-based) read from a PDF or `.ai` (`read`, as [`super::page_document`] reads
|
||||
@@ -306,6 +325,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
None => err(format!("can't open `{name}`: not a format VectorCraft reads (see document.formats)")),
|
||||
})?;
|
||||
let title = file_name(name);
|
||||
// The File Info a PDF, `.ai` or `.ait` gives.
|
||||
let mut file_info = None;
|
||||
let mut converted = false;
|
||||
let mut preview_only = false;
|
||||
let mut editing_data = false;
|
||||
@@ -332,15 +353,22 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
restore_or_import(editing, || import_svg(&text, folder.as_deref()))?
|
||||
}
|
||||
"pdf" | "ai" | "ait" => {
|
||||
// The file is read and checked once, for the document it carries, its pages, the
|
||||
// editor's copy and its File Info.
|
||||
let opened = vectorcraft_pdf::open_pdf(bytes, opts.password.as_deref());
|
||||
// Saved with Preserve Editing: the document it carries, unless some pages are picked.
|
||||
let editing = opts
|
||||
.pages
|
||||
.is_none()
|
||||
.then(|| vectorcraft_pdf::editing_with(bytes, opts.password.as_deref()))
|
||||
let editing = (opts.pages.is_none() && opts.native)
|
||||
.then(|| opened.as_ref().ok().and_then(|o| o.editing()))
|
||||
.flatten()
|
||||
.map(|e| (e.intact, move || Some(e.data)));
|
||||
restore_or_import(editing, || match super::pdfimport::import(bytes, opts, format.id != "pdf") {
|
||||
let imported = || match &opened {
|
||||
Ok(o) => super::pdfimport::import(bytes, o, opts, format.id != "pdf"),
|
||||
Err(e) => Err(err(e)),
|
||||
};
|
||||
let read = restore_or_import(editing, || match imported() {
|
||||
Ok(r) => {
|
||||
// The editor's copy, read once the import is done with the pages.
|
||||
let private = opened.as_ref().ok().and_then(|o| editing_copy(o, opts));
|
||||
// Pages of text alone: the editing copy alone where it reads, as for a file
|
||||
// saved without its PDF part (#1387: else the page, which is the art). So too
|
||||
// pages that draw nothing at all: there is no page art to check the layers
|
||||
@@ -349,30 +377,35 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
// decoded draws nothing either): its notes are at most the page's own.
|
||||
let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w));
|
||||
let alone = (r.only_text || empty)
|
||||
.then(|| from_editing_data_alone(bytes, opts))
|
||||
.then(|| private.as_deref().map(editing_copy_alone))
|
||||
.flatten()
|
||||
.and_then(|read| read.ok())
|
||||
.map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts));
|
||||
let (doc, warnings, read) = match alone {
|
||||
Some((doc, warnings)) => (doc, warnings, true),
|
||||
None => through_editing_data(bytes, opts, r.document, r.warnings, r.user_unit),
|
||||
None => through_editing_data(private.as_deref(), opts, r.document, r.warnings, r.user_unit),
|
||||
};
|
||||
editing_data = read;
|
||||
Ok((doc, warnings))
|
||||
}
|
||||
// Saved without its PDF part: the editing copy is all the file has (`pages` that
|
||||
// name every page read it as the whole file).
|
||||
Err(e) if is_placeholder(&e) => {
|
||||
let whole = LoadOptions { pages: None, ..opts.clone() };
|
||||
from_editing_data_alone(bytes, if every_page(bytes, opts) { &whole } else { opts })
|
||||
.unwrap_or(Err(e))
|
||||
.map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts))
|
||||
.inspect(|_| editing_data = true)
|
||||
}
|
||||
Err(e) if is_placeholder(&e) => opened
|
||||
.as_ref()
|
||||
.ok()
|
||||
.and_then(|o| from_editing_data_alone(o, opts))
|
||||
.unwrap_or(Err(e))
|
||||
.map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts))
|
||||
.inspect(|_| editing_data = true),
|
||||
// A PDF part that can't be read (a stream the import refuses): the editing copy
|
||||
// alone where it reads, else the error.
|
||||
Err(e) => without_pdf_part(bytes, opts, &e).inspect(|_| editing_data = true).ok_or(e),
|
||||
})?
|
||||
})?;
|
||||
// The File Info of a file read from its pages or its editing copy.
|
||||
if !read.2 {
|
||||
file_info = opened.as_ref().ok().map(|o| o.file_info());
|
||||
}
|
||||
read
|
||||
}
|
||||
"dxf" => {
|
||||
let (doc, warnings) = super::dxfimport::import(bytes, &opts.dxf)?;
|
||||
@@ -394,7 +427,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
// it carries, opens with the File Info it gives (a PostScript `.ai` gives none).
|
||||
if matches!(format.id, "pdf" | "ai" | "ait")
|
||||
&& !restored
|
||||
&& let Some(info) = vectorcraft_pdf::file_info(bytes, opts.password.as_deref())
|
||||
&& let Some(info) = file_info
|
||||
{
|
||||
super::super::fileinfo::read_pdf(&mut doc.metadata, info);
|
||||
}
|
||||
|
||||
@@ -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"] {
|
||||
|
||||
@@ -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,
|
||||
@@ -99,6 +105,12 @@ pub const AI_OPTIONS: &[FormatOption] = &[
|
||||
default: "true",
|
||||
description: "compress the PDF's content and the native document it carries (the PDF option compression.compressText)",
|
||||
},
|
||||
FormatOption {
|
||||
name: "editingData",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, paths, fills and strokes, colors, swatches and artboards, with type, gradients, patterns, images, symbols, clipping and live objects as plain filled and stroked paths, without transparency (written only with every artboard, as Preserve Editing is)",
|
||||
},
|
||||
FormatOption {
|
||||
name: "aiVersion",
|
||||
ty: "string",
|
||||
@@ -131,6 +143,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 +164,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 +174,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 +205,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 +231,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 +278,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");
|
||||
}
|
||||
|
||||
@@ -263,7 +263,7 @@ pub const EDITING_NEEDS_EVERY_ARTBOARD: &str =
|
||||
pub fn encode(cmd: &str, doc: &Document, p: &Value) -> Result<(Vec<u8>, Vec<String>)> {
|
||||
// Keep the editable object tree independent of preview fallbacks used by the drawn pages.
|
||||
let (full, mut warnings) = crate::cmd::place::document::full_documents(doc);
|
||||
let (bytes, drawn_warnings) = encode_carrying(cmd, &full, p, || Ok(vectorcraft_format::save(doc, false)))?;
|
||||
let (bytes, drawn_warnings) = encode_carrying(cmd, &full, p, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?;
|
||||
warnings.extend(drawn_warnings);
|
||||
warnings.extend(overflow_warning(cmd, &full, p)?);
|
||||
Ok((bytes, warnings))
|
||||
@@ -281,8 +281,15 @@ fn overflow_warning(cmd: &str, doc: &Document, p: &Value) -> Result<Option<Strin
|
||||
}
|
||||
|
||||
/// [`encode`] the pages of `doc`, carrying `native()` as the editing data (a `.ai` file: the
|
||||
/// native document with its save options, whose pages may be left blank).
|
||||
pub(super) fn encode_carrying(cmd: &str, doc: &Document, p: &Value, native: impl FnOnce() -> Result<Vec<u8>>) -> Result<(Vec<u8>, Vec<String>)> {
|
||||
/// native document with its save options, whose pages may be left blank), and `private()`, the
|
||||
/// editing copy of the art for other apps with what it couldn't hold, on every page.
|
||||
pub(super) fn encode_carrying(
|
||||
cmd: &str,
|
||||
doc: &Document,
|
||||
p: &Value,
|
||||
native: impl FnOnce() -> Result<Vec<u8>>,
|
||||
private: impl FnOnce() -> Result<Option<(vectorcraft_pdf::PrivateData, Vec<String>)>>,
|
||||
) -> Result<(Vec<u8>, Vec<String>)> {
|
||||
let mut opts = options(cmd, doc, p)?;
|
||||
// The pages' background colors, behind the art (the editing data keeps them as colors).
|
||||
let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect());
|
||||
@@ -295,6 +302,10 @@ pub(super) fn encode_carrying(cmd: &str, doc: &Document, p: &Value, native: impl
|
||||
if opts.settings.preserve_editing {
|
||||
if opts.artboards.as_ref().is_none_or(|v| v.iter().copied().eq(0..doc.artboards.len())) {
|
||||
opts.native = Some(native()?);
|
||||
if let Some((data, lost)) = private()? {
|
||||
opts.private_data = Some(data);
|
||||
warnings.extend(lost);
|
||||
}
|
||||
} else {
|
||||
opts.settings.preserve_editing = false;
|
||||
warnings.push(EDITING_NEEDS_EVERY_ARTBOARD.to_string());
|
||||
|
||||
@@ -39,6 +39,9 @@ pub struct LoadOptions {
|
||||
/// A `.ai` opens from its editing copy even where that draws differently from its PDF part
|
||||
/// (which can be older than it), with a warning, instead of from the PDF part.
|
||||
pub trust_editing_data: bool,
|
||||
/// A PDF or `.ai` saved with Preserve Editing opens from the VectorCraft document it carries;
|
||||
/// off, it opens as another app would open it, from the editing copy of its art or its pages.
|
||||
pub native: bool,
|
||||
}
|
||||
|
||||
impl Default for LoadOptions {
|
||||
@@ -54,6 +57,7 @@ impl Default for LoadOptions {
|
||||
dxf: Default::default(),
|
||||
editing_data: true,
|
||||
trust_editing_data: false,
|
||||
native: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,28 +95,25 @@ impl LoadOptions {
|
||||
Some(v) => (v.as_bool().ok_or_else(|| bad(cmd, "editingData must be true, false or \"always\""))?, false),
|
||||
};
|
||||
let dxf = super::dxfimport::options(cmd, p.get("dxf"))?;
|
||||
Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data, trust_editing_data })
|
||||
Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data, trust_editing_data, native: true })
|
||||
}
|
||||
|
||||
/// Does the document read only part of the file, or read it differently (a page range, another
|
||||
/// box, a password, without its hidden layers)? Writing it back would lose the rest, so Save
|
||||
/// doesn't (it asks for a name).
|
||||
/// box, a password, without its hidden layers, without the VectorCraft document it carries)?
|
||||
/// Writing it back would lose the rest, so Save doesn't (it asks for a name).
|
||||
pub fn is_partial(&self) -> bool {
|
||||
self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers
|
||||
self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native
|
||||
}
|
||||
|
||||
/// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible
|
||||
/// `.ai`, or a PDF saved with its editing data, asked for its crop box opens on its trim boxes,
|
||||
/// its editor's artboards, with the bleed round them (its crop box takes the bleed in).
|
||||
fn import_options(&self, bytes: &[u8], editor_document: bool) -> Result<ImportOptions> {
|
||||
fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result<ImportOptions> {
|
||||
let pages = match &self.pages {
|
||||
None => None,
|
||||
Some(range) => {
|
||||
let count = vectorcraft_pdf::info(bytes, self.password.as_deref()).map_err(err)?.pages.len();
|
||||
Some(parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?)
|
||||
}
|
||||
Some(range) => Some(parse_range(range, opened.page_count()).map_err(|e| err(format!("pages: {e}")))?),
|
||||
};
|
||||
let is_ai = self.crop == CropTo::Crop && vectorcraft_pdf::has_illustrator_data(bytes, self.password.as_deref());
|
||||
let is_ai = self.crop == CropTo::Crop && opened.has_illustrator_data();
|
||||
Ok(ImportOptions {
|
||||
pages,
|
||||
crop: if is_ai { CropTo::Trim } else { self.crop },
|
||||
@@ -136,24 +137,33 @@ fn choice<T: Choice + Default>(cmd: &str, key: &str, id: Option<&str>) -> Result
|
||||
.ok_or_else(|| bad(cmd, format!("{key} must be one of {}", T::IDS.join(", "))))
|
||||
}
|
||||
|
||||
/// Import the pages `o` pick → the document, import notes and what else the import tells.
|
||||
/// Import the pages `o` pick of `opened`, the PDF `bytes` already read
|
||||
/// ([`vectorcraft_pdf::open_pdf`]) → the document, import notes and what else the import tells.
|
||||
/// `editor_document`: a `.ai` file.
|
||||
pub(super) fn import(bytes: &[u8], o: &LoadOptions, editor_document: bool) -> Result<vectorcraft_pdf::ImportReport> {
|
||||
vectorcraft_pdf::import_with_report(bytes, &o.import_options(bytes, editor_document)?).map_err(err)
|
||||
pub(super) fn import(
|
||||
bytes: &[u8],
|
||||
opened: &vectorcraft_pdf::Opened,
|
||||
o: &LoadOptions,
|
||||
editor_document: bool,
|
||||
) -> Result<vectorcraft_pdf::ImportReport> {
|
||||
let options = o.import_options(opened, editor_document)?;
|
||||
vectorcraft_pdf::import_opened(bytes, opened, &options).map_err(err)
|
||||
}
|
||||
|
||||
/// Page `page` (0-based) of a PDF as a document of one artboard (its `o.crop` box) and one
|
||||
/// layer of what it shows, with the same text choice as Open, and the import notes.
|
||||
pub fn page_document(bytes: &[u8], page: usize, o: &LoadOptions) -> Result<(Document, Vec<String>)> {
|
||||
let opts = ImportOptions {
|
||||
pages: Some(vec![page]),
|
||||
crop: o.crop,
|
||||
password: o.password.clone(),
|
||||
text_as: o.text_as,
|
||||
layers: false,
|
||||
..Default::default()
|
||||
};
|
||||
vectorcraft_pdf::import_with_report(bytes, &opts).map(|r| (r.document, r.warnings)).map_err(err)
|
||||
vectorcraft_pdf::import_with_report(bytes, &page_options(page, o)).map(|r| (r.document, r.warnings)).map_err(err)
|
||||
}
|
||||
|
||||
/// [`page_document`] of `opened`, the PDF `bytes` already read.
|
||||
fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opened, page: usize, o: &LoadOptions) -> Result<(Document, Vec<String>)> {
|
||||
vectorcraft_pdf::import_opened(bytes, opened, &page_options(page, o)).map(|r| (r.document, r.warnings)).map_err(err)
|
||||
}
|
||||
|
||||
/// The import options of [`page_document`].
|
||||
fn page_options(page: usize, o: &LoadOptions) -> ImportOptions {
|
||||
ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() }
|
||||
}
|
||||
|
||||
const INFO: &str = "document.pdfInfo";
|
||||
@@ -166,13 +176,15 @@ pub(super) fn pdf_info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
if bytes.starts_with(b"%!") || vectorcraft_pdf::is_postscript(&bytes) {
|
||||
return postscript_info(&bytes, p);
|
||||
}
|
||||
let info = match vectorcraft_pdf::info(&bytes, o.password.as_deref()) {
|
||||
Ok(i) => i,
|
||||
// The file is read once, for its pages and the thumbnail.
|
||||
let opened = match vectorcraft_pdf::open_pdf(&bytes, o.password.as_deref()) {
|
||||
Ok(opened) => opened,
|
||||
Err(e @ (PdfError::NeedsPassword | PdfError::WrongPassword)) => {
|
||||
return Ok(json!({"pages": 0, "needsPassword": true, "wrongPassword": e == PdfError::WrongPassword, "pageInfo": []}));
|
||||
}
|
||||
Err(e) => return Err(err(e)),
|
||||
};
|
||||
let info = opened.info();
|
||||
let r4 = |r: vectorcraft_geom::Rect| json!([r.x0, r.y0, r.x1, r.y1]);
|
||||
let pages: Vec<Value> = info
|
||||
.pages
|
||||
@@ -184,7 +196,7 @@ pub(super) fn pdf_info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
.collect();
|
||||
let mut out = json!({"pages": pages.len(), "needsPassword": false, "pageInfo": pages});
|
||||
if let Some(page) = thumbnail_page(p, info.pages.len(), "PDF")? {
|
||||
let (doc, _) = page_document(&bytes, page, &o)?;
|
||||
let (doc, _) = opened_page_document(&bytes, &opened, page, &o)?;
|
||||
out["thumbnail"] = json!(thumbnail(&doc, p)?);
|
||||
}
|
||||
Ok(out)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -248,11 +249,6 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
|
||||
if let Some((key, top, inner)) = disagreeing_option(p, is_svg(format)).map_err(|e| bad(cmd, e))? {
|
||||
return Err(bad(cmd, format!("`{key}: {top}` and `options.{key}: {inner}` disagree: give the option once")));
|
||||
}
|
||||
let notes = NATIVE_OPTIONS
|
||||
.iter()
|
||||
.filter(|k| p.get(**k).is_some_and(|v| !v.is_null()) && !reads_option(format, k))
|
||||
.map(|k| format!("`{k}` was not used: {} files don't read it", format.label))
|
||||
.collect();
|
||||
let mut given: Map<String, Value> = match p.get("options") {
|
||||
Some(Value::Object(o)) => o.iter().filter(|(k, _)| reads_option(format, k)).map(|(k, v)| (k.clone(), v.clone())).collect(),
|
||||
None | Some(Value::Null) => Map::new(),
|
||||
@@ -265,7 +261,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())),
|
||||
@@ -292,11 +288,17 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
|
||||
if let Some(path) = &path {
|
||||
super::check_not_lossy_overwrite(st, path, p, cmd)?;
|
||||
}
|
||||
let written = written_as(cmd, format, &Value::Object(options.clone()));
|
||||
let notes = NATIVE_OPTIONS
|
||||
.iter()
|
||||
.filter(|k| p.get(**k).is_some_and(|v| !v.is_null()) && !reads_option(format, k))
|
||||
.map(|k| format!("`{k}` was not used: {} files don't read it", written.label))
|
||||
.collect();
|
||||
Ok(SavePlan { mode, path, format, options, name, folder, modified, notes })
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -574,6 +576,28 @@ fn blank_pages(doc: &Document) -> Document {
|
||||
|
||||
/// Why a `.ai` file saved without PDF content looks empty elsewhere.
|
||||
const NOT_PDF_COMPATIBLE: &str = "saved without PDF content: VectorCraft opens it as before, other apps show empty pages";
|
||||
/// The same, for a file that carries the editing copy of its art.
|
||||
const NOT_PDF_COMPATIBLE_EDITING: &str =
|
||||
"saved without PDF content: VectorCraft and apps that read its editing data open it, other apps show empty pages";
|
||||
|
||||
/// `f` (`.ai` or `.ait`) named, in its option errors, as a file saved without PDF content.
|
||||
fn without_pdf(f: &Format) -> Format {
|
||||
let label = if f.id == "ait" { "non-PDF-compatible .ait template" } else { "non-PDF-compatible .ai" };
|
||||
Format { label, ..*f }
|
||||
}
|
||||
|
||||
/// `f` named, in its errors and notes, as the file a save with options `p` writes: a version 7
|
||||
/// `.ai` as the legacy `.ai`, and a `.ai` or `.ait` with `pdfCompatible: false` as one saved
|
||||
/// without PDF content.
|
||||
fn written_as(cmd: &str, f: &Format, p: &Value) -> Format {
|
||||
if f.id == "ai" && super::legacy_ai::wanted(cmd, f, p).unwrap_or(false) {
|
||||
super::legacy_ai::named(f)
|
||||
} else if matches!(f.id, "ai" | "ait") && !bool_or(p, "pdfCompatible", true) {
|
||||
without_pdf(f)
|
||||
} else {
|
||||
*f
|
||||
}
|
||||
}
|
||||
|
||||
/// `e`, an error of the export encoders, under the save command `cmd` instead of
|
||||
/// `document.export`.
|
||||
@@ -584,8 +608,39 @@ fn named_for_save(cmd: &str, e: crate::EngineError) -> crate::EngineError {
|
||||
}
|
||||
}
|
||||
|
||||
/// The shared Save and Export encoder for PDF-compatible `.ai` files (and `.ait` templates, the
|
||||
/// same file).
|
||||
/// Refuse the artboards a `.ai` or `.ait` save is given (`artboard`, `artboards`, or a `range`
|
||||
/// that isn't empty) when one of them is not in `doc`, with the error an export gives. The save
|
||||
/// then writes every artboard, or a legacy `.ai` file's `range`, whatever `artboard` and
|
||||
/// `artboards` name. An empty `artboards` list is not refused: the save writes every artboard.
|
||||
fn named_artboards_exist(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<()> {
|
||||
let n = doc.artboards.len();
|
||||
// The encoders refuse a document without artboards themselves.
|
||||
if n == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
// The encoders refuse a value of the wrong type themselves, each with its own label.
|
||||
let Ok(mut picked) = super::encode::options::<ArtboardPick>(&written_as(cmd, f, p), p) else {
|
||||
return Ok(());
|
||||
};
|
||||
picked.range = picked.range.filter(|r| !r.trim().is_empty());
|
||||
if picked.range.is_none() && picked.artboards.as_ref().is_some_and(Vec::is_empty) {
|
||||
return Ok(());
|
||||
}
|
||||
picked.resolve(n).map_err(|e| bad(cmd, e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The `.ai` option `editingData`: whether the file also carries the editing copy of the art that
|
||||
/// other apps read (default on).
|
||||
#[derive(Default, serde::Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
struct AiEditingData {
|
||||
editing_data: Option<bool>,
|
||||
}
|
||||
|
||||
/// The shared Save and Export encoder for `.ai` files (and `.ait` templates, the same file):
|
||||
/// PDF-compatible by default, without PDF content (`pdfCompatible: false`), or legacy version 7
|
||||
/// `.ai` files (`aiVersion: "7"`).
|
||||
pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<Encoded> {
|
||||
if super::legacy_ai::wanted(cmd, f, p)? {
|
||||
return super::legacy_ai::encode(cmd, f, doc, p);
|
||||
@@ -604,8 +659,9 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
|
||||
}
|
||||
}
|
||||
}
|
||||
let native_options = super::native::ai_options(cmd, f, doc, ¶ms)?;
|
||||
let pdf_compatible = bool_or(¶ms, "pdfCompatible", true);
|
||||
let f = &if pdf_compatible { *f } else { without_pdf(f) };
|
||||
let native_options = super::native::ai_options(cmd, f, doc, ¶ms)?;
|
||||
if !pdf_compatible {
|
||||
let picked: ArtboardPick = super::encode::options(f, ¶ms)?;
|
||||
let picked = picked.resolve(doc.artboards.len()).map_err(|e| bad(cmd, e))?;
|
||||
@@ -613,16 +669,46 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
|
||||
return Err(bad(cmd, "pdfCompatible: false needs every artboard to keep the editable artwork"));
|
||||
}
|
||||
}
|
||||
let pages = doc.without_edit_modes();
|
||||
let edited = doc.without_edit_modes();
|
||||
// Resolve placed files only for the drawn pages. Missing files become preview images there;
|
||||
// the native attachment keeps the original placed objects and their relinkable metadata.
|
||||
let (pages, placed_warnings) =
|
||||
if pdf_compatible { crate::cmd::place::document::full_documents(&pages) } else { (std::borrow::Cow::Owned(blank_pages(&pages)), Vec::new()) };
|
||||
let (pages, placed_warnings) = if pdf_compatible {
|
||||
crate::cmd::place::document::full_documents(&edited)
|
||||
} else {
|
||||
(std::borrow::Cow::Owned(blank_pages(&edited)), Vec::new())
|
||||
};
|
||||
let native = || super::native::ai_native(cmd, doc, &native_options);
|
||||
let (bytes, mut warnings) = super::pdf::encode_carrying(cmd, &pages, ¶ms, native)?;
|
||||
let other_apps: AiEditingData = super::encode::options(f, ¶ms)?;
|
||||
let carries_editing = std::cell::Cell::new(false);
|
||||
let private = || {
|
||||
if !other_apps.editing_data.unwrap_or(true) {
|
||||
return Ok(None);
|
||||
}
|
||||
// The art with placed files resolved as the pages draw them, also when the pages are blank.
|
||||
let resolved;
|
||||
let (art, mut resolved_warnings): (&Document, Vec<String>) = if pdf_compatible {
|
||||
(&pages, Vec::new())
|
||||
} else {
|
||||
let (d, w) = crate::cmd::place::document::full_documents(&edited);
|
||||
resolved = d;
|
||||
(&resolved, w)
|
||||
};
|
||||
// With the artboards' background colors, as the pages draw them.
|
||||
let art = super::export::with_artboard_fills(art, ¶ms, 0..art.artboards.len()).map_err(|e| bad(cmd, e))?;
|
||||
let o = vectorcraft_eps::AiEditingOptions {
|
||||
title: doc.title.clone(),
|
||||
created: doc.metadata.created.or_else(vectorcraft_doc::metadata::output_time),
|
||||
};
|
||||
let (data, lost) = vectorcraft_eps::ai_private_data(&art, &o).map_err(|e| bad(cmd, e))?;
|
||||
// Placed files that weren't found are written as their previews here too.
|
||||
resolved_warnings.extend(lost);
|
||||
carries_editing.set(true);
|
||||
Ok(Some((data, resolved_warnings)))
|
||||
};
|
||||
let (bytes, mut warnings) = super::pdf::encode_carrying(cmd, &pages, ¶ms, native, private)?;
|
||||
warnings.extend(placed_warnings);
|
||||
if !pdf_compatible {
|
||||
warnings.push(NOT_PDF_COMPATIBLE.to_string());
|
||||
warnings.push(if carries_editing.get() { NOT_PDF_COMPATIBLE_EDITING } else { NOT_PDF_COMPATIBLE }.to_string());
|
||||
}
|
||||
Ok(Encoded { warnings, ..Encoded::one(bytes) })
|
||||
}
|
||||
@@ -672,11 +758,16 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
let boards = separate_boards(cmd, plan.format, &doc, ¶ms)?;
|
||||
let mut params = super::pdf::expand_preset(s, cmd, ¶ms)?.into_owned();
|
||||
let legacy = super::legacy_ai::wanted(cmd, plan.format, ¶ms)?;
|
||||
if matches!(plan.format.id, "ai" | "ait") {
|
||||
named_artboards_exist(cmd, plan.format, &doc, ¶ms)?;
|
||||
}
|
||||
if let (Some(o), "ai" | "ait") = (params.as_object_mut(), plan.format.id) {
|
||||
// Save keeps every artboard; exports may choose a subset instead. A legacy .ai file per
|
||||
// artboard keeps a range given: the artboards to save.
|
||||
let chosen = legacy && plan.format.id == "ai" && o.get("range").and_then(Value::as_str).is_some_and(|r| !r.trim().is_empty());
|
||||
if !chosen {
|
||||
// A `range` that isn't text is left for the encoder to refuse, as an export refuses it.
|
||||
let text = o.get("range").is_none_or(|r| r.is_string() || r.is_null());
|
||||
if !chosen && text {
|
||||
o.insert("range".into(), json!("all"));
|
||||
}
|
||||
}
|
||||
@@ -839,6 +930,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 +962,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 +1057,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 +1066,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 +1075,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 +1084,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 +1165,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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -82,6 +82,25 @@ fn an_illustrator_ai_file_opens_from_its_editing_data() {
|
||||
assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art", "Hidden"]);
|
||||
}
|
||||
|
||||
/// Opening a `.ai` or a PDF whose PDF part reads, or a `.ai` saved without PDF compatibility,
|
||||
/// reads and checks the file once, on any thread, for the document it may carry, its pages, its
|
||||
/// editing data and its File Info, with pages picked or not.
|
||||
#[test]
|
||||
fn an_ai_or_pdf_file_is_read_once_when_it_opens() {
|
||||
let ai_file = ai::ai(&compressed(&ai::sample_data()), ai::page_pdf());
|
||||
let pdf_file = pdf_with(&[PdfPage::new(100.0, 100.0, "0 0 1 rg 10 10 50 50 re f")], &[], None);
|
||||
let placeholder = ai::ai(&compressed(&ai::sample_data()), PLACEHOLDER);
|
||||
for (name, file) in [("art.ai", &ai_file), ("art.pdf", &pdf_file), ("placeholder.ai", &placeholder)] {
|
||||
for opts in [LoadOptions::default(), LoadOptions { pages: Some("1".into()), ..Default::default() }] {
|
||||
let before = vectorcraft_pdf::reads_of(file);
|
||||
let loaded = load_with(name, file, &opts).unwrap();
|
||||
assert_eq!(vectorcraft_pdf::reads_of(file) - before, 1, "{name}, pages {:?}", opts.pages);
|
||||
let editing_data = name == "placeholder.ai" || (name == "art.ai" && opts.pages.is_none());
|
||||
assert_eq!(loaded.editing_data, editing_data, "{name}, pages {:?}", opts.pages);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ai_file_opens_with_its_artboard_options_raster_settings_and_author() {
|
||||
let document = "%_/Document :\n%_/Dictionary :\n%_/Dictionary :\n%_150 /Int (dpi.) ,\n%_1 /Bool (mask) ,\n%_; (AI Auto Rasterize) ,\n\
|
||||
@@ -127,6 +146,45 @@ fn an_ai_unread_group_keeps_its_layers_and_live_neighbor() {
|
||||
assert!(result["warnings"].to_string().contains("`ZZ` (1)"), "{result}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_differing_object_keeps_the_layers_with_a_note() {
|
||||
let square = |cmyk: &str, x: f64| format!("{cmyk} k\n{}f\n", ai::rect(x, 40.0, x + 16.0, 56.0));
|
||||
let front = square("0 0 0 1", 90.0) + &square("0 0 1 0", 160.0);
|
||||
let data = ai::editing_data(200.0, 100.0, &(ai::layer("Back", &square("0 0 1 0", 20.0)) + &ai::layer("Front", &front)));
|
||||
let page = "0 0 1 0 k 20 40 16 16 re f 1 0 0 0 k 90 40 16 16 re f 0 0 1 0 k 160 40 16 16 re f";
|
||||
let mut session = Session::new();
|
||||
let result = open(&mut session, "differs.ai", &ai::ai(&compressed(data.as_bytes()), page), json!({})).unwrap();
|
||||
let doc = &session.doc().unwrap().doc;
|
||||
assert_eq!(names(&doc.layers), ["Back", "Front"], "{result}");
|
||||
let front = doc.layers[1].children().unwrap();
|
||||
assert!(matches!(front[0].kind, NodeKind::Group { .. }) && matches!(front[1].kind, NodeKind::Path { .. }), "{result}");
|
||||
let replacement = &front[0].children().unwrap()[0];
|
||||
assert!(
|
||||
matches!(replacement.appearance.items.first(), Some(vectorcraft_doc::AppearanceItem::Fill(fill))
|
||||
if fill.paint == vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(1.0, 0.0, 0.0, 0.0))),
|
||||
"{result}"
|
||||
);
|
||||
assert!(
|
||||
result["warnings"].to_string().contains("objects that drew differently from the file's own page came in as its art: Front (1)"),
|
||||
"{result}"
|
||||
);
|
||||
// An export to the file's own path is refused unless it is given `acknowledgeLoss`.
|
||||
let d = std::env::temp_dir().join(format!("vc-aidiffers-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let path = d.join("differs.ai");
|
||||
let file = ai::ai(&compressed(data.as_bytes()), page);
|
||||
std::fs::write(&path, &file).unwrap();
|
||||
let path = path.to_string_lossy().to_string();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
let e = s.execute("document.export", &json!({"path": path})).unwrap_err().to_string();
|
||||
assert!(e.contains("left things out") && e.contains("objects that drew differently"), "{e}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), file);
|
||||
s.execute("document.export", &json!({"path": path, "acknowledgeLoss": true})).unwrap();
|
||||
assert_ne!(std::fs::read(&path).unwrap(), file);
|
||||
std::fs::remove_dir_all(d).ok();
|
||||
}
|
||||
|
||||
/// A palette of three swatches and a color group `Inks` holding a fourth.
|
||||
const INKS_PALETTE: &str = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\n0.04 0.3 0 0 81.96 21 -8 (Pink ink) 0 2 Xx\n(Pink ink)\nPc\n\
|
||||
0.06 0.98 1 0 (Red ink) 0 x\n(Red ink)\nPc\n1 (Inks) 1 Pg\n0.02 0.1 1 0 (Yellow ink) 0 x\n(Yellow ink)\nPc\nPB\n%AI5_EndPalette\n";
|
||||
@@ -617,21 +675,25 @@ fn what_the_reader_doesnt_read_opens_as_before_with_a_warning() {
|
||||
/// A `.ai` whose document data has a variable library opens with its variables, data sets, active
|
||||
/// data set and lock, whether its layers are read or it comes in as its PDF part: `variable.list`
|
||||
/// and `dataset.list` report them. A variable of unknown kind can't be bound. What of the library
|
||||
/// can't be read is noted.
|
||||
/// can't be read is noted. With its layers read, the object a variable is bound to comes in bound,
|
||||
/// and selecting a data set changes it; the bindings to objects the file doesn't have are noted.
|
||||
#[test]
|
||||
fn an_ai_file_opens_its_variable_library() {
|
||||
let library = ai::variable_library_data(&ai::sample_variable_sets("variableAndTypes", &[]));
|
||||
let square = format!("0 1 1 0 1 0 0 Xa\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0));
|
||||
let square = format!("0 1 1 0 1 0 0 Xa\n{}f\n{}", ai::rect(10.0, 50.0, 40.0, 90.0), ai::named("path_x5F_1"));
|
||||
let notes = |r: &Value| {
|
||||
r["warnings"].as_array().map_or(vec![], |w| w.iter().filter(|w| w.as_str().unwrap().contains("variable")).cloned().collect::<Vec<_>>())
|
||||
};
|
||||
let check = |s: &mut Session| {
|
||||
let skipped = |n: usize| {
|
||||
json!(format!("the file's variable bindings weren't all read (bindings skipped: {n}): those objects aren't bound to their variables"))
|
||||
};
|
||||
let check = |s: &mut Session, bound: usize| {
|
||||
let r = s.execute("variable.list", &json!({})).unwrap();
|
||||
assert_eq!(
|
||||
r,
|
||||
json!({"variables": [
|
||||
{"name": "v_text", "kind": "text", "bindings": 0},
|
||||
{"name": "v_visible", "kind": "visibility", "bindings": 0},
|
||||
{"name": "v_visible", "kind": "visibility", "bindings": bound},
|
||||
{"name": "v_file", "kind": "image", "bindings": 0},
|
||||
{"name": "v_graph", "kind": "graph", "bindings": 0},
|
||||
{"name": "v_unbound", "kind": "unknown", "bindings": 0},
|
||||
@@ -651,23 +713,34 @@ fn an_ai_file_opens_its_variable_library() {
|
||||
let file = ai::ai(&compressed(layered.as_bytes()), "1 0 0 rg 10 50 30 40 re f");
|
||||
let r = open(&mut s, "variables.ai", &file, json!({})).unwrap();
|
||||
assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}");
|
||||
assert!(notes(&r).is_empty(), "{r}");
|
||||
check(&mut s);
|
||||
let id = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0;
|
||||
let e = s.execute("variable.bind", &json!({"variable": "v_unbound", "ids": [id]})).unwrap_err();
|
||||
// The library's text and image variables are bound to objects the file doesn't have.
|
||||
assert_eq!(notes(&r), [skipped(2)], "{r}");
|
||||
check(&mut s, 1);
|
||||
let id = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id;
|
||||
assert_eq!(s.doc().unwrap().doc.variables.objects_of("v_visible"), [id]);
|
||||
s.execute("dataset.select", &json!({"name": "ds_two"})).unwrap();
|
||||
assert!(!s.doc().unwrap().doc.node(id).unwrap().visible, "ds_two hides the square");
|
||||
s.execute("dataset.select", &json!({"name": "ds_one"})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(id).unwrap().visible, "ds_one shows it");
|
||||
let e = s.execute("variable.bind", &json!({"variable": "v_unbound", "ids": [id.0]})).unwrap_err();
|
||||
assert!(e.to_string().contains("a variable of unknown kind can't be bound to objects"), "{e}");
|
||||
// Its layers can't be read (a symbol): it comes in as its PDF part, with the library.
|
||||
// Its layers can't be read (a symbol): it comes in as its PDF part, with the library and none
|
||||
// of its bindings.
|
||||
let symbols = ai::editing_data(200.0, 100.0, &format!("{library}{}", ai::layer("Art", "/SymbolInstance :\n(Dot) /SymbolRef ,\n;\n")));
|
||||
let r = open(&mut s, "symbols.ai", &ai::ai(&compressed(symbols.as_bytes()), ai::page_pdf()), json!({})).unwrap();
|
||||
assert!(r["warnings"].to_string().contains("PDF part"), "{r}");
|
||||
assert!(notes(&r).is_empty(), "{r}");
|
||||
check(&mut s);
|
||||
assert_eq!(notes(&r), [skipped(3)], "{r}");
|
||||
check(&mut s, 0);
|
||||
// A graph value isn't read: the note says how many entries were left out.
|
||||
let graph = ai::xml_element("v_graph", &[], &[ai::xml_text(ai::XmlValue::Str("a,b"))]);
|
||||
let partly = ai::variable_library_data(&ai::sample_variable_sets("none", &[graph]));
|
||||
let layered = ai::editing_data(200.0, 100.0, &format!("{partly}{}", ai::layer("Art", &square)));
|
||||
let r = open(&mut s, "graph.ai", &ai::ai(&compressed(layered.as_bytes()), "1 0 0 rg 10 50 30 40 re f"), json!({})).unwrap();
|
||||
assert_eq!(notes(&r), [json!("the file's variable library was partly read (entries skipped: 1): the Variables panel lists the rest")], "{r}");
|
||||
assert_eq!(
|
||||
notes(&r),
|
||||
[json!("the file's variable library was partly read (entries skipped: 1): the Variables panel lists the rest"), skipped(2)],
|
||||
"{r}"
|
||||
);
|
||||
// Without a library, no note and no variables.
|
||||
let plain = ai::editing_data(200.0, 100.0, &ai::layer("Art", &square));
|
||||
let r = open(&mut s, "plain.ai", &ai::ai(&compressed(plain.as_bytes()), "1 0 0 rg 10 50 30 40 re f"), json!({})).unwrap();
|
||||
|
||||
@@ -97,6 +97,18 @@ fn pdf_and_svg_show_the_color_and_their_editing_data_keeps_it_as_the_artboards()
|
||||
assert_eq!(back.layers.len(), doc.layers.len(), "no art made of it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ai_editing_copy_for_other_apps_draws_the_color_as_the_pages_do() {
|
||||
let mut s = session();
|
||||
let opts = LoadOptions { native: false, ..Default::default() };
|
||||
for (more, fill) in [(json!({}), true), (json!({"includeArtboardFill": false}), false)] {
|
||||
let l = load::load_with("a.ai", &file(&mut s, with(json!({"format": "ai"}), &more)), &opts).unwrap();
|
||||
assert!(l.editing_data && !l.restored, "{more}: {:?}", l.warnings);
|
||||
let names: Vec<String> = l.doc.layers.iter().filter_map(|l| l.name.clone()).collect();
|
||||
assert_eq!(names.iter().any(|n| n == "Artboard Fill"), fill, "{more}: {names:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eps_and_postscript_print_draw_the_color() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -403,3 +403,77 @@ fn ai_export_without_artboards_keeps_art_outside_the_original_pages() {
|
||||
assert_eq!(comparable(&s.doc().unwrap().doc), before);
|
||||
assert!(s.execute("document.export", &json!({"format": "ai", "useArtboards": "yes"})).is_err());
|
||||
}
|
||||
|
||||
/// The layers of `doc` as their names and the kinds and bounds of what they hold, rounded.
|
||||
fn outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
|
||||
fn walk(nodes: &[std::sync::Arc<vectorcraft_doc::Node>], depth: usize, out: &mut Vec<String>) {
|
||||
for n in nodes {
|
||||
let b = n.visual_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64));
|
||||
let kind = match &n.kind {
|
||||
vectorcraft_doc::NodeKind::Layer { .. } => "layer",
|
||||
vectorcraft_doc::NodeKind::Group { .. } => "group",
|
||||
vectorcraft_doc::NodeKind::Path { .. } => "path",
|
||||
_ => "other",
|
||||
};
|
||||
out.push(format!("{depth} {kind} {:?} {} {b:?}", n.name, n.visible));
|
||||
walk(n.children().map(Vec::as_slice).unwrap_or_default(), depth + 1, out);
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
walk(&doc.layers, 0, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// A `.ai` also carries the editing copy of its art that other apps read: opened without the
|
||||
/// VectorCraft document it carries, it gives back the same layers, groups and paths, its page
|
||||
/// matching them. `editingData: false` leaves the copy out.
|
||||
#[test]
|
||||
fn ai_files_carry_an_editing_copy_for_other_apps() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap();
|
||||
s.execute("shape.ellipse", &json!({"x": 60, "y": 10, "width": 50, "height": 30})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("layer.new", &json!({"name": "Top"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 120, "y": 50, "width": 60, "height": 40})).unwrap();
|
||||
let before = outline(&s.doc().unwrap().doc);
|
||||
let bytes = b64(&s.execute("document.export", &json!({"format": "ai"})).unwrap());
|
||||
let private = vectorcraft_pdf::illustrator_data(&bytes, None).expect("the editing copy for other apps");
|
||||
assert!(private.starts_with(b"%AI24_ZStandard_Data"));
|
||||
let opts = LoadOptions { native: false, ..Default::default() };
|
||||
let l = load::load_with("art.ai", &bytes, &opts).unwrap();
|
||||
assert!(l.editing_data && !l.restored);
|
||||
assert!(!l.warnings.iter().any(|w| w.contains("editing data")), "{:?}", l.warnings);
|
||||
assert_eq!(outline(&l.doc), before);
|
||||
let r = s.execute("document.export", &json!({"format": "ai", "editingData": false})).unwrap();
|
||||
assert_eq!(vectorcraft_pdf::illustrator_data(&b64(&r), None), None);
|
||||
assert!(s.execute("document.export", &json!({"format": "ai", "editingData": "no"})).is_err());
|
||||
}
|
||||
|
||||
/// A `.ai` whose editing copy for other apps differs from the VectorCraft document it carries (the
|
||||
/// copy has no transparency) opens in VectorCraft from the VectorCraft document.
|
||||
#[test]
|
||||
fn an_ai_file_opens_from_its_vectorcraft_document_when_the_editing_copy_differs() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
|
||||
let bytes = b64(&s.execute("document.export", &json!({"format": "ai"})).unwrap());
|
||||
let opacities = |doc: &vectorcraft_doc::Document| {
|
||||
let mut out = vec![];
|
||||
doc.walk(|n| {
|
||||
if matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }) {
|
||||
out.push(n.opacity);
|
||||
}
|
||||
});
|
||||
out
|
||||
};
|
||||
let copy = load::load_with("art.ai", &bytes, &LoadOptions { native: false, trust_editing_data: true, ..Default::default() }).unwrap();
|
||||
assert!(copy.editing_data && !copy.restored);
|
||||
assert_eq!(opacities(©.doc), [1.0]);
|
||||
let opened = load::load_with("art.ai", &bytes, &LoadOptions::default()).unwrap();
|
||||
assert!(opened.restored);
|
||||
assert_eq!(opacities(&opened.doc), [0.5]);
|
||||
}
|
||||
@@ -141,6 +141,8 @@ fn load_options_read_text_and_layers() {
|
||||
assert!(o.is_partial(), "without its hidden layers, Save doesn't write the file back");
|
||||
let d = LoadOptions::default();
|
||||
assert_eq!((d.text_as, d.layers, d.is_partial()), (TextAs::Text, true, false));
|
||||
let n = LoadOptions { native: false, ..Default::default() };
|
||||
assert!(n.is_partial(), "without the document it carries, Save doesn't write the file back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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]]);
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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]
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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(())
|
||||
|
||||
@@ -42,7 +42,7 @@ use data::{fmt_value, parse_csv, to_csv};
|
||||
use generate::generate;
|
||||
#[cfg(test)]
|
||||
use series::default_series_color;
|
||||
pub(crate) use series::{capture_label_styles, capture_series_paints, paint_targets};
|
||||
pub(crate) use series::{capture_label_styles, capture_series_opacity, capture_series_paints, paint_targets};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -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}`")));
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use super::labels::{
|
||||
FILLED_LINE_BUDGET, Gen, Role, SHADOW_BUDGET, SHADOW_OPACITY, blank_label, label_size, label_width, polyline, recolour_text, runs, shadow_of,
|
||||
};
|
||||
use super::markers::{MARKER_BUDGET, marker_cost, marker_designs};
|
||||
use super::series::series_marks;
|
||||
use super::series::{series_marks, with_series_opacity};
|
||||
use super::{
|
||||
Arc, BezPath, Color, Document, GraphKind, GraphSpec, Justify, Node, NodeKind, Paint, PathData, Point, Rect, TickLength, ValueAxisSide, shapes,
|
||||
};
|
||||
@@ -244,7 +244,8 @@ impl<'a> Plot<'a> {
|
||||
if marker_cost(g, &designs) > MARKER_BUDGET {
|
||||
designs.clear();
|
||||
}
|
||||
let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).max(1);
|
||||
// The same dimensions `GraphSpec::cells` reads: raw rows can be longer than the grid they are read through.
|
||||
let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES);
|
||||
let kinds: Vec<GraphKind> = (0..nser).map(|s| g.series_kind(s)).collect();
|
||||
Plot {
|
||||
g,
|
||||
@@ -253,7 +254,7 @@ impl<'a> Plot<'a> {
|
||||
designs,
|
||||
r: g.rect,
|
||||
nser,
|
||||
ncat: g.rows.len().max(1),
|
||||
ncat: g.rows.len().clamp(1, vectorcraft_doc::MAX_GRAPH_CATEGORIES),
|
||||
vs: label_size(&g.label_styles, Role::Value),
|
||||
cs: label_size(&g.label_styles, Role::Category),
|
||||
ls: label_size(&g.label_styles, Role::Legend),
|
||||
@@ -1001,7 +1002,7 @@ impl<'a> Plot<'a> {
|
||||
}
|
||||
}
|
||||
let name = g.series.get(s).cloned().filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series {}", s + 1));
|
||||
let grp = self.b.series(&name, s, items);
|
||||
let grp = self.b.series(&name, s, with_series_opacity(g, s, items));
|
||||
self.b.out.push(grp);
|
||||
}
|
||||
self.b.out.append(&mut self.on_top);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::labels::{Role, label_style};
|
||||
use super::{CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Result, Session, Value, bad};
|
||||
use super::{Arc, CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Result, Session, Value, bad};
|
||||
|
||||
// ---------- generation ----------
|
||||
|
||||
@@ -25,6 +25,31 @@ pub(super) fn series_marks(g: &GraphSpec, i: usize, series_fill: bool, stroke: P
|
||||
(fill, stroke, width)
|
||||
}
|
||||
|
||||
/// The paths directly inside series `i`'s group (`items`) with the series' kept fill and stroke opacity on their
|
||||
/// topmost fill and stroke. Other art, such as a graph design, keeps its own opacity. A value read from a file is
|
||||
/// held to 0..1, and one that is not a number is left out.
|
||||
pub(super) fn with_series_opacity(g: &GraphSpec, i: usize, mut items: Vec<Arc<Node>>) -> Vec<Arc<Node>> {
|
||||
let Some(slot) = g.series_paints.get(i) else { return items };
|
||||
let kept = |o: Option<f32>| o.filter(|o| o.is_finite()).map(|o| o.clamp(0.0, 1.0));
|
||||
let (fill, stroke) = (kept(slot.fill_opacity), kept(slot.stroke_opacity));
|
||||
if fill.is_none() && stroke.is_none() {
|
||||
return items;
|
||||
}
|
||||
for item in &mut items {
|
||||
if !matches!(item.kind, NodeKind::Path { .. }) {
|
||||
continue;
|
||||
}
|
||||
let ap = &mut Arc::make_mut(item).appearance;
|
||||
if let (Some(o), Some(f)) = (fill, ap.fill_mut()) {
|
||||
f.opacity = o;
|
||||
}
|
||||
if let (Some(o), Some(st)) = (stroke, ap.stroke_mut()) {
|
||||
st.opacity = o;
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
/// Where a node inside a graph's generated series art belongs: the graph, the series group and
|
||||
/// the series index stored on that group.
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -119,6 +144,51 @@ pub(crate) fn capture_series_paints(doc: &mut Document, ids: &[NodeId], fill: bo
|
||||
changed
|
||||
}
|
||||
|
||||
/// Copy the opacity of the topmost fill (`true`) or stroke (`false`) of generated series art just edited (`edited`:
|
||||
/// each object with the kind of row) into that series' fill or stroke opacity; art left without a row of that kind
|
||||
/// keeps none. Called inside the same document edit, so both undo together. Returns whether a series' kept opacity
|
||||
/// changed.
|
||||
pub(crate) fn capture_series_opacity(doc: &mut Document, edited: &[(NodeId, bool)]) -> bool {
|
||||
if edited.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let members = series_members(doc);
|
||||
if members.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let captures: Vec<_> = edited
|
||||
.iter()
|
||||
.filter_map(|(id, fill)| {
|
||||
// Only the paths the graph draws again, not the copy of a graph design.
|
||||
let r = members.get(id).filter(|r| doc.parent_of(*id) == Some(r.group))?;
|
||||
let node = doc.node(*id).filter(|n| matches!(n.kind, NodeKind::Path { .. }))?;
|
||||
let opacity = node.appearance.items.iter().rev().find(|it| it.is_fill() == *fill).map_or(1.0, vectorcraft_doc::AppearanceItem::opacity);
|
||||
Some((r.graph, r.index, *fill, (opacity < 1.0).then_some(opacity)))
|
||||
})
|
||||
.collect();
|
||||
let mut changed = false;
|
||||
for (graph, index, fill, kept) in captures {
|
||||
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
|
||||
// A fully opaque row on a series the graph keeps nothing for leaves the graph as it is.
|
||||
if kept.is_none() && spec.series_paints.len() <= index {
|
||||
continue;
|
||||
}
|
||||
let was = spec.series_paints.clone();
|
||||
// `index` is below the graph's series count (`series_members`).
|
||||
if spec.series_paints.len() <= index {
|
||||
spec.series_paints.resize(index + 1, vectorcraft_doc::SeriesPaint::default());
|
||||
}
|
||||
let Some(slot) = spec.series_paints.get_mut(index) else { continue };
|
||||
if fill {
|
||||
slot.fill_opacity = kept;
|
||||
} else {
|
||||
slot.stroke_opacity = kept;
|
||||
}
|
||||
changed |= spec.series_paints != was;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Graph Data › Transpose row/column: categories become series and series categories.
|
||||
pub(super) fn transpose(g: &mut GraphSpec) {
|
||||
let cells = g.cells();
|
||||
|
||||
Loaded 100 of 521 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user