mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 17:05:55 +01:00
Merge remote-tracking branch 'upstream/main' into fix/3260-halftone-radius-pixels
# Conflicts: # crates/doc/src/limits.rs # crates/engine/src/cmd/fileio/tests_pdfedit.rs # crates/format/src/lib.rs # docs/target-app-parity.md
This commit is contained in:
commit
1a1285fecd
428 files changed
+30074
-2532
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/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitDingbats.pfb | BSD-3-Clause | `845c752392b6c914fb989c75a08b7792b88f542d2499042ef2889f8c814a16ed` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixed.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitFixed.pfb | BSD-3-Clause | `b6c8fe53f134b8b6d4578cd2d544df4cee9624c4efa8d51a560fb40ea296101b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitFixedBold.pfb | BSD-3-Clause | `f1b7159702973f54fc86254ea38bcf3712b2a736eb3a0995751e9f4bb45ad603` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfb | BSD-3-Clause | `8a000945843bd31add06aee63bf9fd41b7578b4f3242a4b7cd46349ad9d24d4d` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitFixedItalic.pfb | BSD-3-Clause | `5007faf8320fa1fcc08b8894b356ad976f60b992ba29ee5272578bbdebaf3876` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSans.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSans.pfb | BSD-3-Clause | `a02339e95d20db14cbdfc1c6baf359cd36a091d5434925c3a4040f60e1a1af9e` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSansBold.pfb | BSD-3-Clause | `7bdfa36de1d5757dcfaf8b8a4be95c6e41c40fa70dbed9d78bf979a7b9959054` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfb | BSD-3-Clause | `555ce45924338e2e4b32821910221ce85da691fd59a9723c4c971a7c5627fc8b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSansItalic.pfb | BSD-3-Clause | `7751cbefeda351708dae8c4a88db043411bc39ab2ae2097685da845d4d16f307` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerif.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSerif.pfb | BSD-3-Clause | `4f57d2b9d884af8f907bf22df6019b52d86cbf6214fdbd02b1ae05472a543f35` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSerifBold.pfb | BSD-3-Clause | `0bdf4b04e964139818d51eda03d566ba999fc3ba2421b1c6c51f9dc969022e80` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfb | BSD-3-Clause | `a406cac82583bf98175cb62c87ed5e95c45fbb34eece63a10b0a13e793cb2e10` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb | BSD-3-Clause | `610ae0687198045c4db5d1a6650fd5e92536631706382eb8b72e38df578d0ae9` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSymbol.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSymbol.pfb | BSD-3-Clause | `47967d055530e7357088a08403115425643ec2cdfd6201ba8af0fbd7116c1539` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc | CC0-1.0 | `73e1ba37d2bad5bab2a964f40a9eed96209666efc067c3322626214bbef234a0` | Default CMYK colour conversion (pinned hayro-interpret) |
|
||||
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-cmap/assets/cmaps.brotli | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged |
|
||||
| `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged |
|
||||
| `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
+16
-15
@@ -970,17 +970,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
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=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
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=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
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=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
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=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
dependencies = [
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
@@ -1024,7 +1024,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
dependencies = [
|
||||
"craft-winprint-gdi",
|
||||
"log",
|
||||
@@ -1038,7 +1038,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
dependencies = [
|
||||
"craft-fonts-build",
|
||||
"craft-i18n",
|
||||
@@ -1085,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",
|
||||
@@ -1096,7 +1096,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"objc2 0.6.5",
|
||||
@@ -2206,7 +2206,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"hayro-postscript",
|
||||
@@ -2215,7 +2215,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -2233,7 +2233,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -2251,12 +2251,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
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=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -2864,7 +2864,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -6284,6 +6284,7 @@ dependencies = [
|
||||
"vectorcraft-effects",
|
||||
"vectorcraft-geom",
|
||||
"vectorcraft-metafile",
|
||||
"vectorcraft-pathops",
|
||||
"vectorcraft-pdf",
|
||||
"vectorcraft-render",
|
||||
"vectorcraft-testkit",
|
||||
|
||||
+13
-13
@@ -11,16 +11,16 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/vectorcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", default-features = false, features = ["interpret", "write"] }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["serde"] }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
|
||||
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 = "f8f8829cc7be65d466d687dae381d1ca60e31242", 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,12 +147,12 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
|
||||
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
|
||||
f8f8829cc7be65d466d687dae381d1ca60e31242. 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/f8f8829cc7be65d466d687dae381d1ca60e31242/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.
|
||||
|
||||
@@ -131,6 +131,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
|
||||
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
|
||||
- 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).
|
||||
|
||||
@@ -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 }
|
||||
|
||||
|
||||
@@ -58,7 +58,12 @@ fn idle_control_socket_releases_its_worker() {
|
||||
fn idle_expiry_closes_without_writing_a_line() {
|
||||
let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("no request expected"));
|
||||
let mut got = Vec::new();
|
||||
client.read_to_end(&mut got).unwrap();
|
||||
match client.read_to_end(&mut got) {
|
||||
// On Windows the server's close can reach the client as a reset.
|
||||
Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset => {}
|
||||
Ok(_) => {}
|
||||
Err(e) => panic!("reading the idle connection: {e}"),
|
||||
}
|
||||
assert_eq!(String::from_utf8_lossy(&got), "", "the app wrote to an idle connection");
|
||||
expect_socket_deadline(client, done, worker);
|
||||
}
|
||||
@@ -334,7 +339,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();
|
||||
|
||||
@@ -753,13 +753,22 @@ enum FirstFrame {
|
||||
Shown,
|
||||
/// Overdue.
|
||||
Hung,
|
||||
/// Overdue, but the UI is still building the first frame: the app's own work (on a slow
|
||||
/// machine, or with antivirus reading every font file), not the adapter, which has been given
|
||||
/// nothing to show yet.
|
||||
Busy,
|
||||
}
|
||||
|
||||
/// The window's start after `frames` frames run, `since` its first frame was due.
|
||||
fn first_frame(frames: u64, since: Duration, minimized: bool) -> FirstFrame {
|
||||
/// The window's start after `frames` frames run, `since` its first frame was due and
|
||||
/// `since_built` the first frame's UI pass ended (`None` while it runs). A frame counts once its
|
||||
/// UI pass ends, before it is painted, so the adapter's time starts there: with no frame run, the
|
||||
/// UI thread is in the app's code, and starting again without the adapter wouldn't help (#5160).
|
||||
fn first_frame(frames: u64, since: Duration, since_built: Option<Duration>, minimized: bool) -> FirstFrame {
|
||||
if frames >= 2 || minimized {
|
||||
FirstFrame::Shown
|
||||
} else if since >= FIRST_FRAME_TIMEOUT {
|
||||
} else if frames == 0 {
|
||||
if since >= FIRST_FRAME_TIMEOUT { FirstFrame::Busy } else { FirstFrame::Wait }
|
||||
} else if since_built.unwrap_or(since) >= FIRST_FRAME_TIMEOUT {
|
||||
FirstFrame::Hung
|
||||
} else {
|
||||
FirstFrame::Wait
|
||||
@@ -767,18 +776,34 @@ fn first_frame(frames: u64, since: Duration, minimized: bool) -> FirstFrame {
|
||||
}
|
||||
|
||||
/// Watch the window's first frame from another thread: once it reaches the screen, clear the start
|
||||
/// from [`START_FILE`]; when it hasn't reached the screen [`FIRST_FRAME_TIMEOUT`] after the app was
|
||||
/// created ([`Startup::ready`]), start the app again without the adapter, as [`finish`] does for
|
||||
/// one that failed, and end this process, whose UI thread is stuck in the graphics driver.
|
||||
/// from [`START_FILE`]; when it hasn't reached the screen [`FIRST_FRAME_TIMEOUT`] after its UI pass
|
||||
/// ended, start the app again without the adapter, as [`finish`] does for one that failed, and end
|
||||
/// this process, whose UI thread is stuck in the graphics driver. A first frame still being built
|
||||
/// that long is waited for, with a note in the log.
|
||||
pub fn watch_first_frame(startup: Arc<Startup>) {
|
||||
let mut built: Option<Instant> = None;
|
||||
let mut noted = false;
|
||||
let watch = move || loop {
|
||||
std::thread::sleep(Duration::from_millis(250));
|
||||
let Some(due) = startup.ready.get() else { continue };
|
||||
let ui = startup.ui.get();
|
||||
let frames = ui.map_or(0, egui::Context::cumulative_frame_nr);
|
||||
if frames >= 1 && built.is_none() {
|
||||
built = Some(Instant::now());
|
||||
}
|
||||
let minimized = ui.and_then(|c| c.input(|i| i.viewport().minimized)).unwrap_or(false);
|
||||
match first_frame(frames, due.elapsed(), minimized) {
|
||||
match first_frame(frames, due.elapsed(), built.map(|t| t.elapsed()), minimized) {
|
||||
FirstFrame::Wait => continue,
|
||||
FirstFrame::Busy => {
|
||||
if !noted {
|
||||
log::warn!(
|
||||
"the window's first frame is still being built after {}s: waiting for it (the app's work, not the graphics adapter)",
|
||||
FIRST_FRAME_TIMEOUT.as_secs()
|
||||
);
|
||||
noted = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
FirstFrame::Shown => {
|
||||
startup.presented();
|
||||
return;
|
||||
|
||||
@@ -366,14 +366,19 @@ fn gpus_without_pci_ids_are_told_apart_by_name() {
|
||||
fn a_first_frame_that_never_reaches_the_screen_hangs_its_adapter() {
|
||||
let s = Duration::from_secs;
|
||||
// The second frame began: the first was presented.
|
||||
assert_eq!(first_frame(2, s(60), false), FirstFrame::Shown);
|
||||
// Still drawing (or presenting) the first frame: waited for, then given up on (#964).
|
||||
for frames in [0, 1] {
|
||||
assert_eq!(first_frame(frames, s(3), false), FirstFrame::Wait);
|
||||
assert_eq!(first_frame(frames, FIRST_FRAME_TIMEOUT, false), FirstFrame::Hung);
|
||||
}
|
||||
assert_eq!(first_frame(2, s(60), Some(s(1)), false), FirstFrame::Shown);
|
||||
// The first frame built and not yet presented: waited for, then given up on (#964), counting
|
||||
// from when its UI pass ended.
|
||||
assert_eq!(first_frame(1, s(3), Some(s(1)), false), FirstFrame::Wait);
|
||||
assert_eq!(first_frame(1, FIRST_FRAME_TIMEOUT, Some(FIRST_FRAME_TIMEOUT), false), FirstFrame::Hung);
|
||||
assert_eq!(first_frame(1, s(45), Some(s(5)), false), FirstFrame::Wait, "a first frame built slowly gets its full time to show");
|
||||
assert_eq!(first_frame(1, FIRST_FRAME_TIMEOUT, None, false), FirstFrame::Hung);
|
||||
// The first frame still being built: the app's work, not the adapter's (#5160).
|
||||
assert_eq!(first_frame(0, s(3), None, false), FirstFrame::Wait);
|
||||
assert_eq!(first_frame(0, FIRST_FRAME_TIMEOUT, None, false), FirstFrame::Busy);
|
||||
assert_eq!(first_frame(0, s(600), None, false), FirstFrame::Busy, "never a restart without an adapter");
|
||||
// A window minimized at the start may not draw again until restored.
|
||||
assert_eq!(first_frame(1, s(60), true), FirstFrame::Shown);
|
||||
assert_eq!(first_frame(1, s(60), Some(s(60)), true), FirstFrame::Shown);
|
||||
// A hung adapter is left out once, like one that failed.
|
||||
let skip = vec!["Dx12:10de:28a0".to_string()];
|
||||
assert_eq!(restart_without(true, 1, Some("Dx12:10de:28a0"), &skip), None);
|
||||
|
||||
@@ -44,19 +44,50 @@ macro_rules! dialog_settings {
|
||||
|
||||
dialog_settings!(rfd::FileDialog, rfd::AsyncFileDialog);
|
||||
|
||||
/// On Linux and the BSDs the dialog is GTK's or the desktop portal's, which match a file type's
|
||||
/// `*.ext` patterns case-sensitively.
|
||||
const CASE_SENSITIVE_FILTERS: bool =
|
||||
cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"));
|
||||
|
||||
/// The extensions an open dialog's filter is given for `exts`: with `any_case`, each extension
|
||||
/// that has a letter is followed by a pattern with each letter as a `[xX]` pair, so the filter for
|
||||
/// `dib` also lists `image.DIB` and `image.Dib`.
|
||||
fn open_extensions(exts: &[impl AsRef<str>], any_case: bool) -> Vec<String> {
|
||||
let mut out = Vec::with_capacity(exts.len() * 2);
|
||||
for e in exts {
|
||||
let e = e.as_ref();
|
||||
out.push(e.to_string());
|
||||
if any_case && e.chars().any(|c| c.is_ascii_alphabetic()) {
|
||||
out.push(
|
||||
e.chars()
|
||||
.map(|c| if c.is_ascii_alphabetic() { format!("[{}{}]", c.to_ascii_lowercase(), c.to_ascii_uppercase()) } else { c.to_string() })
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `d` set up for `request`: its title, file types, folder and suggested name.
|
||||
fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
let pick = match request {
|
||||
PickRequest::Open(pick) | PickRequest::Save(pick) => pick,
|
||||
PickRequest::OpenMany => {
|
||||
return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| {
|
||||
d.filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts)
|
||||
d.filter(
|
||||
vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name),
|
||||
&open_extensions(exts, CASE_SENSITIVE_FILTERS),
|
||||
)
|
||||
});
|
||||
}
|
||||
PickRequest::Folder => return d,
|
||||
};
|
||||
let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_));
|
||||
let d = pick.filters.iter().fold(d, |d, (name, exts)| {
|
||||
d.filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()), exts)
|
||||
d.filter(
|
||||
vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()),
|
||||
&open_extensions(exts, any_case),
|
||||
)
|
||||
});
|
||||
let d = match &pick.folder {
|
||||
Some(folder) => d.folder(folder),
|
||||
@@ -461,24 +492,13 @@ pub(crate) fn windows_candidates(
|
||||
}
|
||||
|
||||
/// The paths PhotoCraft's installer registers under App Paths, for the current user and then for
|
||||
/// everyone (`reg query`, so no extra dependency; a hidden console window).
|
||||
/// everyone.
|
||||
#[cfg(windows)]
|
||||
fn registered_photocraft() -> Vec<std::path::PathBuf> {
|
||||
use std::os::windows::process::CommandExt as _;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
// reg.exe by its full path, so nothing named `reg` in the app's folder or on PATH runs instead.
|
||||
let root = std::env::var_os("SystemRoot").map(std::path::PathBuf::from).unwrap_or_else(|| r"C:\Windows".into());
|
||||
["HKCU", "HKLM"]
|
||||
use windows::Win32::System::Registry::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};
|
||||
[HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE]
|
||||
.into_iter()
|
||||
.filter_map(|hive| {
|
||||
let key = format!(r"{hive}\Software\Microsoft\Windows\CurrentVersion\App Paths\photocraft.exe");
|
||||
let out = std::process::Command::new(root.join("System32").join("reg.exe"))
|
||||
.args(["query", &key, "/ve"])
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.output()
|
||||
.ok()?;
|
||||
registered_path(&String::from_utf8_lossy(&out.stdout))
|
||||
})
|
||||
.filter_map(|hive| registry_default_path(hive, r"Software\Microsoft\Windows\CurrentVersion\App Paths\photocraft.exe"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -487,11 +507,35 @@ fn registered_photocraft() -> Vec<std::path::PathBuf> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// The path in `reg query … /ve` output like
|
||||
/// ` (Default) REG_SZ C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe`.
|
||||
/// 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(text: &str) -> Option<std::path::PathBuf> {
|
||||
text.lines().find_map(|l| l.split_once("REG_SZ")).map(|(_, v)| v.trim().trim_matches('"')).filter(|v| !v.is_empty()).map(std::path::PathBuf::from)
|
||||
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
|
||||
@@ -616,17 +660,118 @@ mod open_with_tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// The registered path is read from `reg query … /ve` output, spaces and quotes included;
|
||||
/// no value, no path.
|
||||
/// 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_reg_query() {
|
||||
let out = "\r\nHKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\photocraft.exe\r\n (Default) REG_SZ C:\\Program Files\\ArtCraft\\PhotoCraft\\photocraft.exe\r\n";
|
||||
assert_eq!(registered_path(out), Some(std::path::PathBuf::from(r"C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe")));
|
||||
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(" (Standard) REG_SZ \"C:\\A B\\photocraft.exe\""),
|
||||
Some(std::path::PathBuf::from(r"C:\A B\photocraft.exe"))
|
||||
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("ERROR: The system was unable to find the specified registry key or value."), None);
|
||||
assert_eq!(registered_path(" (Default) REG_SZ "), None);
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod dialog_tests {
|
||||
use super::{CASE_SENSITIVE_FILTERS, DialogSettings, FilePick, PickRequest, dialog_for, fileio, open_extensions};
|
||||
|
||||
/// The file types a dialog was given, by label.
|
||||
#[derive(Default)]
|
||||
struct Filters(Vec<(String, Vec<String>)>);
|
||||
|
||||
impl DialogSettings for Filters {
|
||||
fn parent(self, _window: &winit::window::Window) -> Self {
|
||||
self
|
||||
}
|
||||
fn title(self, _title: &str) -> Self {
|
||||
self
|
||||
}
|
||||
fn filter(mut self, name: &str, exts: &[impl ToString]) -> Self {
|
||||
self.0.push((name.to_string(), exts.iter().map(ToString::to_string).collect()));
|
||||
self
|
||||
}
|
||||
fn folder(self, _folder: &str) -> Self {
|
||||
self
|
||||
}
|
||||
fn file_name(self, _name: &str) -> Self {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Does the case-sensitive pattern `*.{ext}` match `name`? `ext` may hold literal characters,
|
||||
/// `*` and `[..]` sets.
|
||||
fn matches(ext: &str, name: &str) -> bool {
|
||||
fn here(p: &[char], n: &[char]) -> bool {
|
||||
match p.split_first() {
|
||||
None => n.is_empty(),
|
||||
Some(('*', rest)) => (0..=n.len()).any(|i| here(rest, &n[i..])),
|
||||
Some(('[', rest)) => {
|
||||
let Some(end) = rest.iter().position(|&c| c == ']') else { return false };
|
||||
n.split_first().is_some_and(|(c, n)| rest[..end].contains(c) && here(&rest[end + 1..], n))
|
||||
}
|
||||
Some((c, rest)) => n.split_first().is_some_and(|(d, n)| d == c && here(rest, n)),
|
||||
}
|
||||
}
|
||||
let pattern: Vec<char> = format!("*.{ext}").chars().collect();
|
||||
here(&pattern, &name.chars().collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// Where filters match case-sensitively, every extension of File › Open and Place lists files
|
||||
/// whose extension is in capitals or mixed case, `image.DIB` and `image.Pns` included.
|
||||
#[test]
|
||||
fn open_and_place_filters_list_extensions_in_any_case() {
|
||||
let all = fileio::open_filters().chain(fileio::place_filters());
|
||||
for (label, exts) in all {
|
||||
let patterns = open_extensions(exts, true);
|
||||
for ext in exts {
|
||||
let mut mixed = ext.to_ascii_uppercase();
|
||||
mixed.replace_range(..1, &ext[..1]);
|
||||
for name in [format!("a.{ext}"), format!("a.{}", ext.to_ascii_uppercase()), format!("a.{mixed}")] {
|
||||
assert!(patterns.iter().any(|p| matches(p, &name)), "{label}: {patterns:?} don't match {name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(open_extensions(&["dib", "jp2", "*"], true), ["dib", "[dD][iI][bB]", "jp2", "[jJ][pP]2", "*"]);
|
||||
assert_eq!(open_extensions(&["dib", "PNS"], false), ["dib", "PNS"]);
|
||||
}
|
||||
|
||||
/// Open and Place dialogs get the any-case patterns on Linux and the BSDs; a save dialog's file
|
||||
/// types stay as listed.
|
||||
#[test]
|
||||
fn open_dialogs_get_any_case_patterns_where_filters_are_case_sensitive() {
|
||||
let dib = vec![FilePick::filter("BMP", &["bmp", "dib"])];
|
||||
let pick = FilePick { filters: dib.clone(), ..Default::default() };
|
||||
let expected = |any_case: bool| open_extensions(&["bmp", "dib"], any_case);
|
||||
let opened = dialog_for(Filters::default(), &PickRequest::Open(pick.clone())).0;
|
||||
assert_eq!(opened[0].1, expected(CASE_SENSITIVE_FILTERS));
|
||||
let saved = dialog_for(Filters::default(), &PickRequest::Save(pick)).0;
|
||||
assert_eq!(saved, dib);
|
||||
let placed = dialog_for(Filters::default(), &PickRequest::OpenMany).0;
|
||||
let first = fileio::place_filters().next().map(|(_, exts)| open_extensions(exts, CASE_SENSITIVE_FILTERS));
|
||||
assert_eq!(placed.first().map(|(_, exts)| exts.clone()), first);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -193,3 +193,19 @@ 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"
|
||||
|
||||
[people.FractalEncrypt]
|
||||
sync_github_name = true
|
||||
|
||||
[people.sadkotheguest]
|
||||
real_name = "Alexander Buraga"
|
||||
display_name = "Alexander Buraga"
|
||||
sync_github_name = false
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
+106
-15
@@ -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
|
||||
@@ -846,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;
|
||||
@@ -863,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
|
||||
@@ -871,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 {
|
||||
@@ -883,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -900,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;
|
||||
}
|
||||
@@ -917,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;
|
||||
}
|
||||
@@ -930,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, "");
|
||||
@@ -960,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 [
|
||||
@@ -973,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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+204
-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]
|
||||
|
||||
@@ -86,6 +86,9 @@ const TINT_STEPS: u32 = 16;
|
||||
const MIN_INK_LIGHTNESS_SPAN: f64 = 1.0 / 255.0;
|
||||
/// Most stops on a gradient's curve that [`Gradient::ink_tints`] finds tints for.
|
||||
const MAX_INK_TINTS: usize = 4096;
|
||||
/// How many even steps [`Gradient::ink_mixes`] checks the lightness of two stops' display RGB mix
|
||||
/// at, to tell whether it moves steadily from one stop's lightness to the other's.
|
||||
const INK_MIX_STEPS: u32 = 64;
|
||||
|
||||
/// The mix positions (0..1, after `v0`, before `v1`) between which display RGB mixed linearly
|
||||
/// stays within [`PERCEPTUAL_TOLERANCE`] of the perceptual mix of `a` and `b`: the span halved
|
||||
@@ -401,8 +404,10 @@ impl Gradient {
|
||||
/// The weight is the one at which the two stops' colors mixed in display RGB have the OKLab
|
||||
/// lightness of the color on the curve there, found to [`TINT_STEPS`] halvings, or the mix
|
||||
/// position itself when the two colors' lightness differs by less than
|
||||
/// [`MIN_INK_LIGHTNESS_SPAN`]. `None` for a Classic gradient, and when the curve has more than
|
||||
/// [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
|
||||
/// [`MIN_INK_LIGHTNESS_SPAN`], or when the display RGB mix's lightness turns back somewhere
|
||||
/// on the way from one color's lightness to the other's (checked at [`INK_MIX_STEPS`] even
|
||||
/// steps), as from red to blue. `None` for a Classic gradient, and when the curve has more
|
||||
/// than [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
|
||||
pub fn ink_mixes(&self) -> Option<Vec<(f32, usize, f32, f32)>> {
|
||||
use crate::libraries::srgb_to_oklab;
|
||||
if self.method.is_classic() || !self.fits_ink_tints() {
|
||||
@@ -414,8 +419,16 @@ impl Gradient {
|
||||
out.push((s.offset, i, 0.0, s.opacity));
|
||||
let Some(n) = self.stops.get(i + 1) else { continue };
|
||||
let (l0, l1) = (lightness(&s.color), lightness(&n.color));
|
||||
let mixed_lightness = |w: f32| lightness(&GradientMethod::Classic.mix(&s.color, &n.color, w));
|
||||
// The mix position itself when the lightness doesn't tell the mixes apart.
|
||||
let by_position = (l1 - l0).abs() < MIN_INK_LIGHTNESS_SPAN
|
||||
|| !(0..=INK_MIX_STEPS)
|
||||
.map(|k| mixed_lightness(k as f32 / INK_MIX_STEPS as f32))
|
||||
.collect::<Vec<_>>()
|
||||
.windows(2)
|
||||
.all(|w| (w[1] - w[0]) * (l1 - l0) >= 0.0);
|
||||
for v in perceptual_mixes(s, n) {
|
||||
let weight = if (l1 - l0).abs() < MIN_INK_LIGHTNESS_SPAN {
|
||||
let weight = if by_position {
|
||||
v
|
||||
} else {
|
||||
let want = lightness(&self.method.mix(&s.color, &n.color, v));
|
||||
@@ -423,7 +436,7 @@ impl Gradient {
|
||||
for _ in 0..TINT_STEPS {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
// The mix at `mid` has not yet gone from stop `i`'s lightness to the wanted one.
|
||||
if (lightness(&GradientMethod::Classic.mix(&s.color, &n.color, mid)) - want) * (l1 - l0) < 0.0 {
|
||||
if (mixed_lightness(mid) - want) * (l1 - l0) < 0.0 {
|
||||
lo = mid;
|
||||
} else {
|
||||
hi = mid;
|
||||
|
||||
@@ -585,3 +585,22 @@ fn ink_mixes_follow_the_perceptual_curve() {
|
||||
g.stops = (0..n).map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { magenta } else { Color::WHITE })).collect();
|
||||
assert_eq!(g.ink_mixes(), None);
|
||||
}
|
||||
|
||||
/// From red to blue the display RGB mix darkens past blue's lightness and comes back, so a
|
||||
/// weight found by lightness near the blue stop would be a red-side one and the inks would jump
|
||||
/// there. The weights are the mix positions instead, and reach the blue stop's inks steadily.
|
||||
#[test]
|
||||
fn ink_mixes_use_the_mix_position_when_the_lightness_turns_back() {
|
||||
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
|
||||
let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red), GradientStop::new(1.0, blue)]);
|
||||
g.method = GradientMethod::Perceptual;
|
||||
let mixes = g.ink_mixes().expect("a Perceptual gradient's curve");
|
||||
assert_eq!(mixes[mixes.len() - 1], (1.0, 1, 0.0, 1.0), "the blue stop");
|
||||
let between: Vec<_> = mixes.iter().filter(|m| m.1 == 0 && m.0 > 0.0).collect();
|
||||
assert!(!between.is_empty(), "stops on the curve between red and blue: {mixes:?}");
|
||||
// With the midpoint at ½, a stop's offset on the curve is its mix position.
|
||||
for (t, _, w, _) in &between {
|
||||
assert!((w - t).abs() < 1e-6, "at {t}: weight {w}");
|
||||
}
|
||||
assert!(mixes.windows(2).filter(|p| p[1].1 == 0).all(|p| p[0].2 <= p[1].2), "the weights rise: {mixes:?}");
|
||||
}
|
||||
@@ -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)));
|
||||
}
|
||||
}
|
||||
@@ -99,13 +99,15 @@ impl Document {
|
||||
}
|
||||
|
||||
/// Leave opacity-mask editing and symbol editing: drop the temporary editing layer, a working
|
||||
/// copy of art the mask or the symbol already holds (the engine syncs it after every edit).
|
||||
/// copy of art the mask or the symbol already holds (the engine syncs it after every edit). The
|
||||
/// layer is removed wherever it is, also as a sublayer of another layer; an id that names
|
||||
/// anything other than a layer is left alone.
|
||||
pub fn drop_edit_modes(&mut self) {
|
||||
if let Some(me) = self.mask_edit.take() {
|
||||
self.layers.retain(|l| l.id != me.layer);
|
||||
}
|
||||
if let Some(se) = self.symbol_edit.take() {
|
||||
self.layers.retain(|l| l.id != se.layer);
|
||||
let layers = [self.mask_edit.take().map(|me| me.layer), self.symbol_edit.take().map(|se| se.layer)];
|
||||
for id in layers.into_iter().flatten() {
|
||||
if self.node(id).is_some_and(Node::is_layer) {
|
||||
let _ = self.remove(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Color Halftone's Max Radius was a distance in points until documents of version 2; since then
|
||||
//! Color Halftone's Max Radius was a distance in points until documents of version 3; since then
|
||||
//! it is in pixels of the Document Raster Effects resolution, as public documentation gives it
|
||||
//! (#3260). [`Document::migrate_halftone_radii`] converts the radii of older documents, and
|
||||
//! [`Document::halftone_radii_to_points`] converts them back for a file saved for an older app.
|
||||
@@ -11,7 +11,7 @@ use crate::limits::FORMAT_VERSION;
|
||||
use crate::{Appearance, Document, Effect, Node};
|
||||
|
||||
/// The first document version whose Color Halftone radii are in pixels.
|
||||
const PIXEL_RADII_SINCE: u32 = 2;
|
||||
const PIXEL_RADII_SINCE: u32 = 3;
|
||||
const HALFTONE: &str = "pixelate.colorHalftone";
|
||||
const RADIUS: &str = "maxRadius";
|
||||
/// The radius (points) an older document's halftone without one drew with.
|
||||
@@ -20,7 +20,7 @@ const OLD_DEFAULT: f64 = 8.0;
|
||||
const RANGE: std::ops::RangeInclusive<f64> = 4.0..=127.0;
|
||||
|
||||
impl Document {
|
||||
/// Saved before version 2: each Color Halftone's Max Radius in points becomes the pixels of
|
||||
/// Saved before version 3: each Color Halftone's Max Radius in points becomes the pixels of
|
||||
/// the document's raster effects resolution that draw the same dots, within the 4 to 127 px
|
||||
/// the effect takes (a radius over 127 px, from a large radius at a high resolution, draws
|
||||
/// smaller dots than before). In the art, symbols, patterns, graph designs, opacity masks and
|
||||
@@ -34,10 +34,10 @@ impl Document {
|
||||
self.each_halftone(&mut |e| rescale(e, k));
|
||||
}
|
||||
|
||||
/// For a file saved for an app before version 2 (every native file version before today's):
|
||||
/// For a file saved for an app before version 3 (every native file version before today's):
|
||||
/// each Color Halftone's Max Radius in pixels becomes the points that draw the same dots,
|
||||
/// within the 4 to 127 pt that app takes (a radius under 4 pt, from a fine screen at a high
|
||||
/// resolution, draws bigger dots there), and the document becomes version 1, so reopening the
|
||||
/// resolution, draws bigger dots there), and the document becomes version 2, so reopening the
|
||||
/// file here converts them back.
|
||||
pub fn halftone_radii_to_points(&mut self) {
|
||||
if self.version < PIXEL_RADII_SINCE {
|
||||
@@ -146,7 +146,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_documents_before_version_2_are_converted_once() {
|
||||
fn only_documents_before_version_3_are_converted_once() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
d.raster_effects_ppi = 300.0;
|
||||
let mut style = d.graphic_styles.first().cloned().unwrap();
|
||||
@@ -175,7 +175,7 @@ mod tests {
|
||||
d.graphic_styles.push(style);
|
||||
let r = |d: &Document, i: usize| d.graphic_styles.last().map(|s| radius(&s.appearance.effects[i])).unwrap();
|
||||
d.halftone_radii_to_points();
|
||||
assert_eq!(d.version, 1, "reopened here, it converts back");
|
||||
assert_eq!(d.version, 2, "reopened here, it converts back");
|
||||
assert!((r(&d, 0) - 24.0).abs() < 1e-9, "100 px at 300 ppi is 24 pt: {}", r(&d, 0));
|
||||
assert_eq!(r(&d, 1), 4.0, "0.96 pt is under the 4 pt the older app takes");
|
||||
let points = d.clone();
|
||||
|
||||
@@ -41,6 +41,7 @@ pub mod live;
|
||||
pub mod live_paint;
|
||||
pub mod marks;
|
||||
mod mem;
|
||||
pub use mem::{appearance_heap_bytes, paint_heap_bytes};
|
||||
pub mod metadata;
|
||||
pub mod node;
|
||||
pub mod objects_on_path;
|
||||
@@ -68,6 +69,7 @@ mod symbols;
|
||||
pub use symbols::SymbolBoxes;
|
||||
pub mod text;
|
||||
pub mod trace;
|
||||
pub mod twist;
|
||||
pub mod variables;
|
||||
pub mod xml_id;
|
||||
|
||||
@@ -111,6 +113,7 @@ pub use setup::{Background, DocSetup, ExportText, GridSize, Quotes};
|
||||
pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOptions, SliceSource};
|
||||
pub use style_libs::StyleLibrary;
|
||||
pub use text::FontHeightReference;
|
||||
pub use text::GlyphChoice;
|
||||
pub use text::{
|
||||
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
|
||||
JustificationOptions, Justify, Kinsoku, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign, RubyPosition,
|
||||
@@ -227,8 +230,9 @@ pub struct Document {
|
||||
#[serde(default, skip_serializing)]
|
||||
pub mask_edit: Option<MaskEdit>,
|
||||
/// Symbol editing mode, while active. Never saved (see [`Document::without_edit_modes`]): the
|
||||
/// symbol already holds the art of its editing layer.
|
||||
#[serde(default, skip_serializing)]
|
||||
/// symbol already holds the art of its editing layer. Never read either: a value in file data
|
||||
/// is dropped, so the layer it names is kept and saving does not write the value again.
|
||||
#[serde(default, skip_serializing, deserialize_with = "skip::read_as_none")]
|
||||
pub symbol_edit: Option<SymbolEdit>,
|
||||
next_id: u64,
|
||||
/// Foreign data preserved on round-trip.
|
||||
|
||||
@@ -13,10 +13,11 @@ pub enum DocError {
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
/// The version of the document model new documents are made in: 2 measures Color Halftone's Max
|
||||
/// Radius in pixels of the raster effects resolution (older documents are converted on opening,
|
||||
/// The document version new documents get. Version 2: a positive Twist angle turns clockwise
|
||||
/// ([`crate::twist`]). Version 3: Color Halftone's Max Radius is in pixels of the raster effects
|
||||
/// resolution (older documents are converted on opening,
|
||||
/// [`crate::Document::migrate_halftone_radii`]).
|
||||
pub const FORMAT_VERSION: u32 = 2;
|
||||
pub const FORMAT_VERSION: u32 = 3;
|
||||
|
||||
/// Node, slice and asset ids are handed out below this: no document gets near it by counting, so
|
||||
/// larger ids in a file are damage (or made by hand) and the counter never follows them (#1718).
|
||||
|
||||
+33
-12
@@ -98,7 +98,7 @@ impl Document {
|
||||
vec_bytes(g) + g.iter().map(|g: &SwatchGroup| g.name.capacity() + swatches_bytes(&g.swatches)).sum::<usize>()
|
||||
});
|
||||
n += shared(&self.graphic_styles, &newer.graphic_styles, |g| {
|
||||
vec_bytes(g) + g.iter().map(|g: &GraphicStyle| g.name.capacity() + appearance_heap(&g.appearance)).sum::<usize>()
|
||||
vec_bytes(g) + g.iter().map(|g: &GraphicStyle| g.name.capacity() + appearance_heap_bytes(&g.appearance)).sum::<usize>()
|
||||
});
|
||||
let styles = |s: &Vec<TextStyleDef>| vec_bytes(s) + s.iter().map(|s| s.name.capacity() + map_bytes(&s.attrs)).sum::<usize>();
|
||||
n += shared(&self.char_styles, &newer.char_styles, styles);
|
||||
@@ -245,7 +245,7 @@ fn node_bytes(n: &Node, other: Option<&Node>) -> usize {
|
||||
let mut b = ALLOC + ARC + size_of::<Node>();
|
||||
b += n.name.as_ref().map_or(0, String::capacity);
|
||||
if !other.is_some_and(|m| Shared::ptr_eq(&m.appearance, &n.appearance)) {
|
||||
b += ALLOC + ARC + appearance_heap(&n.appearance);
|
||||
b += ALLOC + ARC + appearance_heap_bytes(&n.appearance);
|
||||
}
|
||||
if let Some(e) = n.extras_box() {
|
||||
b += ALLOC + size_of::<NodeExtras>();
|
||||
@@ -293,32 +293,53 @@ fn text_bytes(t: &TextObject) -> usize {
|
||||
+ vec_bytes(&t.cached_baselines)
|
||||
}
|
||||
|
||||
/// The heap an appearance owns (not the appearance itself).
|
||||
fn appearance_heap(a: &Appearance) -> usize {
|
||||
/// Approximate retained memory of an appearance and its owned buffers, without serialization.
|
||||
pub fn appearance_heap_bytes(a: &Appearance) -> usize {
|
||||
size_of::<Appearance>()
|
||||
+ vec_bytes(&a.items)
|
||||
+ a.items
|
||||
.iter()
|
||||
.map(|i| match i {
|
||||
AppearanceItem::Fill(f) => paint_heap(&f.paint),
|
||||
AppearanceItem::Stroke(s) => paint_heap(&s.paint),
|
||||
.map(|item| {
|
||||
let paint = paint_heap_bytes(item.paint());
|
||||
let effects = effects_heap(item.effects());
|
||||
let stroke = match item {
|
||||
AppearanceItem::Stroke(s) => {
|
||||
s.dash.as_ref().map_or(0, |d| vec_bytes(&d.pattern))
|
||||
+ s.profile.as_ref().map_or(0, |p| vec_bytes(&p.points))
|
||||
+ s.pressure.as_ref().map_or(0, |p| vec_bytes(&p.points))
|
||||
+ s.brush.as_ref().map_or(0, String::capacity)
|
||||
}
|
||||
_ => 0,
|
||||
};
|
||||
paint + effects + stroke
|
||||
})
|
||||
.sum::<usize>()
|
||||
+ vec_bytes(&a.effects)
|
||||
+ a.effects.iter().map(|e: &Effect| e.id.capacity() + json_bytes(&e.params)).sum::<usize>()
|
||||
+ effects_heap(&a.effects)
|
||||
}
|
||||
|
||||
fn paint_heap(p: &Paint) -> usize {
|
||||
fn effects_heap(effects: &Vec<Effect>) -> usize {
|
||||
vec_bytes(effects) + effects.iter().map(|e| e.id.capacity() + json_bytes(&e.params)).sum::<usize>()
|
||||
}
|
||||
|
||||
/// Approximate heap retained by one paint, without serializing it.
|
||||
pub fn paint_heap_bytes(p: &Paint) -> usize {
|
||||
match p {
|
||||
Paint::Solid { swatch, .. } => swatch.as_ref().map_or(0, String::capacity),
|
||||
Paint::Gradient(g) => ALLOC + size_of_val(&**g) + vec_bytes(&g.gradient.stops),
|
||||
Paint::Gradient(g) => {
|
||||
ALLOC
|
||||
+ size_of_val(&**g)
|
||||
+ vec_bytes(&g.gradient.stops)
|
||||
+ g.gradient.stops.iter().map(|s| s.swatch.as_ref().map_or(0, String::capacity)).sum::<usize>()
|
||||
+ g.swatch.as_ref().map_or(0, String::capacity)
|
||||
+ g.freeform.as_ref().map_or(0, |f| vec_bytes(&f.points) + vec_bytes(&f.lines) + f.lines.iter().map(vec_bytes).sum::<usize>())
|
||||
}
|
||||
Paint::Pattern { pattern, .. } => pattern.capacity(),
|
||||
Paint::None => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn swatches_bytes(s: &[Swatch]) -> usize {
|
||||
ALLOC + std::mem::size_of_val(s) + s.iter().map(|w| w.name.capacity() + paint_heap(&w.paint)).sum::<usize>()
|
||||
ALLOC + std::mem::size_of_val(s) + s.iter().map(|w| w.name.capacity() + paint_heap_bytes(&w.paint)).sum::<usize>()
|
||||
}
|
||||
|
||||
/// A vector's buffer (not what its elements own).
|
||||
|
||||
@@ -369,7 +369,12 @@ impl Node {
|
||||
let placed = xf.transform_rect_bbox(art.geometric);
|
||||
match s.placed_visual(symbol, *xf) {
|
||||
Some(v) => v.union(placed),
|
||||
None => placed.inflate(art.reach, art.reach),
|
||||
// Art placed through 9-slice guides can draw outside `placed`.
|
||||
None => s
|
||||
.document()
|
||||
.symbol_slice_map_of(symbol, art.geometric, *xf)
|
||||
.map_or(placed, |m| m.placement_bounds(art.geometric).union(placed))
|
||||
.inflate(art.reach, art.reach),
|
||||
}
|
||||
}
|
||||
None => xf.transform_rect_bbox(SYMBOL_SQUARE),
|
||||
|
||||
@@ -390,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]
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -13,3 +13,8 @@ pub fn is_empty_vec<T>(v: &[T]) -> bool {
|
||||
pub fn is_empty_map(v: &serde_json::Map<String, serde_json::Value>) -> bool {
|
||||
v.is_empty()
|
||||
}
|
||||
/// Read a field's value and drop it, giving `None`: for state that is never taken from a file.
|
||||
pub fn read_as_none<'de, D: serde::Deserializer<'de>, T>(d: D) -> Result<Option<T>, D::Error> {
|
||||
<serde::de::IgnoredAny as serde::Deserialize>::deserialize(d)?;
|
||||
Ok(None)
|
||||
}
|
||||
@@ -98,6 +98,10 @@ impl GraphicStyle {
|
||||
/// The extension (and `format` header) of graphic style library files.
|
||||
pub const STYLES_EXT: &str = "vcstyles";
|
||||
|
||||
/// The version of the `.vcstyles` files [`write`] writes. Version 2: a positive Twist angle turns
|
||||
/// clockwise ([`crate::twist`]).
|
||||
const STYLES_VERSION: u32 = crate::twist::TWIST_CLOCKWISE_SINCE;
|
||||
|
||||
/// The file: a header around the library.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct NativeFile {
|
||||
@@ -109,17 +113,21 @@ struct NativeFile {
|
||||
|
||||
/// `lib` as a `.vcstyles` file.
|
||||
pub fn write(lib: &StyleLibrary) -> String {
|
||||
let file = NativeFile { format: STYLES_EXT.into(), version: 1, library: lib.clone() };
|
||||
let file = NativeFile { format: STYLES_EXT.into(), version: STYLES_VERSION, library: lib.clone() };
|
||||
serde_json::to_string_pretty(&file).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Read a `.vcstyles` file; an unnamed library is called `name`.
|
||||
/// Read a `.vcstyles` file; an unnamed library is called `name`. A version 1 file was written by
|
||||
/// an app that turned Twist counterclockwise: its Twist angles are negated.
|
||||
pub fn read(text: &str, name: &str) -> Result<StyleLibrary, String> {
|
||||
let f: NativeFile = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| format!("not a graphic style library: {e}"))?;
|
||||
if f.format != STYLES_EXT {
|
||||
return Err(format!("not a graphic style library (format `{}`)", f.format));
|
||||
}
|
||||
let mut lib = f.library;
|
||||
if f.version < STYLES_VERSION {
|
||||
crate::twist::negate_library(&mut lib);
|
||||
}
|
||||
if lib.name.trim().is_empty() {
|
||||
lib.name = name.into();
|
||||
}
|
||||
|
||||
@@ -343,6 +343,20 @@ impl NineSliceMap {
|
||||
self.cell_xf(self.x.cell(q.x), self.y.cell(q.y))
|
||||
}
|
||||
|
||||
/// A box that holds everything [`Self::place`] draws of art whose geometric box in symbol space
|
||||
/// is `art`, before strokes and effects: `art` placed by each of the nine cells' maps. An object
|
||||
/// that crosses a guide and draws symbol art is placed by the map of the cell its center is in,
|
||||
/// so it can draw outside the box the corner cells place `art` in.
|
||||
pub fn placement_bounds(&self, art: Rect) -> Rect {
|
||||
let mut b = self.cell_xf(0, 0).transform_rect_bbox(art);
|
||||
for j in 0..3 {
|
||||
for i in 0..3 {
|
||||
b = b.union(self.cell_xf(i, j).transform_rect_bbox(art));
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// The guides in symbol space: the two x values and the two y values.
|
||||
fn cuts(&self) -> ([f64; 2], [f64; 2]) {
|
||||
let inv = self.natural.inverse();
|
||||
@@ -704,6 +718,12 @@ impl Document {
|
||||
NineSliceMap::new(guides, art, self.symbol_natural_xf(name), xf)
|
||||
}
|
||||
|
||||
/// [`Self::symbol_slice_map`] with the guides cutting `art`, the symbol's art box already
|
||||
/// measured.
|
||||
pub(crate) fn symbol_slice_map_of(&self, name: &str, art: Rect, xf: Affine) -> Option<NineSliceMap> {
|
||||
NineSliceMap::new(self.symbol_nine_slice(name)?, art, self.symbol_natural_xf(name), xf)
|
||||
}
|
||||
|
||||
/// Art `art` of symbol `name` (stained as the caller draws it) placed by an instance's
|
||||
/// transform `xf`, with strokes at their own weight: through the symbol's 9-slice guides when
|
||||
/// it has them ([`NineSliceMap::place`]), otherwise by `xf`. `None` when placing it through
|
||||
|
||||
@@ -102,7 +102,9 @@ impl<'a> SymbolBoxes<'a> {
|
||||
|
||||
/// Makes these boxes measure every symbol instance as [`Node::reach_bounds_with`] does, by its
|
||||
/// art box alone. An instance that scales or turns stroked art then measures a little larger
|
||||
/// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it.
|
||||
/// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. The
|
||||
/// visual box of an instance placed through 9-slice guides holds the art box placed by each
|
||||
/// cell's map ([`crate::NineSliceMap::placement_bounds`]).
|
||||
pub fn quick(self) -> Self {
|
||||
self.quick.set(true);
|
||||
self
|
||||
@@ -447,6 +449,25 @@ mod tests {
|
||||
assert_eq!(scaled.reach_bounds_with(&s), Some(Rect::new(0.0, 0.0, 60.0, 30.0).inflate(reach, reach)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_boxes_hold_art_that_9_slice_guides_move_past_the_instance() {
|
||||
// A 100 × 100 frame with guides a quarter in, holding an instance of a bar from x 10 to 70.
|
||||
// Scaled 2 times across, the bar crosses the left guide and is placed by the middle
|
||||
// column's map, x → 3x − 50: it draws from x −20 to 160, past the frame's left edge at 0.
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let bar = rect(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), 0.0);
|
||||
symbol(&mut d, "Bar", vec![bar]);
|
||||
let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0);
|
||||
let inner = instance(&mut d, "Bar", Affine::IDENTITY);
|
||||
symbol(&mut d, "Panel", vec![frame, inner]);
|
||||
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
|
||||
let panel = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
|
||||
let exact = panel.visual_bounds_with(&d.symbol_boxes()).unwrap();
|
||||
assert_eq!(exact, Rect::new(-20.0, 0.0, 200.0, 100.0));
|
||||
let quick = panel.visual_bounds_with(&d.symbol_boxes().quick()).unwrap();
|
||||
assert_eq!(quick.union(exact), quick, "{quick:?} holds {exact:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_symbols_and_symbols_inside_themselves_measure_as_the_square() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
|
||||
@@ -451,3 +451,64 @@ fn pica_form_rejects_exponent_notation() {
|
||||
assert_eq!(Unit::Points.parse(s), None, "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Symbol editing of symbol "S" on `layer`.
|
||||
fn symbol_edit_on(layer: NodeId) -> SymbolEdit {
|
||||
SymbolEdit {
|
||||
symbol: "S".into(),
|
||||
layer,
|
||||
instance: None,
|
||||
xf: Affine::IDENTITY,
|
||||
group: false,
|
||||
changed: false,
|
||||
back_isolation: None,
|
||||
back_layer: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The opacity-mask and symbol editing layers are left out of the saved document wherever they
|
||||
/// are, also when `layer.move` made them sublayers of another layer.
|
||||
#[test]
|
||||
fn edit_mode_layers_are_dropped_as_sublayers_too() {
|
||||
let mut d = Document::new(612.0, 792.0);
|
||||
let host = d.layers[0].id;
|
||||
let mask = d.add_layer(Some("Mask"));
|
||||
let symbol = d.add_layer(Some("Symbol"));
|
||||
d.move_node(mask, Some(host), 0).unwrap();
|
||||
d.move_node(symbol, Some(host), usize::MAX).unwrap();
|
||||
let object = d.alloc_id();
|
||||
d.mask_edit = Some(MaskEdit { object, layer: mask });
|
||||
d.symbol_edit = Some(symbol_edit_on(symbol));
|
||||
let saved = d.without_edit_modes();
|
||||
assert!(saved.node(mask).is_none(), "the mask editing layer is left out");
|
||||
assert!(saved.node(symbol).is_none(), "the symbol editing layer is left out");
|
||||
assert!(saved.node(host).is_some_and(|l| l.children().is_some_and(|c| c.is_empty())));
|
||||
assert!(saved.mask_edit.is_none() && saved.symbol_edit.is_none());
|
||||
}
|
||||
|
||||
/// Symbol editing is never read from a file, so a layer that file data names as the editing layer
|
||||
/// loads and stays in the document, and saving does not write the value again.
|
||||
#[test]
|
||||
fn symbol_edit_is_not_read_from_a_file() {
|
||||
let mut d = Document::new(612.0, 792.0);
|
||||
let layer = d.layers[0].id;
|
||||
let mut v = serde_json::to_value(&d).unwrap();
|
||||
v["symbol_edit"] = serde_json::to_value(symbol_edit_on(layer)).unwrap();
|
||||
d = serde_json::from_value(v).unwrap();
|
||||
assert_eq!(d.symbol_edit, None);
|
||||
assert!(d.extra.is_empty(), "not kept as an unknown key");
|
||||
d.drop_edit_modes();
|
||||
assert!(d.node(layer).is_some(), "the layer is kept");
|
||||
assert!(serde_json::to_value(&d).unwrap().get("symbol_edit").is_none(), "not saved again");
|
||||
}
|
||||
|
||||
/// An opacity-mask editing id in file data that names art inside a layer, not a layer, leaves the
|
||||
/// art in place.
|
||||
#[test]
|
||||
fn mask_edit_naming_art_leaves_it() {
|
||||
let (mut d, a, b) = doc_with_rects();
|
||||
d.mask_edit = Some(MaskEdit { object: b, layer: a });
|
||||
d.drop_edit_modes();
|
||||
assert!(d.node(a).is_some() && d.node(b).is_some());
|
||||
assert_eq!(d.mask_edit, None);
|
||||
}
|
||||
@@ -16,7 +16,7 @@ mod wrap;
|
||||
|
||||
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
|
||||
use char_style::yes;
|
||||
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, ScriptMetrics};
|
||||
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, ScriptMetrics};
|
||||
pub use para_style::{
|
||||
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, LeadingModel, Mojikumi, ParaDirection,
|
||||
ParaStyle, SingleWordJustify,
|
||||
|
||||
@@ -147,6 +147,28 @@ pub struct CharStyle {
|
||||
/// document's language (Document Setup). Saved only when set.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub language: Option<String>,
|
||||
/// Another glyph of the font for the run's first character (Glyphs panel › Show › Alternates
|
||||
/// for Current Selection). The text keeps the character; layout draws the chosen glyph while
|
||||
/// the run starts with that character and is set in the face the choice names, and the
|
||||
/// default glyph otherwise. Saved only when set.
|
||||
#[serde(default, rename = "glyphAlternate", skip_serializing_if = "Option::is_none")]
|
||||
pub glyph_alternate: Option<GlyphChoice>,
|
||||
}
|
||||
|
||||
/// A glyph chosen for one character ([`CharStyle::glyph_alternate`]): the glyph id and the face it
|
||||
/// belongs to, named by its PostScript name and version string, so that a glyph id is never used
|
||||
/// in another font or another version of the font.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct GlyphChoice {
|
||||
/// The character the glyph is drawn for.
|
||||
pub ch: char,
|
||||
/// The glyph id in the face.
|
||||
pub gid: u32,
|
||||
/// The face's PostScript name (`SourceSans3-Regular`).
|
||||
pub font: String,
|
||||
/// The face's version string (`Version 3.052`); empty when it has none.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
/// What a character's font size measures ([`CharStyle::font_height_reference`]): the em square
|
||||
@@ -420,6 +442,7 @@ impl Default for CharStyle {
|
||||
font_height_reference: FontHeightReference::EmBox,
|
||||
no_break: false,
|
||||
language: None,
|
||||
glyph_alternate: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
//! The Twist effect's angle in saved documents. A positive angle turns clockwise on the page in
|
||||
//! VectorCraft 0.21.0 and later; earlier releases turned it counterclockwise. Documents of version
|
||||
//! 2 ([`TWIST_CLOCKWISE_SINCE`]) turn clockwise. Version 1 documents written before 0.21.0 have
|
||||
//! their Twist angles negated when they open, so they draw as they were saved
|
||||
//! ([`Document::migrate_twist_angles`], [`written_clockwise`]), and a save for an earlier app
|
||||
//! negates them back ([`Document::store_legacy_twist_angles`]). Graphic style library files
|
||||
//! (`.vcstyles`) of version 1 have their Twist angles negated when they are read
|
||||
//! ([`crate::style_libs::read`]); [`crate::style_libs::write`] writes version 2.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::style_libs::StyleLibrary;
|
||||
use crate::{Appearance, Document, Effect, Node};
|
||||
|
||||
/// The Twist effect's id.
|
||||
pub const TWIST: &str = "distort.twist";
|
||||
|
||||
/// The first document version whose Twist angles turn clockwise for a positive value.
|
||||
pub const TWIST_CLOCKWISE_SINCE: u32 = 2;
|
||||
|
||||
/// The first release (major, minor) whose Twist turned clockwise for a positive angle.
|
||||
const CLOCKWISE_RELEASE: (u64, u64) = (0, 21);
|
||||
|
||||
/// Did the app named by a native file's `generator` (`"VectorCraft 0.21.0"`) turn Twist effects
|
||||
/// clockwise for a positive angle? It did from 0.21.0. Any other value, or none, is an earlier
|
||||
/// app (DrawCraft included).
|
||||
pub fn written_clockwise(generator: Option<&str>) -> bool {
|
||||
let Some(version) = generator.and_then(|g| g.strip_prefix("VectorCraft ")) else { return false };
|
||||
let mut parts = version.split('.').map(|p| p.parse::<u64>().ok());
|
||||
match (parts.next().flatten(), parts.next().flatten()) {
|
||||
(Some(major), Some(minor)) => (major, minor) >= CLOCKWISE_RELEASE,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The angle a Twist effect without a readable one draws with (`vectorcraft-effects` reads a
|
||||
/// missing or unreadable `angle` as this).
|
||||
const DEFAULT_ANGLE: f64 = 10.0;
|
||||
|
||||
/// The key of `Document::unknown` that holds the brush definitions (`vectorcraft-brush`'s
|
||||
/// `DOC_KEY`), whose art can carry effects.
|
||||
const BRUSHES_KEY: &str = "brushes";
|
||||
|
||||
/// The angle a Twist effect with `params` draws with, read as `vectorcraft-effects` reads it: a
|
||||
/// number, the number a string starts with, or a boolean as 1 or 0; anything else (or a value
|
||||
/// that is not finite) is [`DEFAULT_ANGLE`].
|
||||
fn angle(params: &Value) -> f64 {
|
||||
let v = match params.get("angle") {
|
||||
Some(Value::Number(n)) => n.as_f64(),
|
||||
Some(Value::String(s)) => {
|
||||
let t: String = s.trim().chars().take_while(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E')).collect();
|
||||
t.parse().ok()
|
||||
}
|
||||
Some(Value::Bool(b)) => Some(if *b { 1.0 } else { 0.0 }),
|
||||
_ => None,
|
||||
};
|
||||
v.filter(|v| v.is_finite()).unwrap_or(DEFAULT_ANGLE)
|
||||
}
|
||||
|
||||
/// Write the negated angle a Twist effect with `params` draws with into `params`, as a number.
|
||||
fn negate_params(params: &mut Value) {
|
||||
// `0.0 - a` rather than `-a`: an angle of 0 stays 0, not -0.
|
||||
let turned = Value::from(0.0 - angle(params));
|
||||
match params {
|
||||
Value::Object(m) => {
|
||||
m.insert("angle".into(), turned);
|
||||
}
|
||||
p => *p = json!({ "angle": turned }),
|
||||
}
|
||||
}
|
||||
|
||||
fn has_twist(fx: &[Effect]) -> bool {
|
||||
fx.iter().any(|e| e.id == TWIST)
|
||||
}
|
||||
|
||||
fn appearance_has_twist(a: &Appearance) -> bool {
|
||||
has_twist(&a.effects) || a.items.iter().any(|i| has_twist(i.effects()))
|
||||
}
|
||||
|
||||
fn negate_appearance(a: &mut Appearance) {
|
||||
for e in a.effects.iter_mut().chain(a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut())) {
|
||||
if e.id == TWIST {
|
||||
negate_params(&mut e.params);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The appearances a Shaper Group's face and edge edits paint with.
|
||||
fn shaper_appearances(n: &Node) -> impl Iterator<Item = &Appearance> {
|
||||
let s = n.extras().shaper.as_deref();
|
||||
let faces = s.into_iter().flat_map(|s| s.faces.iter().filter_map(|f| f.paint.as_ref()));
|
||||
let edges = s.into_iter().flat_map(|s| s.edges.iter().filter_map(|e| e.paint.as_ref()));
|
||||
faces.chain(edges)
|
||||
}
|
||||
|
||||
/// Does `n`'s subtree (opacity-mask art and Shaper edits included) hold a Twist effect?
|
||||
fn node_has_twist(n: &Node) -> bool {
|
||||
appearance_has_twist(&n.appearance)
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| node_has_twist(&m.art))
|
||||
|| shaper_appearances(n).any(appearance_has_twist)
|
||||
|| n.children().is_some_and(|c| c.iter().any(|c| node_has_twist(c)))
|
||||
}
|
||||
|
||||
/// Negate the Twist angles of `a`'s subtree, copying only the nodes on the way to them.
|
||||
fn negate_node(a: &mut Arc<Node>) {
|
||||
if !node_has_twist(a) {
|
||||
return;
|
||||
}
|
||||
let n = Arc::make_mut(a);
|
||||
if appearance_has_twist(&n.appearance) {
|
||||
negate_appearance(&mut n.appearance);
|
||||
}
|
||||
if let Some(x) = n.extras_if_any() {
|
||||
if let Some(m) = x.mask.as_mut() {
|
||||
negate_node(&mut m.art);
|
||||
}
|
||||
if let Some(s) = x.shaper.as_mut() {
|
||||
let faces = s.faces.iter_mut().filter_map(|f| f.paint.as_mut());
|
||||
for p in faces.chain(s.edges.iter_mut().filter_map(|e| e.paint.as_mut())) {
|
||||
negate_appearance(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
negate_node(c);
|
||||
}
|
||||
}
|
||||
|
||||
fn is_twist_json(m: &Map<String, Value>) -> bool {
|
||||
m.get("id").and_then(Value::as_str) == Some(TWIST)
|
||||
}
|
||||
|
||||
/// Does JSON `v` (brush definitions) hold a Twist effect?
|
||||
fn json_has_twist(v: &Value) -> bool {
|
||||
match v {
|
||||
Value::Object(m) => is_twist_json(m) || m.values().any(json_has_twist),
|
||||
Value::Array(a) => a.iter().any(json_has_twist),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Negate the Twist angles in JSON `v`: every object whose `id` is [`TWIST`] is a serialized
|
||||
/// [`Effect`] (object ids are numbers).
|
||||
fn negate_json(v: &mut Value) {
|
||||
match v {
|
||||
Value::Object(m) if is_twist_json(m) => negate_params(m.entry("params").or_insert(Value::Null)),
|
||||
Value::Object(m) => m.values_mut().for_each(negate_json),
|
||||
Value::Array(a) => a.iter_mut().for_each(negate_json),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Negate every Twist angle of a graphic style library: its styles' and its patterns' art.
|
||||
pub(crate) fn negate_library(lib: &mut StyleLibrary) {
|
||||
for g in &mut lib.styles {
|
||||
negate_appearance(&mut g.appearance);
|
||||
}
|
||||
for p in &mut lib.patterns {
|
||||
p.art.iter_mut().for_each(negate_node);
|
||||
}
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// A document before version [`TWIST_CLOCKWISE_SINCE`] that holds a Twist effect: when
|
||||
/// `written_clockwise` (asked only then; see [`written_clockwise`]) says the app that saved it
|
||||
/// turned Twist counterclockwise, negate its Twist angles, so it draws as it was saved. A later
|
||||
/// version is left as it is, and the document's version is not changed. It recurses through
|
||||
/// the art, once per level of nesting.
|
||||
pub fn migrate_twist_angles(&mut self, written_clockwise: impl FnOnce() -> bool) {
|
||||
if self.version >= TWIST_CLOCKWISE_SINCE || !self.has_twist() || written_clockwise() {
|
||||
return;
|
||||
}
|
||||
self.negate_twist_angles();
|
||||
}
|
||||
|
||||
/// The reverse of [`Document::migrate_twist_angles`], for saving for an app that turned Twist
|
||||
/// counterclockwise: negate the Twist angles and mark the document version 1. Call it on a
|
||||
/// document whose angles turn clockwise, as every opened or new document's do, whatever
|
||||
/// version another conversion for that save has marked it already.
|
||||
pub fn store_legacy_twist_angles(&mut self) {
|
||||
self.version = TWIST_CLOCKWISE_SINCE - 1;
|
||||
if self.has_twist() {
|
||||
self.negate_twist_angles();
|
||||
}
|
||||
}
|
||||
|
||||
/// Does any Twist effect sit where [`Document::negate_twist_angles`] negates them?
|
||||
fn has_twist(&self) -> bool {
|
||||
let mut roots = self
|
||||
.layers
|
||||
.iter()
|
||||
.chain(self.symbols.iter().map(|s| &s.art))
|
||||
.chain(self.graph_designs.iter().map(|g| &g.art))
|
||||
.chain(self.patterns.iter().flat_map(|p| p.art.iter()))
|
||||
.chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter()));
|
||||
roots.any(|r| node_has_twist(r))
|
||||
|| self.graphic_styles.iter().any(|g| appearance_has_twist(&g.appearance))
|
||||
|| self.unknown.get(BRUSHES_KEY).is_some_and(json_has_twist)
|
||||
}
|
||||
|
||||
/// Negate every Twist angle: in the art of the layers, symbols, graph designs, pattern
|
||||
/// swatches and the pattern definition that pattern editing's Cancel puts back (opacity-mask
|
||||
/// art and Shaper edits included), in the graphic styles and in the brush definitions.
|
||||
fn negate_twist_angles(&mut self) {
|
||||
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 {
|
||||
negate_node(root);
|
||||
}
|
||||
if self.graphic_styles.iter().any(|g| appearance_has_twist(&g.appearance)) {
|
||||
for g in self.graphic_styles.iter_mut() {
|
||||
negate_appearance(&mut g.appearance);
|
||||
}
|
||||
}
|
||||
if self.unknown.get(BRUSHES_KEY).is_some_and(json_has_twist)
|
||||
&& let Some(b) = self.unknown.get_mut(BRUSHES_KEY)
|
||||
{
|
||||
negate_json(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,186 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_geom::{Point, Rect, shapes};
|
||||
|
||||
use super::*;
|
||||
use crate::shaper::{FaceEdit, FaceSelector, ShaperSpec};
|
||||
use crate::{GraphicStyle, OpacityMask, PatternDef, Symbol};
|
||||
|
||||
fn fx(id: &str, params: Value) -> Effect {
|
||||
Effect { id: id.into(), params, visible: true }
|
||||
}
|
||||
|
||||
/// An appearance with a Twist of `params` on the object and on its fill, and a Roughen.
|
||||
fn twisted_appearance(params: &Value) -> Appearance {
|
||||
let mut a = Appearance::default_art();
|
||||
a.effects.push(fx(TWIST, params.clone()));
|
||||
a.effects.push(fx("distort.roughen", json!({"size": 5})));
|
||||
a.items[0].effects_mut().push(fx(TWIST, params.clone()));
|
||||
a
|
||||
}
|
||||
|
||||
fn twisted(d: &mut Document, params: &Value) -> Node {
|
||||
Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), twisted_appearance(params))
|
||||
}
|
||||
|
||||
/// A version 1 document with Twist effects of `params` everywhere one is stored: on a path, in a
|
||||
/// group, in an opacity mask's art, in a Shaper edit, in a symbol, a pattern swatch and a graphic
|
||||
/// style, and `brush` in a brush definition. Its first layer holds the art; its last has no
|
||||
/// Twist.
|
||||
fn document(params: &Value, brush: &Value) -> Document {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let l = d.layers[0].id;
|
||||
let path = twisted(&mut d, params);
|
||||
d.insert(Some(l), 0, path).unwrap();
|
||||
let inner = twisted(&mut d, params);
|
||||
let group = Node::group(d.alloc_id(), vec![Arc::new(inner)]);
|
||||
d.insert(Some(l), 1, group).unwrap();
|
||||
let mask_art = twisted(&mut d, params);
|
||||
let mut masked = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art());
|
||||
masked.extras_mut().mask = Some(Box::new(OpacityMask::new(mask_art, true)));
|
||||
d.insert(Some(l), 2, masked).unwrap();
|
||||
let mut shaper = Node::group(d.alloc_id(), vec![]);
|
||||
let face = FaceEdit {
|
||||
selector: FaceSelector { sources: vec![0], anchor: Point::ZERO },
|
||||
erase: false,
|
||||
erase_edges: false,
|
||||
paint_source: None,
|
||||
merge: None,
|
||||
paint: Some(twisted_appearance(params)),
|
||||
};
|
||||
shaper.extras_mut().shaper = Some(Box::new(ShaperSpec { faces: vec![face], edges: vec![] }));
|
||||
d.insert(Some(l), 3, shaper).unwrap();
|
||||
let art = twisted(&mut d, params);
|
||||
d.symbols.push(Symbol { name: "S".into(), art: Arc::new(art), dynamic: false });
|
||||
let art = twisted(&mut d, params);
|
||||
d.patterns.push(PatternDef::new("P", vec![Arc::new(art)]));
|
||||
d.graphic_styles.push(GraphicStyle::new("G", twisted_appearance(params)));
|
||||
d.unknown.insert(BRUSHES_KEY.into(), json!([{"name": "B", "art": {"id": 99, "appearance": {"effects": [brush]}}}]));
|
||||
d.add_layer(None);
|
||||
d.version = 1;
|
||||
d
|
||||
}
|
||||
|
||||
/// The angle each Twist effect of the saved document draws with, in the order the JSON lists them.
|
||||
fn angles(d: &Document) -> Vec<f64> {
|
||||
fn walk(v: &Value, out: &mut Vec<f64>) {
|
||||
match v {
|
||||
Value::Object(m) => {
|
||||
if is_twist_json(m) {
|
||||
out.push(angle(m.get("params").unwrap_or(&Value::Null)));
|
||||
}
|
||||
m.values().for_each(|c| walk(c, out));
|
||||
}
|
||||
Value::Array(a) => a.iter().for_each(|c| walk(c, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
walk(&serde_json::to_value(d).unwrap(), &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_version_1_document_from_before_0_21_has_its_twist_angles_negated() {
|
||||
let mut d = document(&json!({"angle": 30}), &json!({"id": TWIST}));
|
||||
let before = angles(&d);
|
||||
// Two per path, shaper edit and style; one in the brush.
|
||||
assert_eq!(before.len(), 15, "{before:?}");
|
||||
assert_eq!(before.iter().filter(|&&a| a == DEFAULT_ANGLE).count(), 1, "{before:?}");
|
||||
d.migrate_twist_angles(|| false);
|
||||
assert_eq!(d.version, 1, "the caller sets the version");
|
||||
assert_eq!(angles(&d), before.iter().map(|a| -a).collect::<Vec<_>>());
|
||||
let roughen = serde_json::to_string(&d).unwrap().matches(r#""id":"distort.roughen","params":{"size":5}"#).count();
|
||||
assert_eq!(roughen, 7, "other effects are left alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_that_turned_clockwise_is_left_as_it_is() {
|
||||
let mut d = document(&json!({"angle": 30}), &json!({"id": TWIST, "params": {"angle": 30}}));
|
||||
let before = d.clone();
|
||||
d.migrate_twist_angles(|| true);
|
||||
assert_eq!(d, before, "version 1, written by 0.21.0 or later");
|
||||
d.version = 2;
|
||||
let before = d.clone();
|
||||
d.migrate_twist_angles(|| panic!("a version 2 document's writer is not asked about"));
|
||||
assert_eq!(d, before, "version 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_writer_is_asked_about_only_when_a_twist_is_stored() {
|
||||
let mut d = Document::new(10.0, 10.0);
|
||||
d.version = 1;
|
||||
let before = d.clone();
|
||||
d.migrate_twist_angles(|| panic!("a document without a Twist needs no answer"));
|
||||
assert_eq!(d, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angles_are_read_as_the_effect_reads_them() {
|
||||
let read = |params: Value| {
|
||||
let mut e = fx(TWIST, params);
|
||||
negate_params(&mut e.params);
|
||||
e.params
|
||||
};
|
||||
assert_eq!(read(json!({"angle": 30, "x": 1})), json!({"angle": -30.0, "x": 1}));
|
||||
assert_eq!(read(json!({"angle": "45 deg"})), json!({"angle": -45.0}));
|
||||
assert_eq!(read(json!({"angle": true})), json!({"angle": -1.0}));
|
||||
assert_eq!(read(json!({})), json!({"angle": -10.0}));
|
||||
assert_eq!(read(Value::Null), json!({"angle": -10.0}));
|
||||
let zero = read(json!({"angle": 0}));
|
||||
assert!(zero["angle"].as_f64().is_some_and(|a| a == 0.0 && a.is_sign_positive()), "{zero}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_art_holding_a_twist_is_copied() {
|
||||
let mut d = document(&json!({"angle": 30}), &json!({"id": TWIST}));
|
||||
let plain = d.layers.last().cloned().unwrap();
|
||||
let twisted = d.layers[0].clone();
|
||||
d.migrate_twist_angles(|| false);
|
||||
assert!(Arc::ptr_eq(d.layers.last().unwrap(), &plain), "a layer without a Twist is not copied");
|
||||
assert!(!Arc::ptr_eq(&d.layers[0], &twisted));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn storing_for_an_earlier_app_and_reading_back_round_trips() {
|
||||
let original = document(&json!({"angle": 30.0}), &json!({"id": TWIST, "params": {"angle": -12.5}}));
|
||||
let mut d = original.clone();
|
||||
d.migrate_twist_angles(|| false);
|
||||
d.version = 2;
|
||||
let current = d.clone();
|
||||
assert_eq!(angles(¤t), angles(&original).iter().map(|a| -a).collect::<Vec<_>>());
|
||||
d.store_legacy_twist_angles();
|
||||
assert_eq!(d, original);
|
||||
d.migrate_twist_angles(|| false);
|
||||
d.version = 2;
|
||||
assert_eq!(d, current);
|
||||
// Another conversion for the same save may have marked the document version 1 already.
|
||||
d.version = 1;
|
||||
d.store_legacy_twist_angles();
|
||||
assert_eq!(d, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_version_1_style_library_has_its_twist_angles_negated() {
|
||||
let lib = StyleLibrary { name: "L".into(), styles: vec![GraphicStyle::new("G", twisted_appearance(&json!({"angle": 30.0})))], patterns: vec![] };
|
||||
let text = crate::style_libs::write(&lib);
|
||||
assert!(text.contains(r#""version": 2"#), "{text}");
|
||||
assert_eq!(crate::style_libs::read(&text, "x").unwrap(), lib, "a version 2 file reads as written");
|
||||
let old = crate::style_libs::read(&text.replacen(r#""version": 2"#, r#""version": 1"#, 1), "x").unwrap();
|
||||
let fx = &old.styles[0].appearance.effects;
|
||||
assert_eq!(fx[0].params, json!({"angle": -30.0}));
|
||||
assert_eq!(fx[1], lib.styles[0].appearance.effects[1]);
|
||||
assert_eq!(old.styles[0].appearance.items[0].effects()[0].params, json!({"angle": -30.0}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn releases_from_0_21_turned_twist_clockwise() {
|
||||
for g in ["VectorCraft 0.21.0", "VectorCraft 0.21.4", "VectorCraft 0.22.0-dev", "VectorCraft 1.0.0"] {
|
||||
assert!(written_clockwise(Some(g)), "{g}");
|
||||
}
|
||||
for g in ["VectorCraft 0.20.0", "VectorCraft 0.9.12", "DrawCraft 0.1.0", "VectorCraft", "VectorCraft x.y", "vectorcraft 0.21.0"] {
|
||||
assert!(!written_clockwise(Some(g)), "{g}");
|
||||
}
|
||||
assert!(!written_clockwise(None));
|
||||
}
|
||||
@@ -77,7 +77,7 @@ pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_par
|
||||
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
|
||||
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
|
||||
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
|
||||
pub use raster::{RASTERIZE, RasterFx, Rasterize, outset, raster_effects};
|
||||
pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, outset, raster_effects};
|
||||
pub use reshape::{
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, has_gradient_copies, has_item_geometry, has_transform_art, has_transform_options, image_paint,
|
||||
needs_outline, outline_art, outline_text, reshape,
|
||||
|
||||
@@ -366,7 +366,7 @@ pub fn blend_mode(s: &str) -> BlendMode {
|
||||
}
|
||||
|
||||
/// An effect's `color` parameter (`"#rrggbb"`, `[r, g, b]` 0..1 or a colour object).
|
||||
pub(crate) fn color_param(p: &Value, default: Color) -> Color {
|
||||
pub fn color_param(p: &Value, default: Color) -> Color {
|
||||
match p.get("color") {
|
||||
Some(Value::String(s)) => Color::from_hex(s).unwrap_or(default),
|
||||
Some(Value::Array(a)) if a.len() >= 3 => {
|
||||
|
||||
@@ -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 }
|
||||
@@ -0,0 +1,320 @@
|
||||
//! `cargo run --release -p vectorcraft-engine --example anchor_bench` prints the wall time of the
|
||||
//! engine steps of editing anchors with Direct Selection, on three synthetic documents: one closed path of
|
||||
//! 50,000 anchors, 2,000 closed paths of 50 anchors each, and one open path of 200,000 anchors.
|
||||
//! `ITERS` sets the runs per step (default 7); each row is the median in ms.
|
||||
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_engine::tools::{Mods, PointerEvent, PointerKind};
|
||||
use vectorcraft_engine::{Session, ViewInfo};
|
||||
use vectorcraft_geom::{Affine, Anchor, PathData, Point, SubPath, Vec2};
|
||||
use vectorcraft_render::{RenderOptions, Renderer};
|
||||
|
||||
/// Anchors are 10 pt apart and their handles 3 pt long, along the path.
|
||||
const STEP: f64 = 10.0;
|
||||
const HANDLE: f64 = 3.0;
|
||||
|
||||
/// A test document: its paths, an anchor to hover, click and drag, a point on a segment, and a
|
||||
/// marquee from an empty point over about 10,000 anchors.
|
||||
struct Shape {
|
||||
name: &'static str,
|
||||
doc: Document,
|
||||
ids: Vec<NodeId>,
|
||||
anchor: (NodeId, usize),
|
||||
segment: Point,
|
||||
marquee: (Point, Point),
|
||||
}
|
||||
|
||||
/// A closed path of `n` smooth anchors around `center`.
|
||||
fn circle(center: Point, n: usize) -> PathData {
|
||||
let r = n as f64 * STEP / std::f64::consts::TAU;
|
||||
let anchors = (0..n)
|
||||
.map(|i| {
|
||||
let t = i as f64 / n as f64 * std::f64::consts::TAU;
|
||||
let p = center + Vec2::new(r * t.cos(), r * t.sin());
|
||||
Anchor::smooth(p, p + Vec2::new(-t.sin(), t.cos()) * HANDLE)
|
||||
})
|
||||
.collect();
|
||||
PathData::single(SubPath::new(anchors, true))
|
||||
}
|
||||
|
||||
fn add(doc: &mut Document, path: PathData) -> NodeId {
|
||||
let l = doc.layers.first().map(|l| l.id);
|
||||
let id = doc.alloc_id();
|
||||
doc.insert(l, usize::MAX, Node::path(id, path, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
fn one_outline() -> Shape {
|
||||
let n = 50_000;
|
||||
let mut doc = Document::new(1600.0, 1200.0);
|
||||
let id = add(&mut doc, circle(Point::ZERO, n));
|
||||
let r = n as f64 * STEP / std::f64::consts::TAU;
|
||||
let a = 72f64.to_radians();
|
||||
let mid = (n / 2) as f64 / n as f64 * std::f64::consts::TAU;
|
||||
let next = (n / 2 + 1) as f64 / n as f64 * std::f64::consts::TAU;
|
||||
let segment = Point::new(r * (mid.cos() + next.cos()) / 2.0, r * (mid.sin() + next.sin()) / 2.0);
|
||||
Shape {
|
||||
name: "one closed path, 50,000 anchors",
|
||||
doc,
|
||||
ids: vec![id],
|
||||
anchor: (id, n / 2),
|
||||
segment,
|
||||
marquee: (Point::new(r + 50.0, -5.0), Point::new(r * a.cos() - 1.0, r * a.sin() + 1.0)),
|
||||
}
|
||||
}
|
||||
|
||||
fn many_paths() -> Shape {
|
||||
let mut doc = Document::new(1600.0, 1200.0);
|
||||
let ids: Vec<NodeId> =
|
||||
(0..2000).map(|i| add(&mut doc, circle(Point::new((i % 50) as f64 * 200.0 + 100.0, (i / 50) as f64 * 200.0 + 100.0), 50))).collect();
|
||||
let r = 50.0 * STEP / std::f64::consts::TAU;
|
||||
// Path 1,025 (row 20, column 25), its anchors 0 and 1.
|
||||
let c = Point::new(25.0 * 200.0 + 100.0, 20.0 * 200.0 + 100.0);
|
||||
let t = std::f64::consts::TAU / 50.0;
|
||||
let segment = c + Vec2::new(r * (1.0 + t.cos()) / 2.0, r * t.sin() / 2.0);
|
||||
Shape {
|
||||
name: "2,000 closed paths, 50 anchors each",
|
||||
doc,
|
||||
anchor: (ids[1025], 0),
|
||||
ids,
|
||||
segment,
|
||||
marquee: (Point::ZERO, Point::new(10_000.0, 800.0)),
|
||||
}
|
||||
}
|
||||
|
||||
fn long_open_path() -> Shape {
|
||||
let n = 200_000;
|
||||
let mut doc = Document::new(1600.0, 1200.0);
|
||||
let anchors = (0..n)
|
||||
.map(|i| {
|
||||
let p = Point::new(i as f64 * STEP, 0.0);
|
||||
Anchor::smooth(p, p + Vec2::new(HANDLE, 0.0))
|
||||
})
|
||||
.collect();
|
||||
let id = add(&mut doc, PathData::single(SubPath::new(anchors, false)));
|
||||
Shape {
|
||||
name: "one open path, 200,000 anchors",
|
||||
doc,
|
||||
ids: vec![id],
|
||||
anchor: (id, n / 2),
|
||||
segment: Point::new((n / 2) as f64 * STEP + STEP / 2.0, 0.0),
|
||||
marquee: (Point::new(-5.0, -20.0), Point::new(99_995.0, 30.0)),
|
||||
}
|
||||
}
|
||||
|
||||
fn iters() -> usize {
|
||||
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
|
||||
}
|
||||
|
||||
fn median(mut ms: Vec<f64>) -> f64 {
|
||||
ms.sort_by(f64::total_cmp);
|
||||
ms[ms.len() / 2]
|
||||
}
|
||||
|
||||
fn time(mut f: impl FnMut()) -> f64 {
|
||||
median(
|
||||
(0..iters())
|
||||
.map(|_| {
|
||||
let t = Instant::now();
|
||||
f();
|
||||
t.elapsed().as_secs_f64() * 1000.0
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn ev(kind: PointerKind, p: Point) -> PointerEvent {
|
||||
PointerEvent::new(kind, p.x, p.y)
|
||||
}
|
||||
|
||||
fn exec(s: &mut Session, cmd: &str, p: Value) {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"));
|
||||
}
|
||||
|
||||
fn anchor_at(s: &Session, (id, ai): (NodeId, usize)) -> Anchor {
|
||||
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[ai]
|
||||
}
|
||||
|
||||
/// The anchors selected: those direct-selected, and every anchor of a path selected whole.
|
||||
fn selected_anchors(s: &Session) -> usize {
|
||||
let st = s.doc().unwrap();
|
||||
let count = |id: &NodeId| st.doc.node(*id).and_then(|n| n.path_data()).map_or(0, |pd| pd.anchors().count());
|
||||
st.selection.objects.iter().map(|id| st.selection.partial(*id).map_or_else(|| count(id), |set| set.len())).sum()
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn row(name: &str, ms: f64) {
|
||||
println!(" {name:<58} {ms:>10.3} ms");
|
||||
}
|
||||
|
||||
/// Select `count` anchors: the first ones of the first path, or the first anchors of as many
|
||||
/// paths as needed.
|
||||
fn select_count(s: &mut Session, shape: &Shape, count: usize) {
|
||||
exec(s, "select.none", json!({}));
|
||||
let mut left = count;
|
||||
for id in &shape.ids {
|
||||
if left == 0 {
|
||||
break;
|
||||
}
|
||||
let n = s.doc().unwrap().doc.node(*id).unwrap().path_data().unwrap().subpaths[0].anchors.len();
|
||||
let take = left.min(n);
|
||||
let refs: Vec<[usize; 2]> = (0..take).map(|i| [0, i]).collect();
|
||||
exec(s, "select.anchors", json!({"id": id.0, "anchors": refs, "mode": "add"}));
|
||||
left -= take;
|
||||
}
|
||||
}
|
||||
|
||||
fn bench(shape: Shape) {
|
||||
println!("{}", shape.name);
|
||||
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
|
||||
let mut s = Session::new();
|
||||
s.add_document(shape.doc.clone(), None);
|
||||
s.select_tool("directSelection", view).unwrap();
|
||||
let a = anchor_at(&s, shape.anchor).p;
|
||||
let none = Mods::default();
|
||||
{
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let opt = vectorcraft_doc::hit::HitOptions { tol: 3.0, clip_outlines: true, ..Default::default() };
|
||||
row("hit test at an anchor", time(|| drop(black_box(vectorcraft_doc::hit::hit_test(&doc, a, opt)))));
|
||||
row("hit test at a segment", time(|| drop(black_box(vectorcraft_doc::hit::hit_test(&doc, shape.segment, opt)))));
|
||||
row("hit test beside the path", time(|| drop(black_box(vectorcraft_doc::hit::hit_test(&doc, shape.segment + Vec2::new(0.0, 40.0), opt)))));
|
||||
}
|
||||
|
||||
// Hover with nothing selected, then with one anchor of the path selected.
|
||||
for selected in [false, true] {
|
||||
if selected {
|
||||
exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"}));
|
||||
}
|
||||
let what = if selected { "one anchor selected" } else { "nothing selected" };
|
||||
row(&format!("hover over an anchor, {what}"), time(|| drop(s.pointer(&ev(PointerKind::Move, a), view).unwrap())));
|
||||
row(&format!("cursor over an anchor, {what}"), time(|| _ = black_box(s.cursor(a, none, view))));
|
||||
row(&format!("hover over a segment, {what}"), time(|| drop(s.pointer(&ev(PointerKind::Move, shape.segment), view).unwrap())));
|
||||
row(&format!("cursor over a segment, {what}"), time(|| _ = black_box(s.cursor(shape.segment, none, view))));
|
||||
}
|
||||
|
||||
// A click that selects one anchor.
|
||||
exec(&mut s, "select.none", json!({}));
|
||||
row(
|
||||
"click that selects one anchor",
|
||||
time(|| {
|
||||
s.pointer(&ev(PointerKind::Down, a), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, a), view).unwrap();
|
||||
}),
|
||||
);
|
||||
assert_eq!(selected_anchors(&s), 1, "the click selects one anchor");
|
||||
|
||||
// One anchor dragged: each pointer move, then the release.
|
||||
let undo = undo_len(&s);
|
||||
s.pointer(&ev(PointerKind::Down, a), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, a + Vec2::new(0.0, 20.0)), view).unwrap();
|
||||
let mut y = 20.0;
|
||||
row(
|
||||
"anchor drag, one pointer move",
|
||||
time(|| {
|
||||
y += 1.0;
|
||||
s.pointer(&ev(PointerKind::Drag, a + Vec2::new(0.0, y)), view).unwrap();
|
||||
}),
|
||||
);
|
||||
let t = Instant::now();
|
||||
s.pointer(&ev(PointerKind::Up, a + Vec2::new(0.0, y)), view).unwrap();
|
||||
row("anchor drag, release (commit)", t.elapsed().as_secs_f64() * 1000.0);
|
||||
assert_eq!(undo_len(&s), undo + 1, "the anchor drag records one step");
|
||||
exec(&mut s, "edit.undo", json!({}));
|
||||
|
||||
// The selected anchor's outgoing handle dragged.
|
||||
exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"}));
|
||||
let h = anchor_at(&s, shape.anchor).h_out;
|
||||
let undo = undo_len(&s);
|
||||
s.pointer(&ev(PointerKind::Down, h), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, h + Vec2::new(0.0, 20.0)), view).unwrap();
|
||||
let mut y = 20.0;
|
||||
row(
|
||||
"handle drag, one pointer move",
|
||||
time(|| {
|
||||
y += 1.0;
|
||||
s.pointer(&ev(PointerKind::Drag, h + Vec2::new(0.0, y)), view).unwrap();
|
||||
}),
|
||||
);
|
||||
let t = Instant::now();
|
||||
s.pointer(&ev(PointerKind::Up, h + Vec2::new(0.0, y)), view).unwrap();
|
||||
row("handle drag, release (commit)", t.elapsed().as_secs_f64() * 1000.0);
|
||||
assert_eq!(undo_len(&s), undo + 1, "the handle drag records one step");
|
||||
assert_eq!(anchor_at(&s, shape.anchor).p, a, "the handle drag leaves the anchor in place");
|
||||
exec(&mut s, "edit.undo", json!({}));
|
||||
|
||||
// A marquee over about 10,000 anchors.
|
||||
let (m0, m1) = shape.marquee;
|
||||
let ms = time(|| {
|
||||
exec(&mut s, "select.none", json!({}));
|
||||
s.pointer(&ev(PointerKind::Down, m0), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, m0.lerp(m1, 0.5)), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, m1), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, m1), view).unwrap();
|
||||
});
|
||||
row(&format!("marquee over {} anchors (press to release)", selected_anchors(&s)), ms);
|
||||
|
||||
// Select All with Direct Selection.
|
||||
row("Select All", time(|| exec(&mut s, "select.all", json!({}))));
|
||||
row("tool overlays, everything selected", time(|| drop(s.overlays(view))));
|
||||
|
||||
// Nudges of 1, 1,000 and every anchor, and Undo and Redo of each.
|
||||
let total: usize = shape.ids.iter().map(|id| s.doc().unwrap().doc.node(*id).unwrap().path_data().unwrap().subpaths[0].anchors.len()).sum();
|
||||
for count in [1, 1000, total] {
|
||||
select_count(&mut s, &shape, count);
|
||||
row(&format!("nudge of {count} anchors"), time(|| exec(&mut s, "path.moveAnchors", json!({"dx": 1, "dy": 0}))));
|
||||
row(&format!("undo of a nudge of {count} anchors"), time(|| exec(&mut s, "edit.undo", json!({}))));
|
||||
row(&format!("redo of a nudge of {count} anchors"), time(|| exec(&mut s, "edit.redo", json!({}))));
|
||||
}
|
||||
|
||||
// The render of the document after one anchor moves (the renderer warm).
|
||||
exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"}));
|
||||
let opts = RenderOptions::default();
|
||||
let mut r = Renderer::new();
|
||||
let at = Affine::translate(Vec2::new(800.0 - a.x, 600.0 - a.y));
|
||||
r.render(&s.doc().unwrap().doc, 1600, 1200, at, &opts);
|
||||
let ms = median(
|
||||
(0..iters())
|
||||
.map(|_| {
|
||||
exec(&mut s, "path.moveAnchors", json!({"dx": 0, "dy": 1}));
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let t = Instant::now();
|
||||
drop(r.render(&doc, 1600, 1200, at, &opts));
|
||||
t.elapsed().as_secs_f64() * 1000.0
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
row("render 1600x1200 around the anchor after it moves", ms);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
row("render 1600x1200 around the anchor, nothing changed", time(|| drop(r.render(&doc, 1600, 1200, at, &opts))));
|
||||
|
||||
// Delete of one anchor, undone after each run.
|
||||
let ms = median(
|
||||
(0..iters())
|
||||
.map(|_| {
|
||||
exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"}));
|
||||
let t = Instant::now();
|
||||
exec(&mut s, "edit.clear", json!({}));
|
||||
let ms = t.elapsed().as_secs_f64() * 1000.0;
|
||||
exec(&mut s, "edit.undo", json!({}));
|
||||
ms
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
row("Delete of one anchor", ms);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
bench(one_outline());
|
||||
bench(many_paths());
|
||||
bench(long_open_path());
|
||||
}
|
||||
@@ -168,9 +168,9 @@ pub fn has_selection(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
if st.selection.is_empty() { Err("nothing selected".into()) } else { Ok(()) }
|
||||
}
|
||||
/// Objects are selected, or the Artboard tool is chosen (Copy and Cut take its artboard).
|
||||
pub fn has_selection_or_artboard_tool(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.tool_id() == "artboard" { has_doc(s) } else { has_selection(s) }
|
||||
/// Objects or ruler guides are selected, or the Artboard tool is chosen (what Copy and Cut take).
|
||||
pub fn has_selection_guides_or_artboard_tool(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.tool_id() == "artboard" { has_doc(s) } else { has_selection_or_guides(s) }
|
||||
}
|
||||
/// Objects or ruler guides are selected (what Delete and the arrow keys act on).
|
||||
pub fn has_selection_or_guides(s: &Session) -> std::result::Result<(), String> {
|
||||
@@ -484,9 +484,10 @@ pub fn matrix_param(p: &Value, key: &str) -> Option<Affine> {
|
||||
}
|
||||
/// A colour from `"#rrggbb"`, a colour key (`"cmyk 0 100 100 0"`, `"lab 55 60 40"`), `[r,g,b]` (0..1),
|
||||
/// `{"c":..,"m":..,"y":..,"k":..}` (percent when any component is above 1, else 0..1), `{"gray":..}` or `{"l":..,"a":..,"b":..}` (CIE Lab: L 0..100, a and b about
|
||||
/// −128..127).
|
||||
/// −128..127). `None` for a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without the `#`).
|
||||
pub fn color_value(v: &Value) -> Option<Color> {
|
||||
match v {
|
||||
Value::String(s) if hex_with_alpha(s) => None,
|
||||
// A hex, or a colour key ("cmyk 0 100 100 0", as Recolor Artwork lists colours).
|
||||
Value::String(s) => Color::from_hex(s).or_else(|| vectorcraft_color::recolor::ColorKey::parse(s).map(|k| k.color())),
|
||||
Value::Array(a) if a.len() >= 3 => Some(Color::rgb(a[0].as_f64()? as f32, a[1].as_f64()? as f32, a[2].as_f64()? as f32)),
|
||||
@@ -512,6 +513,23 @@ pub fn color_value(v: &Value) -> Option<Color> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `s` a hex color with an alpha part: eight or four hex digits, with or without the `#`?
|
||||
/// [`Color::from_hex`] reads `#rrggbbaa` as `#rrggbb`, without the alpha.
|
||||
pub(crate) fn hex_with_alpha(s: &str) -> bool {
|
||||
let s = s.trim();
|
||||
let h = s.strip_prefix('#').unwrap_or(s);
|
||||
matches!(h.len(), 4 | 8) && h.chars().all(|c| c.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
/// The color `p` gives for `key`, read by [`color_value`]: `None` when `p` leaves it out or gives
|
||||
/// null. Any other value that is not a color is an error: "bad color {v}".
|
||||
pub(crate) fn color_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Color>> {
|
||||
match p.get(key).filter(|v| !v.is_null()) {
|
||||
None => Ok(None),
|
||||
Some(v) => color_value(v).map(Some).ok_or_else(|| bad(cmd, format!("bad color {v}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` as an object id: an error unless it is a non-negative integer.
|
||||
fn object_id(v: &Value) -> Result<NodeId> {
|
||||
v.as_u64().map(NodeId).ok_or_else(|| EngineError::Other(format!("object ids are non-negative integers, not {v}")))
|
||||
|
||||
@@ -7,6 +7,7 @@ mod color;
|
||||
mod document;
|
||||
mod pathtools;
|
||||
mod pen;
|
||||
mod select;
|
||||
mod typetools;
|
||||
|
||||
use super::CommandSpec;
|
||||
@@ -19,6 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(document::specs());
|
||||
v.extend(pathtools::specs());
|
||||
v.extend(pen::specs());
|
||||
v.extend(select::specs());
|
||||
v.extend(typetools::specs());
|
||||
v
|
||||
}
|
||||
@@ -59,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Find Nearest Swatch",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{library?: a swatch library's id or name (swatch.library.list: the built-in ones, and the colour books and libraries the user saved or loaded) or \"document\" (the document's swatches; the default), color?: colour (look this colour up; default: the selection's), fill?: true, stroke?: true (the selected objects' fills and strokes, their type's and those of the objects inside them: solid colours and gradient stops, once each, the first 100), count?: 1..50 (5), ids?: [id…] (default: the selection)} list the library's colour swatches closest to each colour, closest first, by CIEDE2000 difference (ΔE; under 1 hardly tells apart, about 2 to 3 close). Tint swatches, None and Registration aren't matched → {library, colors: [{values, hex, matches: [{name, values, hex, spot, deltaE}]}]}",
|
||||
"{library?: a swatch library's id or name (swatch.library.list: the built-in ones, and the colour books and libraries the user saved or loaded) or \"document\" (the document's swatches; the default), color?: colour (look this colour up, #rrggbbaa and #rgba refused; default: the selection's), fill?: true, stroke?: true (the selected objects' fills and strokes, their type's and those of the objects inside them: solid colours and gradient stops, once each, the first 100), count?: 1..50 (5), ids?: [id…] (default: the selection)} list the library's colour swatches closest to each colour, closest first, by CIEDE2000 difference (ΔE; under 1 hardly tells apart, about 2 to 3 close). Tint swatches, None and Registration aren't matched → {library, colors: [{values, hex, matches: [{name, values, hex, spot, deltaE}]}]}",
|
||||
has_doc,
|
||||
nearest::find
|
||||
),
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
//! Document Tools (`addon.document.*`), a built-in add-on: Save a Timestamped Copy writes a copy of
|
||||
//! the document named with the date and time through File › Save a Copy's save; New Symbols from
|
||||
//! Layers makes a symbol of each layer's art as New Symbol does; Export All Open Documents writes a
|
||||
//! copy of every open document to one folder as Save a Copy does (#4920). Its submenu (Object › Plug-ins ›
|
||||
//! Document Tools) is the UI's.
|
||||
//! copy of every open document to one folder as Save a Copy does (#4920); Batch Trace Folder traces
|
||||
//! each image of a folder and saves the results to another ([`batch_trace`], #4921). Its submenu
|
||||
//! (Object › Plug-ins › Document Tools) is the UI's.
|
||||
|
||||
mod batch_trace;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -14,7 +16,7 @@ use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolRegistration};
|
||||
|
||||
use super::super::brushsym::{instance_in_place, normalize, place_xf, store_symbol};
|
||||
use super::super::fileio::{self, SaveMode};
|
||||
use super::super::{CommandSpec, bad, checked_ids_param, clock_date, cmd, date_param, has_doc, str_param, switch_or};
|
||||
use super::super::{CommandSpec, always, bad, checked_ids_param, clock_date, cmd, date_param, has_doc, str_param, switch_or};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// The most numbers (`-2`, `-3`…) tried after a timestamped name that is taken.
|
||||
@@ -40,6 +42,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
export_all_open
|
||||
),
|
||||
cmd!(
|
||||
"addon.document.batchTraceFolder",
|
||||
"Batch Trace Folder",
|
||||
["Object", "Plug-ins", "Document Tools"],
|
||||
None,
|
||||
"{folder, destinationFolder, preset?: name (imageTrace.presets; default: Default), expand?: false (true: trace and expand, as Make and Expand), format?: vectorcraft (default)|svg|pdf|ai|eps, includeSubdirs?: false} open each image in folder (png, jpg, tif, bmp, gif, webp, psd), select it, trace it with the preset, save it into destinationFolder as <name>.<ext> (-2, -3… added when that name is taken, so no file is replaced) and close it again, whether it traced or not; the document that was active stays active. Caps: 500 images, 8 folder levels; a folder with more than 1,000 entries is refused. Not on the web (no file system) → {traced: [{path, output}], failed: [{path, error}], format} (#4921)",
|
||||
always,
|
||||
batch_trace::batch_trace_folder
|
||||
),
|
||||
cmd!(
|
||||
"addon.document.symbolsFromLayers",
|
||||
"New Symbols from Layers",
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Batch Trace Folder (`addon.document.batchTraceFolder`, #4921): each image in a folder is opened,
|
||||
//! traced with a preset (and expanded when asked), saved into a destination folder under its own
|
||||
//! name, and closed again, whether it traced or not.
|
||||
|
||||
use serde_json::Value;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use serde_json::json;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::super::super::fileio;
|
||||
use super::super::super::{Result, Session, bad};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::super::super::{bool_or, str_param};
|
||||
|
||||
/// The command id.
|
||||
pub(super) const ID: &str = "addon.document.batchTraceFolder";
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(super) fn batch_trace_folder(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(bad(ID, "no file system here"))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// The image files a batch traces, by extension.
|
||||
const IMAGE_EXTS: [&str; 10] = ["png", "jpg", "jpeg", "tif", "tiff", "bmp", "gif", "webp", "psd", "psb"];
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// Caps on a batch (folders and MCP payloads are untrusted).
|
||||
pub(super) const MAX_FILES: usize = 500;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_DEPTH: usize = 8;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const FORMATS: [&str; 5] = ["vectorcraft", "svg", "pdf", "ai", "eps"];
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// The image files in `folder` (and its subfolders with `deep`), sorted.
|
||||
fn images(folder: &str, deep: bool, depth: usize, out: &mut Vec<String>) -> Result<()> {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err(bad(ID, format!("folders deeper than {MAX_DEPTH} levels")));
|
||||
}
|
||||
let max = MAX_FILES.saturating_mul(2);
|
||||
let (entries, truncated) = fileio::list_dir(folder, max)?;
|
||||
// The listing is cut before it is sorted, so a cut one could skip any image: refuse it.
|
||||
if truncated {
|
||||
return Err(bad(ID, format!("{folder}: more than {max} files and folders")));
|
||||
}
|
||||
let mut subdirs = vec![];
|
||||
for e in entries {
|
||||
let name = e.get("name").and_then(Value::as_str).unwrap_or("");
|
||||
if name.is_empty() || name.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
let path = std::path::Path::new(folder).join(name).to_string_lossy().into_owned();
|
||||
match e.get("kind").and_then(Value::as_str) {
|
||||
Some("file") if IMAGE_EXTS.contains(&fileio::extension(&path).as_str()) => out.push(path),
|
||||
Some("folder") if deep => subdirs.push(path),
|
||||
_ => {}
|
||||
}
|
||||
if out.len() > MAX_FILES {
|
||||
return Err(bad(ID, format!("more than {MAX_FILES} images")));
|
||||
}
|
||||
}
|
||||
for d in subdirs {
|
||||
images(&d, deep, depth + 1, out)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn batch_trace_folder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let folder = str_param(p, "folder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `folder`"))?;
|
||||
let dest = str_param(p, "destinationFolder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `destinationFolder`"))?;
|
||||
let format = str_param(p, "format").unwrap_or("vectorcraft");
|
||||
if !FORMATS.contains(&format) {
|
||||
return Err(bad(ID, format!("`format` must be one of {}", FORMATS.join(", "))));
|
||||
}
|
||||
let preset = str_param(p, "preset").unwrap_or("Default").to_string();
|
||||
let presets = s.execute("imageTrace.presets", &json!({}))?;
|
||||
if !presets["presets"].as_array().into_iter().flatten().any(|q| q["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(&preset))) {
|
||||
return Err(bad(ID, format!("no tracing preset `{preset}` (see imageTrace.presets)")));
|
||||
}
|
||||
let trace = if bool_or(p, "expand", false) { "imageTrace.makeAndExpand" } else { "imageTrace.make" };
|
||||
fileio::may_read(&folder)?;
|
||||
fileio::may_write(&dest)?;
|
||||
let mut files = vec![];
|
||||
images(&folder, bool_or(p, "includeSubdirs", false), 0, &mut files)?;
|
||||
files.sort();
|
||||
if files.is_empty() {
|
||||
return Err(bad(ID, "no images in the folder"));
|
||||
}
|
||||
std::fs::create_dir_all(&dest).map_err(|e| bad(ID, format!("{dest}: {e}")))?;
|
||||
let ext = fileio::save_format(Some(format), None).map_err(|e| bad(ID, e))?.extensions.first().copied().unwrap_or(format);
|
||||
let active = s.active_index();
|
||||
let (mut traced, mut failed, mut taken) = (vec![], vec![], Vec::<String>::new());
|
||||
for path in &files {
|
||||
let opened_before = s.documents().len();
|
||||
let one = |s: &mut Session| -> Result<String> {
|
||||
s.execute("document.open", &json!({ "path": path }))?;
|
||||
s.execute("select.all", &json!({}))?;
|
||||
s.execute(trace, &json!({ "preset": preset }))?;
|
||||
let stem = fileio::file_stem(path);
|
||||
// Names this batch already took count as taken, as do files on disk.
|
||||
let free = super::free_name(&dest, &stem, ext, |o| taken.iter().any(|t| t == o) || std::path::Path::new(o).exists())
|
||||
.ok_or_else(|| bad(ID, "every numbered name for the result is taken"))?;
|
||||
s.execute("document.save", &json!({ "path": free, "format": format }))?;
|
||||
Ok(free)
|
||||
};
|
||||
let result = one(s);
|
||||
// The image's document closes whatever happened, so a failure leaves no tab behind.
|
||||
if s.documents().len() > opened_before
|
||||
&& let Some(i) = s.active_index()
|
||||
{
|
||||
// A just-opened image has no work to lose; if closing fails, one extra tab stays open.
|
||||
let _ = s.execute("file.close", &json!({ "index": i }));
|
||||
}
|
||||
match result {
|
||||
Ok(out) => {
|
||||
taken.push(out.clone());
|
||||
traced.push(json!({ "path": path, "output": out }));
|
||||
}
|
||||
Err(e) => failed.push(json!({ "path": path, "error": e.to_string() })),
|
||||
}
|
||||
}
|
||||
if let Some(i) = active.filter(|i| *i < s.documents().len()) {
|
||||
s.set_active(i);
|
||||
}
|
||||
Ok(json!({ "traced": traced, "failed": failed, "format": format }))
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Document Tools' commands: the timestamped copy's name and place with the document left as it
|
||||
//! was, symbols made of layers, and bad params refused.
|
||||
//! was, symbols made of layers, a folder of images traced, and bad params refused.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -276,3 +276,77 @@ fn export_all_open_documents_keeps_every_page_and_artboard() {
|
||||
assert!(w > 19.0 && w < 30.0, "the SVG shows the art (the square on the second artboard), not the first artboard: viewBox {view}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A 24×24 white PNG with a dark (or red) square in it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn png(path: &Path, dark: bool) {
|
||||
let mut img = image::RgbaImage::from_pixel(24, 24, image::Rgba([255, 255, 255, 255]));
|
||||
for y in 6..18 {
|
||||
for x in 6..18 {
|
||||
img.put_pixel(x, y, if dark { image::Rgba([0, 0, 0, 255]) } else { image::Rgba([200, 30, 30, 255]) });
|
||||
}
|
||||
}
|
||||
img.save(path).unwrap();
|
||||
}
|
||||
|
||||
/// #4921: each image of the folder is traced and saved under its own name; a file that isn't an
|
||||
/// image is left alone, one that can't be read is reported, and every document the batch opened
|
||||
/// is closed again, the active one staying active.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn batch_trace_folder_traces_and_saves_each_image() {
|
||||
const C: &str = "addon.document.batchTraceFolder";
|
||||
let dir = folder("batch-trace");
|
||||
let (src, out) = (dir.join("in"), dir.join("out"));
|
||||
std::fs::create_dir_all(&src).unwrap();
|
||||
png(&src.join("logo.png"), true);
|
||||
png(&src.join("mark.png"), false);
|
||||
std::fs::write(src.join("notes.txt"), "not an image").unwrap();
|
||||
std::fs::write(src.join("broken.png"), b"not a png").unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let docs = s.documents().len();
|
||||
let r = s.execute(C, &json!({"folder": src, "destinationFolder": out, "format": "svg", "expand": true})).unwrap();
|
||||
assert_eq!(r["traced"].as_array().unwrap().len(), 2, "{r}");
|
||||
assert_eq!(r["failed"].as_array().unwrap().len(), 1, "{r}");
|
||||
assert!(r["failed"][0]["path"].as_str().unwrap().ends_with("broken.png"));
|
||||
let mut names: Vec<String> = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["logo.svg", "mark.svg"]);
|
||||
let svg = std::fs::read_to_string(out.join("logo.svg")).unwrap();
|
||||
assert!(svg.contains("<path") && !svg.contains("<image"), "traced and expanded, not the image");
|
||||
assert_eq!(s.documents().len(), docs, "the opened images are closed");
|
||||
assert_eq!(s.active_index(), Some(0));
|
||||
// Again: the taken names are numbered, nothing is replaced.
|
||||
s.execute(C, &json!({"folder": src, "destinationFolder": out, "format": "svg"})).unwrap();
|
||||
assert!(out.join("logo-2.svg").exists() && out.join("mark-2.svg").exists());
|
||||
// Refused: no folders, an unknown preset or format, a folder without images.
|
||||
for bad in [
|
||||
json!({"destinationFolder": out}),
|
||||
json!({"folder": src}),
|
||||
json!({"folder": src, "destinationFolder": out, "preset": "No Such Preset"}),
|
||||
json!({"folder": src, "destinationFolder": out, "format": "docx"}),
|
||||
json!({"folder": out.join("empty"), "destinationFolder": out}),
|
||||
] {
|
||||
assert!(s.execute(C, &bad).is_err(), "{bad}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A folder too big to list in full is refused rather than traced in part.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn batch_trace_folder_refuses_a_folder_it_cannot_list_in_full() {
|
||||
let dir = folder("batch-trace-big");
|
||||
let src = dir.join("in");
|
||||
std::fs::create_dir_all(&src).unwrap();
|
||||
for i in 0..=super::batch_trace::MAX_FILES * 2 {
|
||||
std::fs::write(src.join(format!("note-{i}.txt")), "").unwrap();
|
||||
}
|
||||
png(&src.join("logo.png"), true);
|
||||
let mut s = Session::new();
|
||||
let e = s.execute("addon.document.batchTraceFolder", &json!({"folder": src, "destinationFolder": dir.join("out")})).unwrap_err();
|
||||
assert!(e.to_string().contains("more than"), "{e}");
|
||||
assert!(!dir.join("out").exists(), "nothing traced");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
//! Selection Tools (`addon.select.*`), a built-in add-on: Select by Artboards selects the objects
|
||||
//! overlapping, fully inside or fully outside one or more chosen artboards (#5525). Its submenu
|
||||
//! (Object › Plug-ins › Selection Tools) and dialog are the UI's.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use super::super::select::{on_artboard, selectable};
|
||||
use super::super::{CommandSpec, bad, cmd, has_doc, point_indices, text_param};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// How Select by Artboards relates an object to the chosen artboards (`relation`).
|
||||
pub const RELATIONS: [&str; 3] = ["overlap", "inside", "outside"];
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.select.byArtboards",
|
||||
"Select by Artboards",
|
||||
["Object", "Plug-ins", "Selection Tools"],
|
||||
None,
|
||||
"{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}",
|
||||
has_doc,
|
||||
by_artboards
|
||||
)]
|
||||
}
|
||||
|
||||
fn by_artboards(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.select.byArtboards";
|
||||
let relation = text_param(p, "relation", C)?.unwrap_or("overlap");
|
||||
if !RELATIONS.contains(&relation) {
|
||||
return Err(bad(C, "`relation` must be overlap, inside or outside"));
|
||||
}
|
||||
let listed = p.get("artboards").ok_or_else(|| bad(C, "missing `artboards`"))?;
|
||||
let indices = point_indices(listed).ok_or_else(|| bad(C, "`artboards` must be a list of artboard indices"))?;
|
||||
if indices.is_empty() {
|
||||
return Err(bad(C, "choose at least one artboard"));
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let rects =
|
||||
indices.iter().map(|i| st.doc.artboards.get(*i).map(|a| a.rect)).collect::<Option<Vec<_>>>().ok_or_else(|| bad(C, "no such artboard"))?;
|
||||
let symbols = st.doc.symbol_boxes();
|
||||
let ids: Vec<NodeId> = selectable(&st.doc, st.isolation)
|
||||
.into_iter()
|
||||
.filter(|id| {
|
||||
let Some(n) = st.doc.node(*id) else { return false };
|
||||
match relation {
|
||||
"inside" => n.geometric_bounds_with(&symbols).is_some_and(|b| {
|
||||
rects.iter().any(|r| {
|
||||
vectorcraft_doc::artboard_holds(*r, Point::new(b.x0, b.y0)) && vectorcraft_doc::artboard_holds(*r, Point::new(b.x1, b.y1))
|
||||
})
|
||||
}),
|
||||
"outside" => !rects.iter().any(|r| on_artboard(n, &symbols, *r)),
|
||||
_ => rects.iter().any(|r| on_artboard(n, &symbols, *r)),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
s.select(|_, sel| sel.set(ids))?;
|
||||
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
//! Select by Artboards.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const C: &str = "addon.select.byArtboards";
|
||||
|
||||
/// A document with three 100 × 100 artboards in a row, 50 pt apart: 0 at x 0, 1 at x 150, 2 at x 300.
|
||||
fn three_boards() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
for x in [150, 300] {
|
||||
s.execute("artboard.new", &json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap();
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn pick(s: &mut Session, p: Value) -> Vec<NodeId> {
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let r = s.execute(C, &p).unwrap();
|
||||
let mut ids = s.doc().unwrap().selection.objects.clone();
|
||||
assert_eq!(r["count"], json!(ids.len()));
|
||||
ids.sort();
|
||||
ids
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_by_overlap_inside_and_outside_several_artboards() {
|
||||
let mut s = three_boards();
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); // inside 0
|
||||
let ab = rect(&mut s, 90.0, 40.0, 80.0, 20.0); // across 0 and 1
|
||||
let b = rect(&mut s, 160.0, 10.0, 20.0, 20.0); // inside 1
|
||||
let c = rect(&mut s, 310.0, 10.0, 20.0, 20.0); // inside 2
|
||||
let off = rect(&mut s, 0.0, 200.0, 20.0, 20.0); // on no board
|
||||
let edge = rect(&mut s, 0.0, 0.0, 100.0, 100.0); // flush with board 0
|
||||
let want = |mut v: Vec<NodeId>| {
|
||||
v.sort();
|
||||
v
|
||||
};
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0, 1]})), want(vec![a, ab, b, edge]));
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0, 1], "relation": "overlap"})), want(vec![a, ab, b, edge]));
|
||||
// Wholly within one board, edges included; straddling two boards is not inside either.
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0, 1], "relation": "inside"})), want(vec![a, b, edge]));
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0, 1], "relation": "outside"})), want(vec![c, off]));
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [2], "relation": "outside"})), want(vec![a, ab, b, off, edge]));
|
||||
// One board does what All on Active Artboard does.
|
||||
for i in 0..3u64 {
|
||||
s.execute("select.allOnArtboard", &json!({"artboard": i})).unwrap();
|
||||
let mut on = s.doc().unwrap().selection.objects.clone();
|
||||
on.sort();
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [i]})), on, "board {i}");
|
||||
}
|
||||
// A board listed twice counts once.
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [2, 2]})), vec![c]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_locked_and_isolated_art_follow_select_all() {
|
||||
let mut s = three_boards();
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
let hidden = rect(&mut s, 40.0, 10.0, 20.0, 20.0);
|
||||
let locked = rect(&mut s, 70.0, 10.0, 20.0, 20.0);
|
||||
let far = rect(&mut s, 0.0, 300.0, 20.0, 20.0);
|
||||
s.execute("object.setProps", &json!({"ids": [hidden.0], "visible": false})).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [locked.0], "locked": true})).unwrap();
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0]})), vec![a]);
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "outside"})), vec![far]);
|
||||
// Art held by a locked artboard is left out.
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0]})), vec![]);
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap();
|
||||
// In isolation mode only the isolated group's objects are looked at.
|
||||
let b = rect(&mut s, 20.0, 50.0, 10.0, 10.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.isolate", &json!({"id": g})).unwrap();
|
||||
let mut both = vec![a, b];
|
||||
both.sort();
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "inside"})), both);
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [1]})), vec![]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_errors_and_leave_the_selection() {
|
||||
let mut s = three_boards();
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"artboards": []}),
|
||||
json!({"artboards": [3]}),
|
||||
json!({"artboards": [-1]}),
|
||||
json!({"artboards": [0.5]}),
|
||||
json!({"artboards": "0"}),
|
||||
json!({"artboards": [0], "relation": "near"}),
|
||||
json!({"artboards": [0], "relation": 1}),
|
||||
json!({"artboards": [0], "relatoin": "inside"}),
|
||||
] {
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
assert!(s.execute(C, &p).is_err(), "{p}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![a], "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_instance_is_measured_by_its_art() {
|
||||
// The symbol's art, (100, 60) to (140, 80), drawn 50 pt up and left: (50, 10) to (90, 30), on
|
||||
// the 200 × 120 artboard, while the 20 × 20 square around the instance's origin lies off it.
|
||||
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="120"><defs><symbol id="Far"><rect x="100" y="60" width="40" height="20" fill="#f00"/></symbol></defs><use href="#Far" x="-50" y="-50"/></svg>"##;
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "far.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())})).unwrap();
|
||||
let mut instance = None;
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
if matches!(n.kind, vectorcraft_doc::NodeKind::SymbolInstance { .. }) {
|
||||
instance = Some(n.id);
|
||||
}
|
||||
});
|
||||
let instance = instance.unwrap();
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0]})), vec![instance]);
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "inside"})), vec![instance]);
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "outside"})), vec![]);
|
||||
}
|
||||
@@ -46,7 +46,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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}",
|
||||
"{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 (range endpoints inside a character round down to its start), 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
|
||||
)]
|
||||
@@ -93,25 +93,49 @@ fn text_tweaker(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ranges = type_ranges(s, p, C, |text, _| Some((0, text.len())))?;
|
||||
// Each object's changed characters: (byte, its change), worked out before the edit.
|
||||
let mut plans: Vec<(NodeId, Vec<(usize, CharChange)>)> = vec![];
|
||||
let mut count = 0;
|
||||
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 (a, b) = (edit::floor_char(&text, a), edit::floor_char(&text, b));
|
||||
let chars: Vec<usize> =
|
||||
text.char_indices().filter(|&(i, c)| (a..b).contains(&i) && !(skip && (c.is_whitespace() || c.is_control()))).map(|(i, _)| i).collect();
|
||||
count += chars.len();
|
||||
if count > MAX_CHARS {
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -62,7 +62,8 @@ fn a_straight_ramp_sizes_each_letter_and_skips_spaces() {
|
||||
select(&mut s, &[id]);
|
||||
let n = steps(&s);
|
||||
let out = s.execute(C, &json!({"attribute": "size", "from": 10, "to": 40})).unwrap();
|
||||
assert_eq!(out, json!({"count": 4, "ids": [id.0]}));
|
||||
// `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");
|
||||
@@ -108,7 +109,8 @@ fn each_object_gets_its_own_ramp() {
|
||||
let (a, b) = (text(&mut s, "abc"), text(&mut s, "de"));
|
||||
select(&mut s, &[a, b]);
|
||||
let out = s.execute(C, &json!({"attribute": "rotation", "from": 0, "to": 30})).unwrap();
|
||||
assert_eq!(out["count"], json!(5));
|
||||
// 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]));
|
||||
}
|
||||
@@ -122,6 +124,16 @@ fn a_range_changes_only_its_characters() {
|
||||
assert_eq!(tracking, [0.0, 100.0, 200.0, 300.0, 0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_inside_a_multibyte_character_uses_character_boundaries() {
|
||||
let mut s = session();
|
||||
let id = text(&mut s, "éx");
|
||||
let out = s.execute(C, &json!({"id": id.0, "start": 1, "end": 2, "attribute": "tracking", "from": 100, "to": 300})).unwrap();
|
||||
assert_eq!(out["count"], 1);
|
||||
let tracking: Vec<f64> = styles(&s, id).iter().map(|(_, st)| st.tracking).collect();
|
||||
assert_eq!(tracking, [100.0, 0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_values_stay_in_range_and_repeat_with_the_seed() {
|
||||
let mut s = session();
|
||||
@@ -161,6 +173,19 @@ fn empty_text_and_only_spaces_change_nothing() {
|
||||
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();
|
||||
@@ -179,6 +204,9 @@ fn bad_params_are_refused_without_a_change() {
|
||||
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}");
|
||||
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Fill",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+/"),
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row (a copy of its top fill; type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids` and no `target: \"contents\"`, the new fill is a copy of that row, right above it, and becomes the active row",
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, true)
|
||||
),
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Stroke",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+Alt+/"),
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row (a copy of its top stroke, else the default stroke)",
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, false)
|
||||
),
|
||||
@@ -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> {
|
||||
@@ -340,11 +357,23 @@ pub(crate) fn appearances_differ(d: &vectorcraft_doc::Document, ids: &[NodeId])
|
||||
|
||||
/// Indices `idx` of the first target's items (aligned with `aligned`) in each of `ids`: the first
|
||||
/// target's own, and in each other one the items equal to them there (see [`SharedStack`]), each
|
||||
/// index on its own: one the targets don't share is left out of the others (never taken as the
|
||||
/// same index there). Not aligned, or one target: the same indices in each.
|
||||
/// index and each target on its own: an index a target doesn't share with the first is left out
|
||||
/// of that target (never taken as the same index there), whatever the other targets have. Not
|
||||
/// aligned, or one target: the same indices in each.
|
||||
pub(crate) fn items_per_target(d: &vectorcraft_doc::Document, ids: &[NodeId], idx: &[usize], aligned: bool) -> Vec<Vec<usize>> {
|
||||
match shared_stack(d, ids).filter(|_| aligned) {
|
||||
Some(sh) => (0..ids.len()).map(|k| if k == 0 { idx.to_vec() } else { idx.iter().filter_map(|i| sh.item_in(*i, k)).collect() }).collect(),
|
||||
let aps: Option<Vec<&Appearance>> = ids.iter().map(|id| d.node(*id).map(|n| &*n.appearance)).collect();
|
||||
match aps.filter(|aps| aligned && aps.len() >= 2) {
|
||||
Some(aps) => aps
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, ap)| match aps.first() {
|
||||
Some(first) if k > 0 => {
|
||||
let sh = SharedStack::of(&[*first, *ap]);
|
||||
idx.iter().filter_map(|i| sh.item_in(*i, 1)).collect()
|
||||
}
|
||||
_ => idx.to_vec(),
|
||||
})
|
||||
.collect(),
|
||||
None => vec![idx.to_vec(); ids.len()],
|
||||
}
|
||||
}
|
||||
@@ -490,8 +519,8 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
let ids = require_targets(s, p, if fill { "appearance.addFill" } else { "appearance.addStroke" })?;
|
||||
let defaults = s.paint.clone();
|
||||
// The panel's active Fill row, when the new fill goes on the selection: the new fill is a copy
|
||||
// of that row, right above it in each target that has it (others get a copy of their top fill).
|
||||
// The panel's active Fill row, when the new fill goes on the selection: the new fill takes that
|
||||
// row's paint, right above it in each target that has it (others take their top fill's paint).
|
||||
// Where the new item went in on the active item's object, when it is an image.
|
||||
let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied());
|
||||
// The active row is a row of the active object's stack, which need not come first in `ids`
|
||||
@@ -514,6 +543,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;
|
||||
@@ -529,8 +559,9 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// A copy of the top fill (stroke); without one, type's characters' and otherwise the
|
||||
// default paint, so a new fill on a group or type shows.
|
||||
// The top fill's (stroke's) paint; without one, type's characters' and otherwise the
|
||||
// default paint, so a new fill on a group or type shows. A new stroke takes the top
|
||||
// stroke's weight when that stroke has paint, at least 1 pt.
|
||||
let paint = match (n.appearance.paint_at(None, fill), &n.kind) {
|
||||
(Some(p), _) => p.clone(),
|
||||
(None, NodeKind::Text(_)) => super::paint::proxy_paint(n, !fill, None),
|
||||
@@ -560,6 +591,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 +610,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 +667,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 +722,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 +745,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 +783,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 +828,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 +855,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 +894,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 +957,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 +1001,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 +1100,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 +1127,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 +1153,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<_>>() }))
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ use super::edit::{outermost, selected_roots};
|
||||
use super::pathops::{remove_each, separate};
|
||||
use super::swatch::{anchor, names_param};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, check_numbers, cmd, color_value, find_command, has_doc, has_selection, id_param, named_ids, number_or, ok,
|
||||
CommandSpec, Result, Session, bad, check_numbers, cmd, color_param, find_command, has_doc, has_selection, id_param, named_ids, number_or, ok,
|
||||
str_param, switch_or,
|
||||
};
|
||||
use crate::EngineError;
|
||||
@@ -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
|
||||
),
|
||||
@@ -302,7 +304,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbolism Tool",
|
||||
[],
|
||||
None,
|
||||
"{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y]…], radius?: 40, intensity?: 1..10 (5), alt?: bool, color?, keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}",
|
||||
"{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y]…], radius?: 40, intensity?: 1..10 (5), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}",
|
||||
has_doc,
|
||||
symbol_adjust
|
||||
),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::dynamic::{fit_overrides, type_id, type_param};
|
||||
use super::{
|
||||
Affine, AppearanceItem, Arc, CURRENT_SYMBOL, Color, Document, EngineError, FillLayer, HALF, Node, NodeId, NodeKind, Paint, Point, Result,
|
||||
SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_value, ids_json, json,
|
||||
SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_param, ids_json, json,
|
||||
name_param, number_or, ok, remove_each, roots, selection_art, separate, set_unknown, str_param, switch_or,
|
||||
};
|
||||
|
||||
@@ -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>> {
|
||||
@@ -767,7 +834,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let intensity = number_or(p, "intensity", 5.0, C)?.clamp(1.0, 10.0) / 10.0;
|
||||
let alt = switch_or(p, "alt", false, C)?;
|
||||
let st = s.doc()?;
|
||||
let color = match p.get("color").and_then(color_value) {
|
||||
let color = match color_param(p, "color", C)? {
|
||||
Some(c) => crate::cmd::paint::new_color(s, p, c),
|
||||
None => s.paint.fill.color().unwrap_or(Color::BLACK),
|
||||
};
|
||||
|
||||
@@ -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
|
||||
),
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gap Options",
|
||||
[],
|
||||
None,
|
||||
"{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}",
|
||||
"{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}",
|
||||
has_selection_or_ids,
|
||||
lp_gap_options
|
||||
),
|
||||
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Paint Bucket",
|
||||
[],
|
||||
None,
|
||||
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], color?|swatch?|gradient?|none? (default: current fill), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}",
|
||||
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}",
|
||||
has_doc,
|
||||
lp_fill
|
||||
),
|
||||
|
||||
@@ -93,11 +93,20 @@ pub struct Clipboard {
|
||||
/// The artboards copied with the Artboard tool (`artboard.copy`); `nodes` are then their art.
|
||||
/// Pasting adds a copy of each with the art.
|
||||
pub artboards: Vec<vectorcraft_doc::Artboard>,
|
||||
/// The selected ruler guides copied with (or without) the objects (#3226), as canvas guides on
|
||||
/// no layer: pasting puts them on the layer new art goes to, moved as the objects are.
|
||||
pub guides: Vec<vectorcraft_doc::Guide>,
|
||||
}
|
||||
|
||||
impl Clipboard {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.nodes.is_empty() && self.artboards.is_empty()
|
||||
self.nodes.is_empty() && self.artboards.is_empty() && self.guides.is_empty()
|
||||
}
|
||||
|
||||
/// Does it hold art (objects or artboards) for other apps? Ruler guides stay in VectorCraft:
|
||||
/// a Copy of guides alone empties the system clipboard (#3226).
|
||||
pub fn has_art(&self) -> bool {
|
||||
!self.nodes.is_empty() || !self.artboards.is_empty()
|
||||
}
|
||||
|
||||
/// Objects `roots` of `st`'s document with their resources, source artboard and layers.
|
||||
@@ -195,7 +204,7 @@ impl Clipboard {
|
||||
|
||||
/// The objects as standalone SVG (`None` when there are none).
|
||||
pub fn svg(&self) -> Option<String> {
|
||||
if self.is_empty() {
|
||||
if !self.has_art() {
|
||||
return None;
|
||||
}
|
||||
let d = self.to_document();
|
||||
|
||||
@@ -286,7 +286,7 @@ impl Clipboard {
|
||||
|
||||
/// The MIME types of [`Self::flavours`], without making them.
|
||||
pub fn flavour_types(&self, svg: bool, pdf: bool) -> Vec<&'static str> {
|
||||
if self.is_empty() {
|
||||
if !self.has_art() {
|
||||
return vec![];
|
||||
}
|
||||
let text = (svg && self.image_bytes() <= COPY_TEXT_IMAGE_BYTES) || self.nodes.iter().all(type_only);
|
||||
|
||||
@@ -116,7 +116,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Color Guide",
|
||||
[],
|
||||
None,
|
||||
"{color, rule: complementary|complementary2|splitComplementary|leftComplement|rightComplement|analogous|analogous2|monochromatic|shades|triad|triad2|triad3|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast2|highContrast3|pentagram (or its label), steps?: 1..20 (4), variation?: \"tintsShades\"|\"warmCool\"|\"vividMuted\", amount?: 0..100 (50; how far the outermost steps go), limitTo?: swatch library id or name; or \"document\" (the document's swatches): every colour snaps to its nearest colour there (ΔE 2000)} the Color Guide for a base colour → {rule, colors: [\"#rrggbb\", the base first], grid: [per colour, 2·steps+1 variations from shades/cool/muted to tints/warm/vivid with the colour itself in the centre]}",
|
||||
"{color (#rrggbbaa and #rgba are refused), rule: complementary|complementary2|splitComplementary|leftComplement|rightComplement|analogous|analogous2|monochromatic|shades|triad|triad2|triad3|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast2|highContrast3|pentagram (or its label), steps?: 1..20 (4), variation?: \"tintsShades\"|\"warmCool\"|\"vividMuted\", amount?: 0..100 (50; how far the outermost steps go), limitTo?: swatch library id or name; or \"document\" (the document's swatches): every colour snaps to its nearest colour there (ΔE 2000)} the Color Guide for a base colour → {rule, colors: [\"#rrggbb\", the base first], grid: [per colour, 2·steps+1 variations from shades/cool/muted to tints/warm/vivid with the colour itself in the centre]}",
|
||||
always,
|
||||
harmony
|
||||
),
|
||||
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Convert Color",
|
||||
[],
|
||||
None,
|
||||
"{color, to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}",
|
||||
"{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}",
|
||||
always,
|
||||
convert_color
|
||||
),
|
||||
@@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gamut Warning",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, colors?: [color]} colours that can't be printed in the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}",
|
||||
"{ids?|id?, colors?: [color] (#rrggbbaa and #rgba are refused)} colours that can't be printed in the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}",
|
||||
has_doc,
|
||||
gamut_check
|
||||
),
|
||||
@@ -319,17 +319,138 @@ pub(crate) fn convert_mode(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
changed = set_color_mode(d, mode, convert, intent, grays);
|
||||
Ok(())
|
||||
})?;
|
||||
if convert {
|
||||
if s.in_interaction() && s.batch_stash.is_none() {
|
||||
if let Some(it) = &mut s.doc_mut()?.interaction {
|
||||
it.deferred_color_mode = Some(DeferredColorMode { mode, intent, grays });
|
||||
}
|
||||
} else {
|
||||
let before = new_art_colors_before(s)?;
|
||||
convert_new_art_colors(s, mode, intent, grays)?;
|
||||
record_new_art_colors(s, before)?;
|
||||
}
|
||||
} else if s.batch_stash.is_some() || s.doc()?.undo_group.is_some() {
|
||||
let before = new_art_colors_before(s)?;
|
||||
record_new_art_colors(s, before)?;
|
||||
}
|
||||
Ok(json!({ "changed": changed }))
|
||||
}
|
||||
|
||||
/// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks
|
||||
/// included), symbols, graph designs, pattern tiles (the tile that pattern editing's Cancel puts
|
||||
/// back included), graphic styles, brushes (their art and a Hue Shift key color) and swatches
|
||||
/// through the color settings (`intent`, default: theirs) → how many colors of the art (opacity
|
||||
/// masks included), symbols, graph designs and pattern tiles changed; the colors of graphic
|
||||
/// styles and brushes convert without being counted. Gray colors stay
|
||||
/// Gray (they print on the black plate in either mode); RGB grays are colors like any other and
|
||||
/// separate through the CMYK profile, unless `grays` puts them on the black plate. Lab colors
|
||||
/// The validated conversion choices of the current tentative color-mode preview.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct DeferredColorMode {
|
||||
mode: ColorMode,
|
||||
intent: Option<Intent>,
|
||||
grays: Grays,
|
||||
}
|
||||
|
||||
/// Complete the deferred new-art conversion before the interaction becomes an Undo step.
|
||||
pub(crate) fn commit_new_art_colors(s: &mut Session) -> Result<()> {
|
||||
let pending =
|
||||
s.doc()?.interaction.as_ref().filter(|it| it.preview.is_some() && it.color_mode_paints.is_none()).and_then(|it| it.deferred_color_mode);
|
||||
if let Some(DeferredColorMode { mode, intent, grays }) = pending {
|
||||
let before = new_art_colors_before(s)?;
|
||||
convert_new_art_colors(s, mode, intent, grays)?;
|
||||
record_new_art_colors(s, before)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn record_new_art_colors(s: &mut Session, before: vectorcraft_tools::PaintDefaults) -> Result<()> {
|
||||
let after = s.paint.clone();
|
||||
if before != after || s.batch_stash.is_some() || s.doc()?.undo_group.is_some() {
|
||||
let st = s.doc_mut()?;
|
||||
let slot = if let Some(it) = &mut st.interaction {
|
||||
Some(&mut it.color_mode_paints)
|
||||
} else {
|
||||
st.history.undo.last_mut().map(|e| &mut e.color_mode_paints)
|
||||
};
|
||||
if let Some(slot) = slot {
|
||||
match slot {
|
||||
Some((_, end)) => *end = after,
|
||||
slot => *slot = Some((before, after)),
|
||||
}
|
||||
}
|
||||
if st.interaction.is_none() {
|
||||
if let Some(e) = st.history.undo.last_mut() {
|
||||
e.recost_paints();
|
||||
}
|
||||
st.history.trim();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn new_art_colors_before(s: &Session) -> Result<vectorcraft_tools::PaintDefaults> {
|
||||
let st = s.doc()?;
|
||||
Ok(st.undo_group.as_ref().map(|g| &g.paint).or_else(|| st.interaction.as_ref().map(|it| &it.paint)).cloned().unwrap_or_else(|| s.paint.clone()))
|
||||
}
|
||||
|
||||
/// Convert the fill and stroke that new art takes, and the colors of its template appearance
|
||||
/// (paints and effect colors), as [`set_color_mode`] converted the active document's art. The
|
||||
/// command records their original values for Undo. Previews defer this until acceptance;
|
||||
/// a batch converts immediately and restores the values itself when it fails.
|
||||
fn convert_new_art_colors(s: &mut Session, mode: ColorMode, intent: Option<Intent>, grays: Grays) -> Result<()> {
|
||||
let d = &s.doc()?.doc;
|
||||
let bases = global_bases(d);
|
||||
let conv = mode_converter(mode, intent, grays);
|
||||
let mut f = |col: &Color, link: proof::Link| mode_color(col, link, &bases, &conv);
|
||||
map_paint_colors(&mut s.paint.fill, &mut f);
|
||||
map_paint_colors(&mut s.paint.stroke, &mut f);
|
||||
if let Some(a) = s.paint.appearance.as_mut() {
|
||||
for it in &mut a.items {
|
||||
let paint = match it {
|
||||
vectorcraft_doc::AppearanceItem::Fill(l) => &mut l.paint,
|
||||
vectorcraft_doc::AppearanceItem::Stroke(l) => &mut l.paint,
|
||||
};
|
||||
map_paint_colors(paint, &mut f);
|
||||
}
|
||||
map_effect_colors(a, &mut f);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How Document Color Mode converts a color to `mode` through the color settings (`intent`,
|
||||
/// default: theirs): Gray and Lab colors stay as they are; with `grays` on the black plate, an RGB
|
||||
/// gray becomes K only in CMYK.
|
||||
fn mode_converter(mode: ColorMode, intent: Option<Intent>, grays: Grays) -> impl Fn(&Color) -> Color {
|
||||
let c = cms::active();
|
||||
let intent = intent.unwrap_or(c.settings().intent);
|
||||
let model = if mode == ColorMode::Cmyk { Model::Cmyk } else { Model::Rgb };
|
||||
let k_only = model == Model::Cmyk && grays == Grays::Black;
|
||||
move |col: &Color| match col {
|
||||
Color::Gray { .. } | Color::Lab { .. } => *col,
|
||||
// Grey ink percentage, then K only (a Gray colour's CMYK).
|
||||
Color::Rgb { .. } if k_only && Neutral::of(col).is_some() => c.convert(&c.convert(col, Model::Gray, intent), Model::Cmyk, intent),
|
||||
_ => c.convert(col, model, intent),
|
||||
}
|
||||
}
|
||||
|
||||
/// The name and color of each global swatch of `d`, for [`mode_color`].
|
||||
fn global_bases(d: &vectorcraft_doc::Document) -> Vec<(String, Color)> {
|
||||
d.swatches_iter().filter_map(|w| Some((w.name.clone(), d.global_color(&w.name)?))).collect()
|
||||
}
|
||||
|
||||
/// The color Document Color Mode gives `col` (swatch link `link`): a tint of a global swatch in
|
||||
/// `bases` (already converted) is that swatch's color at its tint; any other color goes through
|
||||
/// `conv` ([`mode_converter`]).
|
||||
fn mode_color(col: &Color, link: proof::Link, bases: &[(String, Color)], conv: &dyn Fn(&Color) -> Color) -> Color {
|
||||
match link.and_then(|(name, tint)| Some((bases.iter().find(|(n, _)| n == name)?, tint))) {
|
||||
Some(((_, base), tint)) if tint < 1.0 => base.tinted(tint),
|
||||
_ => conv(col),
|
||||
}
|
||||
}
|
||||
|
||||
/// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks,
|
||||
/// effect colors and the series paints and label styles that graphs keep included), symbols,
|
||||
/// graph designs, pattern tiles (the tile that pattern editing's Cancel puts back included),
|
||||
/// graphic styles (their effects included), brushes (their art and a Hue Shift key color) and
|
||||
/// swatches through the color settings (`intent`, default: theirs) → how many colors of the art
|
||||
/// (opacity masks, effect colors and graphs' paints included), symbols, graph designs and pattern
|
||||
/// tiles changed; the colors of graphic styles and brushes convert without being counted. Gray
|
||||
/// colors stay Gray (they print on the black plate in either mode); RGB grays are colors like any
|
||||
/// other and separate through the CMYK profile, unless `grays` puts them on the black plate
|
||||
/// ([`mode_converter`]). Lab colors
|
||||
/// (spot color definitions) are device independent and fit either mode. A tint of a global
|
||||
/// swatch becomes the converted swatch's color at its tint. Document Color Mode and
|
||||
/// `document.open {colorMode}` both convert this way.
|
||||
@@ -338,16 +459,7 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
if !convert {
|
||||
return 0;
|
||||
}
|
||||
let c = cms::active();
|
||||
let intent = intent.unwrap_or(c.settings().intent);
|
||||
let model = if mode == ColorMode::Cmyk { Model::Cmyk } else { Model::Rgb };
|
||||
let k_only = model == Model::Cmyk && grays == Grays::Black;
|
||||
let conv = |col: &Color| match col {
|
||||
Color::Gray { .. } | Color::Lab { .. } => *col,
|
||||
// Grey ink percentage, then K only (a Gray colour's CMYK).
|
||||
Color::Rgb { .. } if k_only && Neutral::of(col).is_some() => c.convert(&c.convert(col, Model::Gray, intent), Model::Cmyk, intent),
|
||||
_ => c.convert(col, model, intent),
|
||||
};
|
||||
let conv = mode_converter(mode, intent, grays);
|
||||
for sw in d.swatches_iter_mut() {
|
||||
match &mut sw.paint {
|
||||
Paint::Solid { color, .. } => *color = conv(color),
|
||||
@@ -360,13 +472,10 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
}
|
||||
}
|
||||
// Tints are their converted swatch's colour at their tint (exact ink percentages).
|
||||
let bases: Vec<(String, Color)> = d.swatches_iter().filter_map(|w| Some((w.name.clone(), d.global_color(&w.name)?))).collect();
|
||||
let bases = global_bases(d);
|
||||
let changed = std::cell::Cell::new(0usize);
|
||||
let mut count = |col: &Color, link: proof::Link| {
|
||||
let n = match link.and_then(|(name, tint)| Some((bases.iter().find(|(n, _)| n == name)?, tint))) {
|
||||
Some(((_, base), tint)) if tint < 1.0 => base.tinted(tint),
|
||||
_ => conv(col),
|
||||
};
|
||||
let n = mode_color(col, link, &bases, &conv);
|
||||
if n != *col {
|
||||
changed.set(changed.get() + 1);
|
||||
}
|
||||
@@ -384,12 +493,15 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
}
|
||||
// The reply counts the colors of the document's art only, not those of the graphic styles and brushes.
|
||||
let in_art = changed.get();
|
||||
for it in d.graphic_styles.iter_mut().flat_map(|g| &mut g.appearance.items) {
|
||||
let paint = match it {
|
||||
vectorcraft_doc::AppearanceItem::Fill(l) => &mut l.paint,
|
||||
vectorcraft_doc::AppearanceItem::Stroke(l) => &mut l.paint,
|
||||
};
|
||||
map_paint_colors(paint, &mut count);
|
||||
for g in &mut d.graphic_styles {
|
||||
for it in &mut g.appearance.items {
|
||||
let paint = match it {
|
||||
vectorcraft_doc::AppearanceItem::Fill(l) => &mut l.paint,
|
||||
vectorcraft_doc::AppearanceItem::Stroke(l) => &mut l.paint,
|
||||
};
|
||||
map_paint_colors(paint, &mut count);
|
||||
}
|
||||
map_effect_colors(&mut g.appearance, &mut count);
|
||||
}
|
||||
// Convert each brush's art. A Hue Shift key color takes the converted color of the art color
|
||||
// it matches (a tint of a global swatch included), so the key still matches the converted art;
|
||||
@@ -438,19 +550,28 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
in_art
|
||||
}
|
||||
|
||||
/// [`proof::map_node_colors`] over `n`'s subtree and the art of every opacity mask in it.
|
||||
/// [`proof::map_node_colors`] over `n`'s subtree, then [`map_more_colors`].
|
||||
fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
proof::map_node_colors(n, f);
|
||||
map_mask_colors(n, f);
|
||||
map_more_colors(n, f);
|
||||
}
|
||||
|
||||
fn map_mask_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) {
|
||||
map_art_colors(Arc::make_mut(&mut mask.art), f);
|
||||
/// `f` applied to the colors in `n`'s subtree that [`proof::map_node_colors`] does not visit: the
|
||||
/// effect colors ([`map_effect_colors`]), the series paints and label styles a graph keeps
|
||||
/// ([`map_graph_colors`]) and the art of every opacity mask.
|
||||
fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
map_effect_colors(&mut n.appearance, f);
|
||||
if let Some(e) = n.extras_if_any() {
|
||||
if let Some(g) = e.graph.as_deref_mut() {
|
||||
map_graph_colors(g, f);
|
||||
}
|
||||
if let Some(mask) = e.mask.as_deref_mut() {
|
||||
map_art_colors(Arc::make_mut(&mut mask.art), f);
|
||||
}
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch.iter_mut() {
|
||||
map_mask_colors(Arc::make_mut(c), f);
|
||||
map_more_colors(Arc::make_mut(c), f);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -461,7 +582,46 @@ fn matches_key(c: &Color, key: &Color) -> bool {
|
||||
c.to_rgb().iter().zip(key.to_rgb()).map(|(a, b)| (a - b).abs()).sum::<f32>() < 0.02
|
||||
}
|
||||
|
||||
/// `f` applied to a solid paint's color or a gradient's stop colors, given their swatch link.
|
||||
/// `f` applied to the `color` of each effect in appearance `a` (the object's effects and those of
|
||||
/// each fill and stroke) that has one ([`super::params::effect_color`]). An effect that draws its
|
||||
/// default color stores the new color as its own. The light colors of the 3D effects stay as they
|
||||
/// are.
|
||||
fn map_effect_colors(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut());
|
||||
for e in a.effects.iter_mut().chain(items) {
|
||||
if !(e.params.is_object() || e.params.is_null()) {
|
||||
continue;
|
||||
}
|
||||
let Some(color) = super::params::effect_color(&e.id, &e.params) else { continue };
|
||||
let n = f(&color, None);
|
||||
if n == color {
|
||||
continue;
|
||||
}
|
||||
match &mut e.params {
|
||||
Value::Object(m) => {
|
||||
m.insert("color".into(), json!(n));
|
||||
}
|
||||
p => *p = json!({ "color": n }),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `f` applied to the series paints and the label styles that graph `g` keeps, which its marks and
|
||||
/// labels take each time it is drawn again.
|
||||
fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
for p in g.series_paints.iter_mut() {
|
||||
for paint in [&mut p.fill, &mut p.stroke].into_iter().flatten() {
|
||||
map_paint_colors(paint, f);
|
||||
}
|
||||
}
|
||||
let styles = &mut g.label_styles;
|
||||
for st in [&mut styles.values, &mut styles.categories, &mut styles.legend].into_iter().flatten() {
|
||||
map_paint_colors(&mut st.fill, f);
|
||||
map_paint_colors(&mut st.stroke, f);
|
||||
}
|
||||
}
|
||||
|
||||
/// `f` applied to solid, gradient-stop and freeform-control colors, with any swatch link.
|
||||
fn map_paint_colors(p: &mut Paint, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
match p {
|
||||
Paint::Solid { color, swatch, tint } => *color = f(color, swatch.as_deref().map(|s| (s, *tint))),
|
||||
@@ -469,6 +629,11 @@ fn map_paint_colors(p: &mut Paint, f: &mut dyn FnMut(&Color, proof::Link) -> Col
|
||||
for st in &mut g.gradient.stops {
|
||||
st.color = f(&st.color, st.swatch.as_deref().map(|s| (s, st.tint)));
|
||||
}
|
||||
if let Some(freeform) = &mut g.freeform {
|
||||
for point in &mut freeform.points {
|
||||
point.color = f(&point.color, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -510,7 +675,9 @@ fn convert_color(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn gamut_check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut cols: Vec<Color> = vec![];
|
||||
if let Some(a) = p.get("colors").and_then(Value::as_array) {
|
||||
cols.extend(a.iter().filter_map(color_value));
|
||||
for v in a {
|
||||
cols.push(color_value(v).ok_or_else(|| bad("color.gamutCheck", format!("bad color {v}")))?);
|
||||
}
|
||||
} else {
|
||||
let st = s.doc()?;
|
||||
let ids = targets(s, p)?;
|
||||
|
||||
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Save Theme",
|
||||
["Window", "Color Themes"],
|
||||
None,
|
||||
"{colors: [1–5 colours] | color + rule (a harmony rule id or label, see color.harmony: its 5-colour theme from that base colour, base first), rule?: the rule it was made with, name?: (default \"Theme N\"), replace?: a saved theme's name (overwrite that theme in place, e.g. after editing it; it may be renamed), color?: one colour (as colors: [colour])} save a colour theme to the local theme library (the preferences) → {name, count: themes saved}",
|
||||
"{colors: [1–5 colours] (#rrggbbaa and #rgba are refused) | color + rule (a harmony rule id or label, see color.harmony: its 5-colour theme from that base colour, base first), rule?: the rule it was made with, name?: (default \"Theme N\"), replace?: a saved theme's name (overwrite that theme in place, e.g. after editing it; it may be renamed), color?: one colour (as colors: [colour])} save a colour theme to the local theme library (the preferences) → {name, count: themes saved}",
|
||||
always,
|
||||
save
|
||||
),
|
||||
|
||||
@@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Create Text",
|
||||
[],
|
||||
None,
|
||||
"{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color?, keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
"{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
has_doc,
|
||||
text_create
|
||||
),
|
||||
@@ -706,6 +706,7 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::paint::check_keep_model(p, "text.create")?;
|
||||
check_numbers(p, &["size"], "text.create")?;
|
||||
check_switches(p, &["vertical", "placeholder"], "text.create")?;
|
||||
super::color_param(p, "color", "text.create")?;
|
||||
if let Some(a) = p.get("area") {
|
||||
check_numbers(a, &["width", "height"], "text.create")?;
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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, including a group member selected on its own; when that object is not a symbol instance, such as a group, nothing is 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 (new art while it stays selected excepted), 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",
|
||||
@@ -252,7 +256,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Color Mode",
|
||||
["File", "Document Color Mode"],
|
||||
None,
|
||||
"{mode: \"cmyk\"|\"rgb\", convert?: true (convert every color of the art (opacity masks included), symbols, graph designs, pattern tiles, graphic styles, brushes and swatches through the color settings; swatch links kept; Gray colors stay Gray, on the black plate), intent?, grays?: \"profile\" (default: RGB grays separate through the CMYK profile like any color, into four-color grays and a rich black) | \"black\" (to CMYK, RGB grays with R = G = B go on the black plate only, K = their gray value)} → {changed: how many colors of the art, symbols, graph designs and pattern tiles changed; the colors of graphic styles and brushes are not counted}",
|
||||
"{mode: \"cmyk\"|\"rgb\", convert?: true (convert every color of the art (opacity masks, effect colors and graphs' series and label paints included), symbols, graph designs, pattern tiles, graphic styles (their effect colors included), brushes, swatches and the paints new art takes through the color settings, together in one undo step (Undo restores their original values; Redo reapplies the conversion); swatch links kept; Gray colors stay Gray, on the black plate), intent?, grays?: \"profile\" (default: RGB grays separate through the CMYK profile like any color, into four-color grays and a rich black) | \"black\" (to CMYK, RGB grays with R = G = B go on the black plate only, K = their gray value)} → {changed: how many colors of the art, symbols, graph designs and pattern tiles changed; the colors of graphic styles and brushes are not counted}",
|
||||
has_doc,
|
||||
super::colormgmt::convert_mode
|
||||
),
|
||||
@@ -297,28 +301,23 @@ 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
|
||||
}
|
||||
|
||||
@@ -333,11 +332,12 @@ 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 {
|
||||
if !n.visible || n.locked || n.is_template() {
|
||||
return true;
|
||||
}
|
||||
if matches!(n.kind, NodeKind::Text(_)) && !f(n.id) {
|
||||
@@ -345,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;
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Setup",
|
||||
[],
|
||||
None,
|
||||
"{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup",
|
||||
"{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour; #rrggbbaa and #rgba are refused), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup",
|
||||
has_doc,
|
||||
setup
|
||||
)]
|
||||
|
||||
@@ -10,8 +10,8 @@ use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
use super::clipboard::SwatchChoices;
|
||||
use super::{
|
||||
CommandSpec, Result, Session, always, bad, bool_or, can_clear_history, can_redo, can_undo, checked_ids_param, cmd, f64_or, f64_req,
|
||||
finite_numbers, has_clipboard, has_doc, has_selection, has_selection_or_artboard_tool, has_selection_or_guides, id_param, index, ok, point_param,
|
||||
str_param,
|
||||
finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param, index, ok,
|
||||
point_param, str_param,
|
||||
};
|
||||
use crate::{Clipboard, EngineError, inspect};
|
||||
|
||||
@@ -125,8 +125,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
undo_group_end
|
||||
),
|
||||
cmd!("edit.cut", "Cut", ["Edit"], Some("Cmd+X"), "{} (the Artboard tool chosen: artboard.cut)", has_selection_or_artboard_tool, cut),
|
||||
cmd!("edit.copy", "Copy", ["Edit"], Some("Cmd+C"), "{} (the Artboard tool chosen: artboard.copy)", has_selection_or_artboard_tool, copy),
|
||||
cmd!(
|
||||
"edit.cut",
|
||||
"Cut",
|
||||
["Edit"],
|
||||
Some("Cmd+X"),
|
||||
"{} (selected ruler guides go too; the Artboard tool chosen: artboard.cut)",
|
||||
has_selection_guides_or_artboard_tool,
|
||||
cut
|
||||
),
|
||||
cmd!(
|
||||
"edit.copy",
|
||||
"Copy",
|
||||
["Edit"],
|
||||
Some("Cmd+C"),
|
||||
"{} the selection with what it uses, and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy → {copied, guides}",
|
||||
has_selection_guides_or_artboard_tool,
|
||||
copy
|
||||
),
|
||||
cmd!(
|
||||
"edit.paste",
|
||||
"Paste",
|
||||
@@ -177,7 +193,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear",
|
||||
["Edit"],
|
||||
Some("Delete"),
|
||||
"{ids?} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides)",
|
||||
"{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides)",
|
||||
has_selection_or_guides,
|
||||
clear
|
||||
),
|
||||
@@ -487,6 +503,9 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let selection = shared_selection(selection, st.history.redo.last());
|
||||
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
|
||||
turned.named = e.named;
|
||||
let paints = e.color_mode_paints.clone();
|
||||
turned.color_mode_paints = e.color_mode_paints;
|
||||
turned.recost_paints();
|
||||
st.history.redo.push(turned);
|
||||
st.history.trim();
|
||||
st.revision += 1;
|
||||
@@ -499,6 +518,9 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
leave_isolation_if_gone(st);
|
||||
super::globaledit::follow_history(st);
|
||||
st.drop_stale_variables_highlight();
|
||||
if let Some((before, _)) = paints {
|
||||
s.paint = before;
|
||||
}
|
||||
Ok(json!({ "undone": label }))
|
||||
}
|
||||
|
||||
@@ -516,6 +538,9 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let selection = shared_selection(selection, st.history.undo.last());
|
||||
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
|
||||
turned.named = e.named;
|
||||
let paints = e.color_mode_paints.clone();
|
||||
turned.color_mode_paints = e.color_mode_paints;
|
||||
turned.recost_paints();
|
||||
st.history.undo.push(turned);
|
||||
st.history.trim();
|
||||
st.revision += 1;
|
||||
@@ -527,6 +552,9 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
leave_isolation_if_gone(st);
|
||||
super::globaledit::follow_history(st);
|
||||
st.drop_stale_variables_highlight();
|
||||
if let Some((_, after)) = paints {
|
||||
s.paint = after;
|
||||
}
|
||||
Ok(json!({ "redone": label }))
|
||||
}
|
||||
|
||||
@@ -640,9 +668,35 @@ fn copy(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
if s.tool_id() == "artboard" {
|
||||
return super::panelcmds::artboard_copy(s, &json!({}), false);
|
||||
}
|
||||
let roots = selected_roots(s)?;
|
||||
s.clipboard = Clipboard::copy(s.doc()?, &roots);
|
||||
Ok(json!({ "copied": s.clipboard.nodes.len() }))
|
||||
let st = s.doc()?;
|
||||
// Selected ruler guides come along (#3226), as canvas guides: their layer and artboard stay
|
||||
// behind.
|
||||
let guides: Vec<vectorcraft_doc::Guide> = st
|
||||
.selection
|
||||
.guides
|
||||
.iter()
|
||||
.filter_map(|i| st.doc.guides.get(*i))
|
||||
.map(|g| vectorcraft_doc::Guide { layer: None, artboard: None, ..g.clone() })
|
||||
.collect();
|
||||
let roots = if st.selection.is_empty() && !guides.is_empty() { vec![] } else { selected_roots(s)? };
|
||||
let st = s.doc()?;
|
||||
let mut clip = Clipboard::copy(st, &roots);
|
||||
// Guides alone: the artboard the first one belongs to, or crosses, is where in-place pastes
|
||||
// measure from, as the objects' artboard is.
|
||||
if clip.nodes.is_empty()
|
||||
&& let Some(g) = st.selection.guides.first().and_then(|i| st.doc.guides.get(*i))
|
||||
{
|
||||
let board = g.artboard.and_then(|id| st.doc.artboards.iter().find(|a| a.id == id)).or_else(|| {
|
||||
st.doc
|
||||
.artboards
|
||||
.iter()
|
||||
.find(|a| if g.vertical { (a.rect.x0..=a.rect.x1).contains(&g.pos) } else { (a.rect.y0..=a.rect.y1).contains(&g.pos) })
|
||||
});
|
||||
clip.source_artboard = board.map(|a| a.rect);
|
||||
}
|
||||
clip.guides = guides;
|
||||
s.clipboard = clip;
|
||||
Ok(json!({ "copied": s.clipboard.nodes.len(), "guides": s.clipboard.guides.len() }))
|
||||
}
|
||||
|
||||
fn cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -651,9 +705,15 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Copy promotes a compound member to its compound. Cut must remove the same objects it
|
||||
// copied, while Clear on its own deletes exactly the selected members.
|
||||
// Ruler guides selected on their own: Copy takes them, Clear removes them.
|
||||
if s.doc()?.selection.is_empty() {
|
||||
copy(s, p)?;
|
||||
return clear(s, &json!({}));
|
||||
}
|
||||
let ids = selected_roots(s)?;
|
||||
copy(s, p)?;
|
||||
if s.doc()?.selection.anchors.is_empty() { clear(s, &json!({ "ids": ids })) } else { clear(s, &json!({})) }
|
||||
// The selected ruler guides it copied go with the objects, in the same undo step (#3226).
|
||||
if s.doc()?.selection.anchors.is_empty() { clear(s, &json!({ "ids": ids, "guides": true })) } else { clear(s, &json!({ "guides": true })) }
|
||||
}
|
||||
|
||||
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -667,8 +727,9 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return super::docmenu::guide_remove(s, &json!({}));
|
||||
}
|
||||
let st = s.doc()?;
|
||||
// Guides selected with the art go with it (not when ids are given).
|
||||
let with_guides = explicit.is_none();
|
||||
// Guides selected with the art go with it (not when ids are given, unless `guides` says so:
|
||||
// Cut, which names the objects it copied).
|
||||
let with_guides = explicit.is_none() || bool_or(p, "guides", false);
|
||||
let targets = explicit.unwrap_or_else(|| st.selection.in_paint_order(&st.doc));
|
||||
// Keep the selected ids themselves, without promoting compound members. Delete a selected
|
||||
// ancestor just once; its selected descendants leave with it. Layers themselves are kept.
|
||||
@@ -838,6 +899,13 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
// In place, in front, in back: onto the active artboard when the UI names it.
|
||||
_ => vec![onto_artboard(&st.doc, p, clip)],
|
||||
};
|
||||
// Guides alone don't follow a plain paste's offset or the view centre: they stay where they
|
||||
// were. With objects they move as the objects do.
|
||||
let guide_placements: Vec<Affine> = if !clip.nodes.is_empty() || !matches!(mode, PasteMode::Offset | PasteMode::Library | PasteMode::Drag) {
|
||||
placements.clone()
|
||||
} else {
|
||||
vec![Affine::IDENTITY]
|
||||
};
|
||||
let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| {
|
||||
let imported = clip.import_into(d, choices, same_doc);
|
||||
// Draw Inside: the clip group of the object drawn into, made on the first paste.
|
||||
@@ -885,6 +953,20 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
}
|
||||
}
|
||||
sel.set(new_ids.iter().copied());
|
||||
// Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a
|
||||
// paste of guides alone keeps them where they were, but onto another artboard or every
|
||||
// artboard as the in-place pastes put art); they are selected with the objects.
|
||||
let guide_layer = parent.and_then(|p| if d.node(p).is_some_and(Node::is_layer) { Some(p) } else { d.layer_containing(p) });
|
||||
for xf in &guide_placements {
|
||||
let dv = xf.translation();
|
||||
for g in &clip.guides {
|
||||
let pos = g.pos + if g.vertical { dv.x } else { dv.y };
|
||||
if pos.is_finite() {
|
||||
sel.guides.push(d.guides.len());
|
||||
d.guides.push(vectorcraft_doc::Guide { pos, layer: guide_layer, ..g.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
// Pasted type arrives without the layout bounds cache: fill it so boxes and alignment are
|
||||
// right away (opening the file later would, but paste must not depend on a reopen).
|
||||
super::typecmd::refresh_bounds_of(d, &new_ids);
|
||||
@@ -899,6 +981,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
}
|
||||
Ok(json!({
|
||||
"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(),
|
||||
"guides": clip.guides.len() * guide_placements.len(),
|
||||
"artboard": artboards.first(),
|
||||
"artboards": artboards,
|
||||
"added": imported.added,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -108,7 +108,7 @@ mod export_names;
|
||||
mod formats;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use access::list_dir;
|
||||
pub(crate) use access::list_dir;
|
||||
pub use access::write_file_with;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::{Placed, copy_new, file_metadata};
|
||||
@@ -120,7 +120,7 @@ pub(crate) use access::{drive_share_of, share_of};
|
||||
#[cfg(test)]
|
||||
pub(crate) use access::{drive_share_path, share_path, touched};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use access::{may_read, may_write};
|
||||
pub(crate) use access::{may_read, may_write};
|
||||
pub use commands::specs;
|
||||
pub use export_names::artboard_file_names;
|
||||
pub(crate) use export_names::{default_name, merge, unique_file_names, with_black_output, write_or_return};
|
||||
|
||||
@@ -10,7 +10,7 @@ use super::{EngineError, Result, Session, Value, bad, json};
|
||||
|
||||
/// `path` checked for reading against the automation roots in force.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn may_read(path: &str) -> Result<()> {
|
||||
pub(crate) fn may_read(path: &str) -> Result<()> {
|
||||
#[cfg(test)]
|
||||
touch(path);
|
||||
crate::file_access::check_read(path).map_err(EngineError::Other)
|
||||
@@ -44,7 +44,7 @@ pub(crate) fn touched<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
|
||||
|
||||
/// `path` checked for writing against the automation roots in force.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn may_write(path: &str) -> Result<()> {
|
||||
pub(crate) fn may_write(path: &str) -> Result<()> {
|
||||
crate::file_access::check_write(path).map_err(EngineError::Other)
|
||||
}
|
||||
|
||||
@@ -169,7 +169,7 @@ pub(super) fn file_list(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// The entries of folder `path`, sorted by name: at most `max`, and whether there were more. A
|
||||
/// link isn't followed: its target may lie outside the automation roots.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn list_dir(path: &str, max: usize) -> Result<(Vec<Value>, bool)> {
|
||||
pub(crate) fn list_dir(path: &str, max: usize) -> Result<(Vec<Value>, bool)> {
|
||||
may_read(path)?;
|
||||
let dir = std::fs::read_dir(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let mut entries: Vec<(String, Value)> = vec![];
|
||||
@@ -195,7 +195,7 @@ pub(super) fn list_dir(path: &str, max: usize) -> Result<(Vec<Value>, bool)> {
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(super) fn list_dir(_: &str, _: usize) -> Result<(Vec<Value>, bool)> {
|
||||
pub(crate) fn list_dir(_: &str, _: usize) -> Result<(Vec<Value>, bool)> {
|
||||
Err(EngineError::Other("no file system here".into()))
|
||||
}
|
||||
|
||||
|
||||
@@ -15,12 +15,12 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let artboard = p.get("artboard").and_then(Value::as_u64);
|
||||
// What an error rolls back besides the documents: session-level state a step may change
|
||||
// (paint defaults, drawing mode, clipboard, the Untitled-N count, a begun undo group).
|
||||
let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone());
|
||||
// A drag or typing still in progress is a step of its own, as before Undo: the batch's steps
|
||||
// would otherwise run inside it and take its baseline as theirs (#1697).
|
||||
if s.active().is_some() {
|
||||
if s.active().is_some() && !s.previewing {
|
||||
super::super::edit::settle_interaction(s)?;
|
||||
}
|
||||
let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone());
|
||||
// The documents as they are now, whole: what a failed step brings back. Their art, history,
|
||||
// file, format and saved state share their data with the open ones until a step changes them.
|
||||
let start = s.docs.clone();
|
||||
@@ -47,10 +47,18 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
};
|
||||
// Each document the steps edited keeps them as one undo step.
|
||||
s.remember_pending_paint();
|
||||
for st in &mut s.docs {
|
||||
if let Some(it) = st.interaction.take() {
|
||||
st.keep_interaction(it);
|
||||
if !s.previewing {
|
||||
s.remember_pending_paint();
|
||||
for st in &mut s.docs {
|
||||
if let Some(mut it) = st.interaction.take() {
|
||||
// Redo restores the new-art colors the whole batch left, not the ones right after a
|
||||
// color-mode step.
|
||||
if let Some((_, after)) = &mut it.color_mode_paints {
|
||||
after.clone_from(&s.paint);
|
||||
s.batch_paint_docs.push(st.uid);
|
||||
}
|
||||
st.keep_interaction(it);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The batch journals itself, whichever document it ends in.
|
||||
@@ -58,7 +66,9 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(o) = entry.as_object_mut() {
|
||||
o.insert("commands".into(), Value::Array(cmds));
|
||||
}
|
||||
s.journal.push(("command.batch".into(), entry));
|
||||
if !s.previewing {
|
||||
s.journal.push(("command.batch".into(), entry));
|
||||
}
|
||||
Ok(json!({ "results": results }))
|
||||
}
|
||||
|
||||
@@ -104,6 +114,9 @@ fn run_steps(
|
||||
let held: Vec<(u64, Arc<Document>)> = s.docs.iter().filter(|st| st.undo_group.is_some()).map(|st| (st.uid, st.doc.clone())).collect();
|
||||
let (v, noted) =
|
||||
s.execute_step(&id, ¶ms).map_err(|e| EngineError::Other(format!("batch step {} (`{id}`) failed: {e}", results.len())))?;
|
||||
if s.previewing && s.active().map(|d| d.uid) != start {
|
||||
return Err(bad("command.batch", "a batch preview cannot switch documents"));
|
||||
}
|
||||
grouped.push(step_groups(s, start, &held));
|
||||
// The step's journal entry records what it took from the preferences or the clock (a
|
||||
// save's date, a new document's), as a command of its own would.
|
||||
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path",
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path",
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
|
||||
@@ -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). `layers`: the
|
||||
/// editor's copy ([`editing_copy`]), as far as it was decoded and read.
|
||||
fn through_editing_data(
|
||||
layers: Option<vectorcraft_eps::AiLayers>,
|
||||
opts: &LoadOptions,
|
||||
doc: Document,
|
||||
warnings: Vec<String>,
|
||||
unit: f64,
|
||||
) -> (Document, Vec<String>, bool) {
|
||||
let Some(layers) = layers 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_from(layers, 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,41 @@ 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
|
||||
}
|
||||
|
||||
/// May a file opened with `opts` open from the editor's own copy of its art without its PDF part
|
||||
/// being imported ([`vectorcraft_eps::ai_layers_alone`]): it reads the editor's copy, on the pages'
|
||||
/// trim boxes (the crop box asked for, as a file with the editor's copy opens on them), with its
|
||||
/// type as text?
|
||||
fn reads_layers_alone(opts: &LoadOptions) -> bool {
|
||||
reads_editing_copy(opts) && opts.crop == vectorcraft_pdf::CropTo::Crop && opts.text_as != vectorcraft_pdf::TextAs::Outlines
|
||||
}
|
||||
|
||||
/// 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 +293,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 +333,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,47 +361,86 @@ 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") {
|
||||
Ok(r) => {
|
||||
// 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
|
||||
// against, and the empty page would lose all of it.
|
||||
// A page is empty only when nothing on it was skipped (an image that can't be
|
||||
// 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))
|
||||
.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),
|
||||
};
|
||||
editing_data = read;
|
||||
Ok((doc, warnings))
|
||||
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, || {
|
||||
// Type all from the text document and nothing that needs the PDF part: the layers
|
||||
// alone, the PDF part not imported. Else what was read of the layers is kept for
|
||||
// reading them with the PDF part.
|
||||
let mut layers = None;
|
||||
if let Some((o, private)) = opened.as_ref().ok().filter(|_| reads_layers_alone(opts)).and_then(|o| Some((o, editing_copy(o, opts)?)))
|
||||
{
|
||||
let pages = o.trim_pages();
|
||||
match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit) {
|
||||
Ok((mut doc, warnings)) => {
|
||||
doc.setup.bleed = pages.bleed;
|
||||
editing_data = true;
|
||||
return Ok((doc, warnings));
|
||||
}
|
||||
Err(read) => layers = Some(read),
|
||||
}
|
||||
}
|
||||
// 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 })
|
||||
match imported() {
|
||||
Ok(r) => {
|
||||
// The editor's copy, read once the import is done with the pages, unless
|
||||
// its layers were read before it.
|
||||
let private = layers.is_none().then(|| opened.as_ref().ok().and_then(|o| editing_copy(o, opts))).flatten();
|
||||
// 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
|
||||
// against, and the empty page would lose all of it.
|
||||
// A page is empty only when nothing on it was skipped (an image that can't be
|
||||
// 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 copy_alone = || match &private {
|
||||
Some(private) => Some(editing_copy_alone(private)),
|
||||
None if layers.is_some() => opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p)),
|
||||
None => None,
|
||||
};
|
||||
let alone = (r.only_text || empty)
|
||||
.then(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 => {
|
||||
let layers = layers.or_else(|| private.as_deref().map(vectorcraft_eps::AiLayers::decode));
|
||||
through_editing_data(layers, 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) => 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)
|
||||
.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),
|
||||
}
|
||||
// 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 +462,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);
|
||||
}
|
||||
|
||||
@@ -105,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, compound paths, paths, fills and strokes, colors, swatches, artboards, the transparency of objects and layers, objects' opacity masks, and clipping groups and layers clipped by a path, with type, gradients, patterns, images, symbols, other clipping objects and live objects as plain filled and stroked paths (written only with every artboard, as Preserve Editing is)",
|
||||
},
|
||||
FormatOption {
|
||||
name: "aiVersion",
|
||||
ty: "string",
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -24,8 +24,8 @@ const TRUNCATED: &str = "the Pixar file is cut short";
|
||||
/// define.
|
||||
const DAMAGED: &str = "the Pixar file's header is damaged";
|
||||
|
||||
/// The message for encoded tile data with a packet the format doesn't define, or one that runs
|
||||
/// past the end of its scan line.
|
||||
/// The message for a tile pointer into the header or the tile pointer table, and for encoded tile
|
||||
/// data with a packet the format doesn't define, or one that runs past the end of its scan line.
|
||||
const BAD_DATA: &str = "the Pixar file's image data is damaged";
|
||||
|
||||
/// The channel bits of the picture format field (header byte 424): R, G, B and A, stored in this
|
||||
@@ -115,7 +115,9 @@ pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result<image::RgbaImage, S
|
||||
let layout =
|
||||
Layout { gray: format & 0b1110 == 0b1000, matted: alpha_mode == 0, alpha: format & 1 != 0, sample: if wide { 2 } else { 1 }, wide, stored };
|
||||
let (across, down) = (w.div_ceil(tile_w), h.div_ceil(tile_h));
|
||||
let table = bytes.get(HEADER..HEADER + across * down * 8).ok_or(TRUNCATED)?;
|
||||
// A table end past the largest address is past the end of the file too.
|
||||
let table_end = across.checked_mul(down).and_then(|n| n.checked_mul(8)).and_then(|n| n.checked_add(HEADER)).ok_or(TRUNCATED)?;
|
||||
let table = bytes.get(HEADER..table_end).ok_or(TRUNCATED)?;
|
||||
let empty = if layout.alpha { [0; 4] } else { [0, 0, 0, 255] };
|
||||
let mut img = image::RgbaImage::from_pixel(w as u32, h as u32, image::Rgba(empty));
|
||||
// The encoded data read in all, which a file whose tiles each hold their own data stays within.
|
||||
@@ -131,6 +133,11 @@ pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result<image::RgbaImage, S
|
||||
if length == -1 || pointer >= bytes.len() {
|
||||
return Err(TRUNCATED.into());
|
||||
}
|
||||
// Tile data follows the tile pointer table; a pointer into the header or the table would
|
||||
// read them as pixels.
|
||||
if pointer < table_end {
|
||||
return Err(BAD_DATA.into());
|
||||
}
|
||||
let (x0, y0) = (n % across * tile_w, n / across * tile_h);
|
||||
// The part of the tile inside the picture; the pixels of border tiles past its edges are
|
||||
// stored and skipped.
|
||||
|
||||
@@ -249,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(),
|
||||
@@ -293,6 +288,12 @@ 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 })
|
||||
}
|
||||
|
||||
@@ -575,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`.
|
||||
@@ -585,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);
|
||||
@@ -605,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))?;
|
||||
@@ -614,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) })
|
||||
}
|
||||
@@ -673,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"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
@@ -1148,10 +1221,16 @@ fn half_outlined_line(y: f64, rest: &str, mode: u8) -> String {
|
||||
/// text document (a line starting at (14, 65)), then `more` of a story the text document doesn't
|
||||
/// have. Without `story` the file has no text document.
|
||||
fn half_outlined_ai(story: Option<&str>, more: usize, type_content: &str) -> Vec<u8> {
|
||||
half_outlined_ai_on(story, more, type_content, "", |page| page)
|
||||
}
|
||||
|
||||
/// [`half_outlined_ai`] with the editing data's comments `head` before its art, whose page is
|
||||
/// `page_of` the 200 × 100 pt page it draws on (other boxes, more entries).
|
||||
fn half_outlined_ai_on(story: Option<&str>, more: usize, type_content: &str, head: &str, page_of: impl FnOnce(PdfPage) -> PdfPage) -> Vec<u8> {
|
||||
let text = |story: u32| format!("/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n{story} /StoryIndex ,\n;\n");
|
||||
let texts: String = std::iter::once(text(0)).chain((0..more).map(|_| text(99))).collect();
|
||||
let mut body =
|
||||
format!("%AI3_TemplateBox: 100 50 100 50\n{}", ai::layer("Art", &format!("0.5 g\n{}f\n{texts}", ai::rect(120.0, 20.0, 160.0, 60.0))));
|
||||
format!("{head}%AI3_TemplateBox: 100 50 100 50\n{}", ai::layer("Art", &format!("0.5 g\n{}f\n{texts}", ai::rect(120.0, 20.0, 160.0, 60.0))));
|
||||
if let Some(story) = story {
|
||||
// The story's one line starts at the canvas center (8191.5, the template box's center) moved
|
||||
// to (14, 65): its y runs down the page.
|
||||
@@ -1182,7 +1261,7 @@ fn half_outlined_ai(story: Option<&str>, more: usize, type_content: &str) -> Vec
|
||||
};
|
||||
let cmap = "begincmap\n1 begincodespacerange\n<00> <FF>\nendcodespacerange\n1 beginbfchar\n<41> <FFFD>\nendbfchar\nendcmap\n";
|
||||
pdf_with(
|
||||
&[page],
|
||||
&[page_of(page)],
|
||||
&[&format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len()), &format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())],
|
||||
None,
|
||||
)
|
||||
@@ -1214,6 +1293,12 @@ fn texts(s: &Session) -> Vec<String> {
|
||||
/// (art x 10 to 90 and 110 to 190, y 10 to 90), then a band across the first frame (y 30 to 70),
|
||||
/// made a wrap object with no offset when `wrap` is set.
|
||||
fn wrapped_thread_ai(wrap: bool) -> Vec<u8> {
|
||||
ai::ai(&wrapped_thread_data(wrap.then_some(0.0)), PLACEHOLDER)
|
||||
}
|
||||
|
||||
/// The editing data of [`wrapped_thread_ai`], compressed, with the band a wrap object of `offset`
|
||||
/// when one is given.
|
||||
fn wrapped_thread_data(offset: Option<f64>) -> Vec<u8> {
|
||||
// The template box is centred at (100, 50), the canvas centre 8191.5: y runs down the canvas.
|
||||
let canvas = |x: f64, y: f64| (x + 8091.5, 8241.5 - y);
|
||||
let rect = |x0: f64, y0: f64, x1: f64, y1: f64| {
|
||||
@@ -1233,14 +1318,47 @@ fn wrapped_thread_ai(wrap: bool) -> Vec<u8> {
|
||||
);
|
||||
let lines: Vec<String> = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect();
|
||||
let frame = |f: u32| format!("/AI11Text :\n0 /FreeUndo ,\n{f} /FrameIndex ,\n0 /StoryIndex ,\n;\n");
|
||||
let dict = if wrap { "%_/ArtDictionary :\n%_0 /Real (AI11TextWrapOffset) ,\n%_0 /Bool (AI11TextWrapInvert) ,\n%_;\n%_\n" } else { "" };
|
||||
let dict = offset
|
||||
.map(|o| format!("%_/ArtDictionary :\n%_{o} /Real (AI11TextWrapOffset) ,\n%_0 /Bool (AI11TextWrapInvert) ,\n%_;\n%_\n"))
|
||||
.unwrap_or_default();
|
||||
let art = format!("{}{}0.5 g\n{}f\n{dict}", frame(0), frame(1), ai::rect(10.0, 30.0, 90.0, 70.0));
|
||||
let body = format!(
|
||||
"%AI3_TemplateBox: 100 50 100 50\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n",
|
||||
ai::layer("Art", &art),
|
||||
lines.join("\n")
|
||||
);
|
||||
ai::ai(&compressed(ai::editing_data(200.0, 100.0, &body).as_bytes()), PLACEHOLDER)
|
||||
compressed(ai::editing_data(200.0, 100.0, &body).as_bytes())
|
||||
}
|
||||
|
||||
/// The wrap offset of the first frame of `doc`'s threaded type, as its text resolves it.
|
||||
fn first_frame_wrap_offset(doc: &vectorcraft_doc::Document) -> f64 {
|
||||
match &doc.node(doc.text_threads[0][0]).unwrap().kind {
|
||||
NodeKind::Text(t) => t.wrap[0].wrap.offset,
|
||||
_ => panic!("area type"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A `.ai` in units of 10 points whose threaded area type flows around a wrap object of a 2 unit
|
||||
/// offset opens with the type flowing round it 20 pt off, its PDF part read or not, and when its
|
||||
/// PDF part can't be read. The default graphic styles of a file without its own aren't scaled.
|
||||
#[test]
|
||||
fn wrapped_type_in_units_of_ten_points_flows_round_the_wrap_at_its_size_in_points() {
|
||||
let private = wrapped_thread_data(Some(2.0));
|
||||
let page = "0.5 g 10 30 80 40 re f";
|
||||
let refused = ai::ai_with_entries_and_content(&private, page, "/UserUnit 10", REFUSED_CONTENT);
|
||||
// On the trim boxes the PDF part is imported, and the refused stream stops it.
|
||||
let trim = LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() };
|
||||
let files = [(ai::ai_with(&private, page, "/UserUnit 10"), LoadOptions::default()), (refused, trim)];
|
||||
for (file, opts) in &files {
|
||||
let loaded = load_with("thread.ai", file, opts).unwrap();
|
||||
assert!(loaded.editing_data, "{:?}", loaded.warnings);
|
||||
assert!((first_frame_wrap_offset(&loaded.doc) - 20.0).abs() < 0.01, "{:?}", loaded.warnings);
|
||||
}
|
||||
let loaded = load_with("thread.ai", &files[1].0, &files[1].1).unwrap();
|
||||
assert!(loaded.warnings.iter().any(|w| w.starts_with("the PDF part couldn't be read")), "{:?}", loaded.warnings);
|
||||
// The file has no graphic styles of its own: the default ones aren't scaled either way.
|
||||
let read = load_with("thread.ai", &files[0].0, &files[0].1).unwrap();
|
||||
assert_eq!(loaded.doc.graphic_styles, read.doc.graphic_styles);
|
||||
}
|
||||
|
||||
/// Threaded area type below a wrap object flows around it when the file opens: the text the wrap
|
||||
@@ -1285,6 +1403,77 @@ fn type_from_the_text_document_opens_without_the_pdf_parts_note_on_outlines() {
|
||||
assert!(!r["warnings"].as_array().unwrap().contains(&without_outlines_note(1)), "{r}");
|
||||
}
|
||||
|
||||
/// A `.ai` whose text document makes all of its type, with nothing unread, opens from its layers
|
||||
/// without its PDF part being imported: a page that draws more than the layers isn't compared with
|
||||
/// them. On its trim box it takes the pages' bleed, and pages in units of 10 points draw it ten
|
||||
/// times as large, as when its PDF part is imported. With type the text document can't make,
|
||||
/// editing data on a large canvas, its type asked for as outlines, another box or pages picked, the
|
||||
/// PDF part is imported as before.
|
||||
#[test]
|
||||
fn type_all_from_the_text_document_opens_without_importing_the_pdf_part() {
|
||||
let line = half_outlined_line(65.0, "rst draft", 0);
|
||||
// The page draws a red square the layers don't have.
|
||||
let differs = half_outlined_ai(Some("first draft"), 0, &format!("{line} 1 0 0 rg 20 20 30 30 re f"));
|
||||
let mut s = Session::new();
|
||||
let before = vectorcraft_pdf::imports_of(&differs);
|
||||
let loaded = load_with("draft.ai", &differs, &LoadOptions::default()).unwrap();
|
||||
assert_eq!(vectorcraft_pdf::imports_of(&differs), before, "{:?}", loaded.warnings);
|
||||
assert!(loaded.editing_data, "{:?}", loaded.warnings);
|
||||
assert!(!loaded.warnings.iter().any(|w| w.contains("differently")), "{:?}", loaded.warnings);
|
||||
let r = open(&mut s, "draft.ai", &differs, json!({})).unwrap();
|
||||
assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}");
|
||||
assert_eq!(texts(&s), ["first draft"], "{r}");
|
||||
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "the square and the type, without the page's red square: {r}");
|
||||
// A 10 pt bleed round the trim box, the art drawn in the trim box.
|
||||
let bled = half_outlined_ai_on(Some("first draft"), 0, &line, "", |p| PdfPage {
|
||||
media: [0.0, 0.0, 220.0, 120.0],
|
||||
bleed: Some([0.0, 0.0, 220.0, 120.0]),
|
||||
trim: Some([10.0, 10.0, 210.0, 110.0]),
|
||||
content: format!("1 0 0 1 10 10 cm {}", p.content),
|
||||
..p
|
||||
});
|
||||
let before = vectorcraft_pdf::imports_of(&bled);
|
||||
let loaded = load_with("bled.ai", &bled, &LoadOptions::default()).unwrap();
|
||||
assert_eq!(vectorcraft_pdf::imports_of(&bled), before);
|
||||
assert_eq!(loaded.doc.setup.bleed, [10.0; 4]);
|
||||
// Pages of 10 pt units.
|
||||
let large = half_outlined_ai_on(Some("first draft"), 0, &line, "", |p| PdfPage { entries: format!("{} /UserUnit 10", p.entries), ..p });
|
||||
let before = vectorcraft_pdf::imports_of(&large);
|
||||
let loaded = load_with("large.ai", &large, &LoadOptions::default()).unwrap();
|
||||
assert_eq!(vectorcraft_pdf::imports_of(&large), before);
|
||||
let board = loaded.doc.artboards[0].rect;
|
||||
assert!((board.width() - 2000.0).abs() < 0.01 && (board.height() - 1000.0).abs() < 0.01, "{board:?}");
|
||||
// Opened on the trim boxes with the PDF part imported and compared, as before, both files have
|
||||
// the same artboards and bleed.
|
||||
for file in [&bled, &large] {
|
||||
let alone = load_with("draft.ai", file, &LoadOptions::default()).unwrap();
|
||||
let compared = load_with("draft.ai", file, &LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }).unwrap();
|
||||
assert!(compared.editing_data, "{:?}", compared.warnings);
|
||||
let boards = |d: &vectorcraft_doc::Document| d.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
assert_eq!(boards(&alone.doc), boards(&compared.doc));
|
||||
assert_eq!(alone.doc.setup.bleed, compared.doc.setup.bleed);
|
||||
assert_eq!(names(&alone.doc.layers), names(&compared.doc.layers));
|
||||
// The file has no graphic styles of its own: the default ones aren't scaled.
|
||||
assert_eq!(alone.doc.graphic_styles, compared.doc.graphic_styles);
|
||||
}
|
||||
// The PDF part is imported, once.
|
||||
let unmade = half_outlined_ai(Some("first draft"), 1, &line);
|
||||
// Editing data on a large canvas reads at its own scale when the file has no PDF part.
|
||||
let canvas = half_outlined_ai_on(Some("first draft"), 0, &line, "%AI24_LargeCanvasScale: 2\n", |p| p);
|
||||
let cases = [
|
||||
(&unmade, LoadOptions::default()),
|
||||
(&canvas, LoadOptions::default()),
|
||||
(&differs, LoadOptions { text_as: vectorcraft_pdf::TextAs::Outlines, ..Default::default() }),
|
||||
(&differs, LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }),
|
||||
(&differs, LoadOptions { pages: Some("1".into()), ..Default::default() }),
|
||||
];
|
||||
for (file, opts) in cases {
|
||||
let before = vectorcraft_pdf::imports_of(file);
|
||||
load_with("draft.ai", file, &opts).unwrap();
|
||||
assert_eq!(vectorcraft_pdf::imports_of(file) - before, 1, "{opts:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A text object that takes the page's type lacks the glyphs next to it that the page kept as
|
||||
/// outlines: a note counts such objects, in place of the PDF part's notes. Stroked glyphs that
|
||||
/// come in with the stroked type keep the PDF part's notes.
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -405,7 +405,7 @@ fn ai_export_without_artboards_keeps_art_outside_the_original_pages() {
|
||||
}
|
||||
|
||||
/// Color Halftone's Max Radius is in pixels of the raster effects resolution since document
|
||||
/// version 2 (#3260). A PDF saved with Preserve Editing carries the native document, so one from
|
||||
/// version 3 (#3260). A PDF saved with Preserve Editing carries the native document, so one from
|
||||
/// before that opens with the radius converted, drawing the same dots; one saved since opens as
|
||||
/// it was.
|
||||
#[test]
|
||||
@@ -432,3 +432,223 @@ fn a_preserve_editing_pdf_opens_with_its_halftone_radius_in_pixels() {
|
||||
assert!((halftone(true) - 8.0 * 300.0 / 72.0).abs() < 1e-9, "{}", halftone(true));
|
||||
assert_eq!(halftone(false), 8.0);
|
||||
}
|
||||
|
||||
/// 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 leaves the live effect out) 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();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [id]})).unwrap();
|
||||
let r = s.execute("document.export", &json!({"format": "ai"})).unwrap();
|
||||
assert!(r["warnings"].to_string().contains("live effects"), "{r}");
|
||||
let bytes = b64(&r);
|
||||
let effects = |doc: &vectorcraft_doc::Document| {
|
||||
let mut out = vec![];
|
||||
doc.walk(|n| {
|
||||
if matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }) {
|
||||
out.push(n.appearance.effects.len());
|
||||
}
|
||||
});
|
||||
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!(effects(©.doc), [0]);
|
||||
let opened = load::load_with("art.ai", &bytes, &LoadOptions::default()).unwrap();
|
||||
assert!(opened.restored);
|
||||
assert_eq!(effects(&opened.doc), [1]);
|
||||
}
|
||||
|
||||
/// The layers, groups, compound paths and paths of `doc` with their names, visibility, geometric
|
||||
/// bounds (rounded), transparency, clipping and opacity masks, one line each; a mask's art after
|
||||
/// its object.
|
||||
fn see_through_outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
|
||||
use vectorcraft_doc::NodeKind;
|
||||
fn walk(nodes: &[std::sync::Arc<vectorcraft_doc::Node>], depth: usize, out: &mut Vec<String>) {
|
||||
for n in nodes {
|
||||
let kind = match &n.kind {
|
||||
NodeKind::Layer { clip, .. } => format!("layer clip={clip}"),
|
||||
NodeKind::Group { clip, .. } => format!("group clip={clip}"),
|
||||
NodeKind::Compound { .. } => "compound".into(),
|
||||
NodeKind::Path { clipping, .. } => format!("path clipping={clipping}"),
|
||||
_ => "other".into(),
|
||||
};
|
||||
let b = n.geometric_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64));
|
||||
let mask = n.extras().mask.clone();
|
||||
out.push(format!(
|
||||
"{depth} {kind} {:?} {} {b:?} {} {:?} isolate={} {:?} shape={} mask={:?}",
|
||||
n.name,
|
||||
n.visible,
|
||||
(n.opacity * 100.0).round(),
|
||||
n.blend,
|
||||
n.isolate,
|
||||
n.knockout,
|
||||
n.knockout_shape,
|
||||
mask.as_ref().map(|m| (m.clip, m.invert, m.disabled, m.linked))
|
||||
));
|
||||
if let Some(m) = mask {
|
||||
walk(std::slice::from_ref(&m.art), depth + 1, out);
|
||||
}
|
||||
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 document of two artboards (the art on the first) with a compound path at 70% in Screen, a
|
||||
/// clipping group at 50% in Multiply, a named group (isolated, knockout on, knockout shape) and a
|
||||
/// square with an opacity mask that doesn't clip on layer `Layer 1`, and layer `Cut` (40%,
|
||||
/// clipping) holding two squares.
|
||||
fn see_through_session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 2})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
let id = |v: serde_json::Value| v["id"].as_u64().unwrap();
|
||||
let rect = |s: &mut Session, x: f64, y: f64, w: f64, h: f64| {
|
||||
id(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap())
|
||||
};
|
||||
// A compound path at 70% in Screen.
|
||||
let (a, b) = (rect(&mut s, 10.0, 10.0, 40.0, 40.0), rect(&mut s, 20.0, 20.0, 20.0, 20.0));
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 70, "blend": "Screen"})).unwrap();
|
||||
// A clipping group at 50% in Multiply.
|
||||
let (art, clip) = (rect(&mut s, 60.0, 10.0, 60.0, 40.0), rect(&mut s, 70.0, 20.0, 30.0, 20.0));
|
||||
s.execute("select.set", &json!({"ids": [art, clip]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 50, "blend": "Multiply"})).unwrap();
|
||||
// A named group, isolated, knockout on, whose opacity defines the knockout shape.
|
||||
let (a, b) = (rect(&mut s, 60.0, 60.0, 30.0, 30.0), rect(&mut s, 75.0, 75.0, 30.0, 30.0));
|
||||
let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap());
|
||||
s.execute("object.setProps", &json!({"ids": [g], "name": "Knock", "opacity": 80, "isolate": true, "knockout": "on", "knockoutShape": true}))
|
||||
.unwrap();
|
||||
// A square with an opacity mask that doesn't clip.
|
||||
let masked = rect(&mut s, 130.0, 10.0, 40.0, 40.0);
|
||||
s.execute("paint.setFill", &json!({"color": "#808080"})).unwrap();
|
||||
let mask = rect(&mut s, 140.0, 20.0, 20.0, 20.0);
|
||||
s.execute("select.set", &json!({"ids": [masked, mask]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({"clip": false})).unwrap();
|
||||
// A clipping layer at 40%.
|
||||
let cut = id(s.execute("layer.new", &json!({"name": "Cut"})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
rect(&mut s, 10.0, 100.0, 80.0, 60.0);
|
||||
rect(&mut s, 30.0, 110.0, 40.0, 40.0);
|
||||
s.execute("layer.clippingMask.toggle", &json!({})).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [cut], "opacity": 40})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The editing copy of `bytes` read alone, checked against its page.
|
||||
fn editing_copy(bytes: &[u8]) -> vectorcraft_doc::Document {
|
||||
let l = load::load_with("art.ai", bytes, &LoadOptions { native: false, ..Default::default() }).unwrap();
|
||||
assert!(l.editing_data && !l.restored, "{:?}", l.warnings);
|
||||
assert!(!l.warnings.iter().any(|w| w.contains("editing data")), "{:?}", l.warnings);
|
||||
l.doc
|
||||
}
|
||||
|
||||
/// `nodes` as the editing copy reads them back: an opacity mask's art that isn't a group comes
|
||||
/// back as a plain group holding it.
|
||||
fn mask_art_grouped(nodes: &mut [std::sync::Arc<vectorcraft_doc::Node>]) {
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
for n in nodes {
|
||||
let n = std::sync::Arc::make_mut(n);
|
||||
if let Some(m) = n.extras_mut().mask.as_mut()
|
||||
&& !matches!(m.art.kind, NodeKind::Group { .. })
|
||||
{
|
||||
let art = m.art.clone();
|
||||
m.art = std::sync::Arc::new(Node::new(art.id, NodeKind::Group { children: vec![art], clip: false }));
|
||||
}
|
||||
if let Some(c) = n.children_mut() {
|
||||
mask_art_grouped(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Transparency, a compound path, a clipping group, an opacity mask and a clipping layer come back
|
||||
/// from the editing copy for other apps alone, its page matching it, with every save option that
|
||||
/// writes the copy; the version 7 `.ai` keeps the compound path and the clipping group.
|
||||
#[test]
|
||||
fn transparency_clipping_and_opacity_masks_come_back_from_the_editing_copy() {
|
||||
let mut s = see_through_session();
|
||||
let mut before = (*s.doc().unwrap().doc).clone();
|
||||
// The mask's art is one path; it reads back as a group holding the path.
|
||||
let mut arts = vec![];
|
||||
before.walk(|n| arts.extend(n.extras().mask.as_ref().map(|m| matches!(m.art.kind, vectorcraft_doc::NodeKind::Path { .. }))));
|
||||
assert_eq!(arts, [true]);
|
||||
mask_art_grouped(&mut before.layers);
|
||||
let want = see_through_outline(&before);
|
||||
for opts in [json!({"format": "ai"}), json!({"format": "ai", "compress": false}), json!({"format": "ai", "pdfCompatible": true})] {
|
||||
let bytes = b64(&s.execute("document.export", &opts).unwrap());
|
||||
assert_eq!(see_through_outline(&editing_copy(&bytes)), want, "{opts}");
|
||||
}
|
||||
// Each artboard in a file of its own: the first holds all the art.
|
||||
let path = tmp("see-through.ai");
|
||||
let r = s.execute("document.save", &json!({"path": path, "separateArtboards": true})).unwrap();
|
||||
let files: Vec<String> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
|
||||
assert_eq!(files.len(), 3, "{r}");
|
||||
for f in &files {
|
||||
let copy = editing_copy(&std::fs::read(f).unwrap());
|
||||
if f.ends_with("-2.ai") {
|
||||
assert!(copy.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "{f} {:#?}", see_through_outline(©));
|
||||
} else {
|
||||
assert_eq!(see_through_outline(©), want, "{f}");
|
||||
}
|
||||
}
|
||||
// Version 7 has no transparency; it keeps the compound path and the clipping group.
|
||||
let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": 7})).unwrap();
|
||||
let legacy = load::load_with("art.ai", &b64(&r), &LoadOptions::default()).unwrap();
|
||||
let kinds = see_through_outline(&legacy.doc);
|
||||
assert!(kinds.iter().any(|l| l.contains(" compound ")) && kinds.iter().any(|l| l.contains("group clip=true")), "{kinds:#?}");
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -361,3 +361,17 @@ fn damaged_files_are_refused_with_a_message() {
|
||||
assert!(!is_pxr(&bad), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tile_pointers_into_the_header_or_table_are_refused() {
|
||||
// Tile data follows the tile pointer table, which ends at byte 520 in a one-tile picture.
|
||||
let rgb = one(head(2, 1, RGB, 2), &[1, 2, 3, 4, 5, 6]);
|
||||
for pointer in [4u32, 511, 512, 519] {
|
||||
let mut inside = rgb.clone();
|
||||
inside[512..516].copy_from_slice(&pointer.to_le_bytes());
|
||||
let e = raster_image(&inside).err().expect("refused").to_string();
|
||||
assert_eq!(e, "the Pixar file's image data is damaged", "a pointer to byte {pointer}");
|
||||
}
|
||||
// A pointer at the table's end reads.
|
||||
assert_eq!(pixels(&rgb), [[1, 2, 3, 255], [4, 5, 6, 255]]);
|
||||
}
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it → {index}",
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it → {index}",
|
||||
has_doc,
|
||||
add_point
|
||||
),
|
||||
@@ -28,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{index? (default: the selected point), at?: [x,y] (document coordinates), color?, keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
|
||||
"{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
|
||||
has_doc,
|
||||
set_point
|
||||
),
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient",
|
||||
["Window", "Gradient"],
|
||||
None,
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even, which SVG and PDF exports draw as an image, except that PDF writes one with spot color stops in its inks when every other stop is paper white, CMYK or gray; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear or radial, has spot color stops, every other stop is paper white, CMYK or gray, it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
|
||||
has_doc,
|
||||
edit_gradient
|
||||
),
|
||||
|
||||
@@ -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;
|
||||
@@ -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();
|
||||
|
||||
@@ -289,6 +289,239 @@ fn painting_one_bar_sets_the_colour_used_by_the_whole_series_on_rebuild() {
|
||||
assert!(group(node, "2024").children().unwrap().iter().all(|n| n.appearance.fill_paint().color() == Some(green)));
|
||||
}
|
||||
|
||||
/// An opacity set on the fill or stroke item of one series mark is kept by the graph: every path of that series has
|
||||
/// it after the graph is drawn again, the other series stay opaque, 100% forgets it, and undo takes it back.
|
||||
#[test]
|
||||
fn an_item_opacity_on_a_series_mark_survives_regeneration() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let opacities = |s: &Session, index: u32| -> Vec<(f32, f32)> {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let marks = series(&n, index).children().unwrap().to_vec();
|
||||
marks.iter().map(|m| (m.appearance.fill().unwrap().opacity, m.appearance.stroke().unwrap().opacity)).collect()
|
||||
};
|
||||
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.execute("transparency.set", &json!({"ids": [bar.0], "item": 0, "opacity": 40})).unwrap();
|
||||
s.execute("transparency.set", &json!({"ids": [bar.0], "item": 1, "opacity": 60})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.stroke_opacity), (Some(0.4), Some(0.6)));
|
||||
let restored: GraphSpec = serde_json::from_value(serde_json::to_value(spec(&s, id)).unwrap()).unwrap();
|
||||
assert_eq!(restored, spec(&s, id));
|
||||
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
|
||||
assert!(opacities(&s, 0).iter().all(|o| *o == (0.4, 0.6)), "{:?}", opacities(&s, 0));
|
||||
assert!(opacities(&s, 1).iter().all(|o| *o == (1.0, 1.0)), "{:?}", opacities(&s, 1));
|
||||
// Back to 100%: the graph keeps no opacity for the fill.
|
||||
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.execute("transparency.set", &json!({"ids": [bar.0], "item": 0, "opacity": 100})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, None);
|
||||
s.execute("graph.setType", &json!({"type": "bar"})).unwrap();
|
||||
assert!(opacities(&s, 0).iter().all(|o| *o == (1.0, 0.6)), "{:?}", opacities(&s, 0));
|
||||
// Undo goes back through the type change, the 100% and the data edit, then takes the stroke opacity away with its
|
||||
// edit.
|
||||
for _ in 0..4 {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.stroke_opacity), (Some(0.4), None));
|
||||
}
|
||||
|
||||
/// Clear Appearance and Reduce to Basic Appearance on a series mark take its fill and stroke opacity away, and the
|
||||
/// graph keeps none, so the series stays opaque when it is drawn again.
|
||||
#[test]
|
||||
fn clearing_a_series_marks_appearance_forgets_its_kept_opacity() {
|
||||
for cmd in ["appearance.clear", "appearance.reduceToBasic"] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.execute("transparency.set", &json!({"ids": [bar.0], "item": 0, "opacity": 40})).unwrap();
|
||||
s.execute("transparency.set", &json!({"ids": [bar.0], "item": 1, "opacity": 60})).unwrap();
|
||||
s.execute(cmd, &json!({"ids": [bar.0]})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.stroke_opacity), (None, None), "{cmd}");
|
||||
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert!(series(&n, 0).children().unwrap().iter().all(|m| m.appearance.fill().unwrap().opacity == 1.0), "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Removing the fill whose opacity the graph keeps takes the kept opacity away; an edit that leaves a mark opaque
|
||||
/// (a blend mode alone) keeps nothing for its series.
|
||||
#[test]
|
||||
fn removing_a_series_marks_fill_forgets_its_kept_opacity() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.execute("transparency.set", &json!({"ids": [bar.0], "item": 0, "blend": "multiply"})).unwrap();
|
||||
assert!(spec(&s, id).series_paints.is_empty());
|
||||
s.execute("transparency.set", &json!({"ids": [bar.0], "item": 0, "opacity": 40})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, Some(0.4));
|
||||
s.execute("appearance.removeItem", &json!({"ids": [bar.0], "index": 0})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, None);
|
||||
// An opaque fill added over the kept one takes it away too.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("appearance.addFill", &json!({"ids": [bar.0]})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, None);
|
||||
}
|
||||
|
||||
/// An opacity set on a row added to a graph design's copy inside a series is not kept for the series: the graph draws
|
||||
/// the design again from the design itself.
|
||||
#[test]
|
||||
fn an_opacity_on_a_design_copy_in_a_series_is_not_kept() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
save_design(&mut s, "Square");
|
||||
s.execute("graph.column", &json!({"id": id.0, "design": "Square"})).unwrap();
|
||||
let copy = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].clone();
|
||||
assert!(matches!(copy.kind, NodeKind::Group { .. }));
|
||||
s.execute("appearance.addFill", &json!({"ids": [copy.id.0]})).unwrap();
|
||||
s.execute("transparency.set", &json!({"ids": [copy.id.0], "item": 0, "opacity": 40})).unwrap();
|
||||
assert!(spec(&s, id).series_paints.first().is_none_or(|p| p.fill_opacity.is_none()));
|
||||
}
|
||||
|
||||
/// A series' kept opacity goes on its generated marks only: a column design made of one path keeps its own opacity.
|
||||
#[test]
|
||||
fn a_column_design_keeps_its_own_opacity_under_a_series_opacity() {
|
||||
let mut d = vectorcraft_doc::Document::new(800.0, 800.0);
|
||||
let mut look = vectorcraft_doc::Appearance::basic(Paint::solid(vectorcraft_color::Color::BLACK), Paint::None, 0.0);
|
||||
look.fill_mut().unwrap().opacity = 0.5;
|
||||
let rect = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let art = vectorcraft_doc::Node::path(d.alloc_id(), rect, look);
|
||||
d.graph_designs.push(vectorcraft_doc::GraphDesign { name: "Square".into(), art: std::sync::Arc::new(art) });
|
||||
let options = ColumnDesign { design: "Square".into(), column_type: ColumnType::Vertical, ..ColumnDesign::default() };
|
||||
let paints = vec![vectorcraft_doc::SeriesPaint { fill_opacity: Some(0.2), ..Default::default() }];
|
||||
let g = GraphSpec {
|
||||
rows: vec![vec![35.0]],
|
||||
axis_min: Some(0.0),
|
||||
axis_max: Some(50.0),
|
||||
series_columns: vec![Some(options)],
|
||||
series_paints: paints,
|
||||
..GraphSpec::default()
|
||||
};
|
||||
let out = super::generate(&mut d, &g);
|
||||
let group = out.iter().find(|n| n.extras().series_index == Some(0)).unwrap();
|
||||
let mut fills = vec![];
|
||||
group.walk(&mut |n| {
|
||||
if matches!(n.kind, NodeKind::Path { .. }) {
|
||||
fills.push(n.appearance.fill().unwrap().opacity);
|
||||
}
|
||||
});
|
||||
assert!(!fills.is_empty() && fills.iter().all(|o| *o == 0.5), "{fills:?}");
|
||||
}
|
||||
|
||||
/// An opacity set on an item that the graph does not draw again (a second fill added to a mark) is not kept.
|
||||
#[test]
|
||||
fn an_opacity_on_an_added_item_of_a_series_mark_is_not_kept() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.execute("appearance.addFill", &json!({"ids": [bar.0]})).unwrap();
|
||||
let items = s.doc().unwrap().doc.node(bar).unwrap().appearance.items.clone();
|
||||
let lower = items.iter().position(vectorcraft_doc::AppearanceItem::is_fill).unwrap();
|
||||
assert!(items.iter().rposition(vectorcraft_doc::AppearanceItem::is_fill).unwrap() != lower);
|
||||
s.execute("transparency.set", &json!({"ids": [bar.0], "item": lower, "opacity": 40})).unwrap();
|
||||
assert!(spec(&s, id).series_paints.first().is_none_or(|p| p.fill_opacity.is_none()));
|
||||
}
|
||||
|
||||
/// The fill positions (lowest, topmost) in a mark's appearance stack.
|
||||
fn fill_rows(s: &Session, mark: NodeId) -> (usize, usize) {
|
||||
let items = s.doc().unwrap().doc.node(mark).unwrap().appearance.items.clone();
|
||||
let lower = items.iter().position(vectorcraft_doc::AppearanceItem::is_fill).unwrap();
|
||||
let upper = items.iter().rposition(vectorcraft_doc::AppearanceItem::is_fill).unwrap();
|
||||
assert!(lower < upper);
|
||||
(lower, upper)
|
||||
}
|
||||
|
||||
/// Moving a translucent fill to the top of a series mark's stack, or placing a copy of it there, makes the graph keep
|
||||
/// its opacity.
|
||||
#[test]
|
||||
fn moving_or_duplicating_a_series_marks_fill_to_the_top_keeps_its_opacity() {
|
||||
for cmd in ["appearance.moveItem", "appearance.duplicateItem"] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.execute("appearance.addFill", &json!({"ids": [bar.0]})).unwrap();
|
||||
let (lower, upper) = fill_rows(&s, bar);
|
||||
s.execute("transparency.set", &json!({"ids": [bar.0], "item": lower, "opacity": 40})).unwrap();
|
||||
assert!(spec(&s, id).series_paints.first().is_none_or(|p| p.fill_opacity.is_none()), "{cmd}");
|
||||
let p = if cmd == "appearance.moveItem" {
|
||||
json!({"ids": [bar.0], "from": lower, "to": upper})
|
||||
} else {
|
||||
json!({"ids": [bar.0], "index": lower, "to": upper + 1})
|
||||
};
|
||||
s.execute(cmd, &p).unwrap();
|
||||
let top = fill_rows(&s, bar).1;
|
||||
assert_eq!(s.doc().unwrap().doc.node(bar).unwrap().appearance.items[top].opacity(), 0.4, "{cmd}");
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, Some(0.4), "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Moving or copying a translucent mark's appearance onto a mark of another series (the Layers panel's target
|
||||
/// circle, or the Eyedropper) makes the graph keep the opacity for that series; a move leaves the source series with
|
||||
/// none.
|
||||
#[test]
|
||||
fn moving_or_copying_an_appearance_onto_a_series_mark_keeps_its_opacity() {
|
||||
for (cmd, source_keeps) in [("move", None), ("copy", Some(0.4)), ("eyedropper", Some(0.4))] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let (from, to) = (series(&n, 0).children().unwrap()[0].id, series(&n, 1).children().unwrap()[0].id);
|
||||
s.execute("transparency.set", &json!({"ids": [from.0], "item": 0, "opacity": 40})).unwrap();
|
||||
match cmd {
|
||||
"eyedropper" => s.execute("appearance.copyFrom", &json!({"source": from.0, "ids": [to.0]})).unwrap(),
|
||||
_ => s.execute("appearance.transfer", &json!({"source": from.0, "target": to.0, "copy": cmd == "copy"})).unwrap(),
|
||||
};
|
||||
let paints = spec(&s, id).series_paints;
|
||||
assert_eq!(paints.get(1).and_then(|p| p.fill_opacity), Some(0.4), "{cmd}");
|
||||
assert_eq!(paints[0].fill_opacity, source_keeps, "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A line graph keeps a stroke opacity set on a series' line, and puts it on the line drawn again.
|
||||
#[test]
|
||||
fn a_stroke_opacity_on_a_series_line_survives_regeneration() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = graph(&mut s, "line");
|
||||
let lines = |s: &Session| -> Vec<vectorcraft_doc::Node> {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let marks = series(&n, 0).children().unwrap().to_vec();
|
||||
marks.iter().filter(|m| m.appearance.stroke().is_some_and(|st| st.width > 0.0)).map(|m| (**m).clone()).collect()
|
||||
};
|
||||
let line = lines(&s).first().unwrap().clone();
|
||||
let row = line.appearance.items.iter().rposition(|it| !it.is_fill()).unwrap();
|
||||
s.execute("transparency.set", &json!({"ids": [line.id.0], "item": row, "opacity": 60})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints[0].stroke_opacity, Some(0.6));
|
||||
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4], [2, 5]]})).unwrap();
|
||||
let after = lines(&s);
|
||||
assert!(!after.is_empty() && after.iter().all(|m| m.appearance.stroke().unwrap().opacity == 0.6));
|
||||
}
|
||||
|
||||
/// A kept opacity read from a file outside 0..1 is held to that range, and one that is not a number is left out.
|
||||
#[test]
|
||||
fn a_kept_series_opacity_from_a_file_is_held_to_its_range() {
|
||||
let mut d = vectorcraft_doc::Document::new(800.0, 800.0);
|
||||
let paints = vec![vectorcraft_doc::SeriesPaint { fill_opacity: Some(-1.0), stroke_opacity: Some(f32::NAN), ..Default::default() }];
|
||||
let paints = [paints, vec![vectorcraft_doc::SeriesPaint { fill_opacity: Some(40.0), ..Default::default() }]].concat();
|
||||
let g = GraphSpec { rows: vec![vec![35.0, 20.0]], axis_min: Some(0.0), axis_max: Some(50.0), series_paints: paints, ..GraphSpec::default() };
|
||||
let out = super::generate(&mut d, &g);
|
||||
for (index, want) in [(0, 0.0), (1, 1.0)] {
|
||||
let group = out.iter().find(|n| n.extras().series_index == Some(index)).unwrap();
|
||||
let marks: Vec<_> = group.children().unwrap().iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).collect();
|
||||
assert!(!marks.is_empty());
|
||||
for m in marks {
|
||||
assert_eq!(m.appearance.fill().unwrap().opacity, want);
|
||||
assert!(m.appearance.stroke().is_none_or(|st| st.opacity == 1.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A series index read from a file past the graph's series is not a series: painting its art
|
||||
/// paints the art alone and stores nothing (no allocation sized by the file).
|
||||
#[test]
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Vector Halftone…",
|
||||
["Object"],
|
||||
None,
|
||||
"{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
"{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
has_selection,
|
||||
halftone
|
||||
)]
|
||||
|
||||
@@ -83,7 +83,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Layer Options…",
|
||||
["Window", "Layers"],
|
||||
None,
|
||||
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name} Layer Options; rows that are not layers take name, visible and locked. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step",
|
||||
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step",
|
||||
has_doc,
|
||||
set_props
|
||||
),
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Artboard",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1)} (default place: right of the last)",
|
||||
"{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it, #rrggbbaa and #rgba refused; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1)} (default place: right of the last)",
|
||||
has_doc,
|
||||
artboard_new
|
||||
),
|
||||
@@ -155,7 +155,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Artboard Options…",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{index | artboards: [{index, name?, color?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}",
|
||||
"{index | artboards: [{index, name?, color?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}",
|
||||
has_doc,
|
||||
artboard_set
|
||||
),
|
||||
@@ -297,7 +297,8 @@ pub(crate) fn make_layer(d: &mut Document, name: Option<&str>) -> Node {
|
||||
NewLayers::of(d).make(d, name)
|
||||
}
|
||||
|
||||
/// A layer colour: a preset index (0–26), `#rrggbb` or a preset's name (any case).
|
||||
/// A layer colour: a preset index (0–26), `#rrggbb` or a preset's name (any case). A hex color
|
||||
/// with an alpha part (`#rrggbbaa` or `#rgba`) is an error.
|
||||
pub(super) fn layer_color_param(v: &Value) -> std::result::Result<LayerColor, String> {
|
||||
match v {
|
||||
Value::Number(n) => match n.as_u64() {
|
||||
@@ -308,7 +309,13 @@ pub(super) fn layer_color_param(v: &Value) -> std::result::Result<LayerColor, St
|
||||
if let Some(i) = LAYER_COLORS.iter().position(|(name, _)| name.eq_ignore_ascii_case(s.trim())) {
|
||||
return Ok(LayerColor::Preset(i as u8));
|
||||
}
|
||||
let c = vectorcraft_color::Color::from_hex(s).ok_or_else(|| format!("`{s}` is not a colour (#rrggbb or a preset name)"))?;
|
||||
let refused = || format!("`{s}` is not a colour (#rrggbb or a preset name)");
|
||||
// `Color::from_hex` reads `#rrggbbaa` as `#rrggbb`, dropping the alpha.
|
||||
let digits = s.trim();
|
||||
if digits.strip_prefix('#').unwrap_or(digits).len() == 8 {
|
||||
return Err(refused());
|
||||
}
|
||||
let c = vectorcraft_color::Color::from_hex(s).ok_or_else(refused)?;
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
Ok(LayerColor::Custom([r, g, b]))
|
||||
}
|
||||
|
||||
@@ -643,7 +643,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add to Library",
|
||||
[],
|
||||
None,
|
||||
"{library?: id or name (default: the current library, made when there is none), kind: graphic|fillColor|strokeColor|fillGradient|strokeGradient|fillPattern|strokePattern|charStyle|paraStyle, ids?: objects (default: the selection), name?, color?: colour (a colour to add, instead of the selection's), swatch?: a gradient or pattern swatch of the document (fillGradient…strokePattern: added instead of the selection's paint), group?: name, before?: item | after?: item (an item of the same kind)} add an item from the selection: graphic: a copy of the objects with every resource they use; fillColor/strokeColor: the first selected object's solid fill/stroke colour (else the default fill/stroke); fillGradient/strokeGradient: the first selected object's fill/stroke gradient (else the default's), without its placement or swatch links, named after its swatch, else \"Gradient\"; fillPattern/strokePattern: the first selected object's fill/stroke pattern (else the default's) with the resources its art uses, named after it; charStyle/paraStyle: the selected text's character/paragraph attributes (the Type tool's range, else the first selected text object). A new item goes into `group` (default: none) and, with `before` or `after`, just before or after that item in the order its kind is shown in, as dropping it among the Libraries panel's items does; an item the library already has (same kind and contents) isn't added again, nor moved → {library, kind, name, id?: graphic id, existing: bool, group?: name or null (a new item's)}",
|
||||
"{library?: id or name (default: the current library, made when there is none), kind: graphic|fillColor|strokeColor|fillGradient|strokeGradient|fillPattern|strokePattern|charStyle|paraStyle, ids?: objects (default: the selection), name?, color?: colour (a colour to add, instead of the selection's; #rrggbbaa and #rgba are refused), swatch?: a gradient or pattern swatch of the document (fillGradient…strokePattern: added instead of the selection's paint), group?: name, before?: item | after?: item (an item of the same kind)} add an item from the selection: graphic: a copy of the objects with every resource they use; fillColor/strokeColor: the first selected object's solid fill/stroke colour (else the default fill/stroke); fillGradient/strokeGradient: the first selected object's fill/stroke gradient (else the default's), without its placement or swatch links, named after its swatch, else \"Gradient\"; fillPattern/strokePattern: the first selected object's fill/stroke pattern (else the default's) with the resources its art uses, named after it; charStyle/paraStyle: the selected text's character/paragraph attributes (the Type tool's range, else the first selected text object). A new item goes into `group` (default: none) and, with `before` or `after`, just before or after that item in the order its kind is shown in, as dropping it among the Libraries panel's items does; an item the library already has (same kind and contents) isn't added again, nor moved → {library, kind, name, id?: graphic id, existing: bool, group?: name or null (a new item's)}",
|
||||
has_doc,
|
||||
add
|
||||
),
|
||||
|
||||
@@ -20,7 +20,7 @@ use super::edit::selected_roots;
|
||||
use super::expand::gradient_sampler;
|
||||
use super::pathops::Beside;
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, check_switches, cmd, color_value, f64_or, f64_req, finite_numbers,
|
||||
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, check_switches, cmd, color_param, f64_or, f64_req, finite_numbers,
|
||||
has_doc, has_multi, has_selection, id_param, named_ids, number_or, ok, str_param, switch_or,
|
||||
};
|
||||
|
||||
|
||||
@@ -245,7 +245,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Mesh Point Color",
|
||||
[],
|
||||
None,
|
||||
"{id, index | points: [index…] | items: [{id, index | points}…], color?, keepModel?: bool (as paint.setFill), opacity?: 0..1} colour and/or opacity of gradient mesh points (one undo step; an index out of range changes nothing)",
|
||||
"{id, index | points: [index…] | items: [{id, index | points}…], color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1} colour and/or opacity of gradient mesh points (one undo step; an index out of range changes nothing)",
|
||||
has_doc,
|
||||
mesh_set_color
|
||||
),
|
||||
@@ -272,7 +272,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Mesh Line",
|
||||
[],
|
||||
None,
|
||||
"{id, x, y, color?, keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge → {index}",
|
||||
"{id, x, y, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge → {index}",
|
||||
has_doc,
|
||||
mesh_add_line
|
||||
),
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::common::{fix_ids, ids_json, is_mesh, replace_with, roots_param, selec
|
||||
use super::envelope::{outline_of, rows_cols};
|
||||
use super::{
|
||||
Color, Document, EngineError, EnvelopeKind, GradientMesh, MeshAppearance, Node, NodeId, NodeKind, Paint, Point, Result, Session, Value, bad,
|
||||
check_numbers, color_value, f64_or, f64_req, finite_numbers, gradient_sampler, id_param, json, live, ok, str_param,
|
||||
check_numbers, color_param, f64_or, f64_req, finite_numbers, gradient_sampler, id_param, json, live, ok, str_param,
|
||||
};
|
||||
|
||||
// ---------- Gradient mesh ----------
|
||||
@@ -232,7 +232,7 @@ pub(super) fn mesh_set_color(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["opacity"], C)?;
|
||||
crate::cmd::paint::check_keep_model(p, C)?;
|
||||
let items = point_items(p, C)?;
|
||||
let color = p.get("color").and_then(color_value).map(|c| crate::cmd::paint::new_color(s, p, c));
|
||||
let color = color_param(p, "color", C)?.map(|c| crate::cmd::paint::new_color(s, p, c));
|
||||
let opacity = p.get("opacity").and_then(Value::as_f64);
|
||||
if color.is_none() && opacity.is_none() {
|
||||
return Err(bad(C, "missing `color` or `opacity`"));
|
||||
@@ -283,7 +283,7 @@ pub(super) fn mesh_add_line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
crate::cmd::paint::check_keep_model(p, C)?;
|
||||
check_numbers(p, &["tolerance"], C)?;
|
||||
let tol = f64_or(p, "tolerance", 0.0).max(0.0);
|
||||
let color = p.get("color").and_then(color_value).map(|c| crate::cmd::paint::new_color(s, p, c));
|
||||
let color = color_param(p, "color", C)?.map(|c| crate::cmd::paint::new_color(s, p, c));
|
||||
let index = with_mesh(s, p, C, "Add Mesh Line", true, |m| {
|
||||
let i = m.add_lines_at(q, tol).ok_or_else(|| bad(C, "point is outside the mesh"))?;
|
||||
if let Some(c) = color {
|
||||
|
||||
Loaded 100 of 428 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user