mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Merge origin/main into feat/windows-direct-pdf
This commit is contained in:
commit
35e409ae4d
178 files changed
+10400
-857
No files matched your search
@@ -358,20 +358,20 @@ The shared PDF backend keeps the existing standard-font and CMap features. These
|
||||
|
||||
| Crate / file | Author | Source | Licence | SHA-256 | Use |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitDingbats.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitDingbats.pfb | BSD-3-Clause | `845c752392b6c914fb989c75a08b7792b88f542d2499042ef2889f8c814a16ed` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixed.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixed.pfb | BSD-3-Clause | `b6c8fe53f134b8b6d4578cd2d544df4cee9624c4efa8d51a560fb40ea296101b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixedBold.pfb | BSD-3-Clause | `f1b7159702973f54fc86254ea38bcf3712b2a736eb3a0995751e9f4bb45ad603` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfb | BSD-3-Clause | `8a000945843bd31add06aee63bf9fd41b7578b4f3242a4b7cd46349ad9d24d4d` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixedItalic.pfb | BSD-3-Clause | `5007faf8320fa1fcc08b8894b356ad976f60b992ba29ee5272578bbdebaf3876` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSans.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSans.pfb | BSD-3-Clause | `a02339e95d20db14cbdfc1c6baf359cd36a091d5434925c3a4040f60e1a1af9e` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSansBold.pfb | BSD-3-Clause | `7bdfa36de1d5757dcfaf8b8a4be95c6e41c40fa70dbed9d78bf979a7b9959054` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfb | BSD-3-Clause | `555ce45924338e2e4b32821910221ce85da691fd59a9723c4c971a7c5627fc8b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSansItalic.pfb | BSD-3-Clause | `7751cbefeda351708dae8c4a88db043411bc39ab2ae2097685da845d4d16f307` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerif.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerif.pfb | BSD-3-Clause | `4f57d2b9d884af8f907bf22df6019b52d86cbf6214fdbd02b1ae05472a543f35` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerifBold.pfb | BSD-3-Clause | `0bdf4b04e964139818d51eda03d566ba999fc3ba2421b1c6c51f9dc969022e80` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfb | BSD-3-Clause | `a406cac82583bf98175cb62c87ed5e95c45fbb34eece63a10b0a13e793cb2e10` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb | BSD-3-Clause | `610ae0687198045c4db5d1a6650fd5e92536631706382eb8b72e38df578d0ae9` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSymbol.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSymbol.pfb | BSD-3-Clause | `47967d055530e7357088a08403115425643ec2cdfd6201ba8af0fbd7116c1539` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc | CC0-1.0 | `73e1ba37d2bad5bab2a964f40a9eed96209666efc067c3322626214bbef234a0` | Default CMYK colour conversion (pinned hayro-interpret) |
|
||||
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-cmap/assets/cmaps.brotli | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged |
|
||||
| `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitDingbats.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitDingbats.pfb | BSD-3-Clause | `845c752392b6c914fb989c75a08b7792b88f542d2499042ef2889f8c814a16ed` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixed.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitFixed.pfb | BSD-3-Clause | `b6c8fe53f134b8b6d4578cd2d544df4cee9624c4efa8d51a560fb40ea296101b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitFixedBold.pfb | BSD-3-Clause | `f1b7159702973f54fc86254ea38bcf3712b2a736eb3a0995751e9f4bb45ad603` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfb | BSD-3-Clause | `8a000945843bd31add06aee63bf9fd41b7578b4f3242a4b7cd46349ad9d24d4d` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitFixedItalic.pfb | BSD-3-Clause | `5007faf8320fa1fcc08b8894b356ad976f60b992ba29ee5272578bbdebaf3876` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSans.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSans.pfb | BSD-3-Clause | `a02339e95d20db14cbdfc1c6baf359cd36a091d5434925c3a4040f60e1a1af9e` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSansBold.pfb | BSD-3-Clause | `7bdfa36de1d5757dcfaf8b8a4be95c6e41c40fa70dbed9d78bf979a7b9959054` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfb | BSD-3-Clause | `555ce45924338e2e4b32821910221ce85da691fd59a9723c4c971a7c5627fc8b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSansItalic.pfb | BSD-3-Clause | `7751cbefeda351708dae8c4a88db043411bc39ab2ae2097685da845d4d16f307` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerif.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSerif.pfb | BSD-3-Clause | `4f57d2b9d884af8f907bf22df6019b52d86cbf6214fdbd02b1ae05472a543f35` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSerifBold.pfb | BSD-3-Clause | `0bdf4b04e964139818d51eda03d566ba999fc3ba2421b1c6c51f9dc969022e80` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfb | BSD-3-Clause | `a406cac82583bf98175cb62c87ed5e95c45fbb34eece63a10b0a13e793cb2e10` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb | BSD-3-Clause | `610ae0687198045c4db5d1a6650fd5e92536631706382eb8b72e38df578d0ae9` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSymbol.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSymbol.pfb | BSD-3-Clause | `47967d055530e7357088a08403115425643ec2cdfd6201ba8af0fbd7116c1539` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc | CC0-1.0 | `73e1ba37d2bad5bab2a964f40a9eed96209666efc067c3322626214bbef234a0` | Default CMYK colour conversion (pinned hayro-interpret) |
|
||||
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-cmap/assets/cmaps.brotli | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged |
|
||||
| `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged |
|
||||
Generated
+15
-14
@@ -970,17 +970,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
dependencies = [
|
||||
"fixed_decimal",
|
||||
"icu_decimal",
|
||||
@@ -1003,7 +1003,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"serde",
|
||||
@@ -1013,7 +1013,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
dependencies = [
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
@@ -1024,9 +1024,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
dependencies = [
|
||||
"craft-winprint-gdi",
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
"roxmltree 0.21.2",
|
||||
"tempfile",
|
||||
@@ -1037,7 +1038,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
dependencies = [
|
||||
"craft-fonts-build",
|
||||
"craft-i18n",
|
||||
@@ -1095,7 +1096,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"objc2 0.6.5",
|
||||
@@ -2205,7 +2206,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"hayro-postscript",
|
||||
@@ -2214,7 +2215,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -2232,7 +2233,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -2250,12 +2251,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -2863,7 +2864,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=fb08be5fa19eee8d37e624397fcdc96df6035e92#fb08be5fa19eee8d37e624397fcdc96df6035e92"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
|
||||
+12
-14
@@ -11,14 +11,14 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/vectorcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", default-features = false, features = ["interpret", "write"] }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", default-features = false, features = ["interpret", "write"] }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["serde"] }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
|
||||
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
|
||||
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] }
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["egui"] }
|
||||
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "14d5dbb50c317b8747a9cf9eb35ab8a22515f137" }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
@@ -147,14 +147,12 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
# The PDF writer takes craft-libs#417 (CMYK, gray and spot colors keep their exact inks); the other
|
||||
# craft-libs crates stay at 92d392cf. craft-pdf's sources are the same at both revisions.
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "fb08be5fa19eee8d37e624397fcdc96df6035e92" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
|
||||
@@ -72,10 +72,10 @@ Shared PDF backend
|
||||
|
||||
The patched hayro-interpret 0.7.0, hayro-syntax 0.7.2, hayro-jbig2 0.3.0, hayro-cmap 0.1.0
|
||||
and hayro-postscript 0.1.0 are fetched from https://github.com/storytold/craft-libs at revision
|
||||
92d392cff132eaf53e13afff77f38b5c11b73aa0. Their upstream project is
|
||||
f8f8829cc7be65d466d687dae381d1ca60e31242. Their upstream project is
|
||||
https://github.com/LaurenzV/hayro, licensed MIT OR Apache-2.0. The snapshot retains each
|
||||
crate's upstream licence files. The patch ledger is at
|
||||
https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/README.craft-reader.md.
|
||||
https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/README.craft-reader.md.
|
||||
|
||||
Assets already bundled through Hayro's default features retain their licences:
|
||||
- Foxit standard-14 substitutes: Copyright 2014 PDFium Authors. All rights reserved.
|
||||
|
||||
+3
-1
@@ -9,7 +9,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Color Effects add-on's Find Nearest Swatch; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
|
||||
VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs
|
||||
on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON
|
||||
@@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
- 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923).
|
||||
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
|
||||
@@ -214,6 +215,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-02 | minor | Closed font-family fields accept wheel input for selected text in Character, Properties and Control (#5253); scores and estimates unchanged. |
|
||||
| 2026-11-01 | minor | Progress log row for the Color Effects add-on's Find Nearest Swatch (#4923); headline numbers unchanged. |
|
||||
| 2026-11-01 | minor | Progress log row for the Path Precision Tools add-on's Expand Dashes into Paths (#4922); headline numbers unchanged. |
|
||||
| 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Randomize Opacity (#4925); headline numbers unchanged. |
|
||||
|
||||
+10
-1
@@ -884,7 +884,16 @@ fn leave_out_brushed(doc: &Document, nodes: &mut Vec<Node>, known: &mut Known) {
|
||||
walk(doc, Arc::make_mut(c), known);
|
||||
}
|
||||
}
|
||||
if n.extras().mask.is_some()
|
||||
// A mask's art is drawn too. Its root is filtered like any other node: a symbol instance
|
||||
// there that draws a brushed stroke would run the brush again from inside the mask, so the
|
||||
// mask goes, as such an instance goes from the pieces and their children.
|
||||
let rejected_root = matches!(
|
||||
n.extras().mask.as_ref().map(|m| &m.art.kind),
|
||||
Some(NodeKind::SymbolInstance { symbol, .. }) if draws_brushed(doc, (false, symbol.as_str()), known)
|
||||
);
|
||||
if rejected_root {
|
||||
n.extras_mut().mask = None;
|
||||
} else if n.extras().mask.is_some()
|
||||
&& let Some(mask) = n.extras_mut().mask.as_mut()
|
||||
{
|
||||
walk(doc, Arc::make_mut(&mut mask.art), known);
|
||||
|
||||
@@ -1316,6 +1316,42 @@ fn pieces_leave_out_what_draws_a_brushed_stroke_by_name() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A symbol instance at the root of an opacity mask is filtered like one among the children: when
|
||||
/// its symbol draws a brushed stroke the mask goes (it would run the brush again from inside the
|
||||
/// mask, without end), and a mask whose root symbol is plain stays.
|
||||
#[test]
|
||||
fn pieces_leave_out_a_mask_whose_root_draws_a_brushed_stroke() {
|
||||
use vectorcraft_doc::{OpacityMask, Symbol};
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
let mut brushed = rect_art(10.0, 4.0);
|
||||
brushed.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(StrokeLayer { brush: Some("s".into()), ..stroke(1.0) }));
|
||||
for (name, art) in [("plain", rect_art(10.0, 4.0)), ("brushed", brushed)] {
|
||||
doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: std::sync::Arc::new(art) });
|
||||
}
|
||||
let instance = |symbol: &str| Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
let masked = |symbol: &str| {
|
||||
let mut n = rect_art(10.0, 4.0);
|
||||
n.extras_mut().mask = Some(Box::new(OpacityMask::new(instance(symbol), true)));
|
||||
n
|
||||
};
|
||||
let art = Node::group(NodeId(0), [masked("plain"), masked("brushed")].map(std::sync::Arc::new).into());
|
||||
let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) };
|
||||
let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 100.0, 0.0), &stroke(1.0));
|
||||
assert!(!out.is_empty());
|
||||
for piece in &out {
|
||||
let roots: Vec<Option<&str>> = piece
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|c| match c.extras().mask.as_ref().map(|m| &m.art.kind) {
|
||||
Some(NodeKind::SymbolInstance { symbol, .. }) => Some(symbol.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(roots, [Some("plain"), None], "the plain mask stays and the brushed one goes");
|
||||
}
|
||||
}
|
||||
|
||||
/// Anchors a brushed stroke emitted, which is what the output budget counts.
|
||||
fn anchors(nodes: &[Node]) -> usize {
|
||||
nodes
|
||||
|
||||
@@ -23,10 +23,19 @@ const PT_PER_MM: f64 = 72.0 / 25.4;
|
||||
const THINNEST: f64 = 0.25;
|
||||
/// The most objects an import makes.
|
||||
const MAX_NODES: usize = 2_000_000;
|
||||
/// The most block visits (one per insert copy) an import makes, whatever they produce.
|
||||
const MAX_VISITS: usize = 10_000_000;
|
||||
/// The most block work an import does, whatever it produces: one per insert copy drawn, and one
|
||||
/// per item of the block looked at for it (art on hidden layers too).
|
||||
const MAX_VISITS: usize = if cfg!(test) { 1_000_000 } else { 20_000_000 };
|
||||
/// The most path elements an import makes (blocks drawn as art are copied for every placement).
|
||||
const MAX_ELEMENTS: usize = if cfg!(test) { 1_000_000 } else { 4_000_000 };
|
||||
/// The most dash lengths an import keeps (every dashed path holds its own copy of its pattern).
|
||||
const MAX_DASH_VALUES: usize = if cfg!(test) { 1_000 } else { 4_000_000 };
|
||||
/// The most bytes of text, font names and symbol names an import copies into objects (a block's
|
||||
/// text and name are copied for every placement).
|
||||
const MAX_TEXT_BYTES: usize = if cfg!(test) { 64 << 10 } else { 64 << 20 };
|
||||
/// The longest font family a text style may name; a longer one is not a font, and is set in the
|
||||
/// default.
|
||||
const MAX_FAMILY_BYTES: usize = 256;
|
||||
/// How far from the origin art may lie (points): the canvas.
|
||||
pub(crate) const MAX_EXTENT: f64 = 4.0e6;
|
||||
|
||||
@@ -34,6 +43,8 @@ const NESTED: &str = "blocks nested more than 8 deep, or inside themselves, are
|
||||
const XREFS: &str = "blocks referencing other drawings (external references) are left out";
|
||||
const TOO_MANY: &str = "the drawing has more than 2,000,000 objects: the rest are left out";
|
||||
const TOO_MANY_POINTS: &str = "the drawing has more than 4,000,000 path points: the rest are left out";
|
||||
const TOO_MANY_DASHES: &str = "the drawing has more dashed lines than can be kept: the rest are drawn solid";
|
||||
const TOO_MUCH_TEXT: &str = "the drawing has more than 64 MB of text and block names: the rest are left out";
|
||||
|
||||
/// What a block's art takes from the insert that places it: its colour, lineweight, linetype
|
||||
/// and opacity where the art says "by block", and its layer for art on layer 0.
|
||||
@@ -71,6 +82,9 @@ pub(crate) struct Build<'d, 'a> {
|
||||
visits: usize,
|
||||
/// Path elements made so far.
|
||||
elements: usize,
|
||||
/// Dash lengths and text bytes kept so far.
|
||||
dash_values: usize,
|
||||
text_bytes: usize,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
@@ -128,6 +142,8 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
nodes: 0,
|
||||
visits: 0,
|
||||
elements: 0,
|
||||
dash_values: 0,
|
||||
text_bytes: 0,
|
||||
warnings: vec![],
|
||||
}
|
||||
}
|
||||
@@ -138,6 +154,20 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Take `bytes` of text from [`MAX_TEXT_BYTES`]; false (with a warning) when they don't fit.
|
||||
fn charge_text(&mut self, bytes: usize) -> bool {
|
||||
match self.text_bytes.checked_add(bytes).filter(|t| *t <= MAX_TEXT_BYTES) {
|
||||
Some(t) => {
|
||||
self.text_bytes = t;
|
||||
true
|
||||
}
|
||||
None => {
|
||||
self.warn(TOO_MUCH_TEXT);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Import `layout`; `natural` and `ratio` are points per drawing unit in the drawing's own
|
||||
/// unit and at the scale asked for (fitting computes its own).
|
||||
pub fn run(mut self, layout: &LayoutDef, natural: f64, ratio: f64) -> Result<(Document, Vec<String>), String> {
|
||||
@@ -484,9 +514,15 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut()
|
||||
&& let Some((dash, dots)) = self.dash(&self.linetype(p, inh), p, scale)
|
||||
{
|
||||
s.dash = Some(dash);
|
||||
if dots {
|
||||
s.cap = LineCap::Round;
|
||||
match self.dash_values.checked_add(dash.pattern.len()).filter(|n| *n <= MAX_DASH_VALUES) {
|
||||
Some(n) => {
|
||||
self.dash_values = n;
|
||||
s.dash = Some(dash);
|
||||
if dots {
|
||||
s.cap = LineCap::Round;
|
||||
}
|
||||
}
|
||||
None => self.warn(TOO_MANY_DASHES),
|
||||
}
|
||||
}
|
||||
ap
|
||||
@@ -527,10 +563,15 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
if !(s > 1e-12 && s.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let family = t.family.clone().or_else(|| self.d.styles.get(&t.style).filter(|f| !f.is_empty()).cloned());
|
||||
let d = self.d;
|
||||
let family = t.family.as_deref().or_else(|| d.styles.get(&t.style).map(String::as_str).filter(|f| !f.is_empty()));
|
||||
let family = family.filter(|f| f.len() <= MAX_FAMILY_BYTES);
|
||||
if !self.charge_text(t.text.len().saturating_add(family.map_or(0, str::len))) {
|
||||
return None;
|
||||
}
|
||||
let default = CharStyle::default();
|
||||
let style = CharStyle {
|
||||
font_family: family.unwrap_or(default.font_family.clone()),
|
||||
font_family: family.map_or_else(|| default.font_family.clone(), str::to_string),
|
||||
size: t.height / CAP_HEIGHT * s,
|
||||
h_scale: t.width * 100.0,
|
||||
leading: t.leading.map(|l| l * s),
|
||||
@@ -558,6 +599,13 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
for cell in &ins.cells {
|
||||
let node = match &symbol {
|
||||
Some(name) => {
|
||||
if self.nodes >= MAX_NODES {
|
||||
self.warn(TOO_MANY);
|
||||
break;
|
||||
}
|
||||
if !self.charge_text(name.len()) {
|
||||
break;
|
||||
}
|
||||
let xf = map * *cell * self.symbol_map.inverse();
|
||||
self.nodes += 1;
|
||||
Some(Node::new(self.doc.alloc_id(), NodeKind::SymbolInstance { symbol: name.clone(), xf }))
|
||||
@@ -581,14 +629,19 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
|
||||
/// The art of block `name` drawn by `map`, as one object.
|
||||
fn art(&mut self, name: &str, map: Affine, inh: &Inherit, depth: u32) -> Option<Node> {
|
||||
self.visits += 1;
|
||||
if self.visits > MAX_VISITS {
|
||||
if self.visits == MAX_VISITS + 1 {
|
||||
self.warn(TOO_MANY);
|
||||
}
|
||||
if self.visits >= MAX_VISITS {
|
||||
self.warn(TOO_MANY);
|
||||
return None;
|
||||
}
|
||||
let items = self.block(name)?;
|
||||
let items = self.block(name);
|
||||
// Each placement looks at every item of the block, drawn or not (art on a hidden layer
|
||||
// makes nothing, so the node budget doesn't bound it).
|
||||
self.visits = self.visits.saturating_add(1 + items.as_ref().map_or(0, |i| i.len()));
|
||||
if self.visits > MAX_VISITS {
|
||||
self.warn(TOO_MANY);
|
||||
return None;
|
||||
}
|
||||
let items = items?;
|
||||
if !self.enter(name, depth) {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -1177,3 +1177,101 @@ fn many_array_inserts_of_a_missing_block_stay_bounded() {
|
||||
assert!(total <= 2_000_000 + 3000, "total cells materialised: {total}");
|
||||
assert!(conv.warnings.iter().any(|w| w.contains("array inserts")), "{:?}", conv.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dashed_lines_past_the_dash_budget_are_drawn_solid() {
|
||||
// 600 lines of a two-length linetype: 1,200 dash lengths, past the 1,000 tests import with.
|
||||
let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")];
|
||||
let line = [(0, "LINE"), (6, "DASHED"), (10, "0"), (20, "0"), (11, "100"), (21, "0")];
|
||||
let e: Vec<(i32, &str)> = (0..600).flat_map(|_| line).collect();
|
||||
let r = open(&drawing(&[], &tables, &[], &e), &points());
|
||||
let (mut dashed, mut solid, mut kept) = (0, 0, 0);
|
||||
r.document.walk(|n| {
|
||||
if let NodeKind::Path { .. } = n.kind {
|
||||
match n.appearance.stroke().and_then(|s| s.dash.as_ref()) {
|
||||
Some(d) => {
|
||||
dashed += 1;
|
||||
kept += d.pattern.len();
|
||||
}
|
||||
None => solid += 1,
|
||||
}
|
||||
}
|
||||
});
|
||||
assert_eq!(dashed + solid, 600);
|
||||
assert!(dashed > 0 && solid > 0, "{dashed} dashed, {solid} solid");
|
||||
assert!(kept <= 1_000, "{kept} dash lengths kept");
|
||||
assert!(r.warnings.iter().any(|w| w.contains("drawn solid")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// The bytes of text in the document's text objects.
|
||||
fn text_bytes(doc: &Document) -> usize {
|
||||
let mut bytes = 0;
|
||||
doc.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
bytes += t.runs.iter().map(|r| r.text.len()).sum::<usize>();
|
||||
}
|
||||
});
|
||||
bytes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_copied_into_array_cells_stops_at_the_text_budget() {
|
||||
// 1,000 characters of text in an anonymous block placed 10 × 10: 100 KB of copies, past the
|
||||
// 64 KB tests import with.
|
||||
let long = "x".repeat(1000);
|
||||
let blocks =
|
||||
[(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0"), (0, "TEXT"), (10, "0"), (20, "0"), (40, "1"), (1, long.as_str()), (0, "ENDBLK")];
|
||||
let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "10"), (71, "10"), (44, "1"), (45, "1")];
|
||||
let r = open(&drawing(&[], &[], &blocks, &insert), &points());
|
||||
let bytes = text_bytes(&r.document);
|
||||
assert!(bytes > 0, "some copies are kept");
|
||||
assert!(bytes <= 64 << 10, "{bytes} bytes of text");
|
||||
assert!(r.warnings.iter().any(|w| w.contains("64 MB of text")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_style_naming_an_overlong_font_family_takes_the_default() {
|
||||
let family = "F".repeat(10_000);
|
||||
let tables = [(0, "TABLE"), (2, "STYLE"), (0, "STYLE"), (2, "Big"), (3, "x.ttf"), (1001, "ACAD"), (1000, family.as_str()), (0, "ENDTAB")];
|
||||
let e = [(0, "TEXT"), (10, "0"), (20, "0"), (40, "1"), (1, "Hi"), (7, "Big")];
|
||||
let doc = open(&drawing(&[], &tables, &[], &e), &points()).document;
|
||||
let mut families = vec![];
|
||||
doc.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
families.extend(t.runs.iter().map(|r| r.style.font_family.clone()));
|
||||
}
|
||||
});
|
||||
assert_eq!(families, [vectorcraft_doc::CharStyle::default().font_family]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_instances_of_a_long_block_name_stop_at_the_text_budget() {
|
||||
// A 1,000-byte block name placed 10 × 10: each instance keeps its own copy of the name.
|
||||
let name = "N".repeat(1000);
|
||||
let blocks = [(0, "BLOCK"), (2, name.as_str()), (10, "0"), (20, "0"), (0, "LINE"), (10, "0"), (20, "0"), (11, "1"), (21, "0"), (0, "ENDBLK")];
|
||||
let insert = [(0, "INSERT"), (2, name.as_str()), (10, "0"), (20, "0"), (70, "10"), (71, "10"), (44, "2"), (45, "2")];
|
||||
let r = open(&drawing(&[], &[], &blocks, &insert), &points());
|
||||
let mut instances = 0;
|
||||
r.document.walk(|n| {
|
||||
if let NodeKind::SymbolInstance { .. } = n.kind {
|
||||
instances += 1;
|
||||
}
|
||||
});
|
||||
assert!(instances > 0 && instances < 100, "{instances} instances");
|
||||
assert!(r.warnings.iter().any(|w| w.contains("64 MB of text")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrays_of_blocks_of_hidden_art_stop_at_the_work_budget() {
|
||||
// 500 lines on a hidden layer in an anonymous block placed 50 × 50: they make nothing, but
|
||||
// each placement looks at all of them (1,250,000 items, past the 1,000,000 tests import with).
|
||||
let tables = [(0, "TABLE"), (2, "LAYER"), (0, "LAYER"), (2, "Off"), (70, "0"), (62, "-1"), (0, "ENDTAB")];
|
||||
let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")];
|
||||
for _ in 0..500 {
|
||||
blocks.extend([(0, "LINE"), (8, "Off"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]);
|
||||
}
|
||||
blocks.push((0, "ENDBLK"));
|
||||
let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "50"), (71, "50"), (44, "1"), (45, "1")];
|
||||
let r = open(&drawing(&[], &tables, &blocks, &insert), &points());
|
||||
assert!(r.warnings.iter().any(|w| w.contains("more than")), "{:?}", r.warnings);
|
||||
}
|
||||
@@ -106,6 +106,12 @@ impl IccProfile {
|
||||
if !localized_text_fits(bytes) {
|
||||
return Err(CmsError::BadProfile(format!("its localized names take more than {} KB", MAX_LOCALIZED_TEXT >> 10)));
|
||||
}
|
||||
if let Some(tag) = repeated_tag(bytes) {
|
||||
return Err(CmsError::BadProfile(format!(
|
||||
"its tag table lists the `{}` tag more than once",
|
||||
String::from_utf8_lossy(&tag.to_be_bytes())
|
||||
)));
|
||||
}
|
||||
let p = ColorProfile::new_from_slice(bytes).map_err(|e| CmsError::BadProfile(format!("{e:?}")))?;
|
||||
Ok(Self { source: bytes.to_vec(), ..Self::from_profile(name, p)? })
|
||||
}
|
||||
@@ -417,6 +423,23 @@ pub(super) fn gray_profile(name: &str) -> ColorProfile {
|
||||
labelled(p, name)
|
||||
}
|
||||
|
||||
/// The first tag signature the tag table of ICC `bytes` lists twice, which the ICC
|
||||
/// specification forbids. moxcms parses every entry of the table, so a profile listing one
|
||||
/// description, copyright or table tag thousands of times, each pointing at the same large data,
|
||||
/// would decode and copy that data once per entry. A table it can't read is left to moxcms.
|
||||
pub(crate) fn repeated_tag(bytes: &[u8]) -> Option<u32> {
|
||||
let be32 = |at: usize| bytes.get(at..at.checked_add(4)?).map(|v| u32::from_be_bytes([v[0], v[1], v[2], v[3]]));
|
||||
let tags = be32(128)? as usize;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for i in 0..tags {
|
||||
let sig = be32(i.checked_mul(12)?.checked_add(132)?)?;
|
||||
if !seen.insert(sig) {
|
||||
return Some(sig);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Most bytes of UTF-16 the localized names (`mluc` tags) of a profile may take together.
|
||||
const MAX_LOCALIZED_TEXT: usize = 1 << 20;
|
||||
|
||||
|
||||
@@ -181,6 +181,32 @@ fn aliased_localized_names_are_refused() {
|
||||
assert!(!super::icc::localized_text_fits(&profile(4096, 64 << 10)));
|
||||
}
|
||||
|
||||
/// A tag table that lists one tag many times, every entry pointing at the same long text, is
|
||||
/// refused before moxcms decodes the text once per entry; distinct tags pass.
|
||||
#[test]
|
||||
fn repeated_tags_are_refused() {
|
||||
let profile = |sigs: &[&[u8; 4]], text: usize| {
|
||||
let mut b = vec![0u8; 128];
|
||||
b.extend((sigs.len() as u32).to_be_bytes());
|
||||
let tag_at = 128 + 4 + 12 * sigs.len();
|
||||
let size = 8 + text;
|
||||
for sig in sigs {
|
||||
b.extend(*sig);
|
||||
b.extend((tag_at as u32).to_be_bytes());
|
||||
b.extend((size as u32).to_be_bytes());
|
||||
}
|
||||
b.extend(b"text");
|
||||
b.extend([0; 4]);
|
||||
b.extend(vec![b'a'; text]);
|
||||
b
|
||||
};
|
||||
assert_eq!(super::icc::repeated_tag(&profile(&[b"desc", b"cprt", b"dmdd"], 64)), None);
|
||||
let many: Vec<&[u8; 4]> = std::iter::repeat_n(b"desc", 4096).collect();
|
||||
let bytes = profile(&many, 256 << 10);
|
||||
assert_eq!(super::icc::repeated_tag(&bytes), Some(u32::from_be_bytes(*b"desc")));
|
||||
assert!(matches!(super::icc::IccProfile::from_bytes(None, &bytes), Err(super::CmsError::BadProfile(_))));
|
||||
}
|
||||
|
||||
/// Reloading an RGB profile under the name it had (a new file for "My RGB") changes what CMYK
|
||||
/// converts to in it: the direct CMYK → RGB transform isn't kept from the old file.
|
||||
#[test]
|
||||
|
||||
@@ -862,6 +862,52 @@ impl Spine {
|
||||
pub fn anchor_length(&self, i: usize) -> Option<f64> {
|
||||
self.anchors.get(i).copied()
|
||||
}
|
||||
/// Arc length of the point of the spine nearest `p`. An open spine's end segments run on past
|
||||
/// its ends as lines, so the result is below 0 before the start and above [`Spine::length`]
|
||||
/// beyond the end. With `from`, the arc length of an earlier point a drag followed, each point
|
||||
/// counts as farther by half its distance along the spine from there, so a pointer passing
|
||||
/// near another part of the spine stays on the part it follows. Where two points count as
|
||||
/// near as each other, the one earlier along the spine counts.
|
||||
pub fn length_near(&self, p: Point, from: Option<f64>) -> f64 {
|
||||
self.nearest(p, from).map_or(0.0, |(_, s)| s)
|
||||
}
|
||||
/// [`Spine::length_near`] with how near the point counts: its distance from `p`, plus half its
|
||||
/// distance along the spine from `from`. `None` for a point that is not finite.
|
||||
pub fn nearest(&self, p: Point, from: Option<f64>) -> Option<(f64, f64)> {
|
||||
if !p.x.is_finite() || !p.y.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let last = self.pts.len().saturating_sub(2);
|
||||
let mut best: Option<(f64, f64)> = None;
|
||||
for (i, (w, c)) in self.pts.windows(2).zip(&self.cum).enumerate() {
|
||||
let [a, b] = [w[0], w[1]];
|
||||
let d = b - a;
|
||||
let l2 = d.dot(d);
|
||||
if !l2.is_finite() || l2 <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let t = (p - a).dot(d) / l2;
|
||||
let t = match (self.closed, i == 0, i == last) {
|
||||
(false, true, true) => t,
|
||||
(false, true, false) => t.min(1.0),
|
||||
(false, false, true) => t.max(0.0),
|
||||
_ => t.clamp(0.0, 1.0),
|
||||
};
|
||||
let s = c + t * l2.sqrt();
|
||||
let dist = p.distance(a + d * t) + from.filter(|f| f.is_finite()).map_or(0.0, |f| self.apart(s, f) / 2.0);
|
||||
if dist.is_finite() && best.is_none_or(|(b, _)| dist < b) {
|
||||
best = Some((dist, s));
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
/// How far apart arc lengths `s` and `f` are along the spine: the shorter way round a closed
|
||||
/// spine, across its first anchor.
|
||||
pub fn apart(&self, s: f64, f: f64) -> f64 {
|
||||
let len = self.length();
|
||||
let d = (s - f).abs();
|
||||
if self.closed && len > 0.0 { d.rem_euclid(len).min(len - d.rem_euclid(len)) } else { d }
|
||||
}
|
||||
/// Point and tangent angle (radians) at arc-length fraction `f` (0..1).
|
||||
pub fn at(&self, f: f64) -> (Point, f64) {
|
||||
self.at_length(f.clamp(0.0, 1.0) * self.length())
|
||||
|
||||
+51
-6
@@ -577,7 +577,41 @@ fn may_hit(parent: &Node, i: usize, c: &Node, p: Point, opt: HitOptions, symbols
|
||||
// (An envelope's content sits where it was, not where the envelope draws it.)
|
||||
edits_contents(c)
|
||||
|| c.extras().shaper.is_some() && source_of(c, opt.scope)
|
||||
|| c.reach_bounds_with(symbols).is_none_or(|b| b.inflate(opt.tol, opt.tol).contains(p))
|
||||
|| cull_reach(c, symbols).is_none_or(|b| b.inflate(opt.tol, opt.tol).contains(p))
|
||||
}
|
||||
|
||||
/// A box round everything `c` can paint, for culling clicks: [`Node::reach_bounds_with`], except
|
||||
/// that paths and compound paths are measured by their control points ([`PathData::control_bounds`],
|
||||
/// which hold the curves) instead of along their curves, which a compound path of thousands of
|
||||
/// members takes milliseconds to do on every click and hover. The box only rules points out, and it
|
||||
/// is at least as large, so the same objects are hit.
|
||||
///
|
||||
/// [`PathData::control_bounds`]: vectorcraft_geom::PathData::control_bounds
|
||||
fn cull_reach(c: &Node, symbols: &SymbolBoxes) -> Option<Rect> {
|
||||
let control = match &c.kind {
|
||||
NodeKind::Path { path, .. } => path.control_bounds(),
|
||||
NodeKind::Compound { children, .. } if children.iter().all(|m| m.path_data().is_some()) => {
|
||||
children.iter().filter_map(|m| m.path_data().and_then(vectorcraft_geom::PathData::control_bounds)).reduce(|a, b| a.union(b))
|
||||
}
|
||||
_ => return c.reach_bounds_with(symbols),
|
||||
};
|
||||
let o = c.appearance.outset();
|
||||
control.map(|b| b.inflate(o, o))
|
||||
}
|
||||
|
||||
/// The members of compound path `children` that a click at `p` within `tol` can touch, as one
|
||||
/// path: those whose control points' box, grown by `tol`, holds `p` (edges included). A member
|
||||
/// outside that box is farther than `tol` from `p` and winds zero times round it, so this path's
|
||||
/// outline and fill answer a click as the whole compound path's do, without assembling it.
|
||||
fn compound_members_near(children: &[std::sync::Arc<Node>], p: Point, tol: f64) -> vectorcraft_geom::BezPath {
|
||||
let near = |b: Rect| b.x0 - tol <= p.x && p.x <= b.x1 + tol && b.y0 - tol <= p.y && p.y <= b.y1 + tol;
|
||||
let mut bp = vectorcraft_geom::BezPath::new();
|
||||
for pd in children.iter().filter_map(|m| m.path_data()) {
|
||||
if pd.control_bounds().is_some_and(near) {
|
||||
bp.extend(pd.to_bezpath());
|
||||
}
|
||||
}
|
||||
bp
|
||||
}
|
||||
|
||||
/// Is the first child of `n` the isolated container `scope`?
|
||||
@@ -710,12 +744,23 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
}
|
||||
None
|
||||
}
|
||||
NodeKind::Compound { rule, .. } => {
|
||||
let bp = n.stroke_path()?;
|
||||
if let Some(k) = hit_stroke(n, &bp, *rule, p, opt) {
|
||||
return Some(k);
|
||||
NodeKind::Compound { children, rule } => {
|
||||
// Painted strokes follow the whole compound path (alignment, dashes, width profiles):
|
||||
// they are measured along all of it, as before.
|
||||
if !opt.outline && n.appearance.painted_strokes().next().is_some() {
|
||||
let bp = n.stroke_path()?;
|
||||
if n.appearance.stroke_hit(&bp, *rule, p, opt.tol) {
|
||||
return Some(HitKind::Stroke);
|
||||
}
|
||||
}
|
||||
(!opt.outline && !opt.path_only && fill_contains(&bp, *rule, p)).then_some(HitKind::Fill)
|
||||
// The outline and the fill only need the members near `p`. (Measured without
|
||||
// `stroke_contains`'s box check: the box of the members near `p` is smaller than the
|
||||
// whole path's, and its far edges would turn away points exactly `tol` away.)
|
||||
let near = compound_members_near(children, p, opt.tol);
|
||||
if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol {
|
||||
return Some(HitKind::Outline);
|
||||
}
|
||||
(!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill)
|
||||
}
|
||||
// The type path lies within the bounds: they rule out the rest before it is measured.
|
||||
NodeKind::Text(t) if opt.type_path_only => {
|
||||
|
||||
@@ -1120,3 +1120,223 @@ fn visible_sampling_reads_locked_art_and_layers_but_excludes_hidden_art() {
|
||||
d.node_mut(l).unwrap().visible = false;
|
||||
assert!(hit_test_visible(&d, p, HitOptions::default()).is_none());
|
||||
}
|
||||
|
||||
/// Deterministic xorshift in 0..1.
|
||||
struct Rng(u64);
|
||||
impl Rng {
|
||||
fn next(&mut self) -> f64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
(self.0 % 1_000_000) as f64 / 1_000_000.0
|
||||
}
|
||||
}
|
||||
|
||||
/// A closed blob of `n` smooth anchors round `c` (radius about `r`), turning either way, with
|
||||
/// handles long enough that its control points reach past its curves.
|
||||
fn blob(rng: &mut Rng, c: Point, r: f64, n: usize, clockwise: bool) -> vectorcraft_geom::SubPath {
|
||||
use vectorcraft_geom::{Anchor, Vec2};
|
||||
let anchors = (0..n)
|
||||
.map(|i| {
|
||||
let k = if clockwise { i as f64 } else { (n - i) as f64 };
|
||||
let a = k / n as f64 * std::f64::consts::TAU;
|
||||
let rr = r * (0.6 + 0.8 * rng.next());
|
||||
let p = c + Vec2::new(a.cos(), a.sin()) * rr;
|
||||
let t = Vec2::new(-a.sin(), a.cos()) * (if clockwise { 1.0 } else { -1.0 }) * rr * (0.2 + 1.3 * rng.next());
|
||||
Anchor::smooth(p, p + t)
|
||||
})
|
||||
.collect();
|
||||
vectorcraft_geom::SubPath::new(anchors, true)
|
||||
}
|
||||
|
||||
/// A document with one compound path of `members` blobs (some of them holes), its id and the
|
||||
/// members' paths.
|
||||
fn compound_doc(members: usize, rule: vectorcraft_geom::FillRule, appearance: Appearance) -> (Document, NodeId, Vec<vectorcraft_geom::PathData>) {
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
|
||||
let mut paths = vec![];
|
||||
let mut children = vec![];
|
||||
for i in 0..members {
|
||||
let c = Point::new(20.0 + rng.next() * 600.0, 20.0 + rng.next() * 600.0);
|
||||
let r = 3.0 + rng.next() * 9.0;
|
||||
let pd = vectorcraft_geom::PathData::single(blob(&mut rng, c, r, 3 + i % 4, i % 3 != 0));
|
||||
children.push(Arc::new(Node::path(d.alloc_id(), pd.clone(), Appearance::default())));
|
||||
paths.push(pd);
|
||||
}
|
||||
let id = d.alloc_id();
|
||||
let mut compound = Node::new(id, NodeKind::Compound { children, rule });
|
||||
compound.appearance = appearance.into();
|
||||
d.insert(Some(l), 0, compound).unwrap();
|
||||
(d, id, paths)
|
||||
}
|
||||
|
||||
/// What a click on compound path `n` gave before compound paths were culled by their control
|
||||
/// points and their members near the click: the whole path assembled (`full`), culled by its
|
||||
/// reach measured along the curves.
|
||||
fn compound_hit_before(n: &Node, full: &vectorcraft_geom::BezPath, p: Point, opt: HitOptions) -> Option<HitKind> {
|
||||
let NodeKind::Compound { rule, .. } = &n.kind else { return None };
|
||||
if !n.reach_bounds().is_none_or(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
|
||||
return None;
|
||||
}
|
||||
if !opt.outline && n.appearance.stroke_hit(full, *rule, p, opt.tol) {
|
||||
return Some(HitKind::Stroke);
|
||||
}
|
||||
if stroke_contains(full, 0.0, opt.tol, p) {
|
||||
return Some(HitKind::Outline);
|
||||
}
|
||||
(!opt.outline && !opt.path_only && fill_contains(full, *rule, p)).then_some(HitKind::Fill)
|
||||
}
|
||||
|
||||
/// The points a test clicks for `paths`: random ones over them and past them, and, for some
|
||||
/// members, their anchors, points just over the tolerance from them, and the corners and edge
|
||||
/// midpoints of their control and curve boxes, on them and grown by the tolerance.
|
||||
fn probe_points(paths: &[vectorcraft_geom::PathData], tol: f64, random: usize, every: usize) -> Vec<Point> {
|
||||
let all = paths.iter().filter_map(vectorcraft_geom::PathData::control_bounds).reduce(|a, b| a.union(b)).unwrap().inflate(30.0, 30.0);
|
||||
let mut rng = Rng(7);
|
||||
let mut pts: Vec<Point> = (0..random).map(|_| Point::new(all.x0 + rng.next() * all.width(), all.y0 + rng.next() * all.height())).collect();
|
||||
for pd in paths.iter().step_by(every) {
|
||||
for a in pd.subpaths.iter().flat_map(|sp| &sp.anchors) {
|
||||
pts.extend([a.p, Point::new(a.p.x + tol, a.p.y), Point::new(a.p.x, a.p.y - tol), Point::new(a.p.x + tol * 1.0001, a.p.y)]);
|
||||
}
|
||||
for b in [pd.control_bounds().unwrap(), pd.bounds().unwrap()] {
|
||||
for b in [b, b.inflate(tol, tol)] {
|
||||
let (cx, cy) = (b.center().x, b.center().y);
|
||||
pts.extend(
|
||||
[(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1), (cx, b.y0), (cx, b.y1), (b.x0, cy), (b.x1, cy)]
|
||||
.map(|(x, y)| Point::new(x, y)),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
pts
|
||||
}
|
||||
|
||||
/// A compound path of thousands of members hits exactly as it did when it was assembled
|
||||
/// whole for every click: at random points, on and next to anchors, and on the edges of the
|
||||
/// members' boxes (control points' and curves', with and without the tolerance), for both fill
|
||||
/// rules, in outline mode and with Object Selection by Path Only.
|
||||
#[test]
|
||||
fn culled_compound_hits_as_the_whole_path() {
|
||||
use vectorcraft_geom::FillRule;
|
||||
for (rule, opt) in [
|
||||
(FillRule::NonZero, HitOptions::default()),
|
||||
(FillRule::EvenOdd, HitOptions { tol: 0.5, ..Default::default() }),
|
||||
(FillRule::NonZero, HitOptions { outline: true, tol: 1.0, ..Default::default() }),
|
||||
(FillRule::EvenOdd, HitOptions { path_only: true, ..Default::default() }),
|
||||
] {
|
||||
let (d, id, paths) = compound_doc(2000, rule, Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let n = d.node(id).unwrap();
|
||||
let full = n.stroke_path().unwrap();
|
||||
// The whole path's box grown by the tolerance. Before, a point on its far edges (right
|
||||
// and bottom: `Rect::contains` leaves them out) never hit, even exactly `tol` from the
|
||||
// outline; now it hits there as on the near edges. Those points are clicked too, and
|
||||
// checked against the distance alone.
|
||||
let far = vectorcraft_geom::Shape::bounding_box(&full).inflate(opt.tol, opt.tol);
|
||||
let mut pts = probe_points(&paths, opt.tol, 200, 120);
|
||||
let rightmost = paths.iter().filter_map(vectorcraft_geom::PathData::bounds).max_by(|a, b| a.x1.total_cmp(&b.x1)).unwrap();
|
||||
pts.push(Point::new(far.x1, rightmost.center().y));
|
||||
let (mut hits, mut kinds) = (0, HashSet::new());
|
||||
for p in pts {
|
||||
let before = compound_hit_before(n, &full, p, opt);
|
||||
let now = hit_test(&d, p, opt);
|
||||
if p.x == far.x1 || p.y == far.y1 {
|
||||
let outline = vectorcraft_geom::hit::distance_to_outline(&full, p) <= opt.tol;
|
||||
assert_eq!(now.is_some(), outline || before.is_some(), "{rule:?} {opt:?} on the far edge at {p:?}");
|
||||
continue;
|
||||
}
|
||||
assert_eq!(now.as_ref().map(|h| (h.leaf, h.kind)), before.map(|k| (id, k)), "{rule:?} {opt:?} at {p:?}");
|
||||
hits += usize::from(before.is_some());
|
||||
kinds.extend(before.map(|k| format!("{k:?}")));
|
||||
}
|
||||
// The points reach both hits and misses, and the outline as well as the fill.
|
||||
assert!(hits > 100, "{rule:?} {opt:?}: {hits} hits");
|
||||
assert!(kinds.contains("Outline"), "{rule:?} {opt:?}: {kinds:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A wide stroke paints far past a path's control points: clicks on it there still hit, for a
|
||||
/// path and for a compound path (whose strokes are measured along all of it), exactly as when
|
||||
/// they were culled by their reach measured along the curves.
|
||||
#[test]
|
||||
fn wide_strokes_hit_past_the_control_points() {
|
||||
use vectorcraft_geom::{Anchor, PathData, SubPath};
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 40.0);
|
||||
// A zigzag 10 pt high whose 40 pt stroke reaches 20 pt (more at its mitred turns) past it.
|
||||
let zig = PathData::single(SubPath::new(
|
||||
[(100.0, 100.0), (110.0, 110.0), (120.0, 100.0), (130.0, 110.0)].map(|(x, y)| Anchor::corner(Point::new(x, y))).to_vec(),
|
||||
false,
|
||||
));
|
||||
let path = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::path(path, zig.clone(), stroke.clone())).unwrap();
|
||||
// A compound path of two small rings with the same stroke, further along.
|
||||
let mut rng = Rng(3);
|
||||
let members: Vec<Arc<Node>> = [Point::new(250.0, 250.0), Point::new(262.0, 250.0)]
|
||||
.into_iter()
|
||||
.map(|c| Arc::new(Node::path(d.alloc_id(), PathData::single(blob(&mut rng, c, 4.0, 4, true)), Appearance::default())))
|
||||
.collect();
|
||||
let compound = d.alloc_id();
|
||||
let mut node = Node::new(compound, NodeKind::Compound { children: members, rule: vectorcraft_geom::FillRule::NonZero });
|
||||
node.appearance = stroke.into();
|
||||
d.insert(Some(l), 9, node).unwrap();
|
||||
let symbols = d.symbol_boxes();
|
||||
let opt = HitOptions::default();
|
||||
for id in [path, compound] {
|
||||
let n = d.node(id).unwrap();
|
||||
let full = n.stroke_path().unwrap();
|
||||
let control = match &n.kind {
|
||||
NodeKind::Path { path, .. } => path.control_bounds().unwrap(),
|
||||
_ => n.children().unwrap().iter().filter_map(|m| m.path_data()?.control_bounds()).reduce(|a, b| a.union(b)).unwrap(),
|
||||
};
|
||||
let (mut outside, mut checked) = (0, 0);
|
||||
let area = control.inflate(40.0, 40.0);
|
||||
for i in 0..=80 {
|
||||
for j in 0..=80 {
|
||||
let p = Point::new(area.x0 + area.width() * f64::from(i) / 80.0, area.y0 + area.height() * f64::from(j) / 80.0);
|
||||
let before = match &n.kind {
|
||||
NodeKind::Path { .. } => n
|
||||
.reach_bounds_with(&symbols)
|
||||
.is_none_or(|b| b.inflate(opt.tol, opt.tol).contains(p))
|
||||
.then(|| hit_leaf(n, p, opt, &symbols))
|
||||
.flatten(),
|
||||
_ => compound_hit_before(n, &full, p, opt),
|
||||
};
|
||||
let now = hit_test(&d, p, opt).filter(|h| h.leaf == id).map(|h| h.kind);
|
||||
assert_eq!(now, before, "{id:?} at {p:?}");
|
||||
checked += 1;
|
||||
outside += usize::from(before == Some(HitKind::Stroke) && !control.contains(p));
|
||||
}
|
||||
}
|
||||
assert!(outside > 50, "{id:?}: {outside} of {checked} points hit the stroke outside the control points' box");
|
||||
}
|
||||
}
|
||||
|
||||
/// The box a click is culled by holds the object's reach for paths and compound paths (it is
|
||||
/// measured by their control points, which hold their curves, and grown by the same stroke reach),
|
||||
/// so culling by it never turns away a click the reach let through. (Up to rounding: where a curve's
|
||||
/// extreme is an anchor, the two boxes measure the same point in different ways.)
|
||||
#[test]
|
||||
fn cull_box_holds_the_reach_of_paths_and_compound_paths() {
|
||||
const E: f64 = 1e-9;
|
||||
let holds =
|
||||
|outer: Rect, inner: Rect| outer.x0 - E <= inner.x0 && outer.y0 - E <= inner.y0 && inner.x1 <= outer.x1 + E && inner.y1 <= outer.y1 + E;
|
||||
let stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 12.0);
|
||||
let (mut d, id, _) = compound_doc(200, vectorcraft_geom::FillRule::NonZero, stroke.clone());
|
||||
let path_id = d.alloc_id();
|
||||
let symbols = d.symbol_boxes();
|
||||
let n = d.node(id).unwrap();
|
||||
let mut checked = 0;
|
||||
for node in std::iter::once(n).chain(n.children().unwrap().iter().map(|m| &**m)) {
|
||||
let (cull, reach) = (cull_reach(node, &symbols).unwrap(), node.reach_bounds_with(&symbols).unwrap());
|
||||
assert!(holds(cull, reach), "{:?}: {cull:?} does not hold {reach:?}", node.id);
|
||||
checked += 1;
|
||||
}
|
||||
// A stroked plain path, its handles reaching past its curves.
|
||||
let mut rng = Rng(11);
|
||||
let path = Node::path(path_id, vectorcraft_geom::PathData::single(blob(&mut rng, Point::new(50.0, 50.0), 20.0, 5, true)), stroke);
|
||||
let (cull, reach) = (cull_reach(&path, &symbols).unwrap(), path.reach_bounds_with(&symbols).unwrap());
|
||||
assert!(holds(cull, reach), "{cull:?} does not hold {reach:?}");
|
||||
assert_eq!(checked, 201);
|
||||
}
|
||||
@@ -185,8 +185,13 @@ impl Node {
|
||||
match &self.kind {
|
||||
NodeKind::Path { path, .. } => Some(path.to_bezpath()),
|
||||
NodeKind::Compound { children, .. } => {
|
||||
let mut bp = vectorcraft_geom::BezPath::new();
|
||||
children.iter().filter_map(|c| c.path_data()).for_each(|pd| bp.extend(pd.to_bezpath()));
|
||||
// Sized up front: grown by doubling, the path of a compound path of hundreds of
|
||||
// thousands of anchors is copied into ever larger buffers, up to tens of MB, on
|
||||
// every call.
|
||||
let subpaths = || children.iter().filter_map(|c| c.path_data()).flat_map(|pd| &pd.subpaths);
|
||||
let elements = subpaths().filter(|sp| !sp.anchors.is_empty()).map(|sp| 1 + sp.segment_count() + usize::from(sp.closed)).sum();
|
||||
let mut bp = vectorcraft_geom::BezPath::from_vec(Vec::with_capacity(elements));
|
||||
subpaths().for_each(|sp| sp.to_bezpath_into(&mut bp));
|
||||
Some(bp)
|
||||
}
|
||||
_ => None,
|
||||
@@ -393,6 +398,12 @@ impl Node {
|
||||
self.transform_scaled(a, &scaling.into());
|
||||
}
|
||||
|
||||
/// The path of the child an Objects on Path group's objects are attached to.
|
||||
fn on_path_data(&self) -> Option<&PathData> {
|
||||
let r = self.extras().objects_on_path.as_deref()?;
|
||||
self.children()?.iter().find(|c| c.id == r.path)?.path_data()
|
||||
}
|
||||
|
||||
fn transform_scaled(&mut self, a: Affine, sc: &Scaling) {
|
||||
// A dimension's measurement moves with it.
|
||||
if let Some(e) = self.extras_if_any()
|
||||
@@ -400,12 +411,8 @@ impl Node {
|
||||
{
|
||||
dimension.transform(a);
|
||||
}
|
||||
// The frames of the objects attached to a path move with them.
|
||||
if let Some(e) = self.extras_if_any()
|
||||
&& let Some(on_path) = &mut e.objects_on_path
|
||||
{
|
||||
on_path.transform(a);
|
||||
}
|
||||
// The path the objects are attached to, before it is transformed.
|
||||
let on_path_before = self.on_path_data().cloned();
|
||||
if !self.is_layer() {
|
||||
self.bbox_angle = crate::orient::transformed_angle(self.bbox_angle, a);
|
||||
}
|
||||
@@ -496,6 +503,14 @@ impl Node {
|
||||
NodeKind::Mesh(m) => m.transform(a),
|
||||
NodeKind::Repeat(r) => r.transform(a, *sc),
|
||||
}
|
||||
// The frames of the objects attached to a path move with them, and the distances along the
|
||||
// path follow the path as it is now (a live shape's path is regenerated).
|
||||
let on_path_after = on_path_before.as_ref().and_then(|_| self.on_path_data().cloned());
|
||||
if let Some(e) = self.extras_if_any()
|
||||
&& let Some(on_path) = &mut e.objects_on_path
|
||||
{
|
||||
on_path.transform(a, on_path_before.as_ref().zip(on_path_after.as_ref()));
|
||||
}
|
||||
if let Some(m) = self.extras_if_any().and_then(|e| e.mask.as_mut())
|
||||
&& m.linked
|
||||
{
|
||||
|
||||
@@ -241,6 +241,34 @@ fn uneven_scales_keep_live_corners_circular() {
|
||||
assert_round_corners(&n, Affine::IDENTITY, 40.0);
|
||||
}
|
||||
|
||||
/// Objects attached to a rounded rectangle that keeps its corners when scaled stay where the scale
|
||||
/// takes them on the regenerated path, which is not twice as long when twice the size.
|
||||
#[test]
|
||||
fn objects_on_a_live_rectangle_follow_its_regenerated_path() {
|
||||
use crate::objects_on_path::{CENTER, ObjectsOnPath, stops};
|
||||
let path = live_rect(100.0, 100.0, 20.0, Affine::IDENTITY);
|
||||
let objects: Vec<Node> =
|
||||
(2..5).map(|i| Node::path(NodeId(i), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Default::default())).collect();
|
||||
let members: Vec<&Node> = objects.iter().collect();
|
||||
let rec = ObjectsOnPath { spacing: Some(20.0), start: 10.0, ..ObjectsOnPath::new(NodeId(1), &members, CENTER, 0.0) };
|
||||
let mut children = vec![Arc::new(path)];
|
||||
children.extend(objects.iter().cloned().map(Arc::new));
|
||||
let mut g = Node::new(NodeId(9), NodeKind::Group { children, clip: false });
|
||||
g.extras_mut().objects_on_path = Some(Box::new(rec));
|
||||
let path_of = |g: &Node| g.children().and_then(|c| c.first()).and_then(|p| p.path_data().cloned()).unwrap();
|
||||
let rec_of = |g: &Node| g.extras().objects_on_path.as_deref().cloned().unwrap();
|
||||
let r = rec_of(&g);
|
||||
let before = stops(&path_of(&g), 3, r.spacing, r.start).unwrap();
|
||||
let a = Affine::scale(2.0);
|
||||
g.transform(a, KEEP_CORNERS);
|
||||
assert_round_corners(&g.children().unwrap()[0], Affine::IDENTITY, 20.0);
|
||||
let r = rec_of(&g);
|
||||
let after = stops(&path_of(&g), 3, r.spacing, r.start).unwrap();
|
||||
for ((p, _), (q, _)) in before.iter().zip(&after) {
|
||||
assert!((a * *p).distance(*q) < 1e-6, "{p:?} went to {q:?}: {r:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotated_and_reflected_live_rectangles_scale_along_their_own_sides() {
|
||||
let place = Affine::translate((200.0, 100.0)) * Affine::rotate(30f64.to_radians());
|
||||
@@ -518,3 +546,23 @@ fn fields_before_the_type_are_buffered_within_the_value_budget() {
|
||||
assert!(with_buffered_value_budget(0, || read(&written)).is_ok(), "a saved object buffers nothing: {written}");
|
||||
assert!(read(reordered).is_ok(), "no budget outside a read");
|
||||
}
|
||||
|
||||
/// A compound path's path is its members' paths one after another, open and closed, empty
|
||||
/// members and single anchors included.
|
||||
#[test]
|
||||
fn compound_stroke_path_is_its_members_in_order() {
|
||||
use vectorcraft_geom::{Anchor, PathData, SubPath};
|
||||
let open = PathData::single(SubPath::new([(0.0, 0.0), (5.0, 1.0), (9.0, 7.0)].map(|(x, y)| Anchor::corner(Point::new(x, y))).to_vec(), false));
|
||||
let lone = PathData::single(SubPath::new(vec![Anchor::corner(Point::new(3.0, 3.0))], false));
|
||||
let members =
|
||||
[shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), open, PathData::default(), lone, shapes::ellipse(Rect::new(10.0, 10.0, 20.0, 16.0))];
|
||||
let mut expected = vectorcraft_geom::BezPath::new();
|
||||
for pd in &members {
|
||||
expected.extend(pd.to_bezpath());
|
||||
}
|
||||
let children = members.iter().enumerate().map(|(i, pd)| Arc::new(Node::path(NodeId(i as u64 + 1), pd.clone(), Appearance::default()))).collect();
|
||||
let n = Node::new(NodeId(99), NodeKind::Compound { children, rule: vectorcraft_geom::FillRule::EvenOdd });
|
||||
let bp = n.stroke_path().unwrap();
|
||||
assert_eq!(bp.elements(), expected.elements());
|
||||
assert!(!bp.elements().is_empty());
|
||||
}
|
||||
@@ -5,8 +5,9 @@
|
||||
//! the other children are the attached objects, kept where they are drawn: the group draws, hits,
|
||||
//! saves and exports as a group. The record lists the objects in their order along the path, each
|
||||
//! with the frame it is drawn in and the angle that frame is turned by. [`place`] spreads them
|
||||
//! evenly along the path from its first anchor (the first object sits on that anchor, and the last
|
||||
//! one sits on the end of an open path), puts the attachment point of each one
|
||||
//! along the path ([`stops`]): evenly from its first anchor by default (the first object sits on
|
||||
//! that anchor, and the last one sits on the end of an open path), or [`ObjectsOnPath::spacing`]
|
||||
//! apart from [`ObjectsOnPath::start`]. It puts the attachment point of each one
|
||||
//! ([`ObjectsOnPath::pivot`]) on the path, and turns its frame to the path's direction there,
|
||||
//! tilted by [`ObjectsOnPath::rotate`].
|
||||
//!
|
||||
@@ -45,6 +46,14 @@ pub struct ObjectsOnPath {
|
||||
/// upright object has its frame's x axis along the path's direction at its attachment point.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub rotate: f64,
|
||||
/// Space: the distance along the path (points) from each object's attachment point to the
|
||||
/// next one's. `None` (Auto) spreads the objects evenly ([`layout`]).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub spacing: Option<f64>,
|
||||
/// The distance along the path (points) from its first anchor to the first object's
|
||||
/// attachment point.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub start: f64,
|
||||
}
|
||||
|
||||
/// An object attached to the path of an Objects on Path group.
|
||||
@@ -95,19 +104,38 @@ impl ObjectsOnPath {
|
||||
/// in its frame as drawn ([`upright_frame`]).
|
||||
pub fn new(path: NodeId, members: &[&Node], pivot: u8, rotate: f64) -> Self {
|
||||
let members = members.iter().map(|n| Member::new(n)).collect();
|
||||
Self { path, members, pivot: pivot.min(8), rotate: if rotate.is_finite() { rotate } else { 0.0 } }
|
||||
Self { path, members, pivot: pivot.min(8), rotate: if rotate.is_finite() { rotate } else { 0.0 }, spacing: None, start: 0.0 }
|
||||
}
|
||||
/// The frames go with the group, and each frame's angle becomes the transformed path's
|
||||
/// direction at the object plus the tilt, so that [`place`] keeps each object's scale, shear
|
||||
/// and reflection when it spreads the objects along the transformed path again. A reflection
|
||||
/// also reverses Rotate: the objects keep the mirrored tilt to the mirrored path.
|
||||
pub fn transform(&mut self, a: Affine) {
|
||||
/// also reverses Rotate: the objects keep the mirrored tilt to the mirrored path. With `paths`,
|
||||
/// the group's path before the transform and as it is after it, the start and a Space value
|
||||
/// keep the first and last objects where the transform takes them on the path; a value that
|
||||
/// cannot be followed that way scales by how much the path's length changed. Without `paths`,
|
||||
/// they scale by the transform's average scale (the square root of its area scale). A
|
||||
/// value that would not be finite once scaled stays as it is.
|
||||
pub fn transform(&mut self, a: Affine, paths: Option<(&PathData, &PathData)>) {
|
||||
let before = tilt(self.rotate);
|
||||
let [a0, a1, a2, a3, _, _] = a.as_coeffs();
|
||||
if a.determinant() < 0.0 && self.rotate != 0.0 {
|
||||
self.rotate = -self.rotate;
|
||||
}
|
||||
let along = paths.and_then(|(old, new)| {
|
||||
let s = path_length(new)?.0 / path_length(old)?.0;
|
||||
(s.is_finite() && s > 0.0).then_some(s)
|
||||
});
|
||||
let scale = along.unwrap_or_else(|| a.determinant().abs().sqrt());
|
||||
// A move leaves the distances along the path as they are.
|
||||
let moves = a0 == 1.0 && a1 == 0.0 && a2 == 0.0 && a3 == 1.0;
|
||||
if !moves && scale.is_finite() && scale > 0.0 {
|
||||
let scaled = |v: f64| Some(v * scale).filter(|s| s.is_finite()).unwrap_or(v);
|
||||
let moved = paths.and_then(|(old, new)| self.moved_along(a, old, new, scale));
|
||||
let (spacing, start) = moved.unwrap_or((None, None));
|
||||
self.spacing = self.spacing.map(|g| spacing.unwrap_or_else(|| scaled(g)));
|
||||
self.start = start.unwrap_or_else(|| scaled(self.start));
|
||||
}
|
||||
let after = tilt(self.rotate);
|
||||
let [a0, a1, a2, a3, _, _] = a.as_coeffs();
|
||||
for m in &mut self.members {
|
||||
m.frame = a * m.frame;
|
||||
let (sin, cos) = (m.angle - before).sin_cos();
|
||||
@@ -117,6 +145,41 @@ impl ObjectsOnPath {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The start and Space value on `new`, the path `old` after the transform `a` (regenerated, for
|
||||
/// a live shape), that keep the first object and the last one where `a` takes them: each one's
|
||||
/// point on `old`, mapped by `a`, measured along `new` near `scale` times its distance along
|
||||
/// `old`. Either one is `None` when it cannot be followed that way: a start before or beyond the
|
||||
/// ends of an open path, or a Space value of 0, one the path has no room for, or one with fewer
|
||||
/// than two objects. `None` for a path without length or a start that is not finite.
|
||||
fn moved_along(&self, a: Affine, old: &PathData, new: &PathData, scale: f64) -> Option<(Option<f64>, Option<f64>)> {
|
||||
let (was, is) = (Spine::new(old)?, Spine::new(new)?);
|
||||
let (len, closed) = path_length(old)?;
|
||||
let (new_len, _) = path_length(new)?;
|
||||
if !self.start.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let n = self.members.len();
|
||||
let (s0, gap) = layout(len, closed, n, self.spacing, self.start);
|
||||
let follow = |s: f64| -> Option<f64> {
|
||||
let (p, _) = was.at_length(s);
|
||||
let t = is.nearest(a * p, Some(s * scale))?.1;
|
||||
t.is_finite().then_some(if closed { wrap(t, new_len) } else { t.clamp(0.0, new_len) })
|
||||
};
|
||||
let t0 = follow(s0)?;
|
||||
// On a closed path the start keeps the number of times it goes round, when that stays finite.
|
||||
let start =
|
||||
if closed { Some(t0 + ((self.start - s0) / len).round() * new_len).filter(|s| s.is_finite()) } else { (s0 == self.start).then_some(t0) };
|
||||
let spacing = self.spacing.filter(|g| n > 1 && g.is_finite() && *g > 0.0 && *g <= gap).and_then(|g| {
|
||||
let t1 = follow(nth_length(len, closed, s0, gap, n - 1))?;
|
||||
let steps = (n - 1) as f64;
|
||||
// Round a closed path, the span nearest the scaled one.
|
||||
let expected = steps * g * scale;
|
||||
let span = if closed { wrap(t1 - t0 - expected + new_len / 2.0, new_len) - new_len / 2.0 + expected } else { t1 - t0 };
|
||||
let g = span / steps;
|
||||
(g.is_finite() && g >= 0.0).then_some(g)
|
||||
});
|
||||
Some((spacing, start))
|
||||
}
|
||||
/// The children given new ids (a copy of the group): the path and the objects by their new ids.
|
||||
pub fn rename(&mut self, ids: &HashMap<NodeId, NodeId>) {
|
||||
let to = |id: NodeId| ids.get(&id).copied().unwrap_or(id);
|
||||
@@ -210,19 +273,75 @@ pub fn upright_frame(n: &Node) -> Affine {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where `n` objects attach along `path` (its first subpath): the point and the direction there
|
||||
/// (radians, as `atan2` gives in the document's axes). They are spread evenly by length from the
|
||||
/// first anchor: on an open path the last one is at its end, on a closed path the gaps go all the way
|
||||
/// around. `None` for a path without length.
|
||||
pub fn stops(path: &PathData, n: usize) -> Option<Vec<(Point, f64)>> {
|
||||
let spine = Spine::new(path)?;
|
||||
let len = spine.length();
|
||||
if !len.is_finite() || len <= 1e-9 {
|
||||
return None;
|
||||
}
|
||||
/// The length of `path`'s first subpath and whether it is closed. `None` for a path without
|
||||
/// length.
|
||||
pub fn path_length(path: &PathData) -> Option<(f64, bool)> {
|
||||
let len = Spine::new(path)?.length();
|
||||
let closed = path.subpaths.first().is_some_and(|s| s.closed);
|
||||
let gaps = if closed { n } else { n.saturating_sub(1) }.max(1);
|
||||
Some((0..n).map(|i| spine.at_length(len * i as f64 / gaps as f64)).collect())
|
||||
(len.is_finite() && len > 1e-9).then_some((len, closed))
|
||||
}
|
||||
|
||||
/// Where the first of `n` objects attaches along a path of length `len` (closed or not), and the
|
||||
/// distance from each object's attachment point to the next one's, both along the path (points),
|
||||
/// for Space `spacing` (`None`: Auto) from `start`:
|
||||
/// - The first object is `start` from the first anchor: on an open path no further than its end,
|
||||
/// and on a closed path less than once around.
|
||||
/// - Auto spreads the objects evenly from there: on an open path the last one is at its end, and on
|
||||
/// a closed path the gaps go all the way around.
|
||||
/// - A Space value is kept to what the path has room for, so a shorter path draws the objects
|
||||
/// closer while the value stays: on an open path the last object reaches its end at most, and on
|
||||
/// a closed path the last one stops at least a gap short of the first.
|
||||
///
|
||||
/// A Space value that is negative or not finite counts as Auto, and a `start` that is not finite as 0.
|
||||
pub fn layout(len: f64, closed: bool, n: usize, spacing: Option<f64>, start: f64) -> (f64, f64) {
|
||||
let start = match (start.is_finite(), closed) {
|
||||
(false, _) => 0.0,
|
||||
(true, true) => wrap(start, len),
|
||||
(true, false) => start.clamp(0.0, len.max(0.0)),
|
||||
};
|
||||
let room = if closed {
|
||||
len / n.max(1) as f64
|
||||
} else if n > 1 {
|
||||
(len - start) / (n - 1) as f64
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let room = if room.is_finite() { room.max(0.0) } else { 0.0 };
|
||||
match spacing.filter(|g| g.is_finite() && *g >= 0.0) {
|
||||
Some(g) => (start, g.min(room)),
|
||||
None => (start, room),
|
||||
}
|
||||
}
|
||||
|
||||
/// `s` taken round a closed path of length `len`: 0 or more, and less than `len`.
|
||||
fn wrap(s: f64, len: f64) -> f64 {
|
||||
let w = s.rem_euclid(len);
|
||||
if w.is_finite() && w < len { w } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Where `n` objects attach along `path` (its first subpath): the point and the direction there
|
||||
/// (radians, as `atan2` gives in the document's axes). They go along it as [`layout`] spaces them
|
||||
/// for Space `spacing` (`None`: Auto) from `start`. `None` for a path without length.
|
||||
pub fn stops(path: &PathData, n: usize, spacing: Option<f64>, start: f64) -> Option<Vec<(Point, f64)>> {
|
||||
let spine = Spine::new(path)?;
|
||||
let (len, closed) = path_length(path)?;
|
||||
let (start, gap) = layout(len, closed, n, spacing, start);
|
||||
Some((0..n).map(|i| spine.at_length(nth_length(len, closed, start, gap, i))).collect())
|
||||
}
|
||||
|
||||
/// Where object `i` of `n` attaches along `path`, as [`stops`] places it, without the others.
|
||||
pub fn stop(path: &PathData, n: usize, spacing: Option<f64>, start: f64, i: usize) -> Option<(Point, f64)> {
|
||||
let spine = Spine::new(path)?;
|
||||
let (len, closed) = path_length(path)?;
|
||||
let (start, gap) = layout(len, closed, n, spacing, start);
|
||||
(i < n).then(|| spine.at_length(nth_length(len, closed, start, gap, i)))
|
||||
}
|
||||
|
||||
/// The distance along a path of length `len` (closed or not) to object `i`, from `start` and
|
||||
/// `gap` apart as [`layout`] gives them.
|
||||
pub fn nth_length(len: f64, closed: bool, start: f64, gap: f64, i: usize) -> f64 {
|
||||
let s = start + gap * i as f64;
|
||||
if closed { wrap(s, len) } else { s.min(len) }
|
||||
}
|
||||
|
||||
/// The tilt Rotate gives (radians, the document's axes, where y points down): `rotate` degrees
|
||||
@@ -277,7 +396,7 @@ pub fn place(g: &mut Node, symbols: &SymbolBoxes) -> bool {
|
||||
}
|
||||
}
|
||||
let mut moved = false;
|
||||
if let Some(stops) = path.and_then(|p| stops(&p, rec.members.len())) {
|
||||
if let Some(stops) = path.and_then(|p| stops(&p, rec.members.len(), rec.spacing, rec.start)) {
|
||||
let turn = tilt(rec.rotate);
|
||||
for (m, (p, dir)) in rec.members.iter_mut().zip(stops) {
|
||||
let Some(c) = at.get(&m.id).and_then(|i| children.get_mut(*i)) else { continue };
|
||||
@@ -309,15 +428,192 @@ mod tests {
|
||||
#[test]
|
||||
fn stops_spread_from_the_first_anchor() {
|
||||
let open = shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0));
|
||||
let s = stops(&open, 4).unwrap();
|
||||
let s = stops(&open, 4, None, 0.0).unwrap();
|
||||
let xs: Vec<f64> = s.iter().map(|(p, _)| p.x.round()).collect();
|
||||
assert_eq!(xs, [0.0, 100.0, 200.0, 300.0], "first at the start, last at the end of an open path");
|
||||
let closed = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
let s = stops(&closed, 4).unwrap();
|
||||
let s = stops(&closed, 4, None, 0.0).unwrap();
|
||||
let mut pts: Vec<(i64, i64)> = s.iter().map(|(p, _)| (p.x.round() as i64, p.y.round() as i64)).collect();
|
||||
pts.sort();
|
||||
assert_eq!(pts, [(0, 0), (0, 100), (100, 0), (100, 100)], "a closed path spreads them all the way round");
|
||||
assert!(stops(&shapes::line(Point::ZERO, Point::ZERO), 2).is_none());
|
||||
assert!(stops(&shapes::line(Point::ZERO, Point::ZERO), 2, None, 0.0).is_none());
|
||||
}
|
||||
|
||||
/// The x of each stop on the `len` pt line from (0, 0) to the right, to 1/1000 pt.
|
||||
fn xs_on_line(len: f64, n: usize, spacing: Option<f64>, start: f64) -> Vec<f64> {
|
||||
let open = shapes::line(Point::new(0.0, 0.0), Point::new(len, 0.0));
|
||||
stops(&open, n, spacing, start).unwrap().iter().map(|(p, _)| (p.x * 1000.0).round() / 1000.0).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn space_sets_the_distance_between_the_stops() {
|
||||
assert_eq!(xs_on_line(300.0, 4, Some(60.0), 0.0), [0.0, 60.0, 120.0, 180.0], "the first stays on the first anchor");
|
||||
assert_eq!(xs_on_line(300.0, 4, Some(60.0), 60.0), [60.0, 120.0, 180.0, 240.0], "centered on the path");
|
||||
assert_eq!(xs_on_line(300.0, 4, Some(0.0), 0.0), [0.0; 4], "no space stacks them");
|
||||
// More than the path has room for: the last one reaches the end.
|
||||
assert_eq!(xs_on_line(300.0, 4, Some(500.0), 0.0), [0.0, 100.0, 200.0, 300.0]);
|
||||
assert_eq!(xs_on_line(300.0, 4, Some(500.0), 150.0), [150.0, 200.0, 250.0, 300.0]);
|
||||
// A shorter path draws them closer, while the Space value stays to come back with the length.
|
||||
assert_eq!(xs_on_line(90.0, 4, Some(60.0), 0.0), [0.0, 30.0, 60.0, 90.0]);
|
||||
assert_eq!(layout(90.0, false, 4, Some(60.0), 0.0), (0.0, 30.0));
|
||||
assert_eq!(layout(300.0, false, 4, Some(60.0), 0.0), (0.0, 60.0));
|
||||
// Values that are not usable count as Auto, and a start beyond the end stops at it.
|
||||
assert_eq!(xs_on_line(300.0, 4, Some(f64::NAN), f64::INFINITY), [0.0, 100.0, 200.0, 300.0]);
|
||||
assert_eq!(xs_on_line(300.0, 4, Some(-5.0), 0.0), [0.0, 100.0, 200.0, 300.0]);
|
||||
assert_eq!(xs_on_line(300.0, 2, Some(10.0), 400.0), [300.0, 300.0]);
|
||||
assert_eq!(xs_on_line(300.0, 1, Some(10.0), 20.0), [20.0], "one object has no space to set");
|
||||
assert_eq!(xs_on_line(300.0, 0, Some(10.0), 0.0), Vec::<f64>::new());
|
||||
// One stop on its own is where the stops put it.
|
||||
let open = shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0));
|
||||
let all = stops(&open, 4, Some(60.0), 60.0).unwrap();
|
||||
for (i, s) in all.iter().enumerate() {
|
||||
assert_eq!(stop(&open, 4, Some(60.0), 60.0, i), Some(*s));
|
||||
}
|
||||
assert_eq!(stop(&open, 4, Some(60.0), 60.0, 4), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn space_on_a_closed_path_wraps_at_the_first_anchor_and_stops_short_of_the_first_object() {
|
||||
// The square's outline is 400 pt round, from (0, 0) to the right and on clockwise.
|
||||
let closed = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
let pts = |spacing, start| -> Vec<(i64, i64)> {
|
||||
stops(&closed, 4, spacing, start).unwrap().iter().map(|(p, _)| (p.x.round() as i64, p.y.round() as i64)).collect()
|
||||
};
|
||||
assert_eq!(pts(Some(50.0), 0.0), [(0, 0), (50, 0), (100, 0), (100, 50)]);
|
||||
// Centered on the first anchor: the span goes back past it.
|
||||
assert_eq!(pts(Some(50.0), -75.0), [(0, 75), (0, 25), (25, 0), (75, 0)]);
|
||||
// At most a quarter of the way round each: no two objects meet at the first anchor.
|
||||
assert_eq!(pts(Some(300.0), 0.0), [(0, 0), (100, 0), (100, 100), (0, 100)]);
|
||||
assert_eq!(layout(400.0, true, 4, Some(300.0), 400.0), (0.0, 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_saved_without_space_reads_as_auto() {
|
||||
let a = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let rec = ObjectsOnPath::new(NodeId(1), &[&a], CENTER, 0.0);
|
||||
let v = serde_json::to_value(&rec).unwrap();
|
||||
assert!(v.get("spacing").is_none() && v.get("start").is_none(), "Auto is not written: {v}");
|
||||
let back: ObjectsOnPath = serde_json::from_value(v).unwrap();
|
||||
assert_eq!((back.spacing, back.start), (None, 0.0));
|
||||
let set = ObjectsOnPath { spacing: Some(60.0), start: 12.5, ..rec };
|
||||
let back: ObjectsOnPath = serde_json::from_value(serde_json::to_value(&set).unwrap()).unwrap();
|
||||
assert_eq!(back, set);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transforming_the_group_scales_its_space() {
|
||||
let a = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let mut rec = ObjectsOnPath { spacing: Some(60.0), start: 12.5, ..ObjectsOnPath::new(NodeId(1), &[&a], CENTER, 30.0) };
|
||||
rec.transform(Affine::new([-2.0, 0.0, 0.0, 2.0, 5.0, 5.0]), None);
|
||||
assert_eq!((rec.spacing, rec.start, rec.rotate), (Some(120.0), 25.0, -30.0));
|
||||
rec.transform(Affine::translate((40.0, 0.0)) * Affine::rotate(0.7), None);
|
||||
assert!((rec.spacing.unwrap() - 120.0).abs() < 1e-9 && (rec.start - 25.0).abs() < 1e-9, "{rec:?}");
|
||||
// Twice as wide and no higher: a level path is stretched twice along its length.
|
||||
let level = shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0));
|
||||
let stretch = Affine::new([2.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
|
||||
rec.transform(stretch, Some((&level, &level.transformed(stretch))));
|
||||
assert!((rec.spacing.unwrap() - 240.0).abs() < 1e-9 && (rec.start - 50.0).abs() < 1e-9, "{rec:?}");
|
||||
let mut auto = ObjectsOnPath::new(NodeId(1), &[&a], CENTER, 0.0);
|
||||
auto.transform(Affine::scale(3.0), None);
|
||||
assert_eq!((auto.spacing, auto.start), (None, 0.0), "Auto stays Auto");
|
||||
let mut huge = ObjectsOnPath { spacing: Some(1e308), start: -1e308, ..auto };
|
||||
huge.transform(Affine::scale(2.0), None);
|
||||
assert_eq!((huge.spacing, huge.start), (Some(1e308), -1e308), "kept finite");
|
||||
}
|
||||
|
||||
/// Stretching a path that turns a corner keeps the first and last objects where the stretch
|
||||
/// takes them, not where the whole path's change in length would.
|
||||
#[test]
|
||||
fn a_stretch_keeps_the_first_and_last_objects_where_it_takes_them() {
|
||||
// 100 pt to the right, then 100 pt down; twice as wide, the first part is 200 pt long.
|
||||
let points = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0)];
|
||||
let corner = PathData::single(vectorcraft_geom::SubPath::polyline(&points, false));
|
||||
let stretch = Affine::scale_non_uniform(2.0, 1.0);
|
||||
let wide = corner.transformed(stretch);
|
||||
let (a, b) = (rect(2, Rect::new(0.0, 0.0, 10.0, 10.0)), rect(3, Rect::new(20.0, 0.0, 30.0, 10.0)));
|
||||
let mut rec = ObjectsOnPath { spacing: Some(40.0), start: 50.0, ..ObjectsOnPath::new(NodeId(1), &[&a, &b], CENTER, 0.0) };
|
||||
rec.transform(stretch, Some((&corner, &wide)));
|
||||
assert!((rec.start - 100.0).abs() < 1e-9 && (rec.spacing.unwrap() - 80.0).abs() < 1e-9, "{rec:?}");
|
||||
// Round a closed path, from before its first anchor: the start goes round as many times.
|
||||
let square = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
let wide = square.transformed(stretch);
|
||||
let mut rec = ObjectsOnPath { spacing: Some(50.0), start: -75.0, ..ObjectsOnPath::new(NodeId(1), &[&a, &b], CENTER, 0.0) };
|
||||
let before = stops(&square, 2, rec.spacing, rec.start).unwrap();
|
||||
rec.transform(stretch, Some((&square, &wide)));
|
||||
let after = stops(&wide, 2, rec.spacing, rec.start).unwrap();
|
||||
for ((p, _), (q, _)) in before.iter().zip(&after) {
|
||||
assert!((stretch * *p).distance(*q) < 1e-9, "{p:?} went to {q:?}: {rec:?}");
|
||||
}
|
||||
assert!(rec.start < 0.0, "{rec:?}");
|
||||
}
|
||||
|
||||
/// A start round a closed path so many times that scaling it would not be finite stays as it is.
|
||||
#[test]
|
||||
fn a_closed_path_start_too_large_to_scale_stays_finite() {
|
||||
let square = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
let grow = Affine::scale(2.0);
|
||||
let a = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let mut rec = ObjectsOnPath { start: 1e308, ..ObjectsOnPath::new(NodeId(1), &[&a], CENTER, 0.0) };
|
||||
rec.transform(grow, Some((&square, &square.transformed(grow))));
|
||||
assert_eq!(rec.start, 1e308, "{rec:?}");
|
||||
}
|
||||
|
||||
/// Stretching the group across its level path only keeps the objects where the stretch takes
|
||||
/// them: twice as far apart.
|
||||
#[test]
|
||||
fn a_group_stretched_along_its_path_keeps_the_objects_in_proportion() {
|
||||
let line = Node::path(NodeId(1), shapes::line(Point::new(0.0, 100.0), Point::new(300.0, 100.0)), Default::default());
|
||||
let (a, b) = (rect(2, Rect::new(0.0, 0.0, 10.0, 10.0)), rect(3, Rect::new(20.0, 0.0, 30.0, 10.0)));
|
||||
let mut g = Node::new(NodeId(4), NodeKind::Group { children: vec![Arc::new(line), Arc::new(a.clone()), Arc::new(b.clone())], clip: false });
|
||||
let rec = ObjectsOnPath { spacing: Some(20.0), start: 10.0, ..ObjectsOnPath::new(NodeId(1), &[&a, &b], CENTER, 0.0) };
|
||||
g.extras_mut().objects_on_path = Some(Box::new(rec));
|
||||
let empty = crate::Document::new(1.0, 1.0);
|
||||
let symbols = empty.symbol_boxes();
|
||||
place(&mut g, &symbols);
|
||||
g.transform(Affine::new([2.0, 0.0, 0.0, 1.0, 0.0, 0.0]), false);
|
||||
let rec = g.extras().objects_on_path.as_deref().cloned().unwrap();
|
||||
assert_eq!((rec.spacing, rec.start), (Some(40.0), 20.0));
|
||||
place(&mut g, &symbols);
|
||||
let x = |id| g.children().and_then(|c| c.iter().find(|c| c.id == id).cloned()).unwrap().geometric_bounds().unwrap().center().x;
|
||||
assert!((x(NodeId(2)) - 20.0).abs() < 1e-9 && (x(NodeId(3)) - 60.0).abs() < 1e-9, "{} {}", x(NodeId(2)), x(NodeId(3)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn length_near_measures_along_the_path_and_past_its_ends() {
|
||||
// An L: 400 pt to the right, then 300 pt up.
|
||||
let points = [Point::new(0.0, 300.0), Point::new(400.0, 300.0), Point::new(400.0, 0.0)];
|
||||
let l = PathData::single(vectorcraft_geom::SubPath::polyline(&points, false));
|
||||
let spine = Spine::new(&l).unwrap();
|
||||
assert!((spine.length_near(Point::new(300.0, 320.0), None) - 300.0).abs() < 1e-9);
|
||||
assert!((spine.length_near(Point::new(420.0, 100.0), None) - 600.0).abs() < 1e-9);
|
||||
assert!((spine.length_near(Point::new(400.0, -26.0), None) - 726.0).abs() < 1e-9, "beyond the end");
|
||||
assert!((spine.length_near(Point::new(-50.0, 300.0), None) + 50.0).abs() < 1e-9, "before the start");
|
||||
// A path that turns back near its start: beyond its end, the pointer is nearer the first
|
||||
// segment than the last one, but on the line of the last one.
|
||||
let hook = [Point::new(0.0, 0.0), Point::new(200.0, 0.0), Point::new(200.0, 10.0), Point::new(100.0, 10.0)];
|
||||
let hook = Spine::new(&PathData::single(vectorcraft_geom::SubPath::polyline(&hook, false))).unwrap();
|
||||
assert!((hook.length_near(Point::new(80.0, 10.0), None) - 330.0).abs() < 1e-9);
|
||||
assert!((hook.length_near(Point::new(50.0, 10.0), None) - 360.0).abs() < 1e-9);
|
||||
let closed = Spine::new(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0))).unwrap();
|
||||
assert!((closed.length_near(Point::new(-30.0, -30.0), None)).abs() < 1e-9, "a closed path has no ends");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn length_near_a_point_followed_stays_on_that_part_of_the_path() {
|
||||
// A narrow U, open on the left: its ends are 20 pt apart, 620 pt from each other along it.
|
||||
let u = [Point::new(0.0, 0.0), Point::new(300.0, 0.0), Point::new(300.0, 20.0), Point::new(0.0, 20.0)];
|
||||
let u = Spine::new(&PathData::single(vectorcraft_geom::SubPath::polyline(&u, false))).unwrap();
|
||||
assert!((u.length_near(Point::new(-26.0, 20.0), None) - 646.0).abs() < 1e-9, "beyond the end");
|
||||
// Nearer the first segment's line, the pointer stays beyond the end it was following.
|
||||
assert!((u.length_near(Point::new(-26.0, 8.0), None) + 26.0).abs() < 1e-9);
|
||||
assert!((u.length_near(Point::new(-26.0, 8.0), Some(646.0)) - 646.0).abs() < 1e-9);
|
||||
// Following the path round, it goes on from where it was.
|
||||
assert!((u.length_near(Point::new(305.0, 10.0), Some(312.0)) - 310.0).abs() < 1e-9);
|
||||
// Round a closed path's first anchor: from 10 pt short of it to 20 pt past it.
|
||||
let square = Spine::new(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0))).unwrap();
|
||||
let (at, _) = square.at_length(390.0);
|
||||
assert!((square.length_near(at, None) - 390.0).abs() < 1e-9);
|
||||
assert!((square.length_near(Point::new(20.0, -5.0), Some(390.0)) - 20.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -110,8 +110,9 @@ impl Document {
|
||||
|
||||
/// Visit every color that can link to a swatch (solid paints and gradient stops of fills,
|
||||
/// strokes and text runs) in the art (opacity masks included), symbol definitions, graph
|
||||
/// designs, pattern tiles and the tile that pattern editing's Cancel puts back, graphic styles
|
||||
/// and the swatches themselves (tint swatches, gradient swatches' stops).
|
||||
/// designs, pattern tiles and the tile that pattern editing's Cancel puts back, graphic styles,
|
||||
/// character styles' fill and stroke and the swatches themselves (tint swatches, gradient
|
||||
/// swatches' stops).
|
||||
/// `f(colour, link, tint)` may change them and returns true when it did
|
||||
/// ([`Paint::map_links`]). Only nodes holding a changed paint (and the paths to them) are
|
||||
/// copied. Returns the number of changed paints.
|
||||
@@ -134,6 +135,11 @@ impl Document {
|
||||
for w in self.swatches_iter_mut() {
|
||||
n += usize::from(w.paint.map_links(f));
|
||||
}
|
||||
for def in &mut self.char_styles {
|
||||
for key in ["fill", "stroke"] {
|
||||
n += usize::from(map_style_paint(&mut def.attrs, key, f));
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
@@ -198,6 +204,23 @@ pub fn color_name(c: Color) -> String {
|
||||
/// true when it changed them.
|
||||
pub type LinkFn<'a> = dyn FnMut(&mut Color, &mut Option<String>, &mut f32) -> bool + 'a;
|
||||
|
||||
/// Apply `f` to the paint a character style's attribute `key` holds, as [`Paint::map_links`]
|
||||
/// does, and store the result in the attribute. True when it changed.
|
||||
fn map_style_paint(attrs: &mut serde_json::Map<String, serde_json::Value>, key: &str, f: &mut LinkFn) -> bool {
|
||||
let Some(value) = attrs.get_mut(key) else { return false };
|
||||
let Ok(mut paint) = serde_json::from_value::<Paint>(value.clone()) else { return false };
|
||||
if !paint.map_links(f) {
|
||||
return false;
|
||||
}
|
||||
match serde_json::to_value(&paint) {
|
||||
Ok(changed) => {
|
||||
*value = changed;
|
||||
true
|
||||
}
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every colour in the subtree of `n` with the swatch it links to: solid fills, strokes, text runs
|
||||
/// and gradient stops (with their link), then mesh points (unlinked), in paint order.
|
||||
pub fn node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) {
|
||||
|
||||
@@ -103,6 +103,23 @@ fn shape_modes_follow_the_pathfinder_panel() {
|
||||
assert_eq!(div.len(), 3);
|
||||
}
|
||||
|
||||
/// Divide and Outline draw no piece of a member without fill or stroke, the same as when such
|
||||
/// pieces are left out.
|
||||
#[test]
|
||||
fn divide_and_outline_draw_nothing_for_unpainted_members() {
|
||||
let unpainted =
|
||||
Arc::new(Node::path(NodeId(2), shapes::rectangle(Rect::new(5.0, 0.0, 15.0, 10.0)), Appearance::basic(Paint::None, Paint::None, 0.0)));
|
||||
for effect in ["pathfinder.divide", "pathfinder.outline"] {
|
||||
let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), unpainted.clone()]);
|
||||
g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({}), visible: true });
|
||||
let out = pathfinder_children(&g, None).unwrap();
|
||||
assert!(out.iter().any(|n| n.id == NodeId(1)) && out.iter().any(|n| n.id == NodeId(2)), "{effect}: {out:#?}");
|
||||
for n in out.iter().filter(|n| n.id == NodeId(2)) {
|
||||
assert!(n.appearance.items.iter().all(|i| i.paint().is_none()), "{effect}: {n:#?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an "H" in blue type at 100 pt on a baseline at y = 80, with its stems on either
|
||||
/// side of x = 100.
|
||||
fn type_h() -> Node {
|
||||
|
||||
@@ -125,6 +125,8 @@ pub struct Flavour {
|
||||
|
||||
/// Longest side (px) of the PNG Copy offers: larger art is scaled down to fit.
|
||||
const COPY_PNG_SIDE: f64 = 4096.0;
|
||||
/// The smallest scale (pixels a point) the PNG encoder renders at.
|
||||
const MIN_COPY_PNG_SCALE: f64 = 0.01;
|
||||
/// Most bytes of text `clipboard.importText` takes.
|
||||
const MAX_TEXT: usize = 1 << 20;
|
||||
/// Most bytes of images the SVG markup may embed and still go out as plain text. A paste reads the
|
||||
@@ -293,7 +295,8 @@ impl Clipboard {
|
||||
|
||||
/// What Copy offers other apps, best first, with Include SVG Code (`svg`) and On Copy: PDF
|
||||
/// (`pdf`) as given (see `clipboard.flavours`). A [`Flavour`] that can't be made (art too large
|
||||
/// to render) is left out; the PNG is scaled down to at most [`COPY_PNG_SIDE`] pixels a side.
|
||||
/// to render) is left out; the PNG is scaled down to at most [`COPY_PNG_SIDE`] pixels a side, and
|
||||
/// left out when even [`MIN_COPY_PNG_SCALE`] can't bring it that small.
|
||||
pub fn flavours(&self, svg: bool, pdf: bool) -> Vec<Flavour> {
|
||||
self.flavours_with_warnings(svg, pdf).0
|
||||
}
|
||||
@@ -320,7 +323,14 @@ impl Clipboard {
|
||||
PDF => self.pdf().inspect_err(|e| log::warn!("clipboard PDF: {e}")).ok().flatten().map(&mut keep),
|
||||
_ => {
|
||||
let side = self.bounds().map_or(1.0, |b| b.width().max(b.height()));
|
||||
let scale = (COPY_PNG_SIDE / side).clamp(0.01, 1.0);
|
||||
let scale = (COPY_PNG_SIDE / side).min(1.0);
|
||||
// The encoder renders at no fewer than MIN_COPY_PNG_SCALE pixels a point: art
|
||||
// too large to fit COPY_PNG_SIDE at that scale gets no PNG, rather than one
|
||||
// of up to a gigabyte of pixels.
|
||||
if scale < MIN_COPY_PNG_SCALE {
|
||||
log::warn!("clipboard PNG: art {side} pt across is too large to copy as a picture");
|
||||
continue;
|
||||
}
|
||||
self.png(scale).inspect_err(|e| log::warn!("clipboard PNG: {e}")).ok().flatten().map(|(png, _, _, notes)| keep((png, notes)))
|
||||
}
|
||||
};
|
||||
|
||||
@@ -325,7 +325,7 @@ fn first_text_style(s: &Session) -> Option<CharStyle> {
|
||||
fn same_text(s: &mut Session, cmd: &str, eq: fn(&CharStyle, &CharStyle) -> bool) -> Result<Value> {
|
||||
let r = first_text_style(s).ok_or_else(|| bad(cmd, "select a text object"))?;
|
||||
let ids = candidates(s, |n| match &n.kind {
|
||||
NodeKind::Text(t) => t.runs.iter().any(|run| eq(&run.style, &r)),
|
||||
NodeKind::Text(t) => t.runs.iter().any(|run| !run.text.is_empty() && eq(&run.style, &r)),
|
||||
_ => false,
|
||||
})?;
|
||||
finish_same(s, cmd, ids)
|
||||
|
||||
@@ -698,6 +698,8 @@ fn preset_settings(s: &Session, cmd: &str, given: &Map<String, Value>) -> Result
|
||||
// Refuse what an export would refuse, now rather than when the preset is used.
|
||||
check_settings(s, &Value::Object(settings.clone())).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
Folders::of(&ScreenParams::of(&Value::Object(settings.clone()))?).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
let mut settings = settings;
|
||||
remove_passwords(&mut settings);
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
@@ -1275,9 +1277,33 @@ fn remember(s: &mut Session, p: &Value) {
|
||||
let _ = store_settings(s, settings);
|
||||
}
|
||||
|
||||
/// The PDF passwords an export may be given (`security` of a PDF row or of `settings.pdf`).
|
||||
const PASSWORD_KEYS: [&str; 2] = ["openPassword", "permissionsPassword"];
|
||||
|
||||
/// `settings` without the PDF passwords anywhere in them: settings kept in the document (which
|
||||
/// native saves write) or in the preferences hold the export's choices, never its secrets, as
|
||||
/// the PDF settings themselves are saved without them.
|
||||
fn remove_passwords(settings: &mut Map<String, Value>) {
|
||||
for key in PASSWORD_KEYS {
|
||||
settings.remove(key);
|
||||
}
|
||||
for v in settings.values_mut() {
|
||||
remove_passwords_in(v);
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_passwords_in(v: &mut Value) {
|
||||
match v {
|
||||
Value::Object(m) => remove_passwords(m),
|
||||
Value::Array(items) => items.iter_mut().for_each(remove_passwords_in),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Make `settings` the document's export settings. Not an undo step (like the settings of any
|
||||
/// export); the document has changed only if they differ.
|
||||
pub(crate) fn store_settings(s: &mut Session, settings: Map<String, Value>) -> Result<()> {
|
||||
pub(crate) fn store_settings(s: &mut Session, mut settings: Map<String, Value>) -> Result<()> {
|
||||
remove_passwords(&mut settings);
|
||||
let st = s.doc_mut()?;
|
||||
if st.doc.export_settings != settings {
|
||||
Arc::make_mut(&mut st.doc).export_settings = settings;
|
||||
@@ -1334,4 +1360,21 @@ mod tests {
|
||||
assert_eq!(safe_file_name("lpt9 .png"), "lpt9-.png");
|
||||
assert_eq!(safe_file_name("My CON .png"), "My CON .png");
|
||||
}
|
||||
|
||||
/// The settings an export leaves in the document keep its PDF security choices but not its
|
||||
/// passwords, in a row or in `settings.pdf`.
|
||||
#[test]
|
||||
fn stored_settings_leave_out_pdf_passwords() {
|
||||
let mut s = crate::Session::new();
|
||||
s.execute("file.new", &serde_json::json!({"width": 100, "height": 100})).unwrap();
|
||||
let given = serde_json::json!({
|
||||
"formats": [{"format": "pdf", "security": {"openPassword": "open sesame", "permissionsPassword": "owner", "printing": "low"}}],
|
||||
"settings": {"pdf": {"security": {"openPassword": "open sesame", "copy": false}}},
|
||||
});
|
||||
super::store_settings(&mut s, given.as_object().unwrap().clone()).unwrap();
|
||||
let kept = serde_json::Value::Object(s.doc().unwrap().doc.export_settings.clone());
|
||||
assert!(!kept.to_string().contains("Password"), "{kept}");
|
||||
assert_eq!(kept["formats"][0]["security"]["printing"], "low");
|
||||
assert_eq!(kept["settings"]["pdf"]["security"]["copy"], false);
|
||||
}
|
||||
}
|
||||
@@ -112,8 +112,16 @@ pub(super) fn reach(n: &Node) -> Option<Rect> {
|
||||
Some(b.inflate(fx + 1.0, fx + 1.0))
|
||||
}
|
||||
|
||||
/// Indices of `bounds` grouped by overlap (transitively), each group in index order.
|
||||
pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Vec<Vec<usize>> {
|
||||
/// Indices of `bounds` grouped by overlap (transitively), each group in index order. Boxes that
|
||||
/// only touch overlap; a box with a coordinate that isn't finite overlaps none.
|
||||
///
|
||||
/// A sweep left to right keeps the boxes still open at the current left edge in a tree by their
|
||||
/// tops that knows the lowest bottom below each of its branches, so each box meets only the open
|
||||
/// boxes it overlaps, not every open one (many objects stacked in a column, sharing their
|
||||
/// horizontal extent, would otherwise compare every pair). An open box inside a later box of
|
||||
/// its group, ending no further right, is closed early: whatever overlaps it overlaps that box.
|
||||
/// Fails only when cancelled ([`vectorcraft_doc::cancel`]).
|
||||
pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, vectorcraft_doc::cancel::Cancelled> {
|
||||
fn find(p: &mut [usize], mut i: usize) -> usize {
|
||||
while p[i] != i {
|
||||
p[i] = p[p[i]];
|
||||
@@ -122,19 +130,75 @@ pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Vec<Vec<usize>> {
|
||||
i
|
||||
}
|
||||
let mut parent: Vec<usize> = (0..bounds.len()).collect();
|
||||
let mut order: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.map(|b| (i, b))).collect();
|
||||
order.sort_by(|a, b| a.1.x0.total_cmp(&b.1.x0));
|
||||
// Sweep left to right, comparing each box with those still open at its left edge.
|
||||
let mut open: Vec<(usize, Rect)> = vec![];
|
||||
for (i, b) in order {
|
||||
open.retain(|(_, o)| o.x1 >= b.x0);
|
||||
for (j, o) in &open {
|
||||
if o.y0 <= b.y1 && b.y0 <= o.y1 {
|
||||
let (a, c) = (find(&mut parent, i), find(&mut parent, *j));
|
||||
parent[a.max(c)] = a.min(c);
|
||||
let finite = |b: &Rect| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && b.x0 <= b.x1 && b.y0 <= b.y1;
|
||||
let boxes: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.filter(finite).map(|b| (i, b))).collect();
|
||||
let n = boxes.len();
|
||||
// Each box's place in the tree: by top (then index).
|
||||
let mut by_top: Vec<usize> = (0..n).collect();
|
||||
by_top.sort_by(|&a, &b| boxes[a].1.y0.total_cmp(&boxes[b].1.y0).then(a.cmp(&b)));
|
||||
let tops: Vec<f64> = by_top.iter().map(|&k| boxes[k].1.y0).collect();
|
||||
let mut leaf = vec![0usize; n];
|
||||
for (pos, &k) in by_top.iter().enumerate() {
|
||||
leaf[k] = pos;
|
||||
}
|
||||
// The lowest bottom of the open boxes below each node (−∞: none open).
|
||||
let size = n.next_power_of_two().max(1);
|
||||
let mut low = vec![f64::NEG_INFINITY; 2 * size];
|
||||
let set = |low: &mut [f64], pos: usize, v: f64| {
|
||||
let mut i = pos + size;
|
||||
low[i] = v;
|
||||
while i > 1 {
|
||||
i /= 2;
|
||||
low[i] = low[2 * i].max(low[2 * i + 1]);
|
||||
}
|
||||
};
|
||||
let mut by_left: Vec<usize> = (0..n).collect();
|
||||
by_left.sort_by(|&a, &b| boxes[a].1.x0.total_cmp(&boxes[b].1.x0));
|
||||
let mut by_right: Vec<usize> = (0..n).collect();
|
||||
by_right.sort_by(|&a, &b| boxes[a].1.x1.total_cmp(&boxes[b].1.x1));
|
||||
let mut closing = 0;
|
||||
let mut stack: Vec<(usize, usize, usize)> = vec![];
|
||||
let mut met = vec![];
|
||||
let mut work = 0usize;
|
||||
for &k in &by_left {
|
||||
let b = boxes[k].1;
|
||||
// Close the boxes that end left of this one.
|
||||
while let Some(&c) = by_right.get(closing)
|
||||
&& boxes[c].1.x1 < b.x0
|
||||
{
|
||||
set(&mut low, leaf[c], f64::NEG_INFINITY);
|
||||
closing += 1;
|
||||
}
|
||||
// The open boxes with their top at most this bottom and their bottom at least this top.
|
||||
let below = tops.partition_point(|t| *t <= b.y1);
|
||||
met.clear();
|
||||
stack.clear();
|
||||
stack.push((1, 0, size));
|
||||
while let Some((node, lo, hi)) = stack.pop() {
|
||||
work += 1;
|
||||
if work.is_multiple_of(4096) {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
}
|
||||
if lo >= below || low[node] < b.y0 {
|
||||
continue;
|
||||
}
|
||||
if hi - lo == 1 {
|
||||
met.push(by_top[lo]);
|
||||
continue;
|
||||
}
|
||||
let mid = (lo + hi) / 2;
|
||||
stack.push((2 * node + 1, mid, hi));
|
||||
stack.push((2 * node, lo, mid));
|
||||
}
|
||||
for &o in &met {
|
||||
let (a, c) = (find(&mut parent, boxes[k].0), find(&mut parent, boxes[o].0));
|
||||
parent[a.max(c)] = a.min(c);
|
||||
let ob = boxes[o].1;
|
||||
if ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 {
|
||||
set(&mut low, leaf[o], f64::NEG_INFINITY);
|
||||
}
|
||||
}
|
||||
open.push((i, b));
|
||||
set(&mut low, leaf[k], b.y1);
|
||||
}
|
||||
let mut groups: Vec<Vec<usize>> = vec![];
|
||||
let mut slot: Vec<Option<usize>> = vec![None; bounds.len()];
|
||||
@@ -148,5 +212,84 @@ pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Vec<Vec<usize>> {
|
||||
}
|
||||
}
|
||||
}
|
||||
groups
|
||||
Ok(groups)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// What [`overlapping`] gives, comparing every pair.
|
||||
fn every_pair(bounds: &[Option<Rect>]) -> Vec<Vec<usize>> {
|
||||
let n = bounds.len();
|
||||
let mut group: Vec<usize> = (0..n).collect();
|
||||
let hit = |a: &Rect, b: &Rect| a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1;
|
||||
loop {
|
||||
let mut changed = false;
|
||||
for i in 0..n {
|
||||
for j in 0..n {
|
||||
if let (Some(a), Some(b)) = (bounds[i], bounds[j])
|
||||
&& hit(&a, &b)
|
||||
&& group[j] < group[i]
|
||||
{
|
||||
group[i] = group[j];
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let mut out: Vec<Vec<usize>> = vec![];
|
||||
let mut seen = std::collections::HashMap::new();
|
||||
for (i, &root) in group.iter().enumerate() {
|
||||
let g = *seen.entry(root).or_insert_with(|| {
|
||||
out.push(vec![]);
|
||||
out.len() - 1
|
||||
});
|
||||
out[g].push(i);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Boxes of many sizes, nested, touching and apart, group as comparing every pair groups them.
|
||||
#[test]
|
||||
fn groups_match_comparing_every_pair() {
|
||||
let mut seed = 0x2545_f491_4f6c_dd1du64;
|
||||
let mut next = |m: f64| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed % 1000) as f64 / 1000.0 * m
|
||||
};
|
||||
for round in 0..40 {
|
||||
let n = 5 + round * 4;
|
||||
let bounds: Vec<Option<Rect>> = (0..n)
|
||||
.map(|i| {
|
||||
if i % 11 == 3 {
|
||||
return None;
|
||||
}
|
||||
let (x, y) = (next(100.0).round(), next(100.0).round());
|
||||
Some(Rect::new(x, y, x + next(30.0).round(), y + next(30.0).round()))
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A column of many boxes sharing their horizontal extent: each one meets only its
|
||||
/// neighbours, so they group (here, touching in pairs) without comparing every pair.
|
||||
#[test]
|
||||
fn a_tall_column_groups_by_its_neighbours() {
|
||||
let n = 200_000;
|
||||
let bounds: Vec<Option<Rect>> =
|
||||
(0..n).map(|i| Some(Rect::new(0.0, 3.0 * f64::from(i), 100.0, 3.0 * f64::from(i) + if i % 2 == 0 { 3.0 } else { 1.0 }))).collect();
|
||||
let groups = overlapping(&bounds).unwrap();
|
||||
assert_eq!(groups.len(), n as usize / 2);
|
||||
assert!(groups.iter().enumerate().all(|(g, ids)| ids == &[2 * g, 2 * g + 1]));
|
||||
// Boxes that aren't finite overlap nothing.
|
||||
let odd = [Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(f64::NAN, 0.0, 10.0, 10.0)), Some(Rect::new(5.0, 5.0, 20.0, 20.0))];
|
||||
assert_eq!(overlapping(&odd).unwrap(), vec![vec![0, 2], vec![1]]);
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,40 @@ pub(super) struct Flat {
|
||||
/// Where its image goes, and the image (once rendered).
|
||||
pub(super) area: Option<Area>,
|
||||
raster: Option<Raster>,
|
||||
/// When the group is one block of type over several lines: its lines, to group the regions by.
|
||||
lines: Option<Lines>,
|
||||
}
|
||||
|
||||
/// The lines of a block of type: document space → its line space, where each line spans a band
|
||||
/// across the lines (its ascent above the baseline to its descent below).
|
||||
struct Lines {
|
||||
to_lines: Affine,
|
||||
bands: Vec<(f64, f64)>,
|
||||
}
|
||||
|
||||
impl Lines {
|
||||
/// The lines of `n` when it is type laid out in two lines or more (not on a path).
|
||||
fn of(n: &Node) -> Option<Lines> {
|
||||
let NodeKind::Text(t) = &n.kind else { return None };
|
||||
if t.xf.determinant().abs() < 1e-12 {
|
||||
return None;
|
||||
}
|
||||
let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
if layout.on_path {
|
||||
return None;
|
||||
}
|
||||
let bands: Vec<(f64, f64)> = layout.lines.iter().filter(|l| l.x1 > l.x0).map(|l| (l.baseline - l.ascent, l.baseline + l.descent)).collect();
|
||||
let to_lines = if layout.vertical { layout.line_xf.inverse() * t.xf.inverse() } else { t.xf.inverse() };
|
||||
(bands.len() > 1).then_some(Lines { to_lines, bands })
|
||||
}
|
||||
|
||||
/// The line nearest to the middle of `path`.
|
||||
fn line_of(&self, path: &PathData) -> usize {
|
||||
let Some(b) = path.bounds() else { return 0 };
|
||||
let y = (self.to_lines * b.center()).y;
|
||||
let away = |&(lo, hi): &(f64, f64)| if y < lo { lo - y } else { (y - hi).max(0.0) };
|
||||
self.bands.iter().enumerate().min_by(|a, b| away(a.1).total_cmp(&away(b.1))).map_or(0, |(i, _)| i)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a group's image goes.
|
||||
@@ -79,7 +113,7 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render:
|
||||
let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() };
|
||||
// Baking above stopped early when cancelled; each group is a place to stop (a plan changes nothing).
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
for g in overlapping(&reaches) {
|
||||
for g in overlapping(&reaches)? {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
let ids: Vec<NodeId> = g.iter().map(|&i| roots[i]).collect();
|
||||
let group = g.iter().any(|&i| see_through[i]).then(|| {
|
||||
@@ -97,7 +131,11 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render:
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
out.flat.push(Flat { roots: ids, regions, area, raster });
|
||||
let lines = match g.as_slice() {
|
||||
[i] => Lines::of(&art[*i]),
|
||||
_ => None,
|
||||
};
|
||||
out.flat.push(Flat { roots: ids, regions, area, raster, lines });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -366,7 +404,10 @@ pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan
|
||||
children.push(Arc::new(raster_node(d, r)));
|
||||
rasterized += 1;
|
||||
}
|
||||
// Type over several lines gives a group per line.
|
||||
let mut by_line: Vec<Vec<Arc<Node>>> = f.lines.as_ref().map_or(vec![], |l| vec![vec![]; l.bands.len()]);
|
||||
for (path, fill) in f.regions {
|
||||
let line = f.lines.as_ref().map(|l| l.line_of(&path));
|
||||
let mut n = shape_node(d, path, None);
|
||||
n.appearance = Appearance {
|
||||
items: vec![AppearanceItem::Fill(FillLayer { overprint: fill.overprint, ..FillLayer::new(fill.paint) })],
|
||||
@@ -374,9 +415,20 @@ pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan
|
||||
}
|
||||
.into();
|
||||
n.opacity = fill.alpha.min(1.0);
|
||||
children.push(Arc::new(n));
|
||||
match line.and_then(|i| by_line.get_mut(i)) {
|
||||
Some(l) => l.push(Arc::new(n)),
|
||||
None => children.push(Arc::new(n)),
|
||||
}
|
||||
vector += 1;
|
||||
}
|
||||
by_line.retain(|l| !l.is_empty());
|
||||
if by_line.len() > 1 {
|
||||
for l in by_line {
|
||||
children.push(Arc::new(Node::group(d.alloc_id(), l)));
|
||||
}
|
||||
} else {
|
||||
children.extend(by_line.into_iter().flatten());
|
||||
}
|
||||
let g = Node::group(d.alloc_id(), children);
|
||||
ids.push(g.id);
|
||||
if one_pass {
|
||||
|
||||
+117
-37
@@ -29,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Replace Font",
|
||||
[],
|
||||
None,
|
||||
"{from: {family, style?}, to: {family (any of its names; stored as the font's own family name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); the type in the art of the symbols in scope changes too (all of the document's, or those the selected instances show, so every instance of them follows); text that is hidden or locked, in a hidden or locked group or layer (or group of a symbol's art), or on a locked artboard keeps its font → {runs, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}",
|
||||
"{from: {family, style?}, to: {family (any of its names; stored as the font's own family name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); the type in the art of the symbols in scope changes too (all of the document's, or those the selected instances show, so every instance of them follows); text that is hidden or locked, in a hidden or locked group or layer (or group of a symbol's art), or on a locked artboard keeps its font; when no run changes (text already set in the new font, or none to change), the document and its undo history stay as they are → {runs: the runs changed, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}",
|
||||
has_doc,
|
||||
replace
|
||||
),
|
||||
@@ -549,6 +549,16 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let matches = |st: &vectorcraft_doc::CharStyle| {
|
||||
st.font_family.eq_ignore_ascii_case(&ff) && fs.as_ref().is_none_or(|x| st.font_style.eq_ignore_ascii_case(x))
|
||||
};
|
||||
// The style a matching run is set in after the change, or `None` when the run doesn't match or
|
||||
// is already set in that family and style with no version or Variable Font settings.
|
||||
let new_style = |st: &vectorcraft_doc::CharStyle| {
|
||||
if !matches(st) {
|
||||
return None;
|
||||
}
|
||||
// An explicit style, else the closest the new family has to the old one.
|
||||
let style = ts.clone().or_else(|| db.face(&tf, &st.font_style).map(|f| f.style.clone())).unwrap_or_else(|| st.font_style.clone());
|
||||
(st.font_family != tf || st.font_style != style || st.font_version.is_some() || !st.font_axes.is_empty()).then_some(style)
|
||||
};
|
||||
// Only text the Selection tool can reach changes: not hidden or locked, in a hidden or locked
|
||||
// group or layer, or on a locked artboard. The text left in the font is counted. The type in
|
||||
// the art of the symbols in scope (all of them, or those the selection shows) changes too,
|
||||
@@ -564,54 +574,59 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(None, BTreeSet::new())
|
||||
};
|
||||
let uses = |t: &TextObject| t.runs.iter().any(|r| matches(&r.style));
|
||||
let (ids, skipped) = {
|
||||
// Whether a run of `t` changes.
|
||||
let changes = |t: &TextObject| t.runs.iter().any(|r| new_style(&r.style).is_some());
|
||||
let (ids, skipped, in_symbols) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let editable = d.editable();
|
||||
let (ids, other): (Vec<NodeId>, Vec<NodeId>) = scope(s, selection_only)?.into_iter().partition(|id| editable(*id));
|
||||
let mut skipped = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).count();
|
||||
skipped += symbol_texts(d, symbols.as_ref()).into_iter().filter(|(t, open)| !open && uses(t)).count();
|
||||
let texts = symbol_texts(d, symbols.as_ref());
|
||||
skipped += texts.iter().filter(|(t, open)| !open && uses(t)).count();
|
||||
if !closed.is_empty() {
|
||||
skipped += symbol_texts(d, Some(&closed)).into_iter().filter(|(t, _)| uses(t)).count();
|
||||
}
|
||||
(ids, skipped)
|
||||
// The text that changes: when none does, the document and its undo history stay as they are.
|
||||
let ids: Vec<NodeId> = ids.into_iter().filter(|id| text(d, *id).is_some_and(changes)).collect();
|
||||
let in_symbols = texts.iter().any(|(t, open)| *open && changes(t));
|
||||
(ids, skipped, in_symbols)
|
||||
};
|
||||
// The fonts the replaced runs are set in, for the warning.
|
||||
let mut set = BTreeSet::new();
|
||||
let n = s.edit("Replace Font", |d, _| {
|
||||
let mut n = 0;
|
||||
let mut replace_in = |t: &mut TextObject| {
|
||||
let mut changed = false;
|
||||
for r in &mut t.runs {
|
||||
if matches(&r.style) {
|
||||
// An explicit style, else the closest the new family has to the old one.
|
||||
let style = ts
|
||||
.clone()
|
||||
.or_else(|| db.face(&tf, &r.style.font_style).map(|f| f.style.clone()))
|
||||
.unwrap_or_else(|| r.style.font_style.clone());
|
||||
r.style.font_family = tf.clone();
|
||||
r.style.font_style = style;
|
||||
// Another font: none of the old one's versions or Variable Font settings.
|
||||
r.style.font_version = None;
|
||||
r.style.font_axes.clear();
|
||||
set.insert(font_of(&r.style));
|
||||
changed = true;
|
||||
n += 1;
|
||||
let n = if ids.is_empty() && !in_symbols {
|
||||
0
|
||||
} else {
|
||||
s.edit("Replace Font", |d, _| {
|
||||
let mut n = 0;
|
||||
let mut replace_in = |t: &mut TextObject| {
|
||||
let mut changed = false;
|
||||
for r in &mut t.runs {
|
||||
if let Some(style) = new_style(&r.style) {
|
||||
r.style.font_family = tf.clone();
|
||||
r.style.font_style = style;
|
||||
// Another font: none of the old one's versions or Variable Font settings.
|
||||
r.style.font_version = None;
|
||||
r.style.font_axes.clear();
|
||||
set.insert(font_of(&r.style));
|
||||
changed = true;
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
vectorcraft_text::edit::normalize(&mut t.runs);
|
||||
refresh_bounds(t);
|
||||
}
|
||||
};
|
||||
for id in &ids {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
replace_in(t);
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
vectorcraft_text::edit::normalize(&mut t.runs);
|
||||
refresh_bounds(t);
|
||||
}
|
||||
};
|
||||
for id in &ids {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
replace_in(t);
|
||||
}
|
||||
}
|
||||
edit_symbol_texts(d, symbols.as_ref(), &|t, open| open && uses(t), &mut replace_in);
|
||||
drop(replace_in);
|
||||
Ok(n)
|
||||
})?;
|
||||
edit_symbol_texts(d, symbols.as_ref(), &|t, open| open && changes(t), &mut replace_in);
|
||||
drop(replace_in);
|
||||
Ok(n)
|
||||
})?
|
||||
};
|
||||
let mut out = json!({ "runs": n });
|
||||
let mut warnings = Vec::new();
|
||||
if skipped > 0 {
|
||||
@@ -889,6 +904,71 @@ mod tests {
|
||||
assert_eq!(r, json!({"runs": 2}));
|
||||
}
|
||||
|
||||
/// Replace Font adds no undo step when no run changes: only locked text uses the font, no text
|
||||
/// uses it, or the text is already set in the new font and style.
|
||||
#[test]
|
||||
fn replace_font_that_changes_nothing_adds_no_undo_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
let serif = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Serif", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap();
|
||||
let sans = s.execute("text.create", &json!({"x": 10, "y": 60, "text": "Sans", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [serif]})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let before = steps(&s);
|
||||
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}})).unwrap();
|
||||
assert_eq!(r, json!({"runs": 0, "skipped": 1, "warning": REPLACE_SKIPPED}));
|
||||
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Nothing Uses This"}, "to": {"family": "Source Sans 3"}})).unwrap();
|
||||
assert_eq!(r, json!({"runs": 0}));
|
||||
let style = text(&s.doc().unwrap().doc, NodeId(sans)).unwrap().runs[0].style.font_style.clone();
|
||||
let r =
|
||||
s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Source Sans 3", "style": style}})).unwrap();
|
||||
assert_eq!(r, json!({"runs": 0}));
|
||||
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Source Sans 3"}})).unwrap();
|
||||
assert_eq!(r, json!({"runs": 0}));
|
||||
assert_eq!(steps(&s), before);
|
||||
// A change is still one step.
|
||||
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}})).unwrap();
|
||||
assert_eq!(r, json!({"runs": 1}));
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
assert_eq!(text_family(&s, sans), "Inter");
|
||||
}
|
||||
|
||||
/// Change and Change All add no undo step when the type in a symbol's art already has the new
|
||||
/// font, and a change to that type is still one step.
|
||||
#[test]
|
||||
fn replace_font_in_symbols_that_changes_nothing_adds_no_undo_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Sans", "font": "Source Sans 3"})).unwrap()["id"].clone();
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "ids": [id]})).unwrap();
|
||||
let mut on_layers = 0;
|
||||
s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_))));
|
||||
assert_eq!(on_layers, 0, "the type is only in the symbol");
|
||||
let family = |s: &Session| symbol_texts(&s.doc().unwrap().doc, None)[0].0.runs[0].style.font_family.clone();
|
||||
let style = symbol_texts(&s.doc().unwrap().doc, None)[0].0.runs[0].style.font_style.clone();
|
||||
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let before = steps(&s);
|
||||
// New Symbol selects the instance: Change (the selection) and Change All.
|
||||
for selection_only in [true, false] {
|
||||
for to in [json!({"family": "Source Sans 3"}), json!({"family": "Source Sans 3", "style": style})] {
|
||||
let p = json!({"from": {"family": "Source Sans 3"}, "to": to, "selectionOnly": selection_only});
|
||||
assert_eq!(s.execute("text.replaceFont", &p).unwrap(), json!({"runs": 0}), "{p}");
|
||||
}
|
||||
}
|
||||
assert_eq!(steps(&s), before);
|
||||
// A change is still one step, with the instance selected and without.
|
||||
let r =
|
||||
s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}, "selectionOnly": true})).unwrap();
|
||||
assert_eq!(r, json!({"runs": 1}));
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
assert_eq!(family(&s), "Inter");
|
||||
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Inter"}, "to": {"family": "Source Serif 4"}})).unwrap();
|
||||
assert_eq!(r, json!({"runs": 1}));
|
||||
assert_eq!(steps(&s), before + 2);
|
||||
assert_eq!(family(&s), "Source Serif 4");
|
||||
}
|
||||
|
||||
/// The fonts of the symbols' art: Find Font lists them, and Change All replaces them, leaving
|
||||
/// hidden or locked type in the art as it is.
|
||||
#[test]
|
||||
|
||||
@@ -2588,6 +2588,18 @@ fn formatting_the_whole_graphs_text_survives_it_being_drawn_again() {
|
||||
assert_eq!(spec(&s, id).label_styles, vectorcraft_doc::LabelStyles::default());
|
||||
}
|
||||
|
||||
/// A stroke given to all of a graph's text without a weight is kept at 1 pt, as `paint.setStroke` keeps it.
|
||||
#[test]
|
||||
fn a_stroke_given_to_the_whole_graphs_text_is_kept_at_1_pt() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("text.setStyle", &json!({"stroke": "#ff0000"})).unwrap();
|
||||
let legend = spec(&s, id).label_styles.legend.unwrap();
|
||||
assert_eq!((legend.stroke.color().map(|c| c.to_hex()), legend.stroke_width), (Some("#ff0000".into()), 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formatting_one_label_keeps_that_kind_of_label() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
//! path column by column from left to right, top to bottom in each column, spread evenly from its
|
||||
//! first anchor and turned to follow it. Pivot and Rotate come from the command's params, otherwise
|
||||
//! from the tool's options (Objects on Path Tool Options). `object.objectsOnPath.options` sets the
|
||||
//! group's Pivot and Rotate, and `object.objectsOnPath.expand` makes it a plain group.
|
||||
//! group's Pivot, Rotate and Space (the distance between the objects along the path, and where the
|
||||
//! first one attaches), and `object.objectsOnPath.expand` makes it a plain group.
|
||||
//!
|
||||
//! After every edit, [`refresh`] puts the objects of each Objects on Path group that changed back
|
||||
//! on its path: editing the path moves them, an object moved on its own goes back to its place,
|
||||
@@ -48,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Objects on Path Options",
|
||||
[],
|
||||
None,
|
||||
"{ids?: Objects on Path groups or objects in them (default: the selection), pivot?: 0-8 (the reference point of each object that attaches to the path, row by row from the top left; 4: the center), rotate?: degrees counter-clockwise from upright on the path} set how the objects of the groups attach → {ids}",
|
||||
"{ids?: Objects on Path groups or objects in them (default: the selection), pivot?: 0-8 (the reference point of each object that attaches to the path, row by row from the top left; 4: the center), rotate?: degrees counter-clockwise from upright on the path, spacing?: points along the path from each object's attachment point to the next one's (0 or more, kept to what the path has room for; or \"auto\", the default: spread evenly with the last object at the end of an open path), start?: points along the path from its first anchor to the first object's attachment point (default 0)} set how the objects of the groups attach and are spaced → {ids}",
|
||||
has_objects_on_path,
|
||||
options
|
||||
),
|
||||
@@ -256,16 +257,37 @@ fn attach(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
// ---------- Options ----------
|
||||
|
||||
/// `spacing` and `start` from `p`, each checked: `spacing` takes points (0 or more) or `"auto"`
|
||||
/// (`None`), and `start` points along the path.
|
||||
fn spacing_start(p: &Value, cmd: &str, spacing: Option<f64>, start: f64) -> Result<(Option<f64>, f64)> {
|
||||
let spacing = match p.get("spacing").filter(|v| !v.is_null()) {
|
||||
None => spacing,
|
||||
Some(Value::String(a)) if a == "auto" => None,
|
||||
Some(v) => Some(
|
||||
v.as_f64()
|
||||
.filter(|g| g.is_finite() && *g >= 0.0)
|
||||
.ok_or_else(|| bad(cmd, "`spacing` must be a number of points, 0 or more, or \"auto\""))?,
|
||||
),
|
||||
};
|
||||
let start = match p.get("start").filter(|v| !v.is_null()) {
|
||||
None => start,
|
||||
Some(v) => v.as_f64().filter(|s| s.is_finite()).ok_or_else(|| bad(cmd, "`start` must be a finite number"))?,
|
||||
};
|
||||
Ok((spacing, start))
|
||||
}
|
||||
|
||||
fn options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.objectsOnPath.options";
|
||||
let groups = target_groups(s, p, C)?;
|
||||
pivot_rotate(p, C, CENTER, 0.0)?;
|
||||
spacing_start(p, C, None, 0.0)?;
|
||||
s.edit("Objects on Path Options", |d, _| {
|
||||
for g in &groups {
|
||||
let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?;
|
||||
let Some(rec) = n.extras().objects_on_path.as_deref().cloned() else { continue };
|
||||
let (pivot, rotate) = pivot_rotate(p, C, rec.pivot, rec.rotate)?;
|
||||
n.extras_mut().objects_on_path = Some(Box::new(ObjectsOnPath { pivot, rotate, ..rec }));
|
||||
let (spacing, start) = spacing_start(p, C, rec.spacing, rec.start)?;
|
||||
n.extras_mut().objects_on_path = Some(Box::new(ObjectsOnPath { pivot, rotate, spacing, start, ..rec }));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -818,7 +818,7 @@ fn swatch_unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Some(l) if d.swatch(l).is_some() => links.push((l.clone(), tint)),
|
||||
_ => colors.push(*c),
|
||||
};
|
||||
d.visit_paints(&mut |p| match p {
|
||||
let mut paint = |p: &Paint| match p {
|
||||
Paint::Solid { color: c, swatch, tint } => color(c, swatch.as_ref(), *tint),
|
||||
Paint::Gradient(g) => {
|
||||
g.gradient.stops.iter().for_each(|s| color(&s.color, s.swatch.as_ref(), s.tint));
|
||||
@@ -827,7 +827,16 @@ fn swatch_unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
Paint::Pattern { pattern, .. } => patterns.push(pattern.clone()),
|
||||
Paint::None => {}
|
||||
});
|
||||
};
|
||||
d.visit_paints(&mut paint);
|
||||
// A character style's fill and stroke use their swatches even while no text uses the style.
|
||||
for attrs in d.char_styles.iter().map(|def| &def.attrs) {
|
||||
for key in ["fill", "stroke"] {
|
||||
if let Some(p) = attrs.get(key).and_then(|v| serde_json::from_value::<Paint>(v.clone()).ok()) {
|
||||
paint(&p);
|
||||
}
|
||||
}
|
||||
}
|
||||
let used = |w: &Swatch| {
|
||||
gradient_links.contains(&w.name)
|
||||
|| links.iter().any(|(l, t)| match w.tint_of() {
|
||||
|
||||
@@ -477,10 +477,12 @@ fn name_param<'a>(p: &'a Value, kind: Kind, verb: &str) -> Result<&'a str> {
|
||||
str_param(p, "name").ok_or_else(|| bad(&kind.cmd(verb), "missing `name`"))
|
||||
}
|
||||
|
||||
/// The `attrs` of `p`, validated. `kept` holds the style's current attributes (`charStyle.edit`) or
|
||||
/// the target text's attributes (`charStyle.new`): a language tag that is not in the list, which a
|
||||
/// file can give a style or a run, stays when `attrs` keeps it.
|
||||
fn attrs_param(p: &Value, kind: Kind, verb: &str, kept: Option<&Map<String, Value>>) -> Result<Option<Map<String, Value>>> {
|
||||
/// The `attrs` of `p`, validated. `kept` holds the style's current attributes (`charStyle.edit`,
|
||||
/// `charStyle.setAttrs`), the target text's attributes (`charStyle.new`) or the attributes of the
|
||||
/// style being copied (`charStyle.duplicate`): a language tag that is not in the list, a swatch link the document does
|
||||
/// not have, or an OpenType feature tag the shaper does not know, which a file can give a style or
|
||||
/// a run, stays when `attrs` keeps it.
|
||||
fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Map<String, Value>>) -> Result<Option<Map<String, Value>>> {
|
||||
match p.get("attrs") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::Object(m)) => {
|
||||
@@ -490,12 +492,25 @@ fn attrs_param(p: &Value, kind: Kind, verb: &str, kept: Option<&Map<String, Valu
|
||||
let full = match kind {
|
||||
Kind::Char => {
|
||||
let mut st = with_attrs(&CharStyle::default(), m, &c)?;
|
||||
let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key);
|
||||
// A language of the list, stored as its tag (as text.setFormat takes it).
|
||||
if let Some(l) = &st.language
|
||||
&& kept.and_then(|k| k.get("language")) != m.get("language")
|
||||
{
|
||||
st.language = vectorcraft_doc::setup::char_language(l).map_err(|e| bad(&c, e))?.map(str::to_string);
|
||||
}
|
||||
for (key, paint) in [("fill", &mut st.fill), ("stroke", &mut st.stroke)] {
|
||||
if changed(key) {
|
||||
style_paint(d, paint, key, &c)?;
|
||||
}
|
||||
}
|
||||
let (key, lo, hi) = ("stroke_width", 0.0, vectorcraft_doc::MAX_COORD);
|
||||
if changed(key) && !(lo..=hi).contains(&st.stroke_width) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
if changed("features") {
|
||||
style_features(&st.features, kept, &c)?;
|
||||
}
|
||||
char_attrs(&st)
|
||||
}
|
||||
Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), m, &c)?),
|
||||
@@ -506,6 +521,51 @@ fn attrs_param(p: &Value, kind: Kind, verb: &str, kept: Option<&Map<String, Valu
|
||||
}
|
||||
}
|
||||
|
||||
/// Check a character style's `fill` or `stroke` (`key`): each solid color and gradient stop has a
|
||||
/// tint from 0 to 1, and a link to a global swatch of `d`, whose color at that tint it takes.
|
||||
fn style_paint(d: &Document, paint: &mut vectorcraft_color::Paint, key: &str, c: &str) -> Result<()> {
|
||||
match paint {
|
||||
vectorcraft_color::Paint::Solid { color, swatch, tint } => style_color(d, color, swatch.as_deref(), *tint, key, c),
|
||||
vectorcraft_color::Paint::Gradient(g) => {
|
||||
g.gradient.stops.iter_mut().try_for_each(|stop| style_color(d, &mut stop.color, stop.swatch.as_deref(), stop.tint, key, c))
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one color of a character style's `key` paint for [`style_paint`].
|
||||
fn style_color(d: &Document, color: &mut vectorcraft_color::Color, swatch: Option<&str>, tint: f32, key: &str, c: &str) -> Result<()> {
|
||||
if !(0.0..=1.0).contains(&tint) {
|
||||
let (key, lo, hi) = (format!("{key}.tint"), 0, 1);
|
||||
return Err(bad(c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
if let Some(name) = swatch {
|
||||
if d.swatch(name).is_none() {
|
||||
return Err(bad(c, format!("no swatch `{name}`")));
|
||||
}
|
||||
let base = d.global_color(name).ok_or_else(|| bad(c, format!("`{name}` is a process colour: tints apply to global and spot colours")))?;
|
||||
*color = base.tinted(tint);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check a character style's OpenType `features`: at most [`vectorcraft_text::MAX_STYLE_FEATURES`]
|
||||
/// tags, or no more than the `kept` attributes already list, each one the shaper knows or one the
|
||||
/// `kept` attributes already list.
|
||||
fn style_features(features: &[String], kept: Option<&Map<String, Value>>, c: &str) -> Result<()> {
|
||||
let kept: Vec<&str> = kept.and_then(|k| k.get("features")).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect();
|
||||
let max = vectorcraft_text::MAX_STYLE_FEATURES;
|
||||
if features.len() > max.max(kept.len()) {
|
||||
return Err(bad(c, format!("features lists at most {max} tags")));
|
||||
}
|
||||
// One `-` or `+` at most, as the shaper reads a tag.
|
||||
let known = |t: &str| vectorcraft_text::OtFeatures::known_tag(t) && !t.strip_prefix(['-', '+']).unwrap_or(t).starts_with(['-', '+']);
|
||||
match features.iter().find(|t| !known(t) && !kept.contains(&t.as_str())) {
|
||||
Some(t) => Err(bad(c, format!("unknown OpenType feature `{t}`"))),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The attributes of a new style made from nothing (no `attrs`, no text selected): while the
|
||||
/// interface is in Japanese, new type's em box top-to-top leading (paragraph styles) and em box
|
||||
/// centre alignment (character styles); else none (the defaults).
|
||||
@@ -538,9 +598,15 @@ fn list(s: &mut Session, kind: Kind) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn new(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
new_from(s, p, kind, None)
|
||||
}
|
||||
|
||||
/// `charStyle.new`, `paraStyle.new`: `copied` holds the attributes of the style a copy is made of
|
||||
/// (`charStyle.duplicate`), which `attrs` keeps as [`attrs_param`] keeps the target text's.
|
||||
fn new_from(s: &mut Session, p: &Value, kind: Kind, copied: Option<&Map<String, Value>>) -> Result<Value> {
|
||||
let c = kind.cmd("new");
|
||||
let target = selection_attrs(s, p, kind)?;
|
||||
let attrs = match attrs_param(p, kind, "new", target.as_ref())? {
|
||||
let attrs = match attrs_param(&s.doc()?.doc, p, kind, "new", copied.or(target.as_ref()))? {
|
||||
Some(a) => a,
|
||||
None => match target {
|
||||
Some(a) => a,
|
||||
@@ -668,7 +734,9 @@ fn redefine(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
|
||||
fn set_attrs(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
let name = name_param(p, kind, "setAttrs")?.to_string();
|
||||
let attrs = attrs_param(p, kind, "setAttrs", None)?.ok_or_else(|| bad(&kind.cmd("setAttrs"), "missing `attrs`"))?;
|
||||
let d = &s.doc()?.doc;
|
||||
let old = kind.attrs(d, &name);
|
||||
let attrs = attrs_param(d, p, kind, "setAttrs", old.as_ref())?.ok_or_else(|| bad(&kind.cmd("setAttrs"), "missing `attrs`"))?;
|
||||
redefine_to(s, kind, &name, attrs, "setAttrs")
|
||||
}
|
||||
|
||||
@@ -678,7 +746,7 @@ fn edit_style(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
let to = str_param(p, "to").ok_or_else(|| bad(&c, "missing `to`"))?.trim().to_string();
|
||||
let d = &s.doc()?.doc;
|
||||
let old = kind.attrs(d, &name).ok_or_else(|| bad(&c, format!("no style `{name}`")))?;
|
||||
let attrs = attrs_param(p, kind, "edit", Some(&old))?.ok_or_else(|| bad(&c, "missing `attrs`"))?;
|
||||
let attrs = attrs_param(d, p, kind, "edit", Some(&old))?.ok_or_else(|| bad(&c, "missing `attrs`"))?;
|
||||
if name == kind.normal() {
|
||||
return Err(bad(&c, format!("`{name}` can't be edited this way")));
|
||||
}
|
||||
@@ -726,7 +794,7 @@ fn duplicate(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
.map(|i| if i == 1 { format!("{stem} copy") } else { format!("{stem} copy {i}") })
|
||||
.find(|n| kind.attrs(d, n).is_none())
|
||||
.unwrap_or_else(|| format!("{stem} copy"));
|
||||
new(s, &json!({ "name": copy, "attrs": attrs }), kind)
|
||||
new_from(s, &json!({ "name": copy, "attrs": attrs }), kind, Some(&attrs))
|
||||
}
|
||||
|
||||
fn rename(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
|
||||
@@ -257,6 +257,144 @@ fn new_character_style_keeps_a_language_tag_from_the_text() {
|
||||
assert!(error.contains("unknown language"), "{error}");
|
||||
}
|
||||
|
||||
/// The fill of the first run of `id` and its overprint flags, its stroke and stroke weight.
|
||||
fn run_paints(s: &Session, id: u64) -> (vectorcraft_color::Paint, vectorcraft_color::Paint, f64, bool, bool) {
|
||||
let st = runs(s, id)[0].style.clone();
|
||||
(st.fill, st.stroke, st.stroke_width, st.overprint_fill, st.overprint_stroke)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn character_style_color_and_features_reach_text_and_follow_swatch_edits() {
|
||||
let (mut s, id) = session_with_text("Text 1/2");
|
||||
s.execute("swatch.new", &json!({"name": "Brand", "color": "#2050a0", "global": true})).unwrap();
|
||||
let brand = s.doc().unwrap().doc.tint_paint("Brand", 1.0).unwrap();
|
||||
let mut tinted = serde_json::to_value(s.doc().unwrap().doc.tint_paint("Brand", 1.0).unwrap()).unwrap();
|
||||
// The command takes the color of the link at the tint, whatever color is sent.
|
||||
tinted["tint"] = json!(0.4);
|
||||
let attrs = json!({"fill": brand, "stroke": tinted, "stroke_width": 2.0, "overprint_fill": true, "overprint_stroke": false,
|
||||
"features": ["dlig", "-liga", "tnum", "lnum", "-onum", "-pnum", "ss02", "-ss01"]});
|
||||
s.execute("charStyle.new", &json!({"name": "Ink", "attrs": attrs})).unwrap();
|
||||
s.execute("charStyle.apply", &json!({"name": "Ink", "id": id})).unwrap();
|
||||
let want_stroke = s.doc().unwrap().doc.tint_paint("Brand", 0.4).unwrap();
|
||||
assert_eq!(run_paints(&s, id), (brand, want_stroke.clone(), 2.0, true, false));
|
||||
assert_eq!(runs(&s, id)[0].style.features, ["dlig", "-liga", "tnum", "lnum", "-onum", "-pnum", "ss02", "-ss01"]);
|
||||
let def = |s: &Session| s.doc().unwrap().doc.char_styles.iter().find(|d| d.name == "Ink").unwrap().attrs.clone();
|
||||
assert_eq!(def(&s)["stroke"], serde_json::to_value(&want_stroke).unwrap());
|
||||
let saved = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
assert_eq!(saved.char_styles.iter().find(|d| d.name == "Ink").unwrap().attrs, def(&s));
|
||||
|
||||
s.execute("swatch.edit", &json!({"name": "Brand", "color": "#a02050"})).unwrap();
|
||||
let (brand, tint40) = (s.doc().unwrap().doc.tint_paint("Brand", 1.0).unwrap(), s.doc().unwrap().doc.tint_paint("Brand", 0.4).unwrap());
|
||||
assert_eq!(run_paints(&s, id).0, brand);
|
||||
assert_eq!(run_paints(&s, id).1, tint40);
|
||||
assert_eq!(def(&s)["fill"], serde_json::to_value(&brand).unwrap());
|
||||
assert_eq!(def(&s)["stroke"], serde_json::to_value(&tint40).unwrap());
|
||||
let later = s.execute("text.create", &json!({"x": 10, "y": 90, "text": "Later"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("charStyle.apply", &json!({"name": "Ink", "id": later})).unwrap();
|
||||
assert_eq!(run_paints(&s, later).0, brand);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn character_style_color_and_features_are_checked() {
|
||||
let (mut s, _) = session_with_text("Text");
|
||||
s.execute("swatch.new", &json!({"name": "Brand", "color": "#2050a0", "global": true})).unwrap();
|
||||
s.execute("charStyle.new", &json!({"name": "Body", "attrs": {}})).unwrap();
|
||||
let mut over = serde_json::to_value(s.doc().unwrap().doc.tint_paint("Brand", 1.0).unwrap()).unwrap();
|
||||
over["tint"] = json!(1.5);
|
||||
let mut missing = over.clone();
|
||||
missing["tint"] = json!(0.5);
|
||||
missing["swatch"] = json!("Gone");
|
||||
s.execute("swatch.new", &json!({"name": "Local", "color": "#102030"})).unwrap();
|
||||
let mut local = missing.clone();
|
||||
local["swatch"] = json!("Local");
|
||||
let many: Vec<String> = (0..=vectorcraft_text::MAX_STYLE_FEATURES).map(|_| "dlig".to_string()).collect();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
for (attrs, message) in [
|
||||
(json!({"fill": over}), "`fill.tint` must be from 0 to 1"),
|
||||
(json!({"stroke": missing}), "no swatch `Gone`"),
|
||||
(json!({"stroke": local}), "`Local` is a process colour"),
|
||||
(json!({"stroke_width": -1.0}), "`stroke_width` must be from 0 to 4000000"),
|
||||
(json!({"stroke_width": 5.0e6}), "`stroke_width` must be from 0 to 4000000"),
|
||||
(json!({"features": ["dlig", "zzzz"]}), "unknown OpenType feature `zzzz`"),
|
||||
(json!({"features": ["--liga"]}), "unknown OpenType feature `--liga`"),
|
||||
(json!({"features": many}), "features lists at most 256 tags"),
|
||||
(json!({"fill": {"type": "solid"}}), "missing field"),
|
||||
] {
|
||||
for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] {
|
||||
let p = match cmd {
|
||||
"charStyle.edit" => json!({"name": "Body", "to": "Body", "attrs": attrs}),
|
||||
"charStyle.new" => json!({"name": "Other", "attrs": attrs}),
|
||||
_ => json!({"name": "Body", "attrs": attrs}),
|
||||
};
|
||||
let error = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert!(error.contains(message), "{cmd} {attrs}: {error}");
|
||||
}
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn style_paints_count_as_swatch_uses_and_gradient_stops_are_checked() {
|
||||
let (mut s, _) = session_with_text("Text");
|
||||
s.execute("swatch.new", &json!({"name": "Brand", "color": "#2050a0", "global": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Spare", "color": "#a02050", "global": true})).unwrap();
|
||||
let unused = |s: &mut Session| s.execute("swatch.unused", &json!({})).unwrap()["names"].clone();
|
||||
assert!(unused(&mut s).as_array().unwrap().contains(&json!("Brand")));
|
||||
let brand = s.doc().unwrap().doc.tint_paint("Brand", 0.5).unwrap();
|
||||
s.execute("charStyle.new", &json!({"name": "Ink", "attrs": {"stroke": brand}})).unwrap();
|
||||
let names = unused(&mut s);
|
||||
assert!(!names.as_array().unwrap().contains(&json!("Brand")), "{names}");
|
||||
assert!(names.as_array().unwrap().contains(&json!("Spare")), "{names}");
|
||||
|
||||
let mut g = vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default());
|
||||
g.gradient.stops[0].swatch = Some("Brand".into());
|
||||
g.gradient.stops[0].tint = 0.25;
|
||||
let fill = serde_json::to_value(vectorcraft_color::Paint::Gradient(Box::new(g.clone()))).unwrap();
|
||||
s.execute("charStyle.new", &json!({"name": "Fade", "attrs": {"fill": fill}})).unwrap();
|
||||
let def = s.doc().unwrap().doc.char_styles.iter().find(|d| d.name == "Fade").unwrap().attrs.clone();
|
||||
let want = s.doc().unwrap().doc.global_color("Brand").unwrap().tinted(0.25);
|
||||
assert_eq!(def["fill"]["gradient"]["stops"][0]["color"], serde_json::to_value(want).unwrap());
|
||||
g.gradient.stops[0].swatch = Some("Gone".into());
|
||||
let gone = serde_json::to_value(vectorcraft_color::Paint::Gradient(Box::new(g))).unwrap();
|
||||
let error = s.execute("charStyle.new", &json!({"name": "Bad", "attrs": {"fill": gone}})).unwrap_err().to_string();
|
||||
assert!(error.contains("no swatch `Gone`"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_from_files_keep_their_unknown_feature_tags_and_swatch_links() {
|
||||
let (mut s, _) = session_with_text("Text");
|
||||
s.execute("charStyle.new", &json!({"name": "Body", "attrs": {}})).unwrap();
|
||||
let linked = json!({"type": "solid", "color": {"model": "rgb", "r": 1.0, "g": 0.0, "b": 0.0}, "swatch": "Gone"});
|
||||
if let Some(def) = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).char_styles.iter_mut().find(|d| d.name == "Body") {
|
||||
def.attrs.insert("features".into(), json!(["zzzz", "dlig"]));
|
||||
def.attrs.insert("fill".into(), linked.clone());
|
||||
}
|
||||
let fill = s.doc().unwrap().doc.char_styles[0].attrs["fill"].clone();
|
||||
s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {"features": ["zzzz", "-dlig"], "fill": fill}})).unwrap();
|
||||
let def = s.doc().unwrap().doc.char_styles.iter().find(|d| d.name == "Body").unwrap().attrs.clone();
|
||||
assert_eq!(def["features"], json!(["zzzz", "-dlig"]));
|
||||
let mut replaced = def.clone();
|
||||
replaced.insert("size".into(), json!(14.0));
|
||||
s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": replaced})).unwrap();
|
||||
s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": def})).unwrap();
|
||||
s.execute("charStyle.duplicate", &json!({"name": "Body"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.char_styles.iter().find(|d| d.name == "Body copy").unwrap().attrs, def);
|
||||
// A list longer than a style made here can have stays editable, but does not grow.
|
||||
let long: Vec<String> = (0..300).map(|i| if i % 2 == 0 { "dlig".to_string() } else { "-dlig".to_string() }).collect();
|
||||
if let Some(def) = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).char_styles.iter_mut().find(|d| d.name == "Body") {
|
||||
def.attrs.insert("features".into(), json!(long));
|
||||
}
|
||||
let mut shorter = long.clone();
|
||||
shorter.pop();
|
||||
s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {"features": shorter}})).unwrap();
|
||||
let mut longer = shorter.clone();
|
||||
longer.extend(["swsh".to_string(), "salt".to_string()]);
|
||||
let error = s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {"features": longer}})).unwrap_err().to_string();
|
||||
assert!(error.contains("features lists at most 256 tags"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_character_style_clears_removed_size_without_losing_local_override() {
|
||||
let (mut s, id) = session_with_text("One two");
|
||||
|
||||
@@ -93,7 +93,12 @@ thread_local! {
|
||||
/// makes "changed" a pointer comparison). Deleted frames' text flows into the remaining ones; a
|
||||
/// frame that is now point type leaves its thread with the text it holds.
|
||||
pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|
||||
let threads = std::mem::take(&mut doc.text_threads);
|
||||
// A frame is in one thread, once: a file that lists it again (in its thread or another) would
|
||||
// copy its text into the story each time, and write the grown story back for the next thread
|
||||
// to copy again. Only its first place counts.
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let threads: Vec<Vec<NodeId>> =
|
||||
std::mem::take(&mut doc.text_threads).into_iter().map(|t| t.into_iter().filter(|id| seen.insert(*id)).collect()).collect();
|
||||
let mut kept = vec![];
|
||||
for thread in threads {
|
||||
let changed = thread.iter().any(|id| match (before.node(*id), doc.node(*id)) {
|
||||
|
||||
@@ -40,6 +40,24 @@ fn thread_flows_reflows_on_edit_and_survives_delete() {
|
||||
assert_eq!(s.doc().unwrap().doc.text_threads.len(), 1);
|
||||
}
|
||||
|
||||
/// A file that lists a frame more than once, in its own thread or in another, flows the story
|
||||
/// through each frame once: repeated places would copy its text again and again.
|
||||
#[test]
|
||||
fn frames_listed_twice_flow_the_story_once() {
|
||||
let (mut s, a, b) = setup();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
let mut d = (*s.doc().unwrap().doc).clone();
|
||||
let (fa, fb) = (NodeId(a), NodeId(b));
|
||||
d.text_threads = vec![vec![fa, fb, fa, fb, fa], vec![fb, fa], vec![fa, fb]];
|
||||
reflow(&Document::new(1.0, 1.0), &mut d);
|
||||
assert_eq!(d.text_threads, vec![vec![fa, fb]]);
|
||||
let plain = |id: NodeId| match &d.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => t.plain_text(),
|
||||
_ => panic!("not text"),
|
||||
};
|
||||
assert_eq!(format!("{}{}", plain(fa), plain(fb)), TEXT.repeat(4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_copy_only_the_stories_of_threads_whose_frames_changed() {
|
||||
let (mut s, a, b) = setup();
|
||||
|
||||
@@ -123,7 +123,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour, keepModel?: bool (as paint.setFill), features?: [\"dlig\", \"-liga\", …] OpenType, featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
|
||||
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", …] OpenType, featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
|
||||
has_doc,
|
||||
set_style
|
||||
),
|
||||
@@ -785,11 +785,21 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => None,
|
||||
};
|
||||
super::paint::check_keep_model(p, C)?;
|
||||
let fill = match p.get("fill") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(n)) if n.eq_ignore_ascii_case("none") => Some(vectorcraft_color::Paint::None),
|
||||
Some(v) => Some(vectorcraft_color::Paint::solid(super::paint::new_color(s, p, color_value(v).ok_or_else(|| bad(C, "bad fill colour"))?))),
|
||||
let paint = |k: &str| -> Result<Option<vectorcraft_color::Paint>> {
|
||||
Ok(match p.get(k) {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(n)) if n.eq_ignore_ascii_case("none") => Some(vectorcraft_color::Paint::None),
|
||||
Some(v) => {
|
||||
Some(vectorcraft_color::Paint::solid(super::paint::new_color(s, p, color_value(v).ok_or_else(|| bad(C, format!("bad {k} colour")))?)))
|
||||
}
|
||||
})
|
||||
};
|
||||
let fill = paint("fill")?;
|
||||
let stroke = paint("stroke")?;
|
||||
check_numbers(p, &["strokeWidth"], C)?;
|
||||
// The weight of the character stroke.
|
||||
let mut stroke_weight = super::stroke::StrokeChange::default();
|
||||
stroke_weight.weight = p.get("strokeWidth").and_then(Value::as_f64).map(|w| w.clamp(0.0, 1000.0));
|
||||
let features = super::textedit::features_param(p, C)?;
|
||||
let feature_changes = super::textedit::feature_changes_param(p, C)?;
|
||||
if font.is_none()
|
||||
@@ -799,6 +809,8 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& tracking.is_none()
|
||||
&& justify.is_none()
|
||||
&& fill.is_none()
|
||||
&& stroke.is_none()
|
||||
&& stroke_weight.is_empty()
|
||||
&& features.is_none()
|
||||
&& feature_changes.is_none()
|
||||
{
|
||||
@@ -814,6 +826,8 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
|
||||
let size = size.map(|v| local_type_value(t, v, (0.1, 1296.0), false, C)).transpose()?;
|
||||
let leading = leading.map(|v| v.map(|v| local_type_value(t, v, (0.1, 5000.0), false, C)).transpose()).transpose()?;
|
||||
// The stroke weight is in document points, as stroke.set gives it; the character stroke is drawn in text space.
|
||||
let k = vectorcraft_doc::Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0);
|
||||
let before = protect.then(|| t.runs.clone());
|
||||
style_chars(t, range, |st| {
|
||||
if let Some(f) = &font {
|
||||
@@ -843,6 +857,16 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(f) = &fill {
|
||||
st.fill = f.clone();
|
||||
}
|
||||
if let Some(f) = &stroke {
|
||||
// A painted stroke on a run without a weight gets 1 pt, as with paint.setStroke.
|
||||
if !f.is_none() {
|
||||
super::gradient::run_stroke_weight(st);
|
||||
}
|
||||
st.stroke = f.clone();
|
||||
}
|
||||
if !stroke_weight.is_empty() {
|
||||
stroke_weight.apply_char_scaled(st, k);
|
||||
}
|
||||
if let Some(f) = &features {
|
||||
st.features = f.clone();
|
||||
}
|
||||
@@ -899,6 +923,15 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(f) = &fill {
|
||||
st.fill = f.clone();
|
||||
}
|
||||
if let Some(f) = &stroke {
|
||||
if !f.is_none() {
|
||||
super::gradient::run_stroke_weight(st);
|
||||
}
|
||||
st.stroke = f.clone();
|
||||
}
|
||||
if !stroke_weight.is_empty() {
|
||||
stroke_weight.apply_char(st);
|
||||
}
|
||||
if let Some(f) = &features {
|
||||
st.features = f.clone();
|
||||
}
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
//! variable, anything to a `visibility` variable, a linked image to an `image`
|
||||
//! variable, or a graph root to a `graph` variable (CSV data), put a row of values in
|
||||
//! each dataset, and `dataset.select` swaps the whole document to that row in one undo
|
||||
//! step. `dataset.import` / `dataset.export` move those rows as CSV (header: `name`
|
||||
//! then variable names, which export writes with `#` before a visibility variable and `@`
|
||||
//! before an image variable); import also reads tab-separated files, files without the
|
||||
//! `name` column, and header cells that define new variables (`#` for visibility, `@` for
|
||||
//! image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the
|
||||
//! step. `dataset.import` / `dataset.export` move those rows as CSV (header: one
|
||||
//! variable name per column, which export writes with `#` before a visibility variable and `@`
|
||||
//! before an image variable); import replaces the datasets, names the rows Data Set 1, 2…,
|
||||
//! also reads tab-separated files, and reads header cells that define new variables (`#` for
|
||||
//! visibility, `@` for image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the
|
||||
//! text variables and data sets of a variable library, the XML file of the reference app's Save
|
||||
//! Variable Library, and `variable.saveLibrary` writes the text variables and data sets as one.
|
||||
//! Agents reach every command through `run_command`, like all engine commands.
|
||||
@@ -838,7 +838,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Import Data Sets…",
|
||||
["Window", "Variables"],
|
||||
None,
|
||||
"{path? | data? | dataBase64? | csv?} load datasets from CSV, comma- or tab-separated, in UTF-16 with a byte-order mark, UTF-8 or else Windows-1252 (header: name, then variable names; one row per dataset; without the name column every header is a variable and the rows take the first free names Data Set 1, 2…). A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. Rows whose name already exists are replaced → {imported, updated, names, defined}",
|
||||
"{path? | data? | dataBase64? | csv?} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 with a byte-order mark, UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}",
|
||||
has_doc,
|
||||
dataset_import
|
||||
),
|
||||
@@ -847,7 +847,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Data Sets…",
|
||||
["Window", "Variables"],
|
||||
None,
|
||||
"{path?} write every dataset as CSV (header: name, then one column per variable: `#Name` for a visibility variable, `@Name` for an image variable, and the name alone for a text or graph variable, as dataset.import reads them). Refused when the document has more than 1000 data sets or 256 variables, the most dataset.import reads, or when a variable's header is another variable's name (a visibility variable `Show` next to a text variable `#Show`) → {path, datasets, warning?}; without path → {csv, datasets, warning?}. `warning` names the variables whose header or values make a document without them refuse the file (a % header, a # header whose values aren't true or false); otherwise it names the variables such a document doesn't read back with their kind (text variables whose names start with # or @, graph variables)",
|
||||
"{path?} write every dataset as CSV (header: one column per variable and no dataset names: `#Name` for a visibility variable, `@Name` for an image variable, and the name alone for a text or graph variable, as dataset.import reads them). Refused when the document has more than 1000 data sets or 256 variables, the most dataset.import reads, or when a variable's header is another variable's name (a visibility variable `Show` next to a text variable `#Show`) → {path, datasets, warning?}; without path → {csv, datasets, warning?}. `warning` names the variables whose header or values make a document without them refuse the file (a % header, a # header whose values aren't true or false); otherwise it names the variables such a document doesn't read back with their kind (text variables whose names start with # or @, graph variables)",
|
||||
has_doc,
|
||||
dataset_export
|
||||
),
|
||||
|
||||
@@ -102,7 +102,8 @@ fn tab_separated(text: &str) -> bool {
|
||||
/// by commas, or by tabs when [`tab_separated`] says so. `"` quotes a cell (doubled inside),
|
||||
/// which may then hold separators and line breaks, as [`csv_escape`] writes them. An unquoted
|
||||
/// cell is trimmed. A quoted cell keeps what its quotes hold as written, spaces included, and
|
||||
/// drops white space after the closing quote at the end of the cell. Blank lines are skipped.
|
||||
/// drops white space after the closing quote at the end of the cell. A line whose cells are all
|
||||
/// blank and unquoted is skipped; a quoted empty cell keeps its line as a row.
|
||||
fn parse_datasets_csv(text: &str, cmd: &str) -> Result<Vec<CsvRow>> {
|
||||
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
|
||||
let sep = if tab_separated(text) { '\t' } else { ',' };
|
||||
@@ -132,7 +133,10 @@ fn parse_datasets_csv(text: &str, cmd: &str) -> Result<Vec<CsvRow>> {
|
||||
Some('\n') | None if !in_quotes => {
|
||||
quoted.push(closed.is_some());
|
||||
row.push(end_csv_cell(&mut cur, &mut closed));
|
||||
if row.iter().any(|c| !c.trim().is_empty()) {
|
||||
if row.len() > MAX_CSV_COLS {
|
||||
return Err(bad(cmd, format!("line {line}: more than {MAX_CSV_COLS} columns")));
|
||||
}
|
||||
if row.iter().any(|c| !c.trim().is_empty()) || quoted.contains(&true) {
|
||||
rows.push((start, std::mem::take(&mut row), std::mem::take(&mut quoted)));
|
||||
// +1 for the header.
|
||||
if rows.len() > MAX_CSV_ROWS + 1 {
|
||||
@@ -174,8 +178,10 @@ fn end_csv_cell(cur: &mut String, closed: &mut Option<usize>) -> String {
|
||||
}
|
||||
|
||||
fn csv_escape(s: &str) -> String {
|
||||
// An empty string is quoted so that it reads back as an empty value, not as a missing one.
|
||||
if s.is_empty() || s.contains([',', '"', '\n', '\r']) || s != s.trim() { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() }
|
||||
// An empty string is quoted so that it reads back as an empty value, not as a missing one. A
|
||||
// tab is quoted so that a header of one variable whose name holds a tab isn't read as
|
||||
// tab-separated.
|
||||
if s.is_empty() || s.contains([',', '"', '\n', '\r', '\t']) || s != s.trim() { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() }
|
||||
}
|
||||
|
||||
/// A visibility cell: true/false, 1/0, yes/no (ASCII, case-insensitive). An error names the
|
||||
@@ -240,8 +246,7 @@ fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) {
|
||||
for (i, v) in vars.variables.iter().enumerate() {
|
||||
let header = export_header(v);
|
||||
let cell = header.trim();
|
||||
// Column 1 holds the dataset names.
|
||||
let read = if cell.is_empty() { None } else { header_variable(cell, i + 2, &none, &mut defined, C).ok() };
|
||||
let read = if cell.is_empty() { None } else { header_variable(cell, i + 1, &none, &mut defined, C).ok() };
|
||||
// The import refuses a header that names a variable an earlier column named.
|
||||
let Some((name, kind)) = read.filter(|(name, _)| seen.insert(name.clone())) else {
|
||||
refused.push(v.name.as_str());
|
||||
@@ -260,30 +265,36 @@ fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) {
|
||||
(refused, other)
|
||||
}
|
||||
|
||||
/// Build the CSV of every dataset (header `name` then each variable's [`export_header`] in
|
||||
/// definition order). Refused when a variable's header is another variable's name, which the
|
||||
/// import reads as that variable (a visibility variable `Show` next to a text variable `#Show`).
|
||||
/// Build the CSV of every dataset: a header of each variable's [`export_header`] in definition
|
||||
/// order, then one row per dataset. The dataset names are not written. Refused when a variable's
|
||||
/// header is another variable's name, which the import reads as that variable (a visibility
|
||||
/// variable `Show` next to a text variable `#Show`). A dataset with no value for any variable would
|
||||
/// be a blank line, which the import skips, so its row gets a quoted empty cell: in the first column
|
||||
/// whose variable isn't a text variable, where it reads back as no value, or else in the first
|
||||
/// column, where it reads back as an empty text.
|
||||
fn datasets_to_csv(vars: &Variables, cmd: &str) -> Result<String> {
|
||||
let names: BTreeSet<&str> = vars.variables.iter().map(|v| v.name.as_str()).collect();
|
||||
let mut out = String::from("name");
|
||||
let mut header = Vec::with_capacity(vars.variables.len());
|
||||
for v in &vars.variables {
|
||||
let header = export_header(v);
|
||||
if header != v.name && names.contains(header.as_str()) {
|
||||
let (name, other) = (&v.name, &header);
|
||||
return Err(bad(cmd, format!("the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them")));
|
||||
let cell = export_header(v);
|
||||
if cell != v.name && names.contains(cell.as_str()) {
|
||||
let (name, other) = (&v.name, &cell);
|
||||
return Err(bad(cmd, format!("the header `{cell}` for `{name}` would read back as the variable `{other}`: rename one of them")));
|
||||
}
|
||||
out.push(',');
|
||||
out.push_str(&csv_escape(&header));
|
||||
header.push(csv_escape(&cell));
|
||||
}
|
||||
let mut out = header.join(",");
|
||||
out.push('\n');
|
||||
let keep = vars.variables.iter().position(|v| v.kind != VariableKind::Text).unwrap_or(0);
|
||||
for ds in &vars.datasets {
|
||||
out.push_str(&csv_escape(&ds.name));
|
||||
for v in &vars.variables {
|
||||
out.push(',');
|
||||
if let Some(val) = ds.values.get(&v.name) {
|
||||
out.push_str(&csv_escape(&value_to_cell(val)));
|
||||
}
|
||||
let mut row: Vec<String> =
|
||||
vars.variables.iter().map(|v| ds.values.get(&v.name).map(|val| csv_escape(&value_to_cell(val))).unwrap_or_default()).collect();
|
||||
if row.iter().all(String::is_empty)
|
||||
&& let Some(cell) = row.get_mut(keep)
|
||||
{
|
||||
*cell = csv_escape("");
|
||||
}
|
||||
out.push_str(&row.join(","));
|
||||
out.push('\n');
|
||||
}
|
||||
Ok(out)
|
||||
@@ -329,12 +340,11 @@ fn header_variable(
|
||||
}
|
||||
}
|
||||
|
||||
/// Import datasets from CSV. A first header cell `name` makes the first column the dataset
|
||||
/// names; the other headers name variables, as [`header_variable`] reads them, and the
|
||||
/// variables the document doesn't define yet are defined, unbound. Without the `name` column,
|
||||
/// every header names a variable and the rows take the first free names "Data Set 1", "Data
|
||||
/// Set 2" and so on. Two headers that name one variable are refused. Existing rows of the same
|
||||
/// name are replaced; new names are appended. One undo step.
|
||||
/// Import datasets from CSV. Every header cell names a variable, as [`header_variable`] reads it,
|
||||
/// and the variables the document doesn't define yet are defined, unbound. Two headers that name
|
||||
/// one variable are refused. The rows replace every dataset of the document and are named "Data
|
||||
/// Set 1", "Data Set 2" and so on, in file order. The document's variables and their bindings
|
||||
/// stay. One undo step, and none when the variables and datasets stay as they were.
|
||||
pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "dataset.import";
|
||||
let (bytes, given_as_text) = datasets_csv_bytes(p, C)?;
|
||||
@@ -344,16 +354,10 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let Some((_, header, _)) = rows.first() else {
|
||||
return Err(bad(C, "CSV is empty"));
|
||||
};
|
||||
let name_column = header.first().is_some_and(|h| h.trim().eq_ignore_ascii_case("name"));
|
||||
let (kinds, existing_names) = {
|
||||
let st = s.doc()?;
|
||||
let kinds: BTreeMap<String, VariableKind> = st.doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind)).collect();
|
||||
let existing: BTreeSet<String> = st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect();
|
||||
(kinds, existing)
|
||||
};
|
||||
let kinds: BTreeMap<String, VariableKind> = s.doc()?.doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind)).collect();
|
||||
let mut columns: Vec<(usize, String, VariableKind)> = Vec::new();
|
||||
let mut defined: Vec<Variable> = Vec::new();
|
||||
for (i, h) in header.iter().enumerate().skip(usize::from(name_column)) {
|
||||
for (i, h) in header.iter().enumerate() {
|
||||
let cell = h.trim();
|
||||
if cell.is_empty() {
|
||||
return Err(bad(C, format!("empty header in column {}", i + 1)));
|
||||
@@ -373,27 +377,8 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "CSV has a header but no data rows"));
|
||||
}
|
||||
let mut parsed: Vec<DataSet> = Vec::new();
|
||||
// The names of the rows read so far, and the last number given to a row without a name.
|
||||
let (mut seen, mut number) = (BTreeSet::new(), 0usize);
|
||||
for &(line, ref row, ref quoted) in rows.iter().skip(1) {
|
||||
let raw_name = if name_column { row.first().map_or("", |c| c.trim()) } else { "" };
|
||||
let name = if raw_name.is_empty() {
|
||||
// Same numbering as Capture Data Set when a row leaves the name blank or the file has
|
||||
// no name column. The search starts after the last number given.
|
||||
let (n, name) = (number + 1..)
|
||||
.map(|n| (n, format!("Data Set {n}")))
|
||||
.find(|(_, n)| !seen.contains(n) && !existing_names.contains(n))
|
||||
.unwrap_or_else(|| (line, format!("Data Set {line}")));
|
||||
number = n;
|
||||
name
|
||||
} else if raw_name.chars().count() > MAX_NAME {
|
||||
return Err(bad(C, format!("line {line}: `name` is longer than {MAX_NAME} characters")));
|
||||
} else {
|
||||
raw_name.to_string()
|
||||
};
|
||||
if !seen.insert(name.clone()) {
|
||||
return Err(bad(C, format!("line {line}: dataset `{name}` appears twice")));
|
||||
}
|
||||
for (n, &(line, ref row, ref quoted)) in rows.iter().skip(1).enumerate() {
|
||||
let name = format!("Data Set {}", n + 1);
|
||||
let mut values = BTreeMap::new();
|
||||
for &(col, ref var, kind) in &columns {
|
||||
let cell = row.get(col).map(String::as_str).unwrap_or("");
|
||||
@@ -406,26 +391,23 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let names: Vec<String> = parsed.iter().map(|d| d.name.clone()).collect();
|
||||
let new_variables: Vec<String> = defined.iter().map(|v| v.name.clone()).collect();
|
||||
let deleted: Vec<String> = s.doc()?.doc.variables.datasets.iter().map(|d| d.name.clone()).collect();
|
||||
// The import is one undo step, and an import that leaves the variables and data sets as they
|
||||
// were adds none.
|
||||
let (imported, updated) = super::edit_variables(s, "Import Data Sets", |vars| {
|
||||
vars.variables.extend(defined);
|
||||
let (mut imported, mut updated) = (0usize, 0usize);
|
||||
for row in parsed {
|
||||
if let Some(existing) = vars.datasets.iter_mut().find(|x| x.name == row.name) {
|
||||
*existing = row;
|
||||
updated += 1;
|
||||
} else {
|
||||
vars.datasets.push(row);
|
||||
imported += 1;
|
||||
}
|
||||
// were adds none, so the active data set stays when nothing changes.
|
||||
super::edit_variables(s, "Import Data Sets", |vars| {
|
||||
if defined.is_empty() && vars.datasets == parsed {
|
||||
return Ok(());
|
||||
}
|
||||
Ok((imported, updated))
|
||||
vars.variables.extend(defined);
|
||||
vars.datasets = parsed;
|
||||
vars.active_dataset = None;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"imported": imported, "updated": updated, "names": names, "defined": new_variables}))
|
||||
Ok(json!({"imported": names.len(), "names": names, "defined": new_variables, "deletedDataSets": deleted}))
|
||||
}
|
||||
|
||||
/// Export every dataset as CSV ([`datasets_to_csv`]). With `path`, write the file; else return
|
||||
/// Export every dataset as CSV ([`datasets_to_csv`]: one column per variable, no dataset names).
|
||||
/// With `path`, write the file; else return
|
||||
/// `{csv}`. The reply's `warning` names the variables whose column makes a document without them
|
||||
/// refuse the file, or else the variables it doesn't read back with their kind
|
||||
/// ([`kinds_a_new_document_loses`]); the app shows it in its status bar.
|
||||
@@ -439,7 +421,6 @@ pub(super) fn dataset_export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if st.doc.variables.datasets.len() > MAX_CSV_ROWS {
|
||||
return Err(bad(C, format!("more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS}")));
|
||||
}
|
||||
// The name column comes first, so the import's column cap leaves room for this many variables.
|
||||
if st.doc.variables.variables.len() > MAX_CSV_COLS {
|
||||
return Err(bad(C, format!("more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS}")));
|
||||
}
|
||||
|
||||
@@ -52,6 +52,9 @@ pub struct DocState {
|
||||
pub recalled_selection: RecalledSelection,
|
||||
/// Process-unique id of this open document (tab indices shift when tabs close).
|
||||
pub uid: u64,
|
||||
/// Preferences › User Interface › Open Documents As Tabs when the document opened: cleared,
|
||||
/// the UI opens it in a floating window of its own.
|
||||
pub opened_as_tab: bool,
|
||||
/// View Opacity Mask (Alt-click the mask thumbnail): the masked object whose mask the canvas
|
||||
/// shows alone, in greyscale, while that mask is edited (see [`DocState::shown_mask`]).
|
||||
pub mask_view: Option<NodeId>,
|
||||
@@ -255,6 +258,7 @@ impl DocState {
|
||||
last_selection_cmd: None,
|
||||
recalled_selection: RecalledSelection::default(),
|
||||
uid: NEXT_DOC_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||
opened_as_tab: true,
|
||||
mask_view: None,
|
||||
transparency_grid,
|
||||
format: "vectorcraft",
|
||||
|
||||
@@ -163,6 +163,11 @@ pub struct Session {
|
||||
/// While [`Session::place_queue_read`] runs `file.place.queue`: the files read for it, which
|
||||
/// the command loads the place cursor with instead of reading them; `None` otherwise.
|
||||
pub(crate) queue_hand_off: Option<cmd::place::QueueRead>,
|
||||
/// The automation roots in force when the place cursor was last loaded (`None`: none were).
|
||||
/// The cursor places its files later, on a click that may come from the person at the
|
||||
/// keyboard: those files, and the files they link to, are read under these roots, so a queue
|
||||
/// an agent loaded never reads beyond what it was given.
|
||||
pub(crate) place_queue_roots: Option<std::sync::Arc<file_access::AutomationRoots>>,
|
||||
/// While [`Session::import_image_read`] runs `clipboard.importImage`: the image read for it,
|
||||
/// which the command loads instead of reading `dataBase64`; `None` otherwise.
|
||||
pub(crate) image_hand_off: Option<cmd::clipboard::ImageRead>,
|
||||
@@ -198,6 +203,12 @@ pub struct Session {
|
||||
/// The pointer button is held: the last pointer event was a press or a drag, not a release or
|
||||
/// a move ([`Session::pointer_held`]).
|
||||
pub(crate) pointer_held: bool,
|
||||
/// The id and persistent options of the tool when the press under way began, which a dropped
|
||||
/// press puts back ([`Session::drop_tool_press`]).
|
||||
pub(crate) press_options: Option<(String, serde_json::Map<String, serde_json::Value>)>,
|
||||
/// The freeform gradient point selected once the tool took the press under way, which a
|
||||
/// dropped press selects again ([`Session::drop_tool_press`]).
|
||||
pub(crate) press_point: Option<Option<(usize, cmd::gradient::StopOwner)>>,
|
||||
/// A guide being dragged out of a ruler ([`Session::ruler_guide`]).
|
||||
pub(crate) ruler_guide: Option<vectorcraft_tools::rulerguide::NewGuide>,
|
||||
/// Which selected type overflows its frame, for the ports every tool but the Type tools shows.
|
||||
|
||||
@@ -79,6 +79,7 @@ impl Session {
|
||||
batch_steps: None,
|
||||
place_hand_off: None,
|
||||
queue_hand_off: None,
|
||||
place_queue_roots: None,
|
||||
image_hand_off: None,
|
||||
trace_hand_off: None,
|
||||
place_cursor_requests: false,
|
||||
@@ -91,6 +92,8 @@ impl Session {
|
||||
liquify_stroke: None,
|
||||
plane_widget_press: false,
|
||||
pointer_held: false,
|
||||
press_options: None,
|
||||
press_point: None,
|
||||
ruler_guide: None,
|
||||
port_marks: Default::default(),
|
||||
font_search: None,
|
||||
@@ -206,6 +209,7 @@ impl Session {
|
||||
self.reset_tool_for_doc_switch();
|
||||
let mut st = DocState::new(doc, path);
|
||||
st.history.limit = self.prefs.history_states as usize;
|
||||
st.opened_as_tab = self.prefs.open_documents_as_tabs;
|
||||
self.docs.push(st);
|
||||
let i = self.docs.len() - 1;
|
||||
self.active = Some(i);
|
||||
@@ -236,6 +240,7 @@ impl Session {
|
||||
st.history.limit = old.history.limit;
|
||||
// Same open document (caches keyed by uid stay valid); a new revision redraws it.
|
||||
st.uid = old.uid;
|
||||
st.opened_as_tab = old.opened_as_tab;
|
||||
st.revision = old.revision + 1;
|
||||
st.format = old.format;
|
||||
st.save_options = old.save_options.clone();
|
||||
|
||||
@@ -350,6 +350,25 @@ fn type_only_copies_offer_their_text() {
|
||||
assert!(run(&mut s, "clipboard.exportText", json!({}))["text"].is_null());
|
||||
}
|
||||
|
||||
/// Art too large to fit the clipboard's PNG side at the encoder's smallest scale gets no PNG,
|
||||
/// instead of a picture hundreds of megabytes large.
|
||||
#[test]
|
||||
fn copy_leaves_out_the_png_of_art_too_large_to_scale_down() {
|
||||
let mut s = session();
|
||||
let id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 1_000_000, "height": 1_000_000}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [id]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
assert!(s.clipboard.flavour_types(false, false).contains(&PNG));
|
||||
assert!(s.clipboard.flavours(false, false).iter().all(|f| f.mime != PNG));
|
||||
// Art that fits at that scale still gets its PNG, at most 4096 pixels a side.
|
||||
let id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 200_000, "height": 100}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [id]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
let png = s.clipboard.flavours(false, false).into_iter().find(|f| f.mime == PNG).expect("a PNG");
|
||||
let img = image::load_from_memory(&png.data).unwrap();
|
||||
assert!(img.width() <= 4096 && img.height() <= 4096, "{}x{}", img.width(), img.height());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_offers_flavours_by_the_preferences() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -381,6 +381,33 @@ fn outlined_type_keeps_its_underline() {
|
||||
assert!(b.y1 > 151.0, "{b:?}");
|
||||
}
|
||||
|
||||
/// Flattening transparent type that runs over several lines gives a group per line, each holding
|
||||
/// that line's regions (#5252).
|
||||
#[test]
|
||||
fn flattening_multiline_transparent_text_gives_one_group_per_line() {
|
||||
let _settings = settings_lock();
|
||||
let mut s = session();
|
||||
let text =
|
||||
run(&mut s, "text.create", json!({"x": 10, "y": 40, "text": "First line\nSecond line\nThird line", "size": 24}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "transparency.set", json!({"ids": [text], "opacity": 50}));
|
||||
let NodeKind::Text(t) = &node(&s, text).kind else { panic!("type") };
|
||||
let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
let baselines: Vec<f64> = layout.baselines().iter().map(|(a, _)| (t.xf * *a).y).collect();
|
||||
assert_eq!(baselines.len(), 3, "{baselines:?}");
|
||||
let before = picture(&s);
|
||||
let (ids, vector, _) = flatten(&mut s, json!({"ids": [text]}));
|
||||
assert_eq!(ids.len(), 1);
|
||||
assert!(vector > 0);
|
||||
let g = node(&s, ids[0]);
|
||||
let lines: Vec<&std::sync::Arc<Node>> = g.children().unwrap().iter().filter(|c| matches!(c.kind, NodeKind::Group { .. })).collect();
|
||||
assert_eq!(lines.len(), 3, "expected one group per line, got {} children", g.children().unwrap().len());
|
||||
for (line, y) in lines.iter().zip(&baselines) {
|
||||
let b = line.geometric_bounds().unwrap();
|
||||
assert!(b.y0 > y - 24.0 && b.y1 < y + 10.0, "line at baseline {y} has bounds {b:?}");
|
||||
assert_regions_match(&s, &before, line.id.0, 2, "line");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outlined_type_keeps_its_gradient_on_the_outlines_its_transform_effect_moves() {
|
||||
let _settings = settings_lock();
|
||||
|
||||
@@ -331,3 +331,29 @@ fn type_objects_keep_points_in_text_space() {
|
||||
assert!(close(f.points[i].at, Point::new(90.0, 150.0)), "back in document coordinates: {:?}", f.points[i].at);
|
||||
assert_eq!(f.points[i].color, Color::rgb(1.0, 0.0, 1.0));
|
||||
}
|
||||
|
||||
/// A dropped press (a long touch, a canceled touch) of the Gradient tool that dragged a selected
|
||||
/// point out of the object, and out and back in, keeps the point and its selection.
|
||||
#[test]
|
||||
fn a_dropped_drag_of_a_point_keeps_it_selected() {
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
let (mut s, id) = freeform_rect();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("gradient", v).unwrap();
|
||||
let count = points(&s, id).points.len();
|
||||
assert!(count > 1, "a point can be dragged out");
|
||||
let at = s.proxy_freeform(false).unwrap().0.points[0].at;
|
||||
for back in [false, true] {
|
||||
run(&mut s, "paint.freeform.selectPoint", json!({"index": 0}));
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 400.0, 400.0), v).unwrap();
|
||||
assert_eq!(s.selected_freeform_point(), None, "the removal the drag previews deselects the point");
|
||||
if back {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, at.x + 5.0, at.y + 5.0), v).unwrap();
|
||||
}
|
||||
s.drop_tool_press(v).unwrap();
|
||||
assert!(!s.tool_busy(), "the tool is at rest");
|
||||
assert_eq!(points(&s, id).points.len(), count, "back inside: {back}");
|
||||
assert_eq!(s.selected_freeform_point(), Some(0), "back inside: {back}");
|
||||
}
|
||||
}
|
||||
@@ -1991,6 +1991,19 @@ fn select_same_text_fill_and_stroke_color_needs_both_to_match() {
|
||||
assert!(s.execute("select.same.textFillAndStrokeColor", &json!({})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_same_character_colors_ignore_empty_text() {
|
||||
let mut s = session();
|
||||
let a = id_of(&s.execute("text.create", &json!({"x": 0, "y": 20, "text": "a"})).unwrap());
|
||||
let b = id_of(&s.execute("text.create", &json!({"x": 0, "y": 40, "text": "b"})).unwrap());
|
||||
let empty = id_of(&s.execute("text.create", &json!({"x": 0, "y": 60, "text": ""})).unwrap());
|
||||
for cmd in ["select.same.textFillColor", "select.same.textStrokeColor", "select.same.textFillAndStrokeColor"] {
|
||||
sel(&mut s, &[a]);
|
||||
s.execute(cmd, &json!({})).unwrap();
|
||||
assert_eq!(selected(&s), vec![a, b], "{cmd}: empty object {empty:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_same_link_block_series_selects_the_frames_of_a_thread() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -460,3 +460,91 @@ fn options_and_expand_take_ids_without_a_selection() {
|
||||
assert_eq!(s.doc().unwrap().doc.node(g).unwrap().kind_label(), "Group");
|
||||
assert!(s.execute("object.objectsOnPath.expand", &json!({"ids": [g.0]})).is_err(), "no longer an Objects on Path group");
|
||||
}
|
||||
|
||||
/// The Space and start of group `g`.
|
||||
fn space(s: &Session, g: NodeId) -> (Option<f64>, f64) {
|
||||
let rec = s.doc().unwrap().doc.node(g).unwrap().extras().objects_on_path.as_deref().cloned().unwrap();
|
||||
(rec.spacing, rec.start)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn space_sets_the_distance_between_the_objects_in_one_undo_step() {
|
||||
let mut s = session();
|
||||
let ([left, middle, right], path) = squares_and_line(&mut s);
|
||||
let g = attach(&mut s, path, &[left, middle, right], json!({"rotate": 30, "pivot": 7}));
|
||||
assert_eq!(space(&s, g), (None, 0.0), "Auto");
|
||||
let before = (bounds(&s, left), bounds(&s, middle).width());
|
||||
s.execute("object.objectsOnPath.options", &json!({"spacing": 60})).unwrap();
|
||||
assert_eq!(space(&s, g), (Some(60.0), 0.0));
|
||||
// The first object stays; the others come 60 pt apart, keeping Pivot and Rotate.
|
||||
assert_eq!(bounds(&s, left), before.0);
|
||||
let x = |s: &Session, id| bounds(s, id).center().x - bounds(s, left).center().x;
|
||||
assert!((x(&s, middle) - 60.0).abs() < 1e-6 && (x(&s, right) - 120.0).abs() < 1e-6);
|
||||
assert!((bounds(&s, middle).width() - before.1).abs() < 1e-6, "still turned by Rotate");
|
||||
// Centered: from 90 pt along the 300 pt line.
|
||||
s.execute("object.objectsOnPath.options", &json!({"spacing": 60, "start": 90})).unwrap();
|
||||
assert!((x(&s, right) - 120.0).abs() < 1e-6);
|
||||
assert!((bounds(&s, left).center().x - before.0.center().x - 90.0).abs() < 1e-6);
|
||||
// Pivot and Rotate keep the Space.
|
||||
s.execute("object.objectsOnPath.options", &json!({"rotate": 0, "pivot": 4})).unwrap();
|
||||
assert_eq!(space(&s, g), (Some(60.0), 90.0));
|
||||
assert_eq!(
|
||||
(center(&s, left), center(&s, middle), center(&s, right)),
|
||||
(Point::new(140.0, 300.0), Point::new(200.0, 300.0), Point::new(260.0, 300.0))
|
||||
);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(space(&s, g), (Some(60.0), 0.0), "each change is one undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(space(&s, g), (None, 0.0));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(space(&s, g), (Some(60.0), 0.0));
|
||||
s.execute("object.objectsOnPath.options", &json!({"spacing": "auto", "start": 0})).unwrap();
|
||||
assert_eq!(space(&s, g), (None, 0.0));
|
||||
assert_eq!(center(&s, right).x - center(&s, left).x, 300.0, "Auto spreads them to the end again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_space_that_is_not_usable_is_refused_and_one_too_large_is_kept_to_the_path() {
|
||||
let mut s = session();
|
||||
let ([left, middle, right], path) = squares_and_line(&mut s);
|
||||
let g = attach(&mut s, path, &[left, middle, right], json!({}));
|
||||
for bad in
|
||||
[json!({"spacing": -1}), json!({"spacing": "wide"}), json!({"spacing": true}), json!({"start": "x"}), json!({"spacing": 10, "start": [1]})]
|
||||
{
|
||||
assert!(s.execute("object.objectsOnPath.options", &bad).is_err(), "{bad}");
|
||||
assert_eq!(space(&s, g), (None, 0.0), "{bad} changes nothing");
|
||||
}
|
||||
s.execute("object.objectsOnPath.options", &json!({"spacing": 1e9})).unwrap();
|
||||
assert_eq!(space(&s, g), (Some(1e9), 0.0));
|
||||
assert_eq!((center(&s, middle), center(&s, right)), (Point::new(200.0, 300.0), Point::new(350.0, 300.0)), "the last one reaches the end");
|
||||
// A shorter path draws them closer; the full length brings the Space back.
|
||||
s.execute("object.objectsOnPath.options", &json!({"spacing": 100})).unwrap();
|
||||
set_line(&mut s, path, (50.0, 300.0), (150.0, 300.0));
|
||||
assert_eq!((center(&s, middle), center(&s, right)), (Point::new(100.0, 300.0), Point::new(150.0, 300.0)));
|
||||
assert_eq!(space(&s, g), (Some(100.0), 0.0));
|
||||
set_line(&mut s, path, (50.0, 300.0), (350.0, 300.0));
|
||||
assert_eq!((center(&s, middle), center(&s, right)), (Point::new(150.0, 300.0), Point::new(250.0, 300.0)));
|
||||
// An object moved on its own goes back, and the Space stays.
|
||||
s.execute("object.move", &json!({"ids": [middle.0], "dx": 30, "dy": -40})).unwrap();
|
||||
assert_eq!(center(&s, middle), Point::new(150.0, 300.0));
|
||||
assert_eq!(space(&s, g), (Some(100.0), 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_space_saves_and_reopens_and_goes_with_a_copy() {
|
||||
let mut s = session();
|
||||
let ([left, middle, right], path) = squares_and_line(&mut s);
|
||||
let g = attach(&mut s, path, &[left, middle, right], json!({}));
|
||||
s.execute("object.objectsOnPath.options", &json!({"spacing": 40, "start": 25})).unwrap();
|
||||
let data = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].clone();
|
||||
let mut o = Session::new();
|
||||
o.execute("document.open", &json!({"name": "objects.vectorcraft", "dataBase64": data})).unwrap();
|
||||
assert_eq!(space(&o, g), (Some(40.0), 25.0));
|
||||
assert_eq!(center(&o, right), Point::new(155.0, 300.0));
|
||||
select(&mut s, &[g]);
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let copy = s.doc().unwrap().selection.objects.to_vec();
|
||||
assert_eq!(space(&s, copy[0]), (Some(40.0), 25.0));
|
||||
}
|
||||
@@ -722,6 +722,39 @@ fn a_queue_of_3_with_click_drag_and_esc_places_2() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), 2, "one undo step per placement");
|
||||
}
|
||||
|
||||
/// A place cursor loaded within automation roots places its files within them, even on a later
|
||||
/// click outside any roots (the person at the keyboard's): a queued file outside the roots, or
|
||||
/// one it links to, is not read then. One loaded outside any roots places as before.
|
||||
#[test]
|
||||
fn the_place_cursor_places_within_the_roots_it_was_loaded_in() {
|
||||
let base = std::env::temp_dir().join(format!("vectorcraft-place-roots-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("in")).unwrap();
|
||||
let outside = base.join("outside.png");
|
||||
std::fs::write(&outside, png(40, 20, [9, 9, 9, 255], None)).unwrap();
|
||||
let entry = json!({"params": {"path": outside.to_string_lossy()}, "name": "outside.png", "width": 40, "height": 20});
|
||||
let roots = crate::file_access::AutomationRoots::new(&[&base.join("in")], &[]).unwrap().unwrap();
|
||||
let view = ViewInfo::default();
|
||||
let click = |s: &mut Session| {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), view)?;
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 10.0, 10.0), view)
|
||||
};
|
||||
let mut s = session();
|
||||
s.select_tool("place", view).unwrap();
|
||||
// Loaded within the roots (as a tool option, past the check tool.setOption makes of paths).
|
||||
crate::file_access::confine(Some(&roots), || s.set_tool_option("queue", &json!({"entries": [entry]})));
|
||||
assert!(s.place_queue_roots().is_some());
|
||||
let placed = crate::file_access::unconfined(|| click(&mut s));
|
||||
assert!(top_children(&s).is_empty(), "{placed:?}");
|
||||
// Loaded outside any roots: the click places it.
|
||||
s.select_tool("place", view).unwrap();
|
||||
crate::file_access::unconfined(|| s.set_tool_option("queue", &json!({"entries": [entry]})));
|
||||
assert!(s.place_queue_roots().is_none());
|
||||
crate::file_access::unconfined(|| click(&mut s)).unwrap();
|
||||
assert_eq!(top_children(&s).len(), 1);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// With [`Session::place_cursor_requests`] set, a click of the place cursor asks the frontend to
|
||||
/// place its file ([`UiRequest::Place`]) and places nothing itself; the params it asks with place
|
||||
/// the file as the click places it without the flag.
|
||||
|
||||
@@ -139,6 +139,59 @@ fn feature_changes_keep_each_runs_other_features() {
|
||||
assert_eq!(features(&s), [vec!["smcp", "numr", "liga", "dnom"], vec!["swsh", "numr", "liga", "dnom"], vec!["-onum", "swsh", "dnom"]]);
|
||||
}
|
||||
|
||||
/// `text.setStyle {stroke, strokeWidth}` sets the character stroke of all the text or of a range, as
|
||||
/// `text.setRangeStyle` does, and a call with `fill` and `stroke` sets both in one undo step.
|
||||
#[test]
|
||||
fn set_style_sets_the_character_stroke() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let mut s = session();
|
||||
let id = text(&mut s, "Hello world");
|
||||
let paints =
|
||||
|s: &Session| obj(s, id).runs.iter().map(|r| (r.style.fill.color(), r.style.stroke.color(), r.style.stroke_width)).collect::<Vec<_>>();
|
||||
let red = Some(Color::rgb8(255, 0, 0));
|
||||
let blue = Some(Color::rgb8(0, 0, 255));
|
||||
let fill = obj(&s, id).runs[0].style.fill.color();
|
||||
s.execute("text.setStyle", &json!({"ids": [id.0], "stroke": "#ff0000", "strokeWidth": 2})).unwrap();
|
||||
assert_eq!(paints(&s), [(fill, red, 2.0)], "all the text");
|
||||
s.execute("text.setStyle", &json!({"ids": [id.0], "start": 6, "end": 11, "stroke": "#0000ff"})).unwrap();
|
||||
assert_eq!(paints(&s), [(fill, red, 2.0), (fill, blue, 2.0)], "a range");
|
||||
let before = paints(&s);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("text.setStyle", &json!({"ids": [id.0], "fill": "#0000ff", "stroke": "none", "strokeWidth": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
assert!(
|
||||
obj(&s, id).runs.iter().all(|r| r.style.fill.color() == blue && r.style.stroke == Paint::None && r.style.stroke_width == 0.0),
|
||||
"{:?}",
|
||||
paints(&s)
|
||||
);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(paints(&s), before, "undo restores the fill and the stroke");
|
||||
let e = s.execute("text.setStyle", &json!({"ids": [id.0], "stroke": "nope"})).unwrap_err().to_string();
|
||||
assert!(e.contains("bad stroke colour"), "{e}");
|
||||
assert!(s.execute("text.setStyle", &json!({"ids": [id.0], "strokeWidth": "x"})).is_err(), "strokeWidth must be a number");
|
||||
// The weight is in document points, as stroke.set gives it: type scaled 200% keeps half of it in text space.
|
||||
s.execute("object.scale", &json!({"ids": [id.0], "sx": 200, "sy": 200})).unwrap();
|
||||
s.execute("text.setStyle", &json!({"ids": [id.0], "strokeWidth": 2})).unwrap();
|
||||
assert!(obj(&s, id).runs.iter().all(|r| (r.style.stroke_width - 1.0).abs() < 1e-9), "{:?}", paints(&s));
|
||||
}
|
||||
|
||||
/// `text.setStyle {stroke}` without `strokeWidth` gives type with no stroke weight 1 pt, as
|
||||
/// `paint.setStroke` does, and keeps a weight the type already has.
|
||||
#[test]
|
||||
fn set_style_stroke_without_a_weight_draws_1_pt() {
|
||||
use vectorcraft_color::Color;
|
||||
let mut s = session();
|
||||
let id = text(&mut s, "Hello");
|
||||
assert_eq!(obj(&s, id).runs[0].style.stroke_width, 0.0);
|
||||
s.execute("text.setStyle", &json!({"ids": [id.0], "stroke": "#ff0000"})).unwrap();
|
||||
let st = &obj(&s, id).runs[0].style;
|
||||
assert_eq!((st.stroke.color(), st.stroke_width), (Some(Color::rgb8(255, 0, 0)), 1.0));
|
||||
assert!(st.has_stroke());
|
||||
s.execute("text.setStyle", &json!({"ids": [id.0], "strokeWidth": 3})).unwrap();
|
||||
s.execute("text.setStyle", &json!({"ids": [id.0], "stroke": "#0000ff"})).unwrap();
|
||||
assert_eq!(obj(&s, id).runs[0].style.stroke_width, 3.0, "an existing weight is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optical_command_manual_pair_undo_redo_and_native_reopen() {
|
||||
let mut s = session();
|
||||
@@ -1204,6 +1257,28 @@ fn type_tool_selection_replace_and_delete() {
|
||||
assert_eq!(obj(&s, id).plain_text(), " ");
|
||||
}
|
||||
|
||||
/// A Type tool click inside a ligature (Source Serif 4's fi) puts the caret between its
|
||||
/// characters, and Shift+Right from there selects the i alone.
|
||||
#[test]
|
||||
fn type_tool_click_reaches_the_inside_of_a_ligature() {
|
||||
let mut s = session();
|
||||
let v = ViewInfo::default();
|
||||
let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "fin", "size": 40, "font": "Source Serif 4"})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
s.select_tool("type", v).unwrap();
|
||||
let t = obj(&s, id);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
|
||||
let g = lay.glyphs.iter().find(|g| g.len == 2).expect("f + i is one glyph");
|
||||
let (_, f) = g.carets[0];
|
||||
let p = t.xf * (g.origin + vectorcraft_geom::Vec2::new(g.advance * f + 0.2, -10.0));
|
||||
click(&mut s, p.x, p.y);
|
||||
assert_eq!(s.tool_options()["caret"], json!(1), "between the f and the i");
|
||||
key(&mut s, ToolKey::Right, Mods { shift: true, ..Default::default() });
|
||||
assert_eq!((s.tool_options()["start"].as_u64(), s.tool_options()["end"].as_u64()), (Some(1), Some(2)));
|
||||
s.tool_text("I", v).unwrap();
|
||||
assert_eq!(obj(&s, id).plain_text(), "fIn");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn character_panel_flow_styles_the_selected_range_while_editing() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Tool options that persist across tool switches, documents and launches (`Prefs::tool_settings`).
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
use crate::*;
|
||||
|
||||
@@ -90,6 +91,115 @@ fn a_gesture_keeps_what_it_changed_and_a_document_switch_keeps_options() {
|
||||
assert_eq!(s.tool_options()["segments"], json!(14));
|
||||
}
|
||||
|
||||
/// A dropped press (a long touch, a canceled touch, a second finger) keeps nothing it began: the
|
||||
/// tool ends at rest with the options it had before the press, and the options the drag changed
|
||||
/// are not stored. A release stores them.
|
||||
#[test]
|
||||
fn a_dropped_press_does_not_keep_what_its_drag_changed() {
|
||||
let mut s = session();
|
||||
select(&mut s, "polygon");
|
||||
let v = ViewInfo::default();
|
||||
let drag_with_one_more_side = |s: &mut Session| {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap();
|
||||
s.tool_key(ToolKey::Up, Mods::default(), v).unwrap();
|
||||
};
|
||||
assert_eq!(s.tool_options()["sides"], json!(6));
|
||||
drag_with_one_more_side(&mut s);
|
||||
assert_eq!(s.tool_options()["sides"], json!(7));
|
||||
s.drop_tool_press(v).unwrap();
|
||||
assert!(!s.tool_busy(), "the tool is at rest");
|
||||
let st = s.active().unwrap();
|
||||
assert!(st.interaction.is_none() && st.doc.art_bounds().is_none(), "the polygon is not drawn");
|
||||
assert_eq!(s.tool_options()["sides"], json!(6), "the tool has its sides from before the press");
|
||||
assert_eq!(s.prefs.tool_settings.get("polygon").and_then(|o| o.get("sides")), None, "the dropped drag's sides are not stored");
|
||||
drag_with_one_more_side(&mut s);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap();
|
||||
assert!(s.active().unwrap().doc.art_bounds().is_some(), "a release draws the polygon");
|
||||
assert_eq!(s.prefs.tool_settings["polygon"]["sides"], json!(7), "and stores its sides");
|
||||
}
|
||||
|
||||
/// A dropped Pen press drops only the anchor it was placing: the path being drawn goes on with
|
||||
/// the next click.
|
||||
#[test]
|
||||
fn a_dropped_pen_press_keeps_the_path_being_drawn() {
|
||||
let mut s = session();
|
||||
select(&mut s, "pen");
|
||||
let v = ViewInfo::default();
|
||||
let click = |s: &mut Session, x: f64, y: f64| {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap();
|
||||
};
|
||||
click(&mut s, 10.0, 10.0);
|
||||
click(&mut s, 100.0, 10.0);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 140.0, 120.0), v).unwrap();
|
||||
s.drop_tool_press(v).unwrap();
|
||||
click(&mut s, 10.0, 100.0);
|
||||
let d = &s.active().unwrap().doc;
|
||||
let paths = d.layers[0].children().unwrap();
|
||||
assert_eq!(paths.len(), 1, "no new path starts");
|
||||
assert_eq!(paths[0].path_data().unwrap().anchor_count(), 3, "the dropped anchor is not placed");
|
||||
}
|
||||
|
||||
/// A dropped Pen press on the first anchor does not close the path or end it.
|
||||
#[test]
|
||||
fn a_dropped_pen_close_keeps_the_path_open_and_being_drawn() {
|
||||
let mut s = session();
|
||||
select(&mut s, "pen");
|
||||
let v = ViewInfo::default();
|
||||
let click = |s: &mut Session, x: f64, y: f64| {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap();
|
||||
};
|
||||
click(&mut s, 10.0, 10.0);
|
||||
click(&mut s, 100.0, 10.0);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 40.0, 30.0), v).unwrap();
|
||||
s.drop_tool_press(v).unwrap();
|
||||
click(&mut s, 10.0, 100.0);
|
||||
let d = &s.active().unwrap().doc;
|
||||
let paths = d.layers[0].children().unwrap();
|
||||
assert_eq!(paths.len(), 1, "no new path starts");
|
||||
let pd = paths[0].path_data().unwrap();
|
||||
assert_eq!(pd.anchor_count(), 4, "the next click goes on the path");
|
||||
assert!(!pd.subpaths[0].closed, "the path is not closed");
|
||||
}
|
||||
|
||||
/// A dropped marquee selects nothing: the selection stays as it was before the press.
|
||||
#[test]
|
||||
fn a_dropped_marquee_leaves_the_selection_alone() {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 600, "y": 400, "width": 100, "height": 100})).unwrap();
|
||||
let before = s.doc().unwrap().selection.objects.clone();
|
||||
assert_eq!(before.len(), 1);
|
||||
select(&mut s, "selection");
|
||||
let v = ViewInfo::default();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 300.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 350.0, 350.0), v).unwrap();
|
||||
s.drop_tool_press(v).unwrap();
|
||||
assert!(!s.tool_busy(), "the tool is at rest");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, before);
|
||||
}
|
||||
|
||||
/// A dropped Shift-drag marquee of the Artboard tool toggles no artboard: the tool takes Escape,
|
||||
/// as during a drag, before its release.
|
||||
#[test]
|
||||
fn a_dropped_artboard_marquee_toggles_nothing() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap();
|
||||
select(&mut s, "artboard");
|
||||
let before = s.tool_options()["selected"].clone();
|
||||
let v = ViewInfo::default();
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 1200.0, 500.0).with_mods(shift), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 1250.0, 550.0).with_mods(shift), v).unwrap();
|
||||
s.drop_tool_press(v).unwrap();
|
||||
assert!(!s.tool_busy(), "the tool is at rest");
|
||||
assert_eq!(s.tool_options()["selected"], before, "no artboard is toggled");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_are_saved_with_the_preferences() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -245,25 +245,26 @@ fn mismatched_and_missing_bindings_are_skipped_and_counted() {
|
||||
fn a_row_with_no_value_for_a_bound_variable_warns_that_nothing_was_applied() {
|
||||
let mut s = session();
|
||||
let t = text(&mut s, "x");
|
||||
s.execute("dataset.import", &json!({"csv": "name,Name,Title\nA,Ann,Boss\nB,Bob,Chief\n"})).unwrap();
|
||||
s.execute("dataset.import", &json!({"csv": "Name,Title\nAnn,Boss\nBob,Chief\n"})).unwrap();
|
||||
let (a, b) = ("Data Set 1", "Data Set 2");
|
||||
let warning = |row: &str| format!("nothing in data set {row} was applied: no object is bound to a variable it has a value for");
|
||||
let v = s.execute("dataset.select", &json!({"name": "A"})).unwrap();
|
||||
assert_eq!((v["applied"].as_u64(), v["skipped"].as_u64(), &v["warning"]), (Some(0), Some(0), &json!(warning("A"))), "{v}");
|
||||
let v = s.execute("dataset.select", &json!({"name": a})).unwrap();
|
||||
assert_eq!((v["applied"].as_u64(), v["skipped"].as_u64(), &v["warning"]), (Some(0), Some(0), &json!(warning(a))), "{v}");
|
||||
let v = s.execute("dataset.next", &json!({})).unwrap();
|
||||
assert_eq!(v["warning"], json!(warning("B")), "{v}");
|
||||
assert_eq!(v["warning"], json!(warning(b)), "{v}");
|
||||
let v = s.execute("dataset.prev", &json!({})).unwrap();
|
||||
assert_eq!(v["warning"], json!(warning("A")), "{v}");
|
||||
assert_eq!(v["warning"], json!(warning(a)), "{v}");
|
||||
assert_eq!(plain(&s, t), "x");
|
||||
|
||||
// A bound variable that the row has no value for still applies nothing.
|
||||
s.execute("variable.define", &json!({"name": "Other", "kind": "text"})).unwrap();
|
||||
s.execute("variable.bind", &json!({"variable": "Other", "ids": [t.0]})).unwrap();
|
||||
let v = s.execute("dataset.select", &json!({"name": "B"})).unwrap();
|
||||
assert_eq!((v["applied"].as_u64(), v["skipped"].as_u64(), &v["warning"]), (Some(0), Some(1), &json!(warning("B"))), "{v}");
|
||||
let v = s.execute("dataset.select", &json!({"name": b})).unwrap();
|
||||
assert_eq!((v["applied"].as_u64(), v["skipped"].as_u64(), &v["warning"]), (Some(0), Some(1), &json!(warning(b))), "{v}");
|
||||
|
||||
// Bound to a variable with a value, the row applies it and gives no warning.
|
||||
s.execute("variable.bind", &json!({"variable": "Title", "ids": [t.0]})).unwrap();
|
||||
let v = s.execute("dataset.select", &json!({"name": "A"})).unwrap();
|
||||
let v = s.execute("dataset.select", &json!({"name": a})).unwrap();
|
||||
assert_eq!(v["applied"].as_u64(), Some(1), "{v}");
|
||||
assert!(v.get("warning").is_none(), "{v}");
|
||||
assert_eq!(plain(&s, t), "Boss");
|
||||
@@ -271,7 +272,7 @@ fn a_row_with_no_value_for_a_bound_variable_warns_that_nothing_was_applied() {
|
||||
// Locked art is skipped, and its binding still counts as bound.
|
||||
s.execute("select.set", &json!({"ids": [t.0]})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
let v = s.execute("dataset.select", &json!({"name": "B"})).unwrap();
|
||||
let v = s.execute("dataset.select", &json!({"name": b})).unwrap();
|
||||
assert_eq!(v["applied"].as_u64(), Some(0), "{v}");
|
||||
assert!(v.get("warning").is_none(), "{v}");
|
||||
}
|
||||
@@ -613,8 +614,8 @@ fn locked_variables_refuse_new_deleted_and_renamed_variables() {
|
||||
s.execute("variable.unbind", &json!({"ids": [r.0], "variable": "Show"})).unwrap();
|
||||
s.execute("dataset.capture", &json!({})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "Bob", "values": {"Name": "Bob"}})).unwrap();
|
||||
s.execute("dataset.import", &json!({"csv": "name,Name\nCarol,Carol\n"})).unwrap();
|
||||
s.execute("dataset.select", &json!({"name": "Carol"})).unwrap();
|
||||
s.execute("dataset.import", &json!({"csv": "Name\nCarol\n"})).unwrap();
|
||||
s.execute("dataset.select", &json!({"name": "Data Set 1"})).unwrap();
|
||||
assert_eq!(plain(&s, t), "Carol");
|
||||
|
||||
// Unlocking lets a variable be defined again; `locked` sets the state rather than toggling.
|
||||
@@ -1395,12 +1396,11 @@ fn datasets_csv_keeps_line_breaks_in_quoted_cells() {
|
||||
let value = "Line one, \"quoted\"\nLine two";
|
||||
s.execute("dataset.new", &json!({"name": "A", "values": {"Name": value}})).unwrap();
|
||||
let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string();
|
||||
s.execute("dataset.delete", &json!({"names": ["A"]})).unwrap();
|
||||
s.execute("dataset.import", &json!({"csv": csv})).unwrap();
|
||||
let sets = &s.doc().unwrap().doc.variables.datasets;
|
||||
assert_eq!(sets.len(), 1);
|
||||
assert_eq!(sets[0].values.get("Name"), Some(&vectorcraft_doc::DataValue::Text(value.into())));
|
||||
assert!(s.execute("dataset.import", &json!({"csv": "name,Name\nX,\"open"})).is_err(), "unclosed quote");
|
||||
assert!(s.execute("dataset.import", &json!({"csv": "Name\n\"open"})).is_err(), "unclosed quote");
|
||||
}
|
||||
|
||||
/// An empty text value is not a missing value: it comes back from the exported CSV as an empty
|
||||
@@ -1413,23 +1413,45 @@ fn datasets_csv_keeps_an_empty_text_value() {
|
||||
s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "A", "values": {"Name": ""}})).unwrap();
|
||||
let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string();
|
||||
s.execute("dataset.delete", &json!({"names": ["A"]})).unwrap();
|
||||
s.execute("dataset.import", &json!({"csv": csv})).unwrap();
|
||||
let value = s.doc().unwrap().doc.variables.dataset("A").and_then(|d| d.values.get("Name")).cloned();
|
||||
assert_eq!(value, Some(vectorcraft_doc::DataValue::Text(String::new())));
|
||||
s.execute("dataset.import", &json!({"csv": "name,Name\nB,\nC,\"\"\n"})).unwrap();
|
||||
let value = |name: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get("Name")).cloned();
|
||||
assert_eq!(value("C"), Some(vectorcraft_doc::DataValue::Text(String::new())));
|
||||
let value = |s: &Session, name: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get("Name")).cloned();
|
||||
assert_eq!(value(&s, "Data Set 1"), Some(vectorcraft_doc::DataValue::Text(String::new())));
|
||||
s.execute("variable.define", &json!({"name": "Other", "kind": "text"})).unwrap();
|
||||
s.execute("dataset.import", &json!({"csv": "Name,Other\n,x\n\"\",y\n"})).unwrap();
|
||||
assert_eq!(value(&s, "Data Set 2"), Some(vectorcraft_doc::DataValue::Text(String::new())));
|
||||
// Compatibility rule for files written before empty text was quoted: a bare empty cell stays "no value".
|
||||
assert_eq!(value("B"), None);
|
||||
assert_eq!(value(&s, "Data Set 1"), None);
|
||||
// A data set with no value for the variable exports a bare cell and stays without a value.
|
||||
s.execute("dataset.new", &json!({"name": "D", "values": {}})).unwrap();
|
||||
let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string();
|
||||
assert!(csv.contains("\nD,\n"), "{csv:?}");
|
||||
s.execute("dataset.delete", &json!({"names": ["D"]})).unwrap();
|
||||
assert_eq!(csv, "Name,Other\n,x\n\"\",y\n");
|
||||
s.execute("dataset.import", &json!({"csv": csv})).unwrap();
|
||||
let value = |name: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get("Name")).cloned();
|
||||
assert_eq!(value("D"), None);
|
||||
assert_eq!(value(&s, "Data Set 1"), None);
|
||||
}
|
||||
|
||||
/// A data set with no value for any variable exports as a row that imports back: a quoted empty
|
||||
/// cell in the first column that isn't a text variable reads back as no value, and with only text
|
||||
/// variables the first column reads back as an empty text.
|
||||
#[test]
|
||||
fn datasets_csv_keeps_a_data_set_without_values() {
|
||||
let mut s = session();
|
||||
s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "A", "values": {}})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "B", "values": {"Title": "x"}})).unwrap();
|
||||
let export = |s: &mut Session| s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string();
|
||||
let csv = export(&mut s);
|
||||
assert_eq!(csv, "Title\n\"\"\nx\n");
|
||||
let imp = s.execute("dataset.import", &json!({"csv": csv})).unwrap();
|
||||
assert_eq!(imp["names"], json!(["Data Set 1", "Data Set 2"]));
|
||||
let values = |s: &Session, name: &str| s.doc().unwrap().doc.variables.dataset(name).map(|d| d.values.clone()).unwrap();
|
||||
assert_eq!(values(&s, "Data Set 1").get("Title"), Some(&vectorcraft_doc::DataValue::Text(String::new())));
|
||||
|
||||
s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "C", "values": {}})).unwrap();
|
||||
let csv = export(&mut s);
|
||||
assert!(csv.ends_with("\n,\"\"\n"), "{csv:?}");
|
||||
s.execute("dataset.import", &json!({"csv": csv})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.variables.datasets.len(), 3);
|
||||
assert!(values(&s, "Data Set 3").is_empty());
|
||||
}
|
||||
|
||||
/// A quoted text cell keeps its leading and trailing spaces, so a padded value comes back from
|
||||
@@ -1442,25 +1464,28 @@ fn datasets_csv_keeps_spaces_in_quoted_cells() {
|
||||
s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "A", "values": {"Name": " padded "}})).unwrap();
|
||||
let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string();
|
||||
s.execute("dataset.delete", &json!({"names": ["A"]})).unwrap();
|
||||
s.execute("dataset.import", &json!({"csv": csv})).unwrap();
|
||||
s.execute("dataset.import", &json!({"csv": "name,Name\nB, typed \nC,\" quoted \" \n"})).unwrap();
|
||||
let value = |name: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get("Name")).cloned();
|
||||
let value = |s: &Session, name: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get("Name")).cloned();
|
||||
let text_value = |v: &str| Some(vectorcraft_doc::DataValue::Text(v.into()));
|
||||
assert_eq!(value("A"), text_value(" padded "));
|
||||
assert_eq!(value("B"), text_value("typed"));
|
||||
assert_eq!(value("C"), text_value(" quoted "));
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value(" padded "));
|
||||
s.execute("dataset.import", &json!({"csv": "Name\n typed \n\" quoted \" \n"})).unwrap();
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("typed"));
|
||||
assert_eq!(value(&s, "Data Set 2"), text_value(" quoted "));
|
||||
}
|
||||
|
||||
/// Export refuses a document with more data sets or variables than `dataset.import` reads, so
|
||||
/// every file it writes imports back: 1,000 data sets and 256 variables export and import, and
|
||||
/// one more of either is refused.
|
||||
/// one more of either is refused. The import refuses a line of 257 columns, the last one included.
|
||||
#[test]
|
||||
fn datasets_export_refuses_more_than_import_reads() {
|
||||
let mut s = session();
|
||||
let header: Vec<String> = (1..=256).map(|i| format!("V{i}")).collect();
|
||||
for wide in [format!("{},V257\nx\n", header.join(",")), format!("{}\nx{}\n", header.join(","), ",".repeat(256))] {
|
||||
let err = s.execute("dataset.import", &json!({"csv": wide})).unwrap_err().to_string();
|
||||
assert!(err.contains("more than 256 columns"), "{err}");
|
||||
}
|
||||
let rows: String = (1..=1000).map(|i| format!("Set {i},x\n")).collect();
|
||||
s.execute("dataset.import", &json!({"csv": format!("name,{}\n{rows}", header.join(","))})).unwrap();
|
||||
s.execute("dataset.import", &json!({"csv": format!("{}\n{rows}", header.join(","))})).unwrap();
|
||||
let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string();
|
||||
s.execute("dataset.import", &json!({"csv": csv})).unwrap();
|
||||
|
||||
@@ -1488,59 +1513,102 @@ fn datasets_csv_reads_tab_separated_files() {
|
||||
s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap();
|
||||
s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap();
|
||||
s.execute("variable.define", &json!({"name": "Last, First", "kind": "text"})).unwrap();
|
||||
let tsv = "name\tTitle\tShow\r\nA\tTwo words\ttrue\r\nB\t\"a, b\tc\"\tfalse\r\n";
|
||||
let tsv = "Title\tShow\r\nTwo words\ttrue\r\n\"a, b\tc\"\tfalse\r\n";
|
||||
let imp = s.execute("dataset.import", &json!({"csv": tsv})).unwrap();
|
||||
assert_eq!(imp["names"], json!(["A", "B"]));
|
||||
s.execute("dataset.import", &json!({"csv": "name,Title\nC,one\ttwo"})).unwrap();
|
||||
s.execute("dataset.import", &json!({"csv": "name\t\"Last, First\"\nD\tSmith, Jo"})).unwrap();
|
||||
let value = |name: &str, var: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get(var)).cloned();
|
||||
assert_eq!(imp["names"], json!(["Data Set 1", "Data Set 2"]));
|
||||
let value = |s: &Session, name: &str, var: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get(var)).cloned();
|
||||
let text_value = |v: &str| Some(vectorcraft_doc::DataValue::Text(v.into()));
|
||||
assert_eq!(value("A", "Title"), text_value("Two words"));
|
||||
assert_eq!(value("A", "Show"), Some(vectorcraft_doc::DataValue::Visible(true)));
|
||||
assert_eq!(value("B", "Title"), text_value("a, b\tc"));
|
||||
assert_eq!(value("B", "Show"), Some(vectorcraft_doc::DataValue::Visible(false)));
|
||||
assert_eq!(value("C", "Title"), text_value("one\ttwo"));
|
||||
assert_eq!(value("D", "Last, First"), text_value("Smith, Jo"));
|
||||
let unclosed = s.execute("dataset.import", &json!({"csv": "name\tTitle\t\"Show\nA\tx\ttrue"})).unwrap_err().to_string();
|
||||
assert_eq!(value(&s, "Data Set 1", "Title"), text_value("Two words"));
|
||||
assert_eq!(value(&s, "Data Set 1", "Show"), Some(vectorcraft_doc::DataValue::Visible(true)));
|
||||
assert_eq!(value(&s, "Data Set 2", "Title"), text_value("a, b\tc"));
|
||||
assert_eq!(value(&s, "Data Set 2", "Show"), Some(vectorcraft_doc::DataValue::Visible(false)));
|
||||
s.execute("dataset.import", &json!({"csv": "Title,Show\none\ttwo,true"})).unwrap();
|
||||
assert_eq!(value(&s, "Data Set 1", "Title"), text_value("one\ttwo"));
|
||||
s.execute("dataset.import", &json!({"csv": "\"Last, First\"\tShow\nSmith, Jo\ttrue"})).unwrap();
|
||||
assert_eq!(value(&s, "Data Set 1", "Last, First"), text_value("Smith, Jo"));
|
||||
// A file of one variable whose name holds a tab is exported with the name quoted, and reads back as one column.
|
||||
let mut one = session();
|
||||
one.execute("variable.define", &json!({"name": "Tab\tName", "kind": "text"})).unwrap();
|
||||
one.execute("dataset.new", &json!({"name": "A", "values": {"Tab\tName": "v"}})).unwrap();
|
||||
let csv = one.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string();
|
||||
assert_eq!(csv, "\"Tab\tName\"\nv\n");
|
||||
let imp = one.execute("dataset.import", &json!({"csv": csv})).unwrap();
|
||||
assert_eq!(imp["defined"], json!([]), "{imp}");
|
||||
assert_eq!(value(&one, "Data Set 1", "Tab\tName"), text_value("v"));
|
||||
let unclosed = s.execute("dataset.import", &json!({"csv": "Title\t\"Show\nx\ttrue"})).unwrap_err().to_string();
|
||||
assert!(unclosed.contains("unclosed quote"), "{unclosed}");
|
||||
}
|
||||
|
||||
/// Without a `name` column every header cell is a variable, and the rows take the first free
|
||||
/// names Data Set 1, 2 and so on. A first header cell `name`, in any case, still holds the names.
|
||||
/// Every header cell is a variable, whatever its case: a file laid out as the set-up page shows
|
||||
/// (`Name,Age`) defines and fills `Name`, and `name` and `NAME` are variables too. The rows are
|
||||
/// named Data Set 1, 2 and so on, in file order.
|
||||
#[test]
|
||||
fn datasets_csv_without_a_name_column_numbers_the_rows() {
|
||||
fn datasets_csv_reads_every_header_cell_as_a_variable() {
|
||||
let mut s = session();
|
||||
s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "Data Set 2", "values": {"Title": "kept"}})).unwrap();
|
||||
let imp = s.execute("dataset.import", &json!({"csv": "Title\nx\ny\n"})).unwrap();
|
||||
assert_eq!((imp["imported"].as_u64(), imp["updated"].as_u64()), (Some(2), Some(0)));
|
||||
assert_eq!(imp["names"], json!(["Data Set 1", "Data Set 3"]));
|
||||
let value = |s: &Session, name: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get("Title")).cloned();
|
||||
let text_value = |v: &str| Some(vectorcraft_doc::DataValue::Text(v.into()));
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("x"));
|
||||
assert_eq!(value(&s, "Data Set 2"), text_value("kept"));
|
||||
assert_eq!(value(&s, "Data Set 3"), text_value("y"));
|
||||
let named = s.execute("dataset.import", &json!({"csv": "NAME,Title\nData Set 1,z"})).unwrap();
|
||||
assert_eq!((named["imported"].as_u64(), named["updated"].as_u64()), (Some(0), Some(1)));
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("z"));
|
||||
let t = text(&mut s, "x");
|
||||
let imp = s.execute("dataset.import", &json!({"csv": "Name,Age\nBill Tucker,36\nJo Lee,41\n"})).unwrap();
|
||||
assert_eq!((imp["imported"].as_u64(), &imp["defined"]), (Some(2), &json!(["Name", "Age"])), "{imp}");
|
||||
assert_eq!(imp["names"], json!(["Data Set 1", "Data Set 2"]));
|
||||
s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap();
|
||||
s.execute("dataset.select", &json!({"name": "Data Set 2"})).unwrap();
|
||||
assert_eq!(plain(&s, t), "Jo Lee");
|
||||
for header in ["name", "NAME"] {
|
||||
let imp = s.execute("dataset.import", &json!({"csv": format!("{header},Age\nx,1\n")})).unwrap();
|
||||
assert_eq!((&imp["defined"], &imp["names"]), (&json!([header]), &json!(["Data Set 1"])), "{header}: {imp}");
|
||||
}
|
||||
let value = |s: &Session, var: &str| s.doc().unwrap().doc.variables.dataset("Data Set 1").and_then(|d| d.values.get(var)).cloned();
|
||||
assert_eq!(value(&s, "NAME"), Some(vectorcraft_doc::DataValue::Text("x".into())));
|
||||
}
|
||||
|
||||
/// An error about a row's values or name gives the file line the row starts on, counting blank
|
||||
/// lines and line breaks inside quoted cells.
|
||||
/// An import replaces every data set of the document, as Load Variable Library does, and clears
|
||||
/// the active data set. The document's variables stay with their bindings, including those the
|
||||
/// file has no column for, which then have no value in any data set. Undo brings the data sets back.
|
||||
#[test]
|
||||
fn datasets_csv_import_replaces_the_data_sets() {
|
||||
let mut s = session();
|
||||
let t = text(&mut s, "x");
|
||||
let r = rect(&mut s);
|
||||
s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap();
|
||||
s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap();
|
||||
s.execute("variable.bind", &json!({"variable": "Title", "ids": [t.0]})).unwrap();
|
||||
s.execute("variable.bind", &json!({"variable": "Show", "ids": [r.0]})).unwrap();
|
||||
for (name, title) in [("First", "a"), ("Data Set 2", "b"), ("Data Set 3", "c")] {
|
||||
s.execute("dataset.new", &json!({"name": name, "values": {"Title": title, "Show": true}})).unwrap();
|
||||
}
|
||||
s.execute("dataset.select", &json!({"name": "First"})).unwrap();
|
||||
let imp = s.execute("dataset.import", &json!({"csv": "Title\ny\nz\n"})).unwrap();
|
||||
assert_eq!(imp["names"], json!(["Data Set 1", "Data Set 2"]));
|
||||
assert_eq!(imp["deletedDataSets"], json!(["First", "Data Set 2", "Data Set 3"]));
|
||||
let vars = &s.doc().unwrap().doc.variables;
|
||||
let sets: Vec<_> = vars.datasets.iter().map(|d| (d.name.as_str(), d.values.get("Title").cloned(), d.values.get("Show").cloned())).collect();
|
||||
let text_value = |v: &str| Some(vectorcraft_doc::DataValue::Text(v.into()));
|
||||
assert_eq!(sets, [("Data Set 1", text_value("y"), None), ("Data Set 2", text_value("z"), None)]);
|
||||
assert_eq!(vars.active_dataset, None);
|
||||
let listed = s.execute("variable.list", &json!({})).unwrap();
|
||||
assert_eq!(listed["variables"], json!([{"name": "Title", "kind": "text", "bindings": 1}, {"name": "Show", "kind": "visibility", "bindings": 1}]));
|
||||
s.execute("dataset.select", &json!({"name": "Data Set 2"})).unwrap();
|
||||
assert_eq!(plain(&s, t), "z");
|
||||
|
||||
// The first undo takes back the selection, the second the import.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let vars = &s.doc().unwrap().doc.variables;
|
||||
let names: Vec<&str> = vars.datasets.iter().map(|d| d.name.as_str()).collect();
|
||||
assert_eq!((names, vars.active_dataset.as_deref()), (vec!["First", "Data Set 2", "Data Set 3"], Some("First")));
|
||||
}
|
||||
|
||||
/// An error about a row's values gives the file line the row starts on, counting blank lines and
|
||||
/// line breaks inside quoted cells.
|
||||
#[test]
|
||||
fn datasets_csv_row_errors_name_the_file_line() {
|
||||
let mut s = session();
|
||||
s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap();
|
||||
s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap();
|
||||
let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err().to_string();
|
||||
let blank_line = error(&mut s, "name,Show\n\nX,maybe");
|
||||
let blank_line = error(&mut s, "Show\n\nmaybe");
|
||||
assert!(blank_line.contains("line 3:"), "{blank_line}");
|
||||
let line_break = error(&mut s, "name,Title,Show\nA,\"one\ntwo\",true\nB,x,maybe");
|
||||
let line_break = error(&mut s, "Title,Show\n\"one\ntwo\",true\nx,maybe");
|
||||
assert!(line_break.contains("line 4:"), "{line_break}");
|
||||
let twice = error(&mut s, "name,Title\nA,x\n\nA,y");
|
||||
assert!(twice.contains("line 4:"), "{twice}");
|
||||
let long = error(&mut s, &format!("name,Title\n\n{},x", "n".repeat(256)));
|
||||
assert!(long.contains("line 3:") && long.contains("longer than 255"), "{long}");
|
||||
}
|
||||
|
||||
/// A refused cell's error gives its line and why the value was refused: a visibility value that
|
||||
@@ -1551,10 +1619,10 @@ fn datasets_csv_cell_errors_say_why() {
|
||||
s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap();
|
||||
s.execute("variable.define", &json!({"name": "Sales", "kind": "graph"})).unwrap();
|
||||
let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err();
|
||||
let maybe = error(&mut s, "name,Show\nX,maybe");
|
||||
let maybe = error(&mut s, "Show\nmaybe");
|
||||
let want = "line 2: value for `Show` must be true or false";
|
||||
assert!(matches!(&maybe, EngineError::BadParams { msg, .. } if msg == want), "{maybe}");
|
||||
let long = error(&mut s, &format!("name,Sales\nX,\"{}\"", "1,".repeat(140_000)));
|
||||
let long = error(&mut s, &format!("Sales\n\"{}\"", "1,".repeat(140_000)));
|
||||
let want = "line 2: value for `Sales` is longer than 262144 bytes";
|
||||
assert!(matches!(&long, EngineError::BadParams { msg, .. } if msg == want), "{long}");
|
||||
assert!(s.doc().unwrap().doc.variables.datasets.is_empty());
|
||||
@@ -1567,10 +1635,10 @@ fn datasets_csv_cell_errors_say_why() {
|
||||
#[test]
|
||||
fn datasets_csv_header_prefixes_define_variables() {
|
||||
let mut s = session();
|
||||
let csv = "name,#Shown,@Photo,Title\nA,true,a.png,x";
|
||||
let csv = "#Shown,@Photo,Title\ntrue,a.png,x";
|
||||
let imp = s.execute("dataset.import", &json!({"csv": csv})).unwrap();
|
||||
assert_eq!(imp["defined"], json!(["Shown", "Photo", "Title"]));
|
||||
assert_eq!((imp["imported"].as_u64(), imp["names"].clone()), (Some(1), json!(["A"])));
|
||||
assert_eq!((imp["imported"].as_u64(), imp["names"].clone()), (Some(1), json!(["Data Set 1"])));
|
||||
let listed = s.execute("variable.list", &json!({})).unwrap();
|
||||
assert_eq!(
|
||||
listed["variables"],
|
||||
@@ -1580,23 +1648,23 @@ fn datasets_csv_header_prefixes_define_variables() {
|
||||
{"name": "Title", "kind": "text", "bindings": 0},
|
||||
])
|
||||
);
|
||||
let value = |s: &Session, var: &str| s.doc().unwrap().doc.variables.dataset("A").and_then(|d| d.values.get(var)).cloned();
|
||||
let value = |s: &Session, var: &str| s.doc().unwrap().doc.variables.dataset("Data Set 1").and_then(|d| d.values.get(var)).cloned();
|
||||
assert_eq!(value(&s, "Shown"), Some(vectorcraft_doc::DataValue::Visible(true)));
|
||||
assert_eq!(value(&s, "Photo"), Some(vectorcraft_doc::DataValue::Image("a.png".into())));
|
||||
assert_eq!(value(&s, "Title"), Some(vectorcraft_doc::DataValue::Text("x".into())));
|
||||
|
||||
let again = s.execute("dataset.import", &json!({"csv": "name\t#Shown\t@Photo\tTitle\nA\tfalse\tb.png\ty"})).unwrap();
|
||||
assert_eq!((again["updated"].as_u64(), again["defined"].clone()), (Some(1), json!([])));
|
||||
let again = s.execute("dataset.import", &json!({"csv": "#Shown\t@Photo\tTitle\nfalse\tb.png\ty"})).unwrap();
|
||||
assert_eq!((again["imported"].as_u64(), again["defined"].clone()), (Some(1), json!([])));
|
||||
assert_eq!(value(&s, "Shown"), Some(vectorcraft_doc::DataValue::Visible(false)));
|
||||
|
||||
let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err().to_string();
|
||||
let other_kind = error(&mut s, "name,New,#Title\nB,n,true");
|
||||
let other_kind = error(&mut s, "Shown,New,#Title\ntrue,n,true");
|
||||
assert!(other_kind.contains("column 3:") && other_kind.contains("text variable"), "{other_kind}");
|
||||
let twice = error(&mut s, "Fresh,@Fresh\nn,f.png");
|
||||
assert!(twice.contains("column 2:") && twice.contains("text variable"), "{twice}");
|
||||
let bare = error(&mut s, "name,#\nB,true");
|
||||
let bare = error(&mut s, "Title,#\nx,true");
|
||||
assert!(bare.contains("column 2:") && bare.contains("names no variable"), "{bare}");
|
||||
let long = error(&mut s, &format!("name,@{}\nB,b.png", "n".repeat(256)));
|
||||
let long = error(&mut s, &format!("Title,@{}\nx,b.png", "n".repeat(256)));
|
||||
assert!(long.contains("column 2:") && long.contains("longer than 255"), "{long}");
|
||||
assert_eq!(s.doc().unwrap().doc.variables.variables.len(), 3, "a failed import defines nothing");
|
||||
|
||||
@@ -1620,11 +1688,10 @@ fn datasets_csv_exact_names_win_over_prefixes() {
|
||||
let values = json!({"#Shown": "hello", "@Photo": true, "%Chart": ",Q\nX,3", "Shown": "s.png"});
|
||||
s.execute("dataset.new", &json!({"name": "A", "values": values})).unwrap();
|
||||
let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string();
|
||||
assert!(csv.starts_with("name,#Shown,#@Photo,%Chart,@Shown\n"), "{csv}");
|
||||
s.execute("dataset.delete", &json!({"names": ["A"]})).unwrap();
|
||||
assert!(csv.starts_with("#Shown,#@Photo,%Chart,@Shown\n"), "{csv}");
|
||||
let imp = s.execute("dataset.import", &json!({"csv": csv})).unwrap();
|
||||
assert_eq!((imp["imported"].as_u64(), imp["defined"].clone()), (Some(1), json!([])));
|
||||
let value = |var: &str| s.doc().unwrap().doc.variables.dataset("A").and_then(|d| d.values.get(var)).cloned();
|
||||
let value = |var: &str| s.doc().unwrap().doc.variables.dataset("Data Set 1").and_then(|d| d.values.get(var)).cloned();
|
||||
assert_eq!(value("#Shown"), Some(vectorcraft_doc::DataValue::Text("hello".into())));
|
||||
assert_eq!(value("@Photo"), Some(vectorcraft_doc::DataValue::Visible(true)));
|
||||
assert_eq!(value("%Chart"), Some(vectorcraft_doc::DataValue::Graph(",Q\nX,3".into())));
|
||||
@@ -1644,7 +1711,7 @@ fn datasets_csv_export_marks_visibility_and_image_columns() {
|
||||
}
|
||||
s.execute("dataset.new", &json!({"name": "A", "values": {"Name": "Ann", "Show": false, "Photo": "a.png"}})).unwrap();
|
||||
let out = s.execute("dataset.export", &json!({})).unwrap();
|
||||
assert_eq!(out["csv"], "name,Name,#Show,@Photo\nA,Ann,false,a.png\n");
|
||||
assert_eq!(out["csv"], "Name,#Show,@Photo\nAnn,false,a.png\n");
|
||||
assert!(out.get("warning").is_none(), "{out}");
|
||||
|
||||
let mut fresh = session();
|
||||
@@ -1653,7 +1720,8 @@ fn datasets_csv_export_marks_visibility_and_image_columns() {
|
||||
let listed = fresh.execute("variable.list", &json!({})).unwrap();
|
||||
let kinds: Vec<_> = listed["variables"].as_array().unwrap().iter().map(|v| v["kind"].clone()).collect();
|
||||
assert_eq!(kinds, [json!("text"), json!("visibility"), json!("image")]);
|
||||
let value = |var: &str| fresh.doc().unwrap().doc.variables.dataset("A").and_then(|d| d.values.get(var)).cloned();
|
||||
let value = |var: &str| fresh.doc().unwrap().doc.variables.dataset("Data Set 1").and_then(|d| d.values.get(var)).cloned();
|
||||
assert_eq!(value("Name"), Some(vectorcraft_doc::DataValue::Text("Ann".into())));
|
||||
assert_eq!(value("Show"), Some(vectorcraft_doc::DataValue::Visible(false)));
|
||||
assert_eq!(value("Photo"), Some(vectorcraft_doc::DataValue::Image("a.png".into())));
|
||||
|
||||
@@ -1662,7 +1730,48 @@ fn datasets_csv_export_marks_visibility_and_image_columns() {
|
||||
}
|
||||
let out = s.execute("dataset.export", &json!({})).unwrap();
|
||||
assert_eq!(out["warning"], "a new document won't read these variables back with their kind: `#Tag`, `Chart`, `@Note`");
|
||||
assert!(out["csv"].as_str().unwrap().starts_with("name,Name,#Show,@Photo,#Tag,Chart,@Note\n"), "{out}");
|
||||
assert!(out["csv"].as_str().unwrap().starts_with("Name,#Show,@Photo,#Tag,Chart,@Note\n"), "{out}");
|
||||
}
|
||||
|
||||
/// A file `dataset.export` writes has no column of data set names, and `dataset.import` reads
|
||||
/// every column as a variable, so the file imports back to the same data sets: the same variables
|
||||
/// with their kinds, and each data set's values in order, a data set without values included, named
|
||||
/// Data Set 1, 2 and so on. In a document whose data sets already have those names and values, the
|
||||
/// import changes nothing.
|
||||
#[test]
|
||||
fn datasets_csv_export_imports_back_to_the_same_data_sets() {
|
||||
let mut s = session();
|
||||
for (name, kind) in [("Name", "text"), ("Show", "visibility"), ("Photo", "image")] {
|
||||
s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap();
|
||||
}
|
||||
s.execute("dataset.new", &json!({"name": "A", "values": {"Name": "Ann, Jr.", "Show": true, "Photo": "a.png"}})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "B", "values": {"Show": false}})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "C", "values": {}})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "D", "values": {"Name": "", "Photo": "d.png"}})).unwrap();
|
||||
let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string();
|
||||
assert!(csv.starts_with("Name,#Show,@Photo\n"), "{csv}");
|
||||
let before = s.doc().unwrap().doc.variables.clone();
|
||||
|
||||
let mut fresh = session();
|
||||
fresh.execute("dataset.import", &json!({"csv": csv})).unwrap();
|
||||
let vars = fresh.doc().unwrap().doc.variables.clone();
|
||||
assert_eq!(vars.variables, before.variables, "the same variables, with their kinds");
|
||||
let values = |v: &vectorcraft_doc::Variables| v.datasets.iter().map(|d| d.values.clone()).collect::<Vec<_>>();
|
||||
assert_eq!(values(&vars), values(&before), "the same values in every data set");
|
||||
let names: Vec<&str> = vars.datasets.iter().map(|d| d.name.as_str()).collect();
|
||||
assert_eq!(names, ["Data Set 1", "Data Set 2", "Data Set 3", "Data Set 4"]);
|
||||
|
||||
// Exporting the imported data sets writes the same file, and importing it changes nothing: no
|
||||
// undo step, and the active data set stays.
|
||||
let again = fresh.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string();
|
||||
assert_eq!(again, csv);
|
||||
fresh.execute("dataset.select", &json!({"name": "Data Set 1"})).unwrap();
|
||||
let vars = fresh.doc().unwrap().doc.variables.clone();
|
||||
assert!(vars.active_dataset.is_some());
|
||||
let undo = fresh.doc().unwrap().history.undo.len();
|
||||
fresh.execute("dataset.import", &json!({"csv": again})).unwrap();
|
||||
assert_eq!(fresh.doc().unwrap().history.undo.len(), undo, "no undo step");
|
||||
assert_eq!(fresh.doc().unwrap().doc.variables, vars);
|
||||
}
|
||||
|
||||
/// The export's `warning` names the variables whose column a document without the variables
|
||||
@@ -1719,7 +1828,7 @@ fn datasets_csv_export_refuses_a_header_that_names_another_variable() {
|
||||
fn datasets_csv_refuses_graph_data_file_columns() {
|
||||
let mut s = session();
|
||||
let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err().to_string();
|
||||
let named = error(&mut s, "name,Title,%Sales\nA,x,sales.txt");
|
||||
let named = error(&mut s, "Name,Title,%Sales\nA,x,sales.txt");
|
||||
assert!(named.contains("column 3:") && named.contains("`%Sales`"), "{named}");
|
||||
let unnamed = error(&mut s, "%Sales\tTitle\nsales.txt\tx");
|
||||
assert!(unnamed.contains("column 1:") && unnamed.contains("`%Sales`"), "{unnamed}");
|
||||
@@ -1735,10 +1844,10 @@ fn datasets_csv_refuses_two_columns_for_one_variable() {
|
||||
s.execute("variable.define", &json!({"name": "Shown", "kind": "visibility"})).unwrap();
|
||||
let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err().to_string();
|
||||
for (csv, first, second, var) in [
|
||||
("name,City,City\nR,Paris,Rome", 2, 3, "City"),
|
||||
("name,City,City\nR,Paris,", 2, 3, "City"),
|
||||
("Title,City,City\nR,Paris,Rome", 2, 3, "City"),
|
||||
("Title,City,City\nR,Paris,", 2, 3, "City"),
|
||||
("City,Title,City\nParis,x,Rome", 1, 3, "City"),
|
||||
("name,Shown,#Shown\nR,true,false", 2, 3, "Shown"),
|
||||
("Title,Shown,#Shown\nR,true,false", 2, 3, "Shown"),
|
||||
("Title\t@Photo\t@ Photo\nx\ta.png\tb.png", 2, 3, "Photo"),
|
||||
] {
|
||||
let err = error(&mut s, csv);
|
||||
@@ -1757,21 +1866,22 @@ fn locked_variables_refuse_header_cells_that_define_variables() {
|
||||
s.execute("variable.define", &json!({"name": "Shown", "kind": "visibility"})).unwrap();
|
||||
s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap();
|
||||
s.execute("variable.lock", &json!({"locked": true})).unwrap();
|
||||
for csv in ["name,#Shown,Title,New\nA,true,x,n", "@Photo\nb.png", "name,#Fresh\nA,true"] {
|
||||
for csv in ["#Shown,Title,New\ntrue,x,n", "@Photo\nb.png", "Title,#Fresh\nx,true"] {
|
||||
let e = s.execute("dataset.import", &json!({"csv": csv})).unwrap_err();
|
||||
assert!(matches!(&e, EngineError::Disabled(cmd, why) if cmd == "dataset.import" && why == "variables are locked"), "{csv}: {e}");
|
||||
}
|
||||
let vars = &s.doc().unwrap().doc.variables;
|
||||
assert!(vars.variables.len() == 2 && vars.datasets.is_empty(), "a refused import defines and imports nothing");
|
||||
|
||||
let imp = s.execute("dataset.import", &json!({"csv": "name,#Shown,Title\nA,true,x"})).unwrap();
|
||||
let imp = s.execute("dataset.import", &json!({"csv": "#Shown,Title\ntrue,x"})).unwrap();
|
||||
assert_eq!((imp["imported"].as_u64(), imp["defined"].clone()), (Some(1), json!([])));
|
||||
s.execute("variable.lock", &json!({"locked": false})).unwrap();
|
||||
let imp = s.execute("dataset.import", &json!({"csv": "name,New\nB,n"})).unwrap();
|
||||
let imp = s.execute("dataset.import", &json!({"csv": "New\nn"})).unwrap();
|
||||
assert_eq!(imp["defined"], json!(["New"]));
|
||||
}
|
||||
|
||||
/// Import / export datasets as CSV: header `name` then variables; round-trip keeps values.
|
||||
/// Import / export datasets as CSV: one column per variable and no dataset names; round-trip keeps
|
||||
/// the values in order, and the rows come back as Data Set 1, 2.
|
||||
#[test]
|
||||
fn datasets_csv_round_trips_and_rejects_bad_input() {
|
||||
let dir = Folder::new("vars-csv");
|
||||
@@ -1795,28 +1905,27 @@ fn datasets_csv_round_trips_and_rejects_bad_input() {
|
||||
|
||||
let exported = s.execute("dataset.export", &json!({})).unwrap();
|
||||
let csv = exported["csv"].as_str().unwrap().to_string();
|
||||
assert!(csv.starts_with("name,Name,#Show,@Photo\n"), "{csv}");
|
||||
assert!(csv.starts_with("Name,#Show,@Photo\n"), "{csv}");
|
||||
assert!(csv.contains("Alice") && csv.contains("Bob") && csv.contains("false"), "{csv}");
|
||||
|
||||
// Clear rows, import again, apply B.
|
||||
s.execute("dataset.delete", &json!({"names": ["A", "B"]})).unwrap();
|
||||
// Import again, which replaces A and B, and apply the second row.
|
||||
let imp = s.execute("dataset.import", &json!({"csv": csv})).unwrap();
|
||||
assert_eq!((imp["imported"].as_u64(), imp["updated"].as_u64()), (Some(2), Some(0)));
|
||||
s.execute("dataset.select", &json!({"name": "B"})).unwrap();
|
||||
assert_eq!((imp["imported"].as_u64(), &imp["deletedDataSets"]), (Some(2), &json!(["A", "B"])));
|
||||
s.execute("dataset.select", &json!({"name": "Data Set 2"})).unwrap();
|
||||
assert_eq!(plain(&s, t), "Bob");
|
||||
assert!(!s.doc().unwrap().doc.node(r).unwrap().visible);
|
||||
assert_eq!(image(&s, img).link.as_ref().map(|l| l.path.as_str()), Some(blue_path.as_str()));
|
||||
|
||||
// Re-import updates in place and defines nothing; a bad visibility value is an error.
|
||||
// Re-import replaces the rows and defines nothing; a bad visibility value is an error.
|
||||
let again = s.execute("dataset.import", &json!({"csv": csv})).unwrap();
|
||||
assert_eq!((again["imported"].as_u64(), again["updated"].as_u64()), (Some(0), Some(2)));
|
||||
assert_eq!((again["imported"].as_u64(), &again["deletedDataSets"]), (Some(2), &json!(["Data Set 1", "Data Set 2"])));
|
||||
assert_eq!(again["defined"], json!([]));
|
||||
assert!(s.execute("dataset.import", &json!({"csv": "name,Show\nX,maybe"})).is_err());
|
||||
assert!(s.execute("dataset.import", &json!({"csv": "Show\nmaybe"})).is_err());
|
||||
|
||||
let out = dir.file("sets.csv");
|
||||
s.execute("dataset.export", &json!({"path": out})).unwrap();
|
||||
let from_file = s.execute("dataset.import", &json!({"path": out})).unwrap();
|
||||
assert_eq!(from_file["updated"].as_u64(), Some(2));
|
||||
assert_eq!(from_file["names"], json!(["Data Set 1", "Data Set 2"]));
|
||||
|
||||
// One undo undoes the last import's replacements.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
@@ -1831,17 +1940,17 @@ fn datasets_csv_reads_windows_1252_files() {
|
||||
let import = |s: &mut Session, bytes: &[u8]| s.execute("dataset.import", &json!({"dataBase64": vectorcraft_format::base64_encode(bytes)}));
|
||||
let value = |s: &Session, name: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get("City")).cloned();
|
||||
let text_value = |v: &str| Some(vectorcraft_doc::DataValue::Text(v.into()));
|
||||
let imp = import(&mut s, b"name,City\r\nA,Jos\xe9\r\nB,\x80 5 \x96 \x93Caf\xe9\x94\r\n").unwrap();
|
||||
assert_eq!(imp["names"], json!(["A", "B"]));
|
||||
assert_eq!(value(&s, "A"), text_value("José"));
|
||||
assert_eq!(value(&s, "B"), text_value("€ 5 – “Café”"));
|
||||
import(&mut s, "name,City\nC,José\n".as_bytes()).unwrap();
|
||||
assert_eq!(value(&s, "C"), text_value("José"));
|
||||
import(&mut s, "\u{feff}name,City\nD,Zoë\n".as_bytes()).unwrap();
|
||||
assert_eq!(value(&s, "D"), text_value("Zoë"));
|
||||
let e = import(&mut s, b"\xef\xbb\xbfname,City\nE,Jos\xe9\n").unwrap_err().to_string();
|
||||
let imp = import(&mut s, b"City\r\nJos\xe9\r\n\x80 5 \x96 \x93Caf\xe9\x94\r\n").unwrap();
|
||||
assert_eq!(imp["names"], json!(["Data Set 1", "Data Set 2"]));
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("José"));
|
||||
assert_eq!(value(&s, "Data Set 2"), text_value("€ 5 – “Café”"));
|
||||
import(&mut s, "City\nJosé\n".as_bytes()).unwrap();
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("José"));
|
||||
import(&mut s, "\u{feff}City\nZoë\n".as_bytes()).unwrap();
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("Zoë"));
|
||||
let e = import(&mut s, b"\xef\xbb\xbfCity\nJos\xe9\n").unwrap_err().to_string();
|
||||
assert!(e.contains("CSV is not UTF-8"), "{e}");
|
||||
assert_eq!(value(&s, "E"), None);
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("Zoë"));
|
||||
}
|
||||
|
||||
/// A CSV that starts with a UTF-16 byte-order mark is read as UTF-16, and
|
||||
@@ -1858,24 +1967,24 @@ fn datasets_csv_reads_utf16_files() {
|
||||
let units = text.encode_utf16().flat_map(|u| if le { u.to_le_bytes() } else { u.to_be_bytes() });
|
||||
bom.iter().copied().chain(units).collect()
|
||||
};
|
||||
import(&mut s, &utf16(b"\xff\xfe", "name\tCity\r\nA\tZoë 😀\r\n", true)).unwrap();
|
||||
assert_eq!(value(&s, "A"), text_value("Zoë 😀"));
|
||||
import(&mut s, &utf16(b"\xfe\xff", "name,City\nB,José\n", false)).unwrap();
|
||||
assert_eq!(value(&s, "B"), text_value("José"));
|
||||
let mut odd = utf16(b"\xff\xfe", "name,City\nC,x\n", true);
|
||||
import(&mut s, &utf16(b"\xff\xfe", "City\r\nZoë 😀\r\n", true)).unwrap();
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("Zoë 😀"));
|
||||
import(&mut s, &utf16(b"\xfe\xff", "City\nJosé\n", false)).unwrap();
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("José"));
|
||||
let mut odd = utf16(b"\xff\xfe", "City\nx\n", true);
|
||||
odd.push(b'y');
|
||||
let e = import(&mut s, &odd).unwrap_err().to_string();
|
||||
assert!(e.contains("CSV is not UTF-16"), "{e}");
|
||||
let e = import(&mut s, &[b"\xff\xfe".as_slice(), "name,City\nD,".as_bytes(), b"\x00\xd8"].concat()).unwrap_err().to_string();
|
||||
let e = import(&mut s, &[b"\xff\xfe".as_slice(), "City\nAB,".as_bytes(), b"\x00\xd8"].concat()).unwrap_err().to_string();
|
||||
assert!(e.contains("CSV is not UTF-16"), "{e}");
|
||||
let e = import(&mut s, &utf16(b"", "name,City\nE,x\n", true)).unwrap_err().to_string();
|
||||
let e = import(&mut s, &utf16(b"", "City\nx\n", true)).unwrap_err().to_string();
|
||||
assert!(e.contains("CSV holds NUL bytes"), "{e}");
|
||||
assert_eq!((value(&s, "C"), value(&s, "D"), value(&s, "E")), (None, None, None));
|
||||
s.execute("dataset.new", &json!({"name": "F", "values": {"City": "a\u{0}b"}})).unwrap();
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("José"), "a refused file changes nothing");
|
||||
s.execute("dataset.set", &json!({"name": "Data Set 1", "values": {"City": "a\u{0}b"}})).unwrap();
|
||||
let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string();
|
||||
s.execute("dataset.delete", &json!({"names": ["F"]})).unwrap();
|
||||
s.execute("dataset.delete", &json!({"names": ["Data Set 1"]})).unwrap();
|
||||
s.execute("dataset.import", &json!({"csv": csv})).unwrap();
|
||||
assert_eq!(value(&s, "F"), text_value("a\u{0}b"));
|
||||
assert_eq!(value(&s, "Data Set 1"), text_value("a\u{0}b"));
|
||||
}
|
||||
|
||||
/// A data set of [`library`]: its name, and each variable's name with its paragraphs.
|
||||
@@ -1993,31 +2102,30 @@ fn a_variable_library_replaces_every_variable_and_data_set() {
|
||||
}
|
||||
|
||||
/// An import or a library load that leaves the variables and data sets as they were (the same CSV
|
||||
/// imported again, a row rewritten with its own values, the same library loaded again) records no
|
||||
/// undo step: the step to redo stays, and the document stays unmodified. An import or load that
|
||||
/// changes something is still one undo step.
|
||||
/// imported again, the same rows tab-separated, the file Export Data Sets writes, the same library
|
||||
/// loaded again) records no undo step: the step to redo stays, and the document stays unmodified.
|
||||
/// An import or load that changes something is still one undo step.
|
||||
#[test]
|
||||
fn an_import_or_library_load_that_changes_nothing_records_no_undo_step() {
|
||||
let mut s = session();
|
||||
let t = text(&mut s, "Alice");
|
||||
let csv = "name,Name,#Shown\nA,Ann,true\nB,Bob,false\n";
|
||||
let csv = "Name,#Shown\nAnn,true\nBob,false\n";
|
||||
s.execute("dataset.import", &json!({"csv": csv})).unwrap();
|
||||
for csv in [csv, "name\tName\t#Shown\nB\tBob\tfalse\n", "Name,#Shown\nAnn,true\n"] {
|
||||
let exported = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string();
|
||||
for csv in [csv, "Name\t#Shown\nAnn\ttrue\nBob\tfalse\n", exported.as_str()] {
|
||||
super::select_with_a_step_to_redo(&mut s, &[t]);
|
||||
let before = super::history(&s);
|
||||
assert_eq!((before.1, before.2), (1, false), "a step to redo, and nothing unsaved");
|
||||
let r = s.execute("dataset.import", &json!({"csv": csv})).unwrap();
|
||||
if csv.starts_with("name") {
|
||||
assert_eq!((super::history(&s), r["imported"].clone()), (before, json!(0)), "{csv}");
|
||||
} else {
|
||||
// Without a name column the row is a new data set, which is a change.
|
||||
assert_eq!((super::history(&s), r["imported"].clone()), ((before.0 + 1, 0, true), json!(1)), "{csv}");
|
||||
}
|
||||
assert_eq!((super::history(&s), r["imported"].clone()), (before, json!(2)), "{csv}");
|
||||
}
|
||||
// A file with one of the two rows replaces both data sets with one, which is a change.
|
||||
for csv in ["Name,#Shown\nAnn,true\n", "Name\nCy\n"] {
|
||||
super::select_with_a_step_to_redo(&mut s, &[t]);
|
||||
let undo = super::history(&s).0;
|
||||
s.execute("dataset.import", &json!({"csv": csv})).unwrap();
|
||||
assert_eq!(super::history(&s), (undo + 1, 0, true), "{csv}");
|
||||
}
|
||||
super::select_with_a_step_to_redo(&mut s, &[t]);
|
||||
let undo = super::history(&s).0;
|
||||
s.execute("dataset.import", &json!({"csv": "name,Name\nB,Cy\n"})).unwrap();
|
||||
assert_eq!(super::history(&s), (undo + 1, 0, true));
|
||||
|
||||
let xml = library(&[("Name", "textcontent")], &[("A", &[("Name", &["Ann"])]), ("B", &[("Name", &["Bob"])])]);
|
||||
s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
|
||||
|
||||
@@ -358,26 +358,87 @@ impl Session {
|
||||
|
||||
/// Feed a pointer event to the active tool. Returns requests for the UI.
|
||||
pub fn pointer(&mut self, ev: &PointerEvent, view: ViewInfo) -> Result<Vec<UiRequest>> {
|
||||
self.pointer_event(ev, view, true)
|
||||
}
|
||||
|
||||
/// Drop the press in progress (a long touch, a canceled touch, a second finger): nothing it
|
||||
/// began is kept. Its interaction is undone, the tool drops the press ([`Tool::drop_press`]:
|
||||
/// Escape, as during a drag, for most tools), and a release returns the tool to rest. Of what
|
||||
/// the tool asks for along the way, only a cancel and a notify run, so a marquee selects
|
||||
/// nothing and a click opens no size dialog. The tool gets back the persistent options it had
|
||||
/// when the press began, and none of the press's changes to them are stored. The freeform
|
||||
/// gradient point selected once the tool took the press is selected again.
|
||||
pub fn drop_tool_press(&mut self, view: ViewInfo) -> Result<()> {
|
||||
// Nothing to roll back without a document; the tool still drops the press and gets the release.
|
||||
let _ = self.cancel_interaction();
|
||||
let before = self.press_options.take();
|
||||
let point = self.press_point.take();
|
||||
let mut acts = self.with_tool_cx(view, |t, cx| t.drop_press(cx));
|
||||
acts.retain(|a| matches!(a, Action::Cancel | Action::Notify(_)));
|
||||
let dropped = self.take_tool_panic().and_then(|()| self.apply_actions(acts));
|
||||
let up = PointerEvent { kind: PointerKind::Up, pos: Point::ZERO, mods: Mods::default(), backquote: false, pressure: 1.0, pen: None };
|
||||
let r = dropped.and(self.pointer_event(&up, view, false));
|
||||
// A drag out of the object previews the point's removal, which deselects it.
|
||||
if let Some(p) = point {
|
||||
self.freeform_point = p;
|
||||
}
|
||||
if let Some((id, opts)) = before
|
||||
&& id == self.tool.id()
|
||||
{
|
||||
let now = self.tool.options();
|
||||
for (k, v) in &opts {
|
||||
if now.get(k) != Some(v) {
|
||||
self.tool.set_option(k, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
r.map(drop)
|
||||
}
|
||||
|
||||
/// The options of `t` that [`Self::store_tool_settings`] stores.
|
||||
fn persistent_options(t: &dyn Tool) -> Map<String, Value> {
|
||||
let opts = t.options();
|
||||
let radius = (t.id() == ROUNDED_RECTANGLE).then_some("cornerRadius");
|
||||
let keys = settings::stores(t.id()).flat_map(|(_, keys)| keys.iter().copied()).chain(radius);
|
||||
keys.filter_map(|k| opts.get(k).map(|v| (k.to_string(), v.clone()))).collect()
|
||||
}
|
||||
|
||||
/// [`Self::pointer`]. Without `keep` (a dropped press's release), the tool's options are not
|
||||
/// stored and only the tool's `Cancel` and `Notify` actions run.
|
||||
fn pointer_event(&mut self, ev: &PointerEvent, view: ViewInfo, keep: bool) -> Result<Vec<UiRequest>> {
|
||||
self.last_view = view;
|
||||
match ev.kind {
|
||||
PointerKind::Down | PointerKind::Drag => self.pointer_held = true,
|
||||
PointerKind::Up | PointerKind::Move => self.pointer_held = false,
|
||||
PointerKind::DoubleClick => {}
|
||||
}
|
||||
match ev.kind {
|
||||
PointerKind::Down => self.press_options = Some((self.tool.id().to_string(), Self::persistent_options(self.tool.as_ref()))),
|
||||
PointerKind::Up => self.press_options = None,
|
||||
_ => {}
|
||||
}
|
||||
// The Plane Switching Widget takes its clicks whatever the tool.
|
||||
if let Some(r) = self.plane_widget_pointer(ev, view) {
|
||||
return r;
|
||||
}
|
||||
self.leave_draw_inside(ev, view)?;
|
||||
let ev = &self.lend_selection_tool(ev);
|
||||
let acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev));
|
||||
let mut acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev));
|
||||
if !keep {
|
||||
acts.retain(|a| matches!(a, Action::Cancel | Action::Notify(_)));
|
||||
}
|
||||
let r = self.take_tool_panic().and_then(|()| {
|
||||
// A gesture may change options (Alt-drag sizes a Liquify brush): keep them.
|
||||
if ev.kind == PointerKind::Up {
|
||||
if keep && ev.kind == PointerKind::Up {
|
||||
self.keep_tool_settings();
|
||||
}
|
||||
self.apply_actions(acts)
|
||||
});
|
||||
match ev.kind {
|
||||
PointerKind::Down => self.press_point = Some(self.freeform_point),
|
||||
PointerKind::Up => self.press_point = None,
|
||||
_ => {}
|
||||
}
|
||||
if ev.kind == PointerKind::Up {
|
||||
self.give_back_tool(view)?;
|
||||
}
|
||||
@@ -658,11 +719,27 @@ impl Session {
|
||||
self.tool.options()
|
||||
}
|
||||
pub fn set_tool_option(&mut self, key: &str, v: &Value) {
|
||||
if key == "queue" && self.tool.id() == "place" {
|
||||
self.note_place_queue_roots();
|
||||
}
|
||||
self.tool.set_option(key, v);
|
||||
self.tool_set_since_reset = true;
|
||||
self.keep_tool_settings();
|
||||
}
|
||||
|
||||
/// Keep the automation roots in force now as those the place cursor's queue, being loaded,
|
||||
/// is placed under ([`Session::place_queue_roots`]).
|
||||
fn note_place_queue_roots(&mut self) {
|
||||
self.place_queue_roots = crate::file_access::current();
|
||||
}
|
||||
|
||||
/// The automation roots the place cursor's files are placed under: those in force when it
|
||||
/// was loaded. A frontend that places them itself ([`UiRequest::Place`]) reads them within
|
||||
/// these roots ([`crate::file_access::confine`]).
|
||||
pub fn place_queue_roots(&self) -> Option<std::sync::Arc<crate::file_access::AutomationRoots>> {
|
||||
self.place_queue_roots.clone()
|
||||
}
|
||||
|
||||
/// The options of tool `id`: the active tool's, or those it would have if chosen now.
|
||||
pub fn tool_options_of(&self, id: &str) -> Value {
|
||||
if id == self.tool.id() { self.tool.options() } else { self.make_tool(id).options() }
|
||||
@@ -673,6 +750,9 @@ impl Session {
|
||||
/// Liquify tools' Global Brush Dimensions, the Smooth tool's Fidelity for Pencil, Paintbrush
|
||||
/// and Blob Brush Alt smoothing). Returns the tool's options.
|
||||
pub fn set_tool_options(&mut self, id: Option<&str>, values: &Map<String, Value>) -> Value {
|
||||
if values.contains_key("queue") && id.unwrap_or(self.tool.id()) == "place" {
|
||||
self.note_place_queue_roots();
|
||||
}
|
||||
let active = id.is_none_or(|id| id == self.tool.id());
|
||||
self.tool_set_since_reset |= active;
|
||||
let mut other = (!active).then(|| self.make_tool(id.unwrap_or_default()));
|
||||
@@ -842,6 +922,13 @@ impl Session {
|
||||
}
|
||||
// The place cursor's file, placed by the frontend that asked for it.
|
||||
Action::Exec(cmd, p) if cmd == "file.place" && self.place_cursor_requests => ui.push(UiRequest::Place(p)),
|
||||
// The place cursor's file, read within the roots of whoever loaded the cursor.
|
||||
Action::Exec(cmd, p) if cmd == "file.place" => {
|
||||
let roots = self.place_queue_roots.clone();
|
||||
if let Some(w) = crate::file_access::confine(roots.as_ref(), || self.execute(&cmd, &p))?.get("warning").and_then(Value::as_str) {
|
||||
ui.push(UiRequest::Status(w.to_string()));
|
||||
}
|
||||
}
|
||||
Action::Exec(cmd, p) => {
|
||||
// A command's warning (Crop Image's when the image couldn't be decoded) goes to the
|
||||
// status bar too.
|
||||
|
||||
@@ -3601,6 +3601,40 @@ proptest! {
|
||||
}
|
||||
}
|
||||
|
||||
/// A pattern's definition in the version 7 form (§3.4): a layer whose `_ &` fills the tile's box,
|
||||
/// and one whose tile string has CR-separated lines, comments and escapes.
|
||||
const LEGACY_PATTERN: &str = "%AI3_BeginPattern: (P)\n(P) 0 0 10 10 [\n%AI3_Tile\n(0 O 0 R 0 0 0 0.5 k) @ _ &\n\
|
||||
(0 O 1 R 0 0 0 1 \\(Ink\\) 0 X) @ (\r%AI6_BeginPatternLayer\r1 w u\r0 5 m\\r10 5 L\rS\rU\r%AI6_EndPatternLayer\r) &\n] E\n%AI3_EndPattern\n";
|
||||
|
||||
/// [`NAMED_PROLOG_AI`] with `pattern` in its setup, filling the square.
|
||||
fn legacy_pattern_ai(pattern: &str) -> String {
|
||||
NAMED_PROLOG_AI
|
||||
.replace("%AI5_Begin_NonPrinting", &format!("{pattern}%AI5_Begin_NonPrinting"))
|
||||
.replace("\n10 10 m\n", "\n(P) 5 5 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n10 10 m\n")
|
||||
.replace("10 10 L\nS\n", "10 10 L\nB\n")
|
||||
}
|
||||
|
||||
/// The fixture, as it is, opens with the pattern filling the square.
|
||||
#[test]
|
||||
fn the_legacy_pattern_fixture_opens_with_its_pattern() {
|
||||
let l = vectorcraft_engine::cmd::fileio::load("x.ai", legacy_pattern_ai(LEGACY_PATTERN).as_bytes()).unwrap();
|
||||
assert_eq!(l.doc.pattern("P").map(|p| p.art.len()), Some(2), "{:?}", l.warnings);
|
||||
let square = &l.doc.layers[0].children().unwrap()[0];
|
||||
assert!(matches!(square.appearance.fill().map(|f| &f.paint), Some(vectorcraft_color::Paint::Pattern { .. })));
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(config())]
|
||||
|
||||
/// That `.ai` with its pattern's definition damaged (its strings, `@`, `&`, `_`, the list's
|
||||
/// brackets and its `E`): read, without the pattern where it can't be read whole, or refused.
|
||||
#[test]
|
||||
fn ps_form_ai_legacy_pattern_never_panics(cut in 0usize..500, edits in prop::collection::vec((0usize..500, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '\r', '(', ')', '\\', '[', ']', '%', '@', '&', '_', 'E', 'u', 'U', 'q', 'Q', 'm', 'f', 'S', 'k', 'X'])), 0..12)) {
|
||||
let text = legacy_pattern_ai(&mutate_text(LEGACY_PATTERN, cut, &edits));
|
||||
survive("PostScript-form .ai with a damaged version 7 pattern", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?;
|
||||
}
|
||||
}
|
||||
|
||||
/// An operand of a layer's options (`Lb`): a flag, a colour index or component, a percentage, or
|
||||
/// anything else.
|
||||
fn arb_layer_operand() -> impl Strategy<Value = String> {
|
||||
@@ -3906,6 +3940,10 @@ fn arb_ai_token() -> impl Strategy<Value = String> {
|
||||
"(Fill Style Filter) 0 0 /Filter ,",
|
||||
"(Adobe Outer Glow) 1 0 /Filter ,",
|
||||
"(Adobe Drop Shadow) 1 0 /Filter ,",
|
||||
"(Adobe Pathfinder) 1 0 /Filter ,",
|
||||
"0 /Int (Command) ,",
|
||||
"0.5 /Real (Mix) ,",
|
||||
"(Op) /UnicodeString (DisplayString) ,",
|
||||
"(Adobe Transform) 1 0 /Filter ,",
|
||||
"(Adobe Free Distort) 1 0 /Filter ,",
|
||||
"(Adobe Punk and Bloat) 1 0 /Filter ,",
|
||||
@@ -4116,6 +4154,53 @@ proptest! {
|
||||
survive("hostile editing data in an EPS of its art's box", || vectorcraft_engine::cmd::fileio::load("x.eps", &boxed).ok().map(|l| l.doc))?;
|
||||
}
|
||||
|
||||
/// A group with an Effect › Pathfinder style whose dictionary is hostile: any `Command`, keys of
|
||||
/// any type and value (missing, repeated, unknown, not finite), shown or hidden, the style cut
|
||||
/// short anywhere; in editing data, an EPS and a `.ai`. A `Command` other than 0 never becomes
|
||||
/// a live effect.
|
||||
#[test]
|
||||
fn ai_pathfinder_styles_never_panic(
|
||||
command in prop_oneof![(-3i64..16).prop_map(|c| c.to_string()), arb_num()],
|
||||
keys in prop::collection::vec(
|
||||
(
|
||||
prop::sample::select(vec!["Mix", "Precision", "RemovePoints", "ExtractUnpainted", "ConvertCustom", "TrapTint", "TrapThickness", "Command", "Extra"]),
|
||||
prop::sample::select(vec!["Int", "Real", "Bool", "String"]),
|
||||
arb_num(),
|
||||
),
|
||||
0..16,
|
||||
),
|
||||
hidden in any::<bool>(),
|
||||
cut in 0usize..4_000,
|
||||
) {
|
||||
use vectorcraft_testkit::ai;
|
||||
let dict: String = keys.iter().map(|(k, kind, v)| format!("{v} /{kind} ({k}) ,\n")).collect();
|
||||
let styles = format!(
|
||||
"%AI9_BeginArtStyles\n/KnownStyle :\n(PF) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
|
||||
/BasicFilter :\n(Adobe Pathfinder) 1 0 /Filter ,\n{} /Visible ,\n/Dictionary : /NotRecorded ,\n{command} /Int (Command) ,\n{dict}; /Dict ;\n /Part ,\n\
|
||||
/CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n\
|
||||
%AI9_EndArtStyles\n",
|
||||
u8::from(!hidden)
|
||||
);
|
||||
let styles: String = styles.chars().take(cut.max(1)).collect();
|
||||
let group = "0 Ae\nu\n1 0 0 1 0 0 Xa\n10 10 m\n10 60 L\n80 60 L\n80 10 L\nf\nU\n\
|
||||
%_0 Ae\n%_u\n%_1 0 0 1 0 0 Xa\n%_10 10 m\n%_10 50 L\n%_50 50 L\n%_50 10 L\n%_f\n%_0 0 1 0 0 0 1 Xa\n%_40 20 m\n%_40 60 L\n%_80 60 L\n%_80 20 L\n%_f\n%_U\n1 (PF) XW\n";
|
||||
let data = ai::editing_data(200.0, 100.0, &format!("{styles}{}", ai::layer("L", group)));
|
||||
let live = command.parse::<f64>().is_ok_and(|c| c == 0.0);
|
||||
let check = |d: Option<Document>| {
|
||||
if let Some(d) = &d
|
||||
&& !live
|
||||
{
|
||||
d.walk(|n| assert!(!n.appearance.effects.iter().any(|e| e.id.starts_with("pathfinder.")), "Command {command}: {:?}", n.appearance.effects));
|
||||
}
|
||||
d
|
||||
};
|
||||
survive("hostile Pathfinder style", || check(Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0)))?;
|
||||
let eps = ai::eps(data.as_bytes(), ai::page_ps());
|
||||
survive("hostile Pathfinder style in an EPS", || check(vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc)))?;
|
||||
let file = ai::ai(data.as_bytes(), ai::page_pdf());
|
||||
survive("hostile Pathfinder style in a .ai", || check(vectorcraft_engine::cmd::fileio::load("x.ai", &file).ok().map(|l| l.doc)))?;
|
||||
}
|
||||
|
||||
/// Art styles with Offset Path, Outline Object and Outline Stroke, in any order, shown or hidden,
|
||||
/// whose dictionaries hold any of Offset Path's entries and unknown ones, as any kind, with any
|
||||
/// value (huge, tiny, not a number, a string), repeated or left out, on the whole object, a fill
|
||||
|
||||
@@ -127,6 +127,9 @@ impl Reader<'_> {
|
||||
/// `type To`: a text object begins.
|
||||
pub(super) fn begin_text(&mut self, vals: &[V], hidden: bool) {
|
||||
self.end_path_quietly();
|
||||
if self.pattern.is_some() {
|
||||
self.unreadable("type in a pattern", false);
|
||||
}
|
||||
let kind = nums::<1>(vals).map_or(0, |[k]| k as i64);
|
||||
self.text = Some(LegacyText { kind, gs: self.gs.clone(), hidden, ..LegacyText::default() });
|
||||
}
|
||||
|
||||
@@ -52,9 +52,13 @@
|
||||
//! lines and `1 (style) XW`: the drawn look is kept, named after the object.
|
||||
//! - Patterns: `%AI3_BeginPattern: (name)`, `(name) llx lly urx ury` (the tile, in the pattern's
|
||||
//! space, y up), the tile's art (on `%_` lines in newer files), `E`, `%AI3_EndPattern`; each is
|
||||
//! read by a reader of its own and becomes a pattern swatch. A fill or stroke with one:
|
||||
//! read by a reader of its own and becomes a pattern swatch. In the version 7 form (§3.4) a list
|
||||
//! of layers follows the tile, `[ (colors) @ (tile) & … ] E`, each layer's tile read from its
|
||||
//! string with the colors' state (`_ &`: the tile's box filled). A fill or stroke with one:
|
||||
//! `(name) x y scaleX scaleY angle reflect axis shear shearAxis [matrix] p` (`P`), the matrix
|
||||
//! taking the pattern's space to art space (the other operands are what it is made of).
|
||||
//! taking the pattern's space to art space (the other operands are what it is made of). With a
|
||||
//! pattern defined in the version 7 form, the other operands are applied in order (§5.4.1) before
|
||||
//! the initial matrix.
|
||||
//!
|
||||
//! - Type in the legacy format (version 7 specification §15): `type To` … `TO`, read by
|
||||
//! [`legacy_text`].
|
||||
@@ -327,6 +331,9 @@ struct Reader<'a> {
|
||||
pattern: Option<PatternHead>,
|
||||
/// The tile (y down) of each pattern read, by name.
|
||||
pattern_tiles: HashMap<String, Rect>,
|
||||
/// The patterns read from a definition in the version 7 form, whose fills apply their other
|
||||
/// operands before the matrix (see [`Reader::pattern_paint`]).
|
||||
v7_patterns: HashSet<String>,
|
||||
/// The legacy text object being read (`To` … `TO`), and the modal type attributes.
|
||||
text: Option<legacy_text::LegacyText>,
|
||||
type_state: legacy_text::TypeState,
|
||||
@@ -431,6 +438,7 @@ impl<'a> Reader<'a> {
|
||||
ruler_units: None,
|
||||
pattern: None,
|
||||
pattern_tiles: HashMap::new(),
|
||||
v7_patterns: HashSet::new(),
|
||||
text: None,
|
||||
type_state: legacy_text::TypeState::default(),
|
||||
graph: None,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::art::{four, sane, two};
|
||||
use super::types::{
|
||||
FLIP, Kind, MAX_HEX, MAX_NOTE, MAX_PATTERNS, MAX_PLACED_FOLDER, MAX_STACK, MAX_SUBREADERS, PatternHead, Place, Raster, SKIPPED, VERSIONED_UNENDED,
|
||||
FLIP, GState, Kind, MAX_HEX, MAX_NOTE, MAX_PATTERNS, MAX_PLACED_FOLDER, MAX_STACK, MAX_SUBREADERS, PatternHead, Place, Raster, SKIPPED,
|
||||
VERSIONED_UNENDED,
|
||||
};
|
||||
use super::{Arc, Node, PatternDef, Reader, Rect, Tok, V, marker};
|
||||
|
||||
@@ -82,10 +83,14 @@ impl<'a> Reader<'a> {
|
||||
return Ok(());
|
||||
}
|
||||
let m = marker(line);
|
||||
// A pattern's definition (one inside another's isn't read).
|
||||
if m == "BeginPattern" && self.pattern.is_none() {
|
||||
// A pattern's definition. One inside another's isn't read, and the outer tile is then incomplete.
|
||||
if m == "BeginPattern" {
|
||||
let section = self.section("EndPattern")?;
|
||||
self.define_pattern(section);
|
||||
if self.pattern.is_some() {
|
||||
self.unsupported.insert("patterns inside patterns".into());
|
||||
} else {
|
||||
self.define_pattern(section);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if m == "BeginSymbol" {
|
||||
@@ -322,6 +327,11 @@ impl<'a> Reader<'a> {
|
||||
if self.pattern_tiles.len() >= MAX_PATTERNS || self.subreader_depth >= MAX_SUBREADERS {
|
||||
return;
|
||||
}
|
||||
match legacy_pattern(section) {
|
||||
Legacy::No => {}
|
||||
Legacy::Malformed => return,
|
||||
Legacy::Yes(def) => return self.define_legacy_pattern(&def),
|
||||
}
|
||||
let mut sub = Reader::new(section);
|
||||
sub.subreader_depth = self.subreader_depth + 1;
|
||||
sub.pattern = Some(PatternHead::default());
|
||||
@@ -339,6 +349,98 @@ impl<'a> Reader<'a> {
|
||||
&& sub.unread.is_empty()
|
||||
&& sub.hidden_unread.is_empty()
|
||||
&& sub.frames.len() == 1;
|
||||
self.keep_pattern(sub, whole, false);
|
||||
}
|
||||
|
||||
/// A definition in the version 7 form ([`legacy_pattern`]), read layer by layer into one group:
|
||||
/// each layer's colors (`@`) set the state its tile string (`&`) is read with, or the fill of the
|
||||
/// tile's box (`_ &`). Each layer starts from the state the definition starts with.
|
||||
fn define_legacy_pattern(&mut self, def: &LegacyPattern) {
|
||||
let mut sub = Reader::new(b"");
|
||||
sub.subreader_depth = self.subreader_depth + 1;
|
||||
sub.pattern = Some(PatternHead { taken: true, name: def.name.clone(), tile: Some(def.tile) });
|
||||
sub.gradients = std::mem::take(&mut self.gradients);
|
||||
sub.nodes = self.nodes;
|
||||
sub.template = self.template;
|
||||
let mut read = sub.open(Kind::Group, false);
|
||||
for layer in &def.layers {
|
||||
if read.is_err() {
|
||||
break;
|
||||
}
|
||||
read = sub.pattern_layer(layer, def.tile);
|
||||
}
|
||||
self.nodes = sub.nodes;
|
||||
self.gradients = std::mem::take(&mut sub.gradients);
|
||||
let whole = read.is_ok()
|
||||
&& sub.unsupported.is_empty()
|
||||
&& sub.unknown.is_empty()
|
||||
&& sub.unread.is_empty()
|
||||
&& sub.hidden_unread.is_empty()
|
||||
&& sub.frames.len() == 1;
|
||||
self.keep_pattern(sub, whole, true);
|
||||
}
|
||||
|
||||
/// One layer of a definition in the version 7 form, read into the definition's group.
|
||||
fn pattern_layer(&mut self, layer: &'a LegacyLayer, tile: Rect) -> Result<(), String> {
|
||||
self.gs = GState::default();
|
||||
self.pending_fill = None;
|
||||
self.pending_stroke = None;
|
||||
self.pending_unread_fill = false;
|
||||
self.pending_unread_stroke = false;
|
||||
self.instance = None;
|
||||
self.end_path_quietly();
|
||||
// The color part has the overprint and the colors only.
|
||||
let mut lex = super::Lexer::new(&layer.color);
|
||||
while let Some(t) = lex.next_token() {
|
||||
match t.tok {
|
||||
Tok::Num(_) | Tok::Str(_) | Tok::Hex(_) => {}
|
||||
Tok::Word(w) if LAYER_COLOR_OPS.contains(&w) => {}
|
||||
_ => return Err("a pattern layer's colors hold something else".into()),
|
||||
}
|
||||
}
|
||||
self.run_string(&layer.color)?;
|
||||
match &layer.tile {
|
||||
Some(art) => self.run_string(art)?,
|
||||
None => {
|
||||
let corner = |x: f64, y: f64| [V::Num(x), V::Num(y)];
|
||||
self.path_op("m", &corner(tile.x0, tile.y0))?;
|
||||
for (x, y) in [(tile.x0, tile.y1), (tile.x1, tile.y1), (tile.x1, tile.y0)] {
|
||||
self.path_op("L", &corner(x, y))?;
|
||||
}
|
||||
self.paint("f", false, false)?;
|
||||
}
|
||||
}
|
||||
// A path the layer leaves unpainted paints nothing.
|
||||
self.end_path_quietly();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run this reader on one of a pattern layer's strings, which must end everything it starts.
|
||||
fn run_string(&mut self, bytes: &'a [u8]) -> Result<(), String> {
|
||||
let depth = self.frames.len();
|
||||
self.lex = super::Lexer::new(bytes);
|
||||
let read = self.run();
|
||||
let open = self.done
|
||||
|| self.frames.len() != depth
|
||||
|| self.stack.iter().any(|v| matches!(v, V::Mark))
|
||||
|| !self.marks.is_empty()
|
||||
|| self.text.is_some()
|
||||
|| self.raster.is_some()
|
||||
|| self.place.is_some()
|
||||
|| self.mesh.is_some()
|
||||
|| self.gradient_def.is_some();
|
||||
self.stack.clear();
|
||||
self.marks.clear();
|
||||
read?;
|
||||
if open {
|
||||
return Err("a pattern layer doesn't end what it starts".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Keep the pattern `sub` read, when it read it `whole`, as a pattern swatch; `v7` when it was
|
||||
/// defined in the version 7 form.
|
||||
fn keep_pattern(&mut self, mut sub: Reader<'_>, whole: bool, v7: bool) {
|
||||
let (Some(head), Some(frame)) = (sub.pattern.take(), sub.frames.pop()) else { return };
|
||||
let Some(tile) = head.tile.filter(|t| whole && sane(*t) && t.width() > 0.0 && t.height() > 0.0 && !frame.children.is_empty()) else {
|
||||
return;
|
||||
@@ -349,6 +451,11 @@ impl<'a> Reader<'a> {
|
||||
if self.pattern_tiles.insert(def.name.clone(), def.tile).is_some() {
|
||||
self.doc.patterns.retain(|p| p.name != def.name);
|
||||
}
|
||||
if v7 {
|
||||
self.v7_patterns.insert(def.name.clone());
|
||||
} else {
|
||||
self.v7_patterns.remove(&def.name);
|
||||
}
|
||||
self.doc.patterns.push(def);
|
||||
for (key, blob) in sub.doc.images {
|
||||
self.doc.images.entry(key).or_insert(blob);
|
||||
@@ -404,6 +511,117 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The operators a pattern layer's colors (`@`) may hold: overprint, gray, process and custom colors.
|
||||
const LAYER_COLOR_OPS: &[&[u8]] = &[b"O", b"R", b"g", b"G", b"k", b"K", b"x", b"X"];
|
||||
|
||||
/// The longest string a pattern layer may have (the format's limit, 64K bytes).
|
||||
const MAX_LAYER_STRING: usize = 65_535;
|
||||
|
||||
/// Most layers in one pattern's definition.
|
||||
const MAX_LAYERS: usize = 65_536;
|
||||
|
||||
/// A pattern's definition in the version 7 form: its head, then a list of layers painted in order,
|
||||
/// the first the lowest.
|
||||
struct LegacyPattern {
|
||||
name: String,
|
||||
/// The tile in the pattern's space (y up).
|
||||
tile: Rect,
|
||||
layers: Vec<LegacyLayer>,
|
||||
}
|
||||
|
||||
/// `(colors) @ (tile) &`, or `(colors) @ _ &` (no tile: the tile's box is filled with the colors' fill).
|
||||
struct LegacyLayer {
|
||||
color: Vec<u8>,
|
||||
tile: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
enum Legacy {
|
||||
/// Another form: the definition's art follows its head as operators.
|
||||
No,
|
||||
/// The version 7 form, which can't be read.
|
||||
Malformed,
|
||||
Yes(LegacyPattern),
|
||||
}
|
||||
|
||||
/// The next token that isn't a comment; `Err` at a pattern's definition inside this one.
|
||||
fn next_operand<'s>(lex: &mut super::Lexer<'s>) -> Result<Option<super::super::lex::Token<'s>>, ()> {
|
||||
while let Some(t) = lex.next_token() {
|
||||
match t.tok {
|
||||
Tok::Comment(c) if marker(&String::from_utf8_lossy(c)) == "BeginPattern" => return Err(()),
|
||||
Tok::Comment(_) => {}
|
||||
_ => return Ok(Some(t)),
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// A pattern's definition in the version 7 form: `(name) llx lly urx ury [`, then for each layer
|
||||
/// `(colors) @` and `(tile) &` or `_ &`, then `] E` (version 7 specification §3.4). It is that form
|
||||
/// when a `[` that isn't on a `%_` line follows the head.
|
||||
fn legacy_pattern(section: &[u8]) -> Legacy {
|
||||
let mut lex = super::Lexer::new(section);
|
||||
let mut next = || next_operand(&mut lex).ok().flatten().map(|t| (t.tok, t.hidden));
|
||||
let name = match next() {
|
||||
Some((Tok::Str(s), _)) => super::obj::text(&s),
|
||||
_ => return Legacy::No,
|
||||
};
|
||||
let mut tile = [0.0; 4];
|
||||
for v in &mut tile {
|
||||
match next() {
|
||||
Some((Tok::Num(n), _)) => *v = n,
|
||||
_ => return Legacy::No,
|
||||
}
|
||||
}
|
||||
if !matches!(next(), Some((Tok::Word(b"["), false))) {
|
||||
return Legacy::No;
|
||||
}
|
||||
let [x0, y0, x1, y1] = tile;
|
||||
let mut layers = vec![];
|
||||
let string = |t: Option<(Tok, bool)>| match t {
|
||||
Some((Tok::Str(s) | Tok::Hex(s), _)) if s.len() <= MAX_LAYER_STRING => Some(s),
|
||||
_ => None,
|
||||
};
|
||||
let word = |t: Option<(Tok, bool)>, w: &[u8]| matches!(t, Some((Tok::Word(x), _)) if x == w);
|
||||
loop {
|
||||
// Before the first layer, anything but a string or `] E` is the newer form's art (`[]0 d`).
|
||||
let first = layers.is_empty();
|
||||
let color = match next() {
|
||||
Some((Tok::Word(b"]"), _)) if !first => break,
|
||||
Some((Tok::Word(b"]"), _)) => {
|
||||
return match next() {
|
||||
Some((Tok::Word(b"E"), _)) => Legacy::Yes(LegacyPattern { name, tile: Rect::new(x0, y0, x1, y1), layers }),
|
||||
_ => Legacy::No,
|
||||
};
|
||||
}
|
||||
t @ Some((Tok::Str(_) | Tok::Hex(_), _)) => match string(t) {
|
||||
Some(s) => s,
|
||||
None => return Legacy::Malformed,
|
||||
},
|
||||
_ if first => return Legacy::No,
|
||||
_ => return Legacy::Malformed,
|
||||
};
|
||||
if !word(next(), b"@") {
|
||||
return Legacy::Malformed;
|
||||
}
|
||||
let tile = match next() {
|
||||
Some((Tok::Word(b"_"), _)) => None,
|
||||
t => match string(t) {
|
||||
Some(s) => Some(s),
|
||||
None => return Legacy::Malformed,
|
||||
},
|
||||
};
|
||||
if !word(next(), b"&") || layers.len() >= MAX_LAYERS {
|
||||
return Legacy::Malformed;
|
||||
}
|
||||
layers.push(LegacyLayer { color, tile });
|
||||
}
|
||||
// `] E` ends the definition: nothing but comments may follow it.
|
||||
if !word(next(), b"E") || !matches!(next_operand(&mut lex), Ok(None)) {
|
||||
return Legacy::Malformed;
|
||||
}
|
||||
Legacy::Yes(LegacyPattern { name, tile: Rect::new(x0, y0, x1, y1), layers })
|
||||
}
|
||||
|
||||
/// How many custom colors the header may define.
|
||||
pub(super) const MAX_CUSTOM_COLORS: usize = 1000;
|
||||
|
||||
|
||||
@@ -182,7 +182,7 @@ fn apply_one(doc: &mut Document, found: &OnPath, at: &HashMap<NodeId, Vec<usize>
|
||||
let center = doc.node_at(place)?.geometric_bounds()?.center();
|
||||
members.push(Member { id, frame: Affine::rotate_about(angle, center), angle });
|
||||
}
|
||||
let on_path = ObjectsOnPath { path, members, pivot: r.pivot, rotate: r.rotate };
|
||||
let on_path = ObjectsOnPath { path, members, pivot: r.pivot, rotate: r.rotate, spacing: None, start: 0.0 };
|
||||
doc.node_mut_at(group_at)?.extras_mut().objects_on_path = Some(Box::new(on_path));
|
||||
Some(())
|
||||
}
|
||||
@@ -402,7 +402,8 @@ impl<'a> Reader<'a> {
|
||||
|
||||
/// `(name) x y scaleX scaleY angle reflect axis shear shearAxis [matrix] p` (`P`: the stroke's):
|
||||
/// the pattern swatch `name`, its space taken to art space by the matrix. A pattern this hasn't
|
||||
/// read can't be drawn.
|
||||
/// read can't be drawn. For a pattern defined in the version 7 form, the other operands are
|
||||
/// applied in order before the initial matrix ([`pattern_controls`]).
|
||||
fn pattern_paint(&mut self, w: &str, vals: &[V]) {
|
||||
// In the setup it paints nothing (and the art's space isn't fixed yet).
|
||||
if self.frames.is_empty() {
|
||||
@@ -413,7 +414,16 @@ impl<'a> Reader<'a> {
|
||||
self.unread_pattern(w);
|
||||
return;
|
||||
};
|
||||
let matrix = vals.iter().rev().find_map(|v| if let V::Arr(a) = v { paint::affine(&Self::nums(a)) } else { None });
|
||||
let mut matrix = vals.iter().rev().find_map(|v| if let V::Arr(a) = v { paint::affine(&Self::nums(a)) } else { None });
|
||||
if name.as_ref().is_some_and(|n| self.v7_patterns.contains(n)) {
|
||||
let controls: Vec<f64> =
|
||||
vals.iter().skip_while(|v| !matches!(v, V::Str(_))).skip(1).take_while(|v| !matches!(v, V::Arr(_))).filter_map(V::num).collect();
|
||||
let Some(controls) = pattern_controls(&controls) else {
|
||||
self.unread_pattern(w);
|
||||
return;
|
||||
};
|
||||
matrix = Some(matrix.unwrap_or(Affine::IDENTITY) * controls);
|
||||
}
|
||||
let Some(xf) = pattern_xf(self.space(), matrix, tile) else {
|
||||
self.unread_pattern(w);
|
||||
return;
|
||||
@@ -596,11 +606,14 @@ impl<'a> Reader<'a> {
|
||||
return;
|
||||
}
|
||||
// A style read here: the object, painted as it says.
|
||||
if let Some(mut appearance) = self
|
||||
.styles
|
||||
.get(&style)
|
||||
.and_then(|st| styled(object, look, st, &StylePaints { gradients: &self.gradients, patterns: &self.pattern_tiles, space }))
|
||||
{
|
||||
if let Some(mut appearance) = self.styles.get(&style).and_then(|st| {
|
||||
styled(
|
||||
object,
|
||||
look,
|
||||
st,
|
||||
&StylePaints { gradients: &self.gradients, patterns: &self.pattern_tiles, v7_patterns: &self.v7_patterns, space },
|
||||
)
|
||||
}) {
|
||||
// Strokes and effects at the document's scale, as the art (a Large Canvas copy's is scaled up).
|
||||
let k = space.determinant().abs().sqrt();
|
||||
if k.is_finite() && k > 0.0 && (k - 1.0).abs() > 1e-9 {
|
||||
@@ -694,10 +707,33 @@ fn pattern_xf(space: Affine, matrix: Option<Affine>, tile: Rect) -> Option<Affin
|
||||
(xf.determinant().abs() >= 1e-12 && xf.as_coeffs().iter().all(|v| v.is_finite())).then_some(xf)
|
||||
}
|
||||
|
||||
/// What a style's fills paint with: the file's gradients and pattern tiles, and art space → the document.
|
||||
/// A pattern fill's `x y scaleX scaleY angle reflect axis shear shearAxis` as one transform of the
|
||||
/// pattern's space, applied before its initial matrix: the shear (by `shear` degrees along the line
|
||||
/// at `shearAxis` degrees), the reflection about the line at `axis` degrees when `reflect` isn't
|
||||
/// 0, the counterclockwise rotation by `angle` degrees, the scale, then the move to `x y`. `None`
|
||||
/// unless there are nine finite numbers.
|
||||
fn pattern_controls(n: &[f64]) -> Option<Affine> {
|
||||
let &[x, y, sx, sy, angle, reflect, axis, shear, shear_axis] = n else { return None };
|
||||
if !n.iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let turn = |deg: f64| Affine::rotate(deg.to_radians());
|
||||
let reflection = if reflect != 0.0 { turn(axis) * Affine::scale_non_uniform(1.0, -1.0) * turn(-axis) } else { Affine::IDENTITY };
|
||||
let shearing = if shear != 0.0 {
|
||||
turn(shear_axis) * Affine::new([1.0, 0.0, shear.to_radians().tan(), 1.0, 0.0, 0.0]) * turn(-shear_axis)
|
||||
} else {
|
||||
Affine::IDENTITY
|
||||
};
|
||||
let xf = Affine::translate((x, y)) * Affine::scale_non_uniform(sx, sy) * turn(angle) * reflection * shearing;
|
||||
xf.as_coeffs().iter().all(|v| v.is_finite()).then_some(xf)
|
||||
}
|
||||
|
||||
/// What a style's fills paint with: the file's gradients and pattern tiles, the patterns defined in
|
||||
/// the version 7 form, and art space → the document.
|
||||
struct StylePaints<'a> {
|
||||
gradients: &'a HashMap<String, Gradient>,
|
||||
patterns: &'a HashMap<String, Rect>,
|
||||
v7_patterns: &'a HashSet<String>,
|
||||
space: Affine,
|
||||
}
|
||||
|
||||
@@ -740,7 +776,8 @@ fn placed_paints(look: &Node, out: &mut HashMap<String, Paint>, depth: usize) {
|
||||
const PATTERN_KEY: &str = "\u{1}pattern ";
|
||||
|
||||
/// `object`'s appearance with style `st`, its drawn look `look`: `None` when the style isn't one
|
||||
/// this reads, or asks a group for fills or strokes.
|
||||
/// this reads, asks a group for fills or strokes, or has Pathfinder effects on anything but a group
|
||||
/// with no fills or strokes.
|
||||
fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, paints: &StylePaints) -> Option<Appearance> {
|
||||
use crate::import::ai::style::StyleItem;
|
||||
// A text object's slot (an empty group standing for it) takes the style as the type will.
|
||||
@@ -748,6 +785,8 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p
|
||||
if !st.plain
|
||||
|| (!slot && !st.simple)
|
||||
|| (object.is_container() && !slot && !matches!(object.kind, NodeKind::Compound { .. }) && !st.items.is_empty())
|
||||
|| (st.pathfinder
|
||||
&& (slot || !st.items.is_empty() || object.is_compound_shape() || !matches!(object.kind, NodeKind::Group { clip: false, .. })))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
@@ -778,11 +817,15 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p
|
||||
};
|
||||
AppearanceItem::Fill(FillLayer::new(paint))
|
||||
}
|
||||
StyleItem::Pattern { name, matrix } => match placed.get(&format!("{PATTERN_KEY}{name}")) {
|
||||
StyleItem::Pattern { name, matrix, controls } => match placed.get(&format!("{PATTERN_KEY}{name}")) {
|
||||
Some(p) => AppearanceItem::Fill(FillLayer::new(p.clone())),
|
||||
None => {
|
||||
let tile = paints.patterns.get(name).copied()?;
|
||||
let xf = pattern_xf(paints.space, matrix.and_then(|m| paint::affine(&m)), tile)?;
|
||||
let mut matrix = matrix.and_then(|m| paint::affine(&m));
|
||||
if paints.v7_patterns.contains(name) {
|
||||
matrix = Some(matrix.unwrap_or(Affine::IDENTITY) * pattern_controls(controls)?);
|
||||
}
|
||||
let xf = pattern_xf(paints.space, matrix, tile)?;
|
||||
AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: name.clone(), xf }))
|
||||
}
|
||||
},
|
||||
|
||||
@@ -35,13 +35,15 @@
|
||||
//! A style is *plain* when every filter in it is one read here: fills and strokes (in a colour; fills
|
||||
//! with a pattern or gradient too), each with its own transparency and effects, and the effects of
|
||||
//! [`effect`]. Such objects are read as themselves with an appearance of those fills, strokes and
|
||||
//! effects; others keep their drawn look.
|
||||
//! effects; others keep their drawn look. Effect › Pathfinder effects (`(Adobe Pathfinder)` in the
|
||||
//! object's chain) are read on a group with no fills or strokes of its own, which keeps its members.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::{Dash, Effect, Knockout, LineCap, LineJoin, WidthProfile};
|
||||
use vectorcraft_effects::is_pathfinder;
|
||||
|
||||
use super::lex::{Lexer, Tok};
|
||||
use super::obj::V;
|
||||
@@ -68,6 +70,7 @@ const ZIG_ZAG: &str = "Adobe Zigzag"; // brand-ok: the filter's name in the file
|
||||
const GAUSSIAN: &str = "Adobe PSL Gaussian Blur"; // brand-ok: the filter's name in the files
|
||||
const BAS_RELIEF: &str = "PSAdapter_plugin_BsRl";
|
||||
const SHAPE_EFFECTS: &str = "Adobe Shape Effects"; // brand-ok: the filter's name in the files
|
||||
const PATHFINDER: &str = "Adobe Pathfinder"; // brand-ok: the filter's name in the files
|
||||
|
||||
const CHAIN: &str = "Chain Style Filter";
|
||||
const STACK: &str = "Stack Style Filter";
|
||||
@@ -101,6 +104,26 @@ pub(super) fn warp_style(n: i64) -> Option<&'static str> {
|
||||
id.strip_prefix("warp.")
|
||||
}
|
||||
|
||||
/// The keys of an Effect › Pathfinder › Add filter's dictionary besides `DisplayString`, each with
|
||||
/// the kind and the one value read: `Command` 0 is Add, and the rest are its Pathfinder Options,
|
||||
/// Soft Mix and Trap settings
|
||||
/// (https://community.adobe.com/questions-652/liveeffect-xml-effect-is-added-under-the-object-795137).
|
||||
const PATHFINDER_ADD: [(&str, Kind, f64); 13] = [
|
||||
("Command", Kind::Int, 0.0),
|
||||
("ConvertCustom", Kind::Bool, 1.0),
|
||||
("ExtractUnpainted", Kind::Bool, 1.0),
|
||||
("Mix", Kind::Real, 0.5),
|
||||
("Precision", Kind::Real, 10.0),
|
||||
("RemovePoints", Kind::Bool, 0.0),
|
||||
("TrapAspect", Kind::Real, 1.0),
|
||||
("TrapConvertCustom", Kind::Bool, 0.0),
|
||||
("TrapMaxTint", Kind::Real, 1.0),
|
||||
("TrapReverse", Kind::Bool, 0.0),
|
||||
("TrapThickness", Kind::Real, 0.25),
|
||||
("TrapTint", Kind::Real, 0.4),
|
||||
("TrapTintTolerance", Kind::Real, 0.05),
|
||||
];
|
||||
|
||||
/// A plain style's paint, as the object comes in.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(super) struct ArtStyle {
|
||||
@@ -108,7 +131,8 @@ pub(super) struct ArtStyle {
|
||||
pub plain: bool,
|
||||
/// It is one fill and one stroke at most, in solid colours or the object's own gradient, with
|
||||
/// no transparency or effects of their own, and only Drop Shadow, Inner Glow, Outer Glow,
|
||||
/// Feather, Round Corners, Scribble, Convert to Shape and the Path effects (Offset Path, Outline Object, Outline Stroke) on the object: what any object is read with. Type takes the other plain styles too (its drawn look
|
||||
/// Feather, Round Corners, Scribble, Convert to Shape and the Path effects (Offset Path, Outline Object, Outline Stroke) on the object
|
||||
/// (and Pathfinder effects when it has no fills or strokes): what any object is read with. Type takes the other plain styles too (its drawn look
|
||||
/// can't be retyped); other objects keep their drawn look, which is the app's own rendering.
|
||||
pub simple: bool,
|
||||
/// Its fills and strokes, bottom first.
|
||||
@@ -122,6 +146,8 @@ pub(super) struct ArtStyle {
|
||||
/// The object's own opacity, blend mode, isolation and knockout (its blend filter), when the
|
||||
/// style has them.
|
||||
pub transparency: Option<(f32, BlendMode, bool, Knockout)>,
|
||||
/// [`Self::effects`] holds Effect › Pathfinder effects, which only a group is read with.
|
||||
pub pathfinder: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -133,10 +159,12 @@ pub(super) enum StyleItem {
|
||||
name: Option<String>,
|
||||
angle: f64,
|
||||
},
|
||||
/// A fill with pattern swatch `name`, its space taken to art space by `matrix`.
|
||||
/// A fill with pattern swatch `name`, its space taken to art space by `matrix`; `controls`, the
|
||||
/// numbers before the matrix, apply first when the pattern was defined in the version 7 form.
|
||||
Pattern {
|
||||
name: String,
|
||||
matrix: Option<[f64; 6]>,
|
||||
controls: Vec<f64>,
|
||||
},
|
||||
Stroke {
|
||||
paint: Paint,
|
||||
@@ -185,6 +213,8 @@ struct Filter {
|
||||
params: HashMap<String, f64>,
|
||||
/// How each key of its dictionary is written.
|
||||
kinds: HashMap<String, Kind>,
|
||||
/// A key of its dictionary is written more than once.
|
||||
repeated: bool,
|
||||
/// Its dictionary's arrays (`/Array : v /Real , … ; (key) ,`), by key.
|
||||
arrays: HashMap<String, Vec<f64>>,
|
||||
fill: Option<Paint>,
|
||||
@@ -199,8 +229,8 @@ struct Filter {
|
||||
gradient: bool,
|
||||
/// The gradient's swatch and angle (`Bg`).
|
||||
gradient_of: Option<(Option<String>, f64)>,
|
||||
/// `(name) … [matrix] p`.
|
||||
pattern: Option<(String, Option<[f64; 6]>)>,
|
||||
/// `(name) … [matrix] p`, and the numbers between the name and the matrix.
|
||||
pattern: Option<(String, Option<[f64; 6]>, Vec<f64>)>,
|
||||
/// `mode opacity … Xy`.
|
||||
xy: Option<(usize, f32)>,
|
||||
/// `… isolate knockout … Xy`.
|
||||
@@ -216,6 +246,7 @@ impl Default for Filter {
|
||||
compound: false,
|
||||
params: HashMap::new(),
|
||||
kinds: HashMap::new(),
|
||||
repeated: false,
|
||||
arrays: HashMap::new(),
|
||||
fill: None,
|
||||
stroke: None,
|
||||
@@ -358,7 +389,8 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap<String, ArtStyle> {
|
||||
}
|
||||
b"Array" => dict_array = Some(vec![]),
|
||||
b"Int" | b"Real" | b"Bool" => {
|
||||
let value = operands.iter().rev().find_map(V::num);
|
||||
// The number right before the type: an earlier one isn't this value.
|
||||
let value = operands.last().and_then(V::num);
|
||||
operands.clear();
|
||||
if let Some(a) = dict_array.as_mut() {
|
||||
a.extend(value);
|
||||
@@ -378,7 +410,7 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap<String, ArtStyle> {
|
||||
Some(value) => f.params.insert(key.clone(), value),
|
||||
None => f.params.remove(&key),
|
||||
};
|
||||
f.kinds.insert(key, kind);
|
||||
f.repeated |= f.kinds.insert(key, kind).is_some();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -417,7 +449,7 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap<String, ArtStyle> {
|
||||
None => entry.map(|k| (k, Kind::Other)),
|
||||
};
|
||||
if let (Some((key, kind)), Some(f)) = (key, filters.last_mut()) {
|
||||
f.kinds.insert(key, kind);
|
||||
f.repeated |= f.kinds.insert(key, kind).is_some();
|
||||
}
|
||||
}
|
||||
if let Some(f) = filters.last_mut() {
|
||||
@@ -518,8 +550,10 @@ fn paint_op(f: &mut Filter, op: &str, vals: &[V]) {
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let controls: Vec<f64> =
|
||||
vals.iter().skip_while(|v| !matches!(v, V::Str(_))).skip(1).take_while(|v| !matches!(v, V::Arr(_))).filter_map(V::num).collect();
|
||||
if let Some(name) = name {
|
||||
f.pattern = Some((name, matrix));
|
||||
f.pattern = Some((name, matrix, controls));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -987,18 +1021,33 @@ fn effect(f: &Filter, under: Under) -> Option<Effect> {
|
||||
// Its settings are in a Photoshop plug-in's binary block: the effect's defaults stand in.
|
||||
BAS_RELIEF => ("sketch.basRelief", json!({"detail": 13.0, "smoothness": 3.0, "lightDirection": "bottom"})),
|
||||
SHAPE_EFFECTS => return shape_effect(f),
|
||||
PATHFINDER => return pathfinder_effect(f),
|
||||
_ => return None,
|
||||
};
|
||||
Some(Effect { id: id.into(), params, visible: f.visible })
|
||||
}
|
||||
|
||||
/// Effect › Pathfinder › Add, when every key of [`PATHFINDER_ADD`] is there with its kind and value
|
||||
/// and the only other key is the `DisplayString` text, each written once. `None` for anything else,
|
||||
/// which keeps the drawn look.
|
||||
fn pathfinder_effect(f: &Filter) -> Option<Effect> {
|
||||
let known = f.kinds.iter().all(|(key, kind)| (key == "DisplayString" && *kind == Kind::Other) || PATHFINDER_ADD.iter().any(|(k, ..)| k == key));
|
||||
if !known || f.repeated || !f.arrays.is_empty() || f.fill.is_some() || f.stroke.is_some() || f.gradient || f.pattern.is_some() {
|
||||
return None;
|
||||
}
|
||||
if !PATHFINDER_ADD.iter().all(|(key, kind, value)| f.kinds.get(*key) == Some(kind) && f.params.get(*key) == Some(value)) {
|
||||
return None;
|
||||
}
|
||||
Some(Effect { id: "pathfinder.add".into(), params: json!({}), visible: f.visible })
|
||||
}
|
||||
|
||||
/// The fill or stroke basic filter `f` paints, `Ok(None)` when it paints nothing, `Err` when it
|
||||
/// paints in a way this doesn't read.
|
||||
fn paint_item(f: &Filter) -> Result<Option<StyleItem>, ()> {
|
||||
match f.name.as_str() {
|
||||
FILL if !f.paints.1 => Ok(None),
|
||||
FILL => match (&f.pattern, &f.gradient_of, &f.fill) {
|
||||
(Some((name, matrix)), ..) => Ok(Some(StyleItem::Pattern { name: name.clone(), matrix: *matrix })),
|
||||
(Some((name, matrix, controls)), ..) => Ok(Some(StyleItem::Pattern { name: name.clone(), matrix: *matrix, controls: controls.clone() })),
|
||||
(None, Some((name, angle)), _) => Ok(Some(StyleItem::Gradient { name: name.clone(), angle: *angle })),
|
||||
(None, None, _) if f.gradient => Ok(Some(StyleItem::Gradient { name: None, angle: 0.0 })),
|
||||
(None, None, Some(p)) => Ok(Some(StyleItem::Fill(p.clone()))),
|
||||
@@ -1092,9 +1141,9 @@ impl Builder<'_> {
|
||||
}
|
||||
}
|
||||
// Convert to Shape on one fill or stroke isn't read yet: what it draws there is
|
||||
// the drawn look's.
|
||||
// the drawn look's. A fill's or stroke's own Pathfinder effect isn't read either.
|
||||
_ => match effect(c, under) {
|
||||
Some(e) if !e.id.starts_with("convertToShape.") => look.effects.push(e),
|
||||
Some(e) if !e.id.starts_with("convertToShape.") && !is_pathfinder(&e.id) => look.effects.push(e),
|
||||
_ => self.plain = false,
|
||||
},
|
||||
}
|
||||
@@ -1132,6 +1181,7 @@ fn style(filters: &[Filter]) -> ArtStyle {
|
||||
let mut st = ArtStyle { plain: true, ..ArtStyle::default() };
|
||||
let Some(root) = filters.iter().position(|f| f.parent.is_none()) else { return st };
|
||||
let mut b = Builder { filters, plain: true };
|
||||
let chained = filters[root].compound && filters[root].name == CHAIN;
|
||||
let top = if filters[root].compound { b.children(root) } else { vec![root] };
|
||||
for id in top {
|
||||
let f = &filters[id];
|
||||
@@ -1151,12 +1201,19 @@ fn style(filters: &[Filter]) -> ArtStyle {
|
||||
st.transparency = Some((opacity, super::read::blend_mode(mode), isolate, knockout));
|
||||
}
|
||||
}
|
||||
// The object's Pathfinder effects are read only in its own chain.
|
||||
_ => match effect(f, ANYTHING) {
|
||||
Some(e) => st.effects.push(e),
|
||||
None => b.plain = false,
|
||||
Some(e) if chained || !is_pathfinder(&e.id) => st.effects.push(e),
|
||||
_ => b.plain = false,
|
||||
},
|
||||
}
|
||||
}
|
||||
st.pathfinder = st.effects.iter().any(|e| is_pathfinder(&e.id));
|
||||
// A group's Pathfinder effects are drawn before its other effects: one listed after another
|
||||
// effect keeps the drawn look.
|
||||
if st.effects.iter().skip_while(|e| is_pathfinder(&e.id)).any(|e| is_pathfinder(&e.id)) {
|
||||
b.plain = false;
|
||||
}
|
||||
st.plain = b.plain;
|
||||
let count = |stroke: bool| st.items.iter().filter(|i| matches!(i, StyleItem::Stroke { .. }) == stroke).count();
|
||||
st.simple = st.plain
|
||||
@@ -1179,8 +1236,10 @@ fn style(filters: &[Filter]) -> ArtStyle {
|
||||
| "path.offsetPath"
|
||||
| "path.outlineObject"
|
||||
| "path.outlineStroke"
|
||||
)
|
||||
});
|
||||
) || is_pathfinder(&e.id)
|
||||
})
|
||||
// Pathfinder effects on a group with no fills or strokes of its own (`styled` checks the group).
|
||||
&& (!st.pathfinder || st.items.is_empty());
|
||||
st
|
||||
}
|
||||
|
||||
|
||||
@@ -471,6 +471,58 @@ fn an_effect_not_read_here_keeps_the_drawn_look() {
|
||||
assert!(!art_styles(data.as_bytes())["Odd"].plain);
|
||||
}
|
||||
|
||||
/// The dictionary of an Effect › Pathfinder filter with `Command` `command` and `Mix` `mix`, and
|
||||
/// the other options at the values the effect reads.
|
||||
fn pathfinder_keys(command: &str, mix: &str) -> String {
|
||||
format!(
|
||||
"0 /Bool (RemovePoints) ,\n{mix} /Real (Mix) ,\n1 /Bool (ConvertCustom) ,\n{command} /Int (Command) ,\n1 /Real (TrapMaxTint) ,\n\
|
||||
1 /Real (TrapAspect) ,\n0.4 /Real (TrapTint) ,\n0.25 /Real (TrapThickness) ,\n0 /Bool (TrapReverse) ,\n10 /Real (Precision) ,\n\
|
||||
(Op) /UnicodeString (DisplayString) ,\n0 /Bool (TrapConvertCustom) ,\n0.05 /Real (TrapTintTolerance) ,\n1 /Bool (ExtractUnpainted) ,\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// The style `Group`: the object's chain holding `effects`, a stack whose fill and stroke paint
|
||||
/// nothing, and the object's transparency.
|
||||
fn group_style(effects: &[String]) -> ArtStyle {
|
||||
let stack = compound(
|
||||
"Stack Style Filter",
|
||||
&[
|
||||
basic("Stroke Style Filter", "/StrokeStyle : 0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 0 Xd\n/Def ;\n (StrokeStyle) ,\n"),
|
||||
basic("Conduit Filter", ""),
|
||||
basic(
|
||||
"Fill Style Filter",
|
||||
"/FillStyle : 0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 0 Xd\n/Def ;\n (FillStyle) ,\n0 /Bool (UseEvenOdd) ,\n",
|
||||
),
|
||||
],
|
||||
);
|
||||
let mut kids = effects.to_vec();
|
||||
kids.extend([stack, blend(0, 1.0)]);
|
||||
let data = format!("/KnownStyle :\n(Group) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &kids));
|
||||
art_styles(data.as_bytes()).remove("Group").unwrap_or_default()
|
||||
}
|
||||
|
||||
fn pathfinder(keys: &str) -> String {
|
||||
basic("Adobe Pathfinder", keys)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pathfinder_add_is_read_as_its_effect() {
|
||||
// GUARDS: an `Adobe Pathfinder` filter made the style not plain, so a group with it came in as its drawn look.
|
||||
let st = group_style(&[pathfinder(&pathfinder_keys("0", "0.5"))]);
|
||||
assert!(st.plain && st.simple && st.pathfinder, "{st:?}");
|
||||
assert!(st.items.is_empty(), "{st:?}");
|
||||
let [e] = st.effects.as_slice() else { panic!("{st:?}") };
|
||||
assert_eq!((e.id.as_str(), &e.params, e.visible), ("pathfinder.add", &json!({}), true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pathfinder_commands_other_than_add_keep_the_drawn_look() {
|
||||
for command in 1..=12 {
|
||||
let st = group_style(&[pathfinder(&pathfinder_keys(&command.to_string(), "0.5"))]);
|
||||
assert!(!st.plain && !st.pathfinder && st.effects.is_empty(), "{command}: {st:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn stroke(paint: &str) -> String {
|
||||
basic("Stroke Style Filter", &format!("/StrokeStyle : 0 1 0 0 0 Xy\n0 J 0 j 2 w 10 M []0 d0 XR\n{paint}\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n"))
|
||||
}
|
||||
@@ -519,6 +571,92 @@ fn offset_path_on_the_object_is_read_with_its_settings() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_pathfinder_effect_comes_in_hidden() {
|
||||
let st = group_style(&[pathfinder(&pathfinder_keys("0", "0.5")).replacen("1 /Visible", "0 /Visible", 1)]);
|
||||
assert!(st.simple, "{st:?}");
|
||||
let [e] = st.effects.as_slice() else { panic!("{st:?}") };
|
||||
assert_eq!((e.id.as_str(), e.visible), ("pathfinder.add", false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pathfinder_effects_keep_their_order_among_the_objects_effects() {
|
||||
let offset = basic("Adobe Offset Path", "3 /Real (ofst) ,\n0 /Int (jntp) ,\n4 /Real (mlim) ,\n");
|
||||
let st = group_style(&[pathfinder(&pathfinder_keys("0", "0.5")), offset.clone()]);
|
||||
assert!(st.plain, "{st:?}");
|
||||
assert_eq!(ids(&st.effects), ["pathfinder.add", "path.offsetPath"]);
|
||||
// GUARDS: an effect before the Pathfinder effect was read too, and the group drew the Pathfinder
|
||||
// effect first, which isn't what the file draws.
|
||||
let st = group_style(&[offset, pathfinder(&pathfinder_keys("0", "0.5"))]);
|
||||
assert!(!st.plain, "{st:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pathfinder_settings_this_does_not_read_keep_the_drawn_look() {
|
||||
let add = pathfinder_keys("0", "0.5");
|
||||
let cases = [
|
||||
("no Command", add.replace("0 /Int (Command) ,\n", "")),
|
||||
("Trap", add.replace("0 /Int (Command)", "12 /Int (Command)")),
|
||||
("unknown Command", add.replace("0 /Int (Command)", "40 /Int (Command)")),
|
||||
("negative Command", add.replace("0 /Int (Command)", "-1 /Int (Command)")),
|
||||
("fractional Command", add.replace("0 /Int (Command)", "2.5 /Int (Command)")),
|
||||
("huge Command", add.replace("0 /Int (Command)", "1e999 /Int (Command)")),
|
||||
("Command as a real", add.replace("0 /Int (Command)", "0 /Real (Command)")),
|
||||
("Command without a number", add.replace("0 /Int (Command)", "(zero) /Int (Command)")),
|
||||
// A number before the string isn't its value.
|
||||
("Command with a string after a number", add.replace("0 /Int (Command)", "3 (zero) /Int (Command)")),
|
||||
("Command twice", add.clone() + "1 /Int (Command) ,\n"),
|
||||
// GUARDS: the last of a repeated key was read, so a Trap command followed by Add was read as Add.
|
||||
("Command twice, Add last", add.replace("0 /Int (Command)", "12 /Int (Command) ,\n0 /Int (Command)")),
|
||||
("Command twice, both Add", add.replace("0 /Int (Command)", "0 /Int (Command) ,\n0 /Int (Command)")),
|
||||
("an option twice, the read value last", add.replace("10 /Real (Precision)", "5 /Real (Precision) ,\n10 /Real (Precision)")),
|
||||
("unknown key", add.clone() + "1 /Int (Extra) ,\n"),
|
||||
("unknown string", add.clone() + "(x) /String (Extra) ,\n"),
|
||||
("an array", add.clone() + "/Array :\n1 /Real ,\n; (Extra) ,\n"),
|
||||
("many strings", add.clone() + &(0..40).map(|i| format!("(x) /String (DisplayString{i}) ,\n")).collect::<String>()),
|
||||
("missing option", add.replace("0.25 /Real (TrapThickness) ,\n", "")),
|
||||
("missing Mix", add.replace("0.5 /Real (Mix) ,\n", "")),
|
||||
("option of the wrong type", add.replace("10 /Real (Precision)", "10 /Int (Precision)")),
|
||||
("other Precision", add.replace("10 /Real (Precision)", "5 /Real (Precision)")),
|
||||
("huge Precision", add.replace("10 /Real (Precision)", "1e999 /Real (Precision)")),
|
||||
("Remove Redundant Points", add.replace("0 /Bool (RemovePoints)", "1 /Bool (RemovePoints)")),
|
||||
("unpainted art kept", add.replace("1 /Bool (ExtractUnpainted)", "0 /Bool (ExtractUnpainted)")),
|
||||
("other trap tint", add.replace("0.4 /Real (TrapTint)", "0.25 /Real (TrapTint)")),
|
||||
("Mix on Add", add.replace("0.5 /Real (Mix)", "0.3 /Real (Mix)")),
|
||||
("Mix as a bool", add.replace("0.5 /Real (Mix)", "1 /Bool (Mix)")),
|
||||
];
|
||||
for (case, keys) in cases {
|
||||
let st = group_style(&[pathfinder(&keys)]);
|
||||
assert!(!st.plain && !st.pathfinder && st.effects.is_empty(), "{case}: {st:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pathfinder_effect_outside_the_objects_chain_keeps_the_drawn_look() {
|
||||
let pf = pathfinder(&pathfinder_keys("0", "0.5"));
|
||||
// On a fill of its own.
|
||||
let item = compound("Chain Style Filter", &[pf.clone(), fill("0 0 0 1 0 0 0 Xa")]);
|
||||
let data =
|
||||
format!("/KnownStyle :\n(Item) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &[compound("Stack Style Filter", &[item])]));
|
||||
let st = &art_styles(data.as_bytes())["Item"];
|
||||
assert!(!st.plain, "{st:?}");
|
||||
// In a style that isn't an object's chain.
|
||||
let data = format!("/KnownStyle :\n(Bare) /Name ,\n/ActiveStyle :\n{pf}");
|
||||
let st = &art_styles(data.as_bytes())["Bare"];
|
||||
assert!(!st.plain && st.effects.is_empty(), "{st:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pathfinder_effect_with_fills_of_its_own_keeps_the_drawn_look() {
|
||||
let stack = compound("Stack Style Filter", &[fill("0 0 0 1 0 0 0 Xa"), basic("Conduit Filter", "")]);
|
||||
let data = format!(
|
||||
"/KnownStyle :\n(Filled) /Name ,\n/ActiveStyle :\n{}",
|
||||
compound("Chain Style Filter", &[pathfinder(&pathfinder_keys("0", "0.5")), stack])
|
||||
);
|
||||
let st = &art_styles(data.as_bytes())["Filled"];
|
||||
assert!(st.pathfinder && !st.simple, "{st:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_object_and_outline_stroke_are_read_with_no_settings() {
|
||||
// GUARDS: `Adobe Outline Type` and `Adobe Outline Stroke` weren't read, so the style kept its drawn look.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::{Point, Rect};
|
||||
use kurbo::{Affine, Point, Rect};
|
||||
use vectorcraft_color::gradient::GradientKind;
|
||||
use vectorcraft_color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, ColorMode, Document, Guide, Knockout, LayerColor, LineCap, LineJoin, Node, NodeKind, Unit};
|
||||
@@ -525,7 +525,7 @@ fn a_gradient_in_a_patterns_definition_is_placed_from_the_canvas() {
|
||||
/// has that isn't read, where it shows. Its definition costs nothing else.
|
||||
#[test]
|
||||
fn a_pattern_it_cant_read_is_an_error_only_where_it_fills() {
|
||||
let unread = "%AI3_BeginPattern: (Old)\n(Old) 0 0 8 8 [\n(0 O 0 R 0 g) @\n(\n0 0 m 8 8 L S\n) &\n] E\n%AI3_EndPattern\n\
|
||||
let unread = "%AI3_BeginPattern: (Old)\n(Old) 0 0 8 8 [\n(0 O 0 R 0 g) @\n(\n0 0 m 8 8 L frobnicate S\n) &\n] E\n%AI3_EndPattern\n\
|
||||
%AI3_BeginPattern: (Odd)\n(Odd) 0 0 8 8\n%_U\nE\n%AI3_EndPattern\n%AI3_BeginPattern: (Flat)\n(Flat) 0 0 8 0\n%_0 0 m\n%_8 0 L\n%_S\nE\n%AI3_EndPattern\n";
|
||||
let s = read_ok(&format!("{unread}{}", layer(&(rect_path(0.0, 0.0, 1.0, 1.0) + "f\n"))));
|
||||
assert!(s.doc.patterns.is_empty() && s.doc.swatches.iter().all(|w| !matches!(w.paint, Paint::Pattern { .. })));
|
||||
@@ -565,6 +565,231 @@ fn a_pattern_painting_with_an_unread_pattern_is_not_kept() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A pattern's definition inside another's isn't read, so the outer one isn't kept either.
|
||||
#[test]
|
||||
fn a_pattern_with_a_definition_inside_it_isnt_kept() {
|
||||
let tile = rect_path(0.0, 0.0, 8.0, 8.0).replace('\n', "\n%_");
|
||||
let inner = "%AI3_BeginPattern: (In)\n(In) 0 0 1 1\n%_0 0 m\n%_1 1 L\n%_S\nE\n%AI3_EndPattern\n";
|
||||
let def = format!("%AI3_BeginPattern: (Out)\n(Out) 0 0 8 8\n{inner}%_{tile}f\nE\n%AI3_EndPattern\n");
|
||||
let s = read_ok(&format!("{def}{}", layer("")));
|
||||
assert!(s.doc.patterns.is_empty(), "{:?}", s.doc.patterns.iter().map(|p| &p.name).collect::<Vec<_>>());
|
||||
// Without the definition inside it, it is kept.
|
||||
let s = read_ok(&format!("{}{}", def.replace(inner, ""), layer("")));
|
||||
assert!(s.doc.pattern("Out").is_some());
|
||||
}
|
||||
|
||||
/// A definition whose art follows its head as operators is still read when that art starts with a
|
||||
/// dash array (`[]0 d`) off `%_` lines, which isn't a version 7 layer list.
|
||||
#[test]
|
||||
fn a_pattern_whose_art_starts_with_a_dash_array_is_read() {
|
||||
let def = format!("%AI3_BeginPattern: (Dash)\n(Dash) 0 0 8 8 []0 d\n{}f\nE\n%AI3_EndPattern\n", rect_path(0.0, 0.0, 8.0, 8.0));
|
||||
let s = read_ok(&format!("{def}{}", layer("")));
|
||||
assert_eq!(s.doc.pattern("Dash").map(|p| p.art.len()), Some(1));
|
||||
}
|
||||
|
||||
/// Editing data in the version 7 form: `%AI5_FileFormat 2.0`, the art size around the template
|
||||
/// box's center (an artboard 200 by 100 from the origin), `setup` (pattern definitions), then `body`.
|
||||
fn pattern_stream7(setup: &str, body: &str) -> String {
|
||||
format!(
|
||||
"%!PS-Adobe-3.0\n%%Creator: test\n%AI5_FileFormat 2.0\n%AI5_ArtSize: 200 100\n%AI3_TemplateBox: 100 50 100 50\n%%EndComments\n%%BeginProlog\n%%EndProlog\n%%BeginSetup\n{setup}%%EndSetup\n{body}\n%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// One layer named `name` with the version 7 form's ten operands before `Lb`, holding `art`.
|
||||
fn pattern_layer7(name: &str, art: &str) -> String {
|
||||
format!("%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n({name}) Ln\n0 A\n{art}LB\n%AI5_EndLayer--\n")
|
||||
}
|
||||
|
||||
/// A definition of `name` in the version 7 form: its 20-point tile, then `layers`, the layer list.
|
||||
fn pattern7(name: &str, layers: &str) -> String {
|
||||
format!("%AI3_BeginPattern: ({name})\n({name}) 0 0 20 20 [\n%AI3_Tile\n{layers}] E\n%AI3_EndPattern\n")
|
||||
}
|
||||
|
||||
fn pattern_read7(setup: &str, body: &str) -> Structure {
|
||||
match read(pattern_stream7(setup, body).as_bytes()) {
|
||||
Ok(s) => s,
|
||||
Err(e) => panic!("{e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A definition in the version 7 form (§3.4): each layer's colors (`@`) paint its tile's art (`&`),
|
||||
/// the first layer the lowest. The operator lines in the strings end in CR, and each layer starts
|
||||
/// from the definition's state, so the second layer's stroke doesn't take the first one's width.
|
||||
#[test]
|
||||
fn version_7_pattern_layers_paint_in_order_with_their_own_colors() {
|
||||
let layers = "(0 O 0 R 1 0 0 0 k\r1 0 0 0 K) @\n(\r%AI6_BeginPatternLayer\r0 J 0 j 3 w 4 M []0 d\r2 2 m\r9 2 L\r9 9 L\r2 9 L\rf\r%AI6_EndPatternLayer\r) &\n\
|
||||
(0 O 1 R 0 0 0 1 k\r0 0 0 1 K) @\n(\r2 12 m\r18 12 L\rS\r) &\n";
|
||||
let fill_with = format!("(Grid) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(10.0, 10.0, 90.0, 90.0));
|
||||
let s = pattern_read7(&pattern7("Grid", layers), &pattern_layer7("Art", &fill_with));
|
||||
assert!(s.unread.is_empty() && s.warnings.is_empty(), "{:?} {:?}", s.unread, s.warnings);
|
||||
let def = s.doc.pattern("Grid").unwrap();
|
||||
assert_eq!(def.tile, Rect::new(0.0, -20.0, 20.0, 0.0), "the tile, y down");
|
||||
assert_eq!(def.art.len(), 2, "one path for each layer");
|
||||
let (square, line) = (&def.art[0], &def.art[1]);
|
||||
assert_eq!(square.geometric_bounds(), Some(Rect::new(2.0, -9.0, 9.0, -2.0)));
|
||||
assert_eq!(fill(square).color(), Some(Color::cmyk(1.0, 0.0, 0.0, 0.0)));
|
||||
assert!(square.appearance.stroke().is_none());
|
||||
assert!(line.appearance.fill().is_none());
|
||||
let stroke = line.appearance.stroke().unwrap();
|
||||
assert_eq!(stroke.paint.color(), Some(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
|
||||
assert_eq!(stroke.width, 1.0, "the first layer's width stays with it");
|
||||
assert!(stroke.overprint);
|
||||
assert!(matches!(fill(&art(&s.doc)[0]), Paint::Pattern { pattern, .. } if pattern == "Grid"));
|
||||
}
|
||||
|
||||
/// `_ &` fills the tile's box with the layer's fill color, without a stroke (§3.4).
|
||||
#[test]
|
||||
fn a_version_7_patterns_underbar_fills_the_tile_box() {
|
||||
let layers = "(0 O 0 R 0 1 0 0 k 0 0 0 1 K) @ _ &\n(0 0 0 1 k 0 0 0 1 K) @ (2 2 m 18 18 L S) &\n";
|
||||
let s = pattern_read7(&pattern7("Back", layers), &pattern_layer7("Art", ""));
|
||||
let def = s.doc.pattern("Back").unwrap();
|
||||
let back = &def.art[0];
|
||||
assert_eq!(back.geometric_bounds(), Some(def.tile));
|
||||
assert_eq!(fill(back).color(), Some(Color::cmyk(0.0, 1.0, 0.0, 0.0)));
|
||||
assert!(back.appearance.stroke().is_none());
|
||||
assert!(def.art[1].appearance.stroke().is_some());
|
||||
}
|
||||
|
||||
/// A layer's strings are read with their escapes undone: `\r`, `\n`, an octal tab, a backslash at
|
||||
/// a line's end, and escaped parentheses around a custom color's name.
|
||||
#[test]
|
||||
fn a_version_7_patterns_strings_are_read_with_their_escapes_undone() {
|
||||
let layers = "(0 O 0 R 0 0 0 1 \\(Ink \\(A\\)\\) 0 x) @\n(2 2 m\\r9 2 L\\n9 9 L\\0112 9 \\\nL f) &\n";
|
||||
let s = pattern_read7(&pattern7("Ink", layers), &pattern_layer7("Art", ""));
|
||||
let def = s.doc.pattern("Ink").unwrap();
|
||||
assert_eq!(def.art.len(), 1);
|
||||
assert_eq!(def.art[0].geometric_bounds(), Some(Rect::new(2.0, -9.0, 9.0, -2.0)));
|
||||
assert!(s.doc.swatch("Ink (A)").is_some(), "{:?}", s.doc.swatches.iter().map(|w| &w.name).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
/// A definition in the version 7 form that can't be read whole isn't kept, and a fill with it is
|
||||
/// something the file has that isn't read: an operator it doesn't know, type, a definition inside
|
||||
/// it, colors with other operators, a layer without its tile or its `&`, a string longer than the
|
||||
/// format allows, an `E`, a group or an array a layer doesn't end, more than 65,536 layers, a list
|
||||
/// without its `]` or its `E`, anything after its `E`.
|
||||
#[test]
|
||||
fn a_version_7_pattern_it_cant_read_whole_isnt_kept() {
|
||||
let line = "(0 0 m 8 8 L S) &\n";
|
||||
let long = format!("(0 g) @ ({}0 0 m 8 8 L S) &\n", " ".repeat(65_536));
|
||||
let open = "%AI3_BeginPattern: (P)\n(P) 0 0 20 20 [\n(0 g) @ (0 0 m 8 8 L S) &\n";
|
||||
let defs = [
|
||||
pattern7("P", "(0 g) @ (0 0 m 8 8 L frobnicate S) &\n"),
|
||||
pattern7("P", "(0 g) @ (0 To 1 0 0 1 2 2 0 Tp TP (a) Tx TO) &\n"),
|
||||
pattern7("P", "(0 g) @ (\r%AI3_BeginPattern: (In)\r(In) 0 0 1 1\rE\r%AI3_EndPattern\r0 0 m 8 8 L S) &\n"),
|
||||
pattern7("P", &format!("%AI3_BeginPattern: (In)\n(In) 0 0 1 1 [\n] E\n%AI3_EndPattern\n(0 g) @ {line}")),
|
||||
pattern7("P", &format!("(0 g 0 0 m) @ {line}")),
|
||||
pattern7("P", "(0 g) @\n"),
|
||||
pattern7("P", "(0 g) @ _\n"),
|
||||
pattern7("P", &long),
|
||||
pattern7("P", "(0 g) @ (0 0 m 8 8 L S E) &\n"),
|
||||
pattern7("P", "(0 g) @ (u 0 0 m 8 8 L S) &\n"),
|
||||
pattern7("P", "(0 g) @ (0 0 m 8 8 L S [) &\n"),
|
||||
pattern7("P", "(0 g) @ ([ 0 0 m 8 8 L S) &\n"),
|
||||
pattern7("P", &"(0 g) @ _ &\n".repeat(65_537)),
|
||||
format!("{open}E\n%AI3_EndPattern\n"),
|
||||
format!("{open}]\n%AI3_EndPattern\n"),
|
||||
format!("{open}] E\n0 0 m 8 8 L S\n%AI3_EndPattern\n"),
|
||||
];
|
||||
let fill_with = format!("(P) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(0.0, 0.0, 1.0, 1.0));
|
||||
for (i, def) in defs.iter().enumerate() {
|
||||
assert!(pattern_read7(def, &pattern_layer7("Art", "")).doc.patterns.is_empty(), "case {i}");
|
||||
assert_unread(&pattern_read7(def, &pattern_layer7("Art", &fill_with)), "pattern fills");
|
||||
}
|
||||
// The same definition, whole, is kept.
|
||||
let s = pattern_read7(&pattern7("P", &format!("(0 g) @ {line}")), &pattern_layer7("Art", &fill_with));
|
||||
assert!(s.doc.pattern("P").is_some() && s.unread.is_empty());
|
||||
}
|
||||
|
||||
/// With a pattern defined in the version 7 form, a fill's other operands are applied in order
|
||||
/// before its initial matrix (§5.4.1): the shear along its axis, the reflection about the line at
|
||||
/// its angle, the rotation, the scale, then the offset. Identity ones move the tiles by the offset
|
||||
/// alone. `P` places a stroke's tiles the same way.
|
||||
#[test]
|
||||
fn a_pattern_fill_applies_its_offset_scale_rotation_reflection_and_shear() {
|
||||
let def = pattern7("Grid", "(0 g) @ _ &\n");
|
||||
// The operands, and the pattern's space → art space they make (a b c d e f).
|
||||
let cases = [
|
||||
("10 15 1 1 0 0 0 0 0 [1 0 0 1 0 0]", [1.0, 0.0, 0.0, 1.0, 10.0, 15.0]),
|
||||
("25 30 1.5 .75 30 1 45 10 0 [1 0 0 1 0 0]", [-0.75, 0.649519, 1.166793, 0.489528, 25.0, 30.0]),
|
||||
("-5 7 2 .5 -45 0 0 -15 45 [1 0 0 1 0 0]", [1.793151, -0.353553, 1.035276, 0.353553, -5.0, 7.0]),
|
||||
("3 -4 1.2 .8 20 1 30 12 25 [.8 .1 -.2 1.1 4 -6]", [-0.028557, 0.816531, 1.054026, 0.117492, 7.2, -10.1]),
|
||||
];
|
||||
// Art space → the document (the artboard is 100 high), and a tile's art (y down from its top
|
||||
// left) → the pattern's space.
|
||||
let space = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 100.0]);
|
||||
let tile = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 20.0]);
|
||||
for (ops, want) in cases {
|
||||
for (op, paint) in [("p", "f"), ("P", "S")] {
|
||||
let s = pattern_read7(&def, &pattern_layer7("Art", &format!("(Grid) {ops} {op}\n{}{paint}\n", rect_path(10.0, 10.0, 90.0, 90.0))));
|
||||
let node = &art(&s.doc)[0];
|
||||
let p = if op == "p" { fill(node) } else { node.appearance.stroke().unwrap().paint.clone() };
|
||||
let Paint::Pattern { xf, .. } = p else { panic!("{ops} {op}: {p:?}") };
|
||||
let got = (space.inverse() * xf * tile.inverse()).as_coeffs();
|
||||
assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-6), "{ops} {op}: {got:?}");
|
||||
}
|
||||
}
|
||||
// The tiles' corners: with identity operands but the offset, the tile's top left (0, 20) is at
|
||||
// (10, 35) in art space; with the last ones, its lower right (20, 0) is at (6.628860, 6.230623).
|
||||
let placed = |ops: &str| {
|
||||
let s = pattern_read7(&def, &pattern_layer7("Art", &format!("(Grid) {ops} p\n{}f\n", rect_path(10.0, 10.0, 90.0, 90.0))));
|
||||
let Paint::Pattern { xf, .. } = fill(&art(&s.doc)[0]) else { panic!() };
|
||||
xf
|
||||
};
|
||||
assert_eq!(placed(cases[0].0) * Point::ZERO, Point::new(10.0, 65.0));
|
||||
assert!((placed(cases[3].0) * Point::new(20.0, 20.0)).distance(Point::new(6.628860, 93.769377)) < 1e-5);
|
||||
// Without its nine operands, a fill with the pattern isn't read.
|
||||
let r = pattern_read7(&def, &pattern_layer7("Art", &format!("(Grid) 0 0 1 1 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(10.0, 10.0, 90.0, 90.0))));
|
||||
assert_unread(&r, "pattern fills");
|
||||
}
|
||||
|
||||
/// With a pattern defined in the newer form (art on `%_` lines), the matrix alone places the tiles
|
||||
/// (#1025): the other operands don't move them, and a fill without all nine is still read.
|
||||
#[test]
|
||||
fn a_newer_pattern_fill_is_placed_by_its_matrix_alone() {
|
||||
let placed = |ops: &str| {
|
||||
let s = read_ok(&format!("{DOTS}{}", layer(&format!("(Dots) {ops} p\n{}f\n", rect_path(10.0, 20.0, 70.0, 80.0)))));
|
||||
assert!(s.unread.is_empty() && s.warnings.is_empty(), "{ops}: {:?} {:?}", s.unread, s.warnings);
|
||||
let Paint::Pattern { xf, .. } = fill(&art(&s.doc)[0]) else { panic!("{ops}: {:?}", fill(&art(&s.doc)[0])) };
|
||||
xf
|
||||
};
|
||||
let plain = placed("0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]");
|
||||
assert_eq!(plain * Point::ZERO, Point::new(0.0, 92.0));
|
||||
assert_eq!(placed("25 30 1.5 .75 30 1 45 10 0 [1 0 0 1 0 0]"), plain);
|
||||
assert_eq!(placed("0 0 1 1 0 0 0 0 [1 0 0 1 0 0]"), plain);
|
||||
}
|
||||
|
||||
/// An art style `Tiled` whose fill is `(name) {ops} p`.
|
||||
fn tiled_style(name: &str, ops: &str) -> String {
|
||||
format!(
|
||||
"%AI9_BeginArtStyles\n/KnownStyle :\n(Tiled) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
|
||||
/CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
|
||||
/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n({name}) {ops} p\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\
|
||||
/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n%AI9_EndArtStyles\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// A fill set through an art style on a text object places the tiles as a `p` fill with the same
|
||||
/// operands does: with the other operands before the matrix for a pattern defined in the version 7
|
||||
/// form, by the matrix alone for one defined in the newer form.
|
||||
#[test]
|
||||
fn a_style_pattern_fill_is_placed_as_a_direct_one() {
|
||||
let rect = rect_path(10.0, 20.0, 70.0, 80.0);
|
||||
// The text object's drawn look (without a pattern to take the placement from), then the object.
|
||||
let look = "0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\nU\n";
|
||||
let own = "%_/AI11Text :\n%_0 /FreeUndo ,\n%_0 /FrameIndex ,\n%_0 /StoryIndex ,\n%_;\n";
|
||||
let ops = "25 30 1.5 .75 30 1 45 10 0 [.8 .1 -.2 1.1 4 -6]";
|
||||
for (name, def) in [("Grid", pattern7("Grid", "(0 g) @ _ &\n")), ("Dots", DOTS.to_string())] {
|
||||
let styled = read_ok(&format!("{}{def}{}", tiled_style(name, ops), layer(&format!("{look}{own}1 (Tiled) XW\n"))));
|
||||
let direct = read_ok(&format!("{def}{}", layer(&format!("({name}) {ops} p\n{rect}f\n"))));
|
||||
let xf = |s: &Structure| match fill(&art(&s.doc)[0]) {
|
||||
Paint::Pattern { xf, .. } => xf,
|
||||
p => panic!("{name}: {p:?} {:?} {:?}", s.unread, s.warnings),
|
||||
};
|
||||
let (got, want) = (xf(&styled).as_coeffs(), xf(&direct).as_coeffs());
|
||||
assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-9), "{name}: {got:?} {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compound_paths_and_clipping() {
|
||||
let art_ = format!(
|
||||
@@ -3023,6 +3248,80 @@ fn an_object_with_a_feather_style_comes_in_with_a_live_effect() {
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// An art style section with style `PF`: an Effect › Pathfinder filter with `Command` `command`
|
||||
/// and `Mix` `mix` in the object's chain, over a fill and stroke that paint nothing.
|
||||
fn pathfinder_styles(command: u32, mix: f64) -> String {
|
||||
format!(
|
||||
"%AI9_BeginArtStyles\n/KnownStyle :\n(PF) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
|
||||
/BasicFilter :\n(Adobe Pathfinder) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\
|
||||
0 /Bool (RemovePoints) ,\n{mix} /Real (Mix) ,\n1 /Bool (ConvertCustom) ,\n{command} /Int (Command) ,\n1 /Real (TrapMaxTint) ,\n\
|
||||
1 /Real (TrapAspect) ,\n0.4 /Real (TrapTint) ,\n0.25 /Real (TrapThickness) ,\n0 /Bool (TrapReverse) ,\n10 /Real (Precision) ,\n\
|
||||
(Op) /UnicodeString (DisplayString) ,\n0 /Bool (TrapConvertCustom) ,\n0.05 /Real (TrapTintTolerance) ,\n1 /Bool (ExtractUnpainted) ,\n\
|
||||
; /Dict ;\n /Part ,\n\
|
||||
/CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
|
||||
/BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n\
|
||||
/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n\
|
||||
/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\
|
||||
;\n /Part ,\n;\n%AI9_EndArtStyles\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// A group of a red and a blue square with style `PF`: its drawn look (one path of their area),
|
||||
/// then the group on `%_` lines.
|
||||
fn pathfinder_group() -> String {
|
||||
let hidden = |color: &str, x: f64| format!("{color}{}f\n", rect_path(x, 0.0, x + 10.0, 10.0)).replace('\n', "\n%_");
|
||||
format!(
|
||||
"0 Ae\nu\n{RED}{}f\nU\n%_0 Ae\n%_u\n%_{}{}U\n1 (PF) XW\n",
|
||||
rect_path(0.0, 0.0, 15.0, 10.0),
|
||||
hidden(RED, 0.0),
|
||||
hidden("0 0 1 0 0 0 1 Xa\n", 5.0)
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_with_a_pathfinder_effect_keeps_its_members_and_the_effect() {
|
||||
// GUARDS: the style was not read, and the group came in as its drawn look: one path, with no effect.
|
||||
let r = read_ok(&format!("{}{}", pathfinder_styles(0, 0.5), layer(&pathfinder_group())));
|
||||
let a = art(&r.doc);
|
||||
assert_eq!(a.len(), 1, "{a:#?}");
|
||||
let members = a[0].children().cloned().unwrap_or_default();
|
||||
assert_eq!(members.len(), 2, "the squares, not the look: {a:#?}");
|
||||
assert!(members.iter().all(|m| matches!(m.kind, NodeKind::Path { .. })), "{members:#?}");
|
||||
assert_eq!((fill(&members[0]).color(), fill(&members[1]).color()), (Some(Color::rgb(1.0, 0.0, 0.0)), Some(Color::rgb(0.0, 0.0, 1.0))));
|
||||
let effects: Vec<_> = a[0].appearance.effects.iter().map(|e| (e.id.as_str(), e.visible)).collect();
|
||||
assert_eq!(effects, [("pathfinder.add", true)]);
|
||||
assert!(a[0].appearance.items.is_empty(), "{:?}", a[0].appearance);
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pathfinder_style_this_does_not_read_keeps_the_drawn_look() {
|
||||
// Another command (Intersect, Trap), and a Precision other than the one read.
|
||||
let other = pathfinder_styles(0, 0.5).replace("10 /Real (Precision)", "5 /Real (Precision)");
|
||||
for styles in [pathfinder_styles(1, 0.5), pathfinder_styles(12, 0.5), other] {
|
||||
let r = read_ok(&format!("{styles}{}", layer(&pathfinder_group())));
|
||||
let a = art(&r.doc);
|
||||
assert_eq!(a.len(), 1, "{a:#?}");
|
||||
let look = a[0].children().cloned().unwrap_or_default();
|
||||
assert_eq!(look.len(), 1, "the look's one path: {a:#?}");
|
||||
assert!(a[0].appearance.effects.is_empty(), "{:?}", a[0].appearance);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_with_a_pathfinder_effect_keeps_its_drawn_look() {
|
||||
// Effect › Pathfinder doesn't apply to a lone path: its style stays the drawn look's.
|
||||
let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_");
|
||||
let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_{hidden_rect}f\n1 (PF) XW\n", rect_path(0.0, 0.0, 10.0, 10.0));
|
||||
let r = read_ok(&format!("{}{}", pathfinder_styles(0, 0.5), layer(&art_)));
|
||||
let a = art(&r.doc);
|
||||
assert_eq!(a.len(), 1, "{a:#?}");
|
||||
assert!(matches!(a[0].kind, NodeKind::Group { .. }), "the look, not the path: {a:#?}");
|
||||
let mut effects = 0;
|
||||
r.doc.walk(|n| effects += n.appearance.effects.len());
|
||||
assert_eq!(effects, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_with_convert_to_shape_comes_in_as_itself_with_the_effect_live() {
|
||||
// GUARDS: `Adobe Shape Effects` wasn't read, so the object came in as its drawn look.
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
use super::ops::MAX_DATA;
|
||||
use super::{
|
||||
DecodeSettings, Decoder, DecoderContext, DictRef, EncodingMode, ImageBlob, Key, Obj, PsError, Rc, Res, find, hex_decode, jpeg_components, ps,
|
||||
ps_err,
|
||||
DecodeSettings, Decoder, DecoderContext, DictRef, EncodingMode, ImageBlob, Key, Obj, PsError, Rc, RefCell, Res, find, hex_decode,
|
||||
jpeg_components, ps, ps_err,
|
||||
};
|
||||
|
||||
/// A file object: the program itself, or data a filter decoded.
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum Stream {
|
||||
Current,
|
||||
/// Filters over the program's own data, decoded when first read.
|
||||
Pending(Vec<Filter>),
|
||||
/// Filters over the data the program reads, decoded when first read, from the file they were
|
||||
/// made over: a file being run (`from`), or else the program's own file.
|
||||
Pending {
|
||||
chain: Vec<Filter>,
|
||||
from: Option<Rc<RefCell<Stream>>>,
|
||||
},
|
||||
Buf {
|
||||
data: Vec<u8>,
|
||||
pos: usize,
|
||||
|
||||
@@ -29,7 +29,10 @@ impl Interp<'_> {
|
||||
pub fn data_op(&mut self, op: Op) -> Res {
|
||||
use Op::*;
|
||||
match op {
|
||||
CurrentFile => self.push(Obj::File { stream: Rc::new(RefCell::new(Stream::Current)), exec: false })?,
|
||||
CurrentFile => {
|
||||
let stream = self.running.last().cloned().unwrap_or_else(|| Rc::new(RefCell::new(Stream::Current)));
|
||||
self.push(Obj::File { stream, exec: false })?;
|
||||
}
|
||||
Filter => self.filter()?,
|
||||
ReadHexString | ReadString => {
|
||||
let s = self.pop_str()?;
|
||||
@@ -94,7 +97,7 @@ impl Interp<'_> {
|
||||
let n = match &*f.borrow() {
|
||||
Stream::Current => self.lex.rest().len(),
|
||||
Stream::Buf { data, pos, .. } => data.len().saturating_sub(*pos),
|
||||
Stream::Pending(_) => 0,
|
||||
Stream::Pending { .. } => 0,
|
||||
};
|
||||
self.push(Obj::Int(n as i64))?;
|
||||
}
|
||||
@@ -163,18 +166,7 @@ impl Interp<'_> {
|
||||
self.push(o)?;
|
||||
}
|
||||
Obj::File { stream: f, .. } => {
|
||||
self.materialize(&f)?;
|
||||
let (o, immediate) = match &mut *f.borrow_mut() {
|
||||
Stream::Current => (self.lex.next()?, self.lex.immediate),
|
||||
Stream::Buf { data, pos, .. } => {
|
||||
let rest = data.get(*pos..).unwrap_or_default();
|
||||
let mut lex = Lexer::new(rest);
|
||||
let o = lex.next()?;
|
||||
*pos += rest.len() - lex.data().len();
|
||||
(o, lex.immediate)
|
||||
}
|
||||
Stream::Pending(_) => (None, false),
|
||||
};
|
||||
let (o, immediate) = self.next_in(&f)?;
|
||||
let Some(o) = o else { return self.push(Obj::Bool(false)) };
|
||||
let o = self.scanned(o, immediate)?;
|
||||
self.push(o)?;
|
||||
@@ -184,6 +176,23 @@ impl Interp<'_> {
|
||||
self.push(Obj::Bool(true))
|
||||
}
|
||||
|
||||
/// The next object in file `f` (`token`, and a file being run), read with the whitespace
|
||||
/// after it, and whether it has `//name`s in it.
|
||||
pub(in super::super) fn next_in(&mut self, f: &Rc<RefCell<Stream>>) -> Res<(Option<Obj>, bool)> {
|
||||
self.materialize(f)?;
|
||||
Ok(match &mut *f.borrow_mut() {
|
||||
Stream::Current => (self.lex.next()?, self.lex.immediate),
|
||||
Stream::Buf { data, pos, .. } => {
|
||||
let rest = data.get(*pos..).unwrap_or_default();
|
||||
let mut lex = Lexer::new(rest);
|
||||
let o = lex.next()?;
|
||||
*pos += rest.len() - lex.data().len();
|
||||
(o, lex.immediate)
|
||||
}
|
||||
Stream::Pending { .. } => (None, false),
|
||||
})
|
||||
}
|
||||
|
||||
/// Up to `n` bytes of file `f`.
|
||||
fn read(&mut self, f: &Rc<RefCell<Stream>>, n: usize) -> Res<Vec<u8>> {
|
||||
self.materialize(f)?;
|
||||
@@ -201,7 +210,7 @@ impl Interp<'_> {
|
||||
*pos = end;
|
||||
data.get(start..end).unwrap_or_default().to_vec()
|
||||
}
|
||||
Stream::Pending(_) => vec![],
|
||||
Stream::Pending { .. } => vec![],
|
||||
})
|
||||
}
|
||||
|
||||
@@ -220,7 +229,7 @@ impl Interp<'_> {
|
||||
*pos += 1;
|
||||
}
|
||||
}
|
||||
Stream::Pending(_) => {}
|
||||
Stream::Pending { .. } => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -275,23 +284,28 @@ impl Interp<'_> {
|
||||
let spec = Filter { name, sub, predictor, fax };
|
||||
let stream = match self.pop()? {
|
||||
Obj::File { stream: f, .. } => {
|
||||
if let Stream::Buf { data, pos, .. } = &*f.borrow() {
|
||||
self.alloc(data.len().saturating_sub(*pos))?;
|
||||
// A filter over the program's own file or the file being run waits until it is
|
||||
// first read, and keeps which of them it reads, wherever the program runs by then.
|
||||
let running = self.running.last().is_some_and(|r| Rc::ptr_eq(r, &f));
|
||||
match &*f.borrow() {
|
||||
Stream::Buf { data, pos, .. } if !running => self.alloc(data.len().saturating_sub(*pos))?,
|
||||
_ => {}
|
||||
}
|
||||
let chain = match &*f.borrow() {
|
||||
Stream::Current => Some(vec![]),
|
||||
Stream::Pending(c) => Some(c.clone()),
|
||||
let pending = match &*f.borrow() {
|
||||
Stream::Current => Some((vec![], None)),
|
||||
Stream::Buf { .. } if running => Some((vec![], Some(f.clone()))),
|
||||
Stream::Pending { chain, from } => Some((chain.clone(), from.clone())),
|
||||
Stream::Buf { .. } => None,
|
||||
};
|
||||
match chain {
|
||||
Some(mut c) => {
|
||||
match pending {
|
||||
Some((mut chain, from)) => {
|
||||
// The new filter reads a pending one's data: it has none left of its own
|
||||
// (`flushfile` on it skips nothing more).
|
||||
if !c.is_empty() {
|
||||
if !chain.is_empty() {
|
||||
*f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None };
|
||||
}
|
||||
c.push(spec);
|
||||
Stream::Pending(c)
|
||||
chain.push(spec);
|
||||
Stream::Pending { chain, from }
|
||||
}
|
||||
None => {
|
||||
let mut b = f.borrow_mut();
|
||||
@@ -325,15 +339,6 @@ impl Interp<'_> {
|
||||
self.push(Obj::File { stream, exec: false })
|
||||
}
|
||||
|
||||
/// The data an executable file runs as a program: what is left of it. `None` for the
|
||||
/// program's own file, which is being run already.
|
||||
pub(in super::super) fn program_of(&mut self, f: &Rc<RefCell<Stream>>) -> Res<Option<Vec<u8>>> {
|
||||
if matches!(&*f.borrow(), Stream::Current) {
|
||||
return Ok(None);
|
||||
}
|
||||
self.read(f, MAX_DATA).map(Some)
|
||||
}
|
||||
|
||||
/// The decoded data left in file `f`, without reading it (a shading's or function's data).
|
||||
pub(in super::super) fn peek_all(&mut self, f: &Rc<RefCell<Stream>>) -> Res<Vec<u8>> {
|
||||
self.materialize(f)?;
|
||||
@@ -343,20 +348,32 @@ impl Interp<'_> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Decode the filters a file waits to run over the program's data, from where it is now.
|
||||
fn materialize(&mut self, f: &Rc<RefCell<Stream>>) -> Res {
|
||||
let chain = match &*f.borrow() {
|
||||
Stream::Pending(c) => c.clone(),
|
||||
/// Decode the filters a file waits to run over the data the program reads, from where it is
|
||||
/// now in the file they were made over: a file being run, or the program's own file.
|
||||
pub(in super::super) fn materialize(&mut self, f: &Rc<RefCell<Stream>>) -> Res {
|
||||
let (chain, from) = match &*f.borrow() {
|
||||
Stream::Pending { chain, from } => (chain.clone(), from.clone()),
|
||||
_ => return Ok(()),
|
||||
};
|
||||
let mut buf: Option<(Vec<u8>, Option<u8>)> = None;
|
||||
for spec in &chain {
|
||||
buf = Some(match buf.take() {
|
||||
None => {
|
||||
let raw = self.lex.data();
|
||||
let (data, used, rgb) = decode(spec, raw)?;
|
||||
let (data, rgb) = match &from {
|
||||
Some(r) => {
|
||||
let mut b = r.borrow_mut();
|
||||
let Stream::Buf { data, pos, .. } = &mut *b else { return io("filter") };
|
||||
let (out, used, rgb) = decode(spec, data.get(*pos..).unwrap_or_default())?;
|
||||
*pos = pos.saturating_add(used);
|
||||
(out, rgb)
|
||||
}
|
||||
None => {
|
||||
let (out, used, rgb) = decode(spec, self.lex.data())?;
|
||||
self.lex.advance(used);
|
||||
(out, rgb)
|
||||
}
|
||||
};
|
||||
self.charge_decoded(data.len())?;
|
||||
self.lex.advance(used);
|
||||
(data, rgb)
|
||||
}
|
||||
Some((prev, was)) => {
|
||||
@@ -418,10 +435,11 @@ impl Interp<'_> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `eexec`: an encrypted font program follows. It is skipped (type is drawn in the app's
|
||||
/// fonts, by name): the font dictionary it would complete is defined as it is.
|
||||
/// `file eexec`: an encrypted font program follows in `file`. It is skipped there, up to the
|
||||
/// `cleartomark` that ends it (type is drawn in the app's fonts, by name): the font
|
||||
/// dictionary it would complete is defined as it is.
|
||||
fn eexec(&mut self) -> Res {
|
||||
self.pop()?;
|
||||
let src = self.pop()?;
|
||||
if let Some(Obj::Dict(d)) = self.stack.last().cloned() {
|
||||
let name = d.borrow().get(&Key::name("FontName")).cloned();
|
||||
if let Some(k) = name.and_then(|n| n.key()) {
|
||||
@@ -429,9 +447,24 @@ impl Interp<'_> {
|
||||
self.fonts.borrow_mut().insert(k, Obj::Dict(d));
|
||||
}
|
||||
}
|
||||
let rest = self.lex.data();
|
||||
let at = find(rest, b"cleartomark").ok_or(PsError::Ps("ioerror", "eexec".into()))?;
|
||||
self.lex.advance(at);
|
||||
// `currentfile eexec`: the program's own file or the file being run. A string operand
|
||||
// skips in the file being read.
|
||||
let f = match src {
|
||||
Obj::File { stream, .. } => stream,
|
||||
_ => self.running.last().cloned().unwrap_or_else(|| Rc::new(RefCell::new(Stream::Current))),
|
||||
};
|
||||
self.materialize(&f)?;
|
||||
let missing = || PsError::Ps("ioerror", "eexec".into());
|
||||
match &mut *f.borrow_mut() {
|
||||
Stream::Buf { data, pos, .. } => {
|
||||
let at = find(data.get(*pos..).unwrap_or_default(), b"cleartomark").ok_or_else(missing)?;
|
||||
*pos += at;
|
||||
}
|
||||
_ => {
|
||||
let at = find(self.lex.data(), b"cleartomark").ok_or_else(missing)?;
|
||||
self.lex.advance(at);
|
||||
}
|
||||
}
|
||||
self.push(Obj::Mark)
|
||||
}
|
||||
|
||||
|
||||
@@ -4,10 +4,12 @@
|
||||
//! Every operation counts against a budget and procedures nest only so deep, so a looping or
|
||||
//! recursing program ends with [`PsError::Limit`] instead of hanging.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
use super::data::Stream;
|
||||
use super::graphics::{GState, Out};
|
||||
use super::lex::{IMMEDIATE, Lexer};
|
||||
use super::obj::{Dict, DictRef, Key, Obj, Op, PsError, Res, Shared, ps_err};
|
||||
@@ -32,6 +34,9 @@ pub(crate) struct Interp<'a> {
|
||||
/// The list of the arrays and dictionaries made since this started ([`super::obj::track`]).
|
||||
made: u64,
|
||||
pub lex: Lexer<'a>,
|
||||
/// The files being run (`cvx exec`), innermost last: the program reads from the last one, and
|
||||
/// it is `currentfile` while it runs.
|
||||
pub running: Vec<Rc<RefCell<Stream>>>,
|
||||
pub stack: Vec<Obj>,
|
||||
pub dicts: Vec<DictRef>,
|
||||
system: DictRef,
|
||||
@@ -105,13 +110,18 @@ impl<'a> Interp<'a> {
|
||||
pub fn new(src: &'a [u8], g: GState, out: Out) -> Self {
|
||||
let made = super::obj::track();
|
||||
let system = new_dict();
|
||||
// The standard encodings are also instances of the Encoding category, the same arrays
|
||||
// (PLRM 3rd ed., §3.9.2 and `findencoding`, <https://www.adobe.com/jp/print/postscript/pdfs/PLRM.pdf>).
|
||||
let encodings = new_dict();
|
||||
{
|
||||
let mut d = system.borrow_mut();
|
||||
for (op, name) in Op::ALL {
|
||||
d.insert(Key::name(name), Obj::Op(*op));
|
||||
}
|
||||
for name in ["StandardEncoding", "ISOLatin1Encoding"] {
|
||||
d.insert(Key::name(name), encoding());
|
||||
let e = encoding();
|
||||
d.insert(Key::name(name), e.clone());
|
||||
encodings.borrow_mut().insert(Key::name(name), e);
|
||||
}
|
||||
// An integer, as interpreters have it (`systemdict /languagelevel get 2 ge`): run, the
|
||||
// name pushes it all the same.
|
||||
@@ -122,6 +132,7 @@ impl<'a> Interp<'a> {
|
||||
CATEGORIES.split_whitespace().map(|c| (Key::name(c), Obj::dict(Dict::from([(Key::name("Category"), Obj::name(c))])))).collect();
|
||||
let resources = new_dict();
|
||||
resources.borrow_mut().insert(Key::name("Category"), Obj::dict(categories));
|
||||
resources.borrow_mut().insert(Key::name("Encoding"), Obj::Dict(encodings));
|
||||
let fonts = new_dict();
|
||||
system.borrow_mut().insert(Key::name("FontDirectory"), Obj::Dict(fonts.clone()));
|
||||
for name in ["GlobalFontDirectory", "SharedFontDirectory"] {
|
||||
@@ -145,6 +156,7 @@ impl<'a> Interp<'a> {
|
||||
Self {
|
||||
made,
|
||||
lex: Lexer::new(src),
|
||||
running: vec![],
|
||||
stack: vec![],
|
||||
dicts: vec![system.clone(), global.clone(), user.clone()],
|
||||
system,
|
||||
@@ -382,10 +394,7 @@ impl<'a> Interp<'a> {
|
||||
pub fn call(&mut self, v: Obj) -> Res {
|
||||
match v {
|
||||
Obj::Array { items, exec: true } => self.run_proc(&items),
|
||||
Obj::File { stream, exec: true } => match self.program_of(&stream)? {
|
||||
Some(program) => self.run_program(&program),
|
||||
None => Ok(()),
|
||||
},
|
||||
Obj::File { stream, exec: true } => self.run_file(&stream),
|
||||
Obj::ExecStr(s) => self.run_program(&s.to_vec()),
|
||||
// Through the depth guard: `stopped` and the like call back into here.
|
||||
Obj::Op(op) => {
|
||||
@@ -422,7 +431,35 @@ impl<'a> Interp<'a> {
|
||||
r
|
||||
}
|
||||
|
||||
/// Run `program` (what is left of an executable file, an executable string), token by token.
|
||||
/// Run file `f` (`cvx exec`), reading its objects from it as it goes. While it runs it is
|
||||
/// `currentfile`, the topmost file being run (PLRM 3rd ed., `currentfile`, <https://www.adobe.com/jp/print/postscript/pdfs/PLRM.pdf>),
|
||||
/// so data the program reads from there (an inline image's samples) comes from `f`, after the
|
||||
/// object that reads it. The program's own file is being run already.
|
||||
fn run_file(&mut self, f: &Rc<RefCell<Stream>>) -> Res {
|
||||
if matches!(&*f.borrow(), Stream::Current) {
|
||||
return Ok(());
|
||||
}
|
||||
// Its data, decoded from the program it was made over, before it becomes the program.
|
||||
self.materialize(f)?;
|
||||
self.enter()?;
|
||||
self.running.push(f.clone());
|
||||
let r = loop {
|
||||
match self.next_in(f) {
|
||||
Ok((Some(o), immediate)) => {
|
||||
if let Err(e) = self.scanned(o, immediate).and_then(|o| self.exec_token(o)) {
|
||||
break Err(e);
|
||||
}
|
||||
}
|
||||
Ok((None, _)) => break Ok(()),
|
||||
Err(e) => break Err(e),
|
||||
}
|
||||
};
|
||||
self.running.pop();
|
||||
self.depth -= 1;
|
||||
r
|
||||
}
|
||||
|
||||
/// Run `program` (an executable string), token by token.
|
||||
fn run_program(&mut self, program: &[u8]) -> Res {
|
||||
self.enter()?;
|
||||
let mut lex = Lexer::new(program);
|
||||
@@ -1044,10 +1081,10 @@ impl<'a> Interp<'a> {
|
||||
self.insert(&d, k, Some(v))?;
|
||||
}
|
||||
Known => {
|
||||
let k = self.pop()?.key().ok_or(PsError::Ps("typecheck", String::new()))?;
|
||||
let k = self.pop()?;
|
||||
let d = self.pop_dict()?;
|
||||
let known = d.borrow().contains_key(&k);
|
||||
self.push(Obj::Bool(known))?;
|
||||
let found = known(&d, &k)?;
|
||||
self.push(Obj::Bool(found))?;
|
||||
}
|
||||
Where => {
|
||||
let k = self.pop()?.key().ok_or(PsError::Ps("typecheck", String::new()))?;
|
||||
@@ -1412,6 +1449,17 @@ fn index(k: &Obj) -> Res<usize> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `known`: a key may be any object but null (PLRM 3rd ed., §3.3.9, <https://www.adobe.com/jp/print/postscript/pdfs/PLRM.pdf>),
|
||||
/// and one that can't be a key here (an array, a dictionary, a real with a fraction) is in no
|
||||
/// dictionary, since `put` here refuses it.
|
||||
fn known(d: &DictRef, k: &Obj) -> Res<bool> {
|
||||
match k.key() {
|
||||
Some(key) => Ok(d.borrow().contains_key(&key)),
|
||||
None if matches!(k, Obj::Null) => ps_err("typecheck", "known"),
|
||||
None => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// `eq`: numbers by value, strings and names by text, composites by identity.
|
||||
fn equal(a: &Obj, b: &Obj) -> bool {
|
||||
match (a, b) {
|
||||
|
||||
@@ -717,14 +717,20 @@ fn type_42_fonts_set_type_at_their_size() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The encrypted part of a font program is skipped up to its `cleartomark` in the file it is in:
|
||||
/// the program's own file, or a file being run (`cvx exec`), as Ghostscript's `eps2write` runs
|
||||
/// each Type 1 font it embeds.
|
||||
#[test]
|
||||
fn embedded_font_programs_are_skipped() {
|
||||
let body = "/MyFont 10 dict begin /FontName /MyFont def /FontMatrix [0.001 0 0 0.001 0 0] def currentdict end currentfile eexec\n\
|
||||
0123456789abcdef garbage that is encrypted\n0000000000000000000000000000000000000000000000000000000000000000\ncleartomark\n\
|
||||
/MyFont findfont 10 scalefont setfont 10 10 moveto (x) show";
|
||||
let r = read(body);
|
||||
let NodeKind::Text(t) = &objects(&r.document)[0].kind else { panic!("{:?}", r.warnings) };
|
||||
assert_eq!(t.runs[0].style.font_family, "My Font");
|
||||
for program in [body.to_string(), format!("currentfile 0 (endstream) /SubFileDecode filter cvx exec\n{body}\nendstream\n")] {
|
||||
let r = read(&program);
|
||||
let NodeKind::Text(t) = &objects(&r.document)[0].kind else { panic!("{program}: {:?}", r.warnings) };
|
||||
assert_eq!(t.runs[0].style.font_family, "My Font");
|
||||
assert!(r.warnings.is_empty(), "{program}: {:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
/// A document with what the writer writes in its own ways: gradients, type, an image with
|
||||
@@ -892,6 +898,17 @@ fn the_generic_category_defines_new_categories() {
|
||||
check("{ /X 5 /Category defineresource } stopped");
|
||||
}
|
||||
|
||||
/// The standard encodings are instances of the Encoding category, the same arrays as the names in
|
||||
/// `systemdict` (PLRM 3rd ed., §3.9.2 and `findencoding`, <https://www.adobe.com/jp/print/postscript/pdfs/PLRM.pdf>).
|
||||
/// Ghostscript's `eps2write` finds `StandardEncoding` that way for the fonts it embeds.
|
||||
#[test]
|
||||
fn the_standard_encodings_are_encoding_resources() {
|
||||
check("/StandardEncoding /Encoding findresource StandardEncoding eq");
|
||||
check("/ISOLatin1Encoding /Encoding findresource ISOLatin1Encoding eq");
|
||||
check("/StandardEncoding /Encoding resourcestatus { pop pop true } { false } ifelse");
|
||||
check("{ /Nope /Encoding findresource } stopped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clipsave_and_cliprestore_bring_the_clip_back() {
|
||||
// #234.
|
||||
@@ -985,6 +1002,18 @@ fn the_standard_dictionaries_are_dictionaries_in_systemdict() {
|
||||
check("SharedFontDirectory type /dicttype eq");
|
||||
}
|
||||
|
||||
/// A key may be any object but null (PLRM 3rd ed., §3.3.9, <https://www.adobe.com/jp/print/postscript/pdfs/PLRM.pdf>),
|
||||
/// so `known` answers for every other key.
|
||||
/// Ghostscript's `eps2write` looks an inline image's filter up in a dictionary of abbreviations,
|
||||
/// and the filter may be an array of them.
|
||||
#[test]
|
||||
fn known_answers_false_for_keys_no_dictionary_holds() {
|
||||
check("<< /A85 /ASCII85Decode >> [ /A85 /LZW ] known not");
|
||||
check("1 dict 1 dict known not 1 dict 1.5 known not and 1 dict mark known not and");
|
||||
check("<< /A85 /ASCII85Decode >> /A85 known << 1 2 >> 1.0 known and");
|
||||
check("{ 1 dict null known } stopped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dictstack_and_internaldict_answer() {
|
||||
check("10 array dictstack length countdictstack eq");
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::Point;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::clipnest::MAX_NEST;
|
||||
use vectorcraft_doc::{LayerColor, LineCap, Node, NodeKind};
|
||||
@@ -123,6 +124,31 @@ fn a_postscript_ai_that_names_its_prolog_without_including_it_opens_with_its_lay
|
||||
assert_eq!(tree(d.layers[1].children().unwrap()), "p");
|
||||
}
|
||||
|
||||
/// A `.ai` in PostScript form with a pattern defined in the version 7 form (§3.4): the layer keeps
|
||||
/// its name, and the pattern is a swatch that fills the path from its offset.
|
||||
#[test]
|
||||
fn a_postscript_ai_with_a_version_7_pattern_fills_with_it() {
|
||||
let pattern = "%AI3_BeginPattern: (Stripes)\n(Stripes) 0 0 10 10 [\n%AI3_Tile\n(0 O 0 R 0 0 0 0.5 k) @ _ &\n\
|
||||
(0 O 0 R 0 0 0 1 K) @ (\r1 w\r0 5 m\r10 5 L\rS\r) &\n] E\n%AI3_EndPattern\n";
|
||||
let setup = "Adobe_IllustratorA_AI3 /initialize get exec\n";
|
||||
let style = "0 i 1 J 1 j 0.8 w 4 M []0 d\n0 D\n";
|
||||
let src = NAMED_PROLOG
|
||||
.replace(setup, &format!("{setup}{pattern}"))
|
||||
.replace(style, &format!("{style}(Stripes) 5 5 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n"))
|
||||
.replace("10 10 L\nS\n", "10 10 L\nB\n");
|
||||
let r = import(src.as_bytes()).unwrap();
|
||||
assert!(r.warnings.is_empty() && !r.preview, "{:?}", r.warnings);
|
||||
let d = &r.document;
|
||||
assert_eq!(d.layers[0].name.as_deref(), Some("SECTION::Cut"));
|
||||
assert!(matches!(&d.swatch("Stripes").unwrap().paint, Paint::Pattern { pattern, .. } if pattern == "Stripes"));
|
||||
assert_eq!(d.pattern("Stripes").unwrap().art.len(), 2);
|
||||
let square = &d.layers[0].children().unwrap()[0];
|
||||
let Some(Paint::Pattern { pattern, xf }) = square.appearance.fill().map(|f| f.paint.clone()) else { panic!("{:?}", square.appearance) };
|
||||
assert_eq!(pattern, "Stripes");
|
||||
// The tile's top left, (0, 10) in its space, is at (5, 15) in art space: 85 down the 100-point page.
|
||||
assert_eq!(xf * Point::ZERO, Point::new(5.0, 85.0));
|
||||
}
|
||||
|
||||
/// A `.ai` in PostScript form with a graph on each of two layers (version 7 specification §17): its
|
||||
/// data on `%_` lines, then its drawn art in a group, each object followed by `%_… Go`.
|
||||
fn graphs_on_layers() -> String {
|
||||
|
||||
@@ -77,6 +77,60 @@ fn separate_sources_keep_their_planes() {
|
||||
assert_eq!(pixels(&r, 3, 2), [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [16, 64, 112, 255], [32, 80, 128, 255], [48, 96, 144, 255]]);
|
||||
}
|
||||
|
||||
/// A program run from a file (`filter cvx exec`, as Ghostscript's `eps2write` runs each page's
|
||||
/// content) reads data through `currentfile` from that file, right after the operator that reads
|
||||
/// it (PLRM 3rd ed., `currentfile`, <https://www.adobe.com/jp/print/postscript/pdfs/PLRM.pdf>): an image's
|
||||
/// samples, kept after it as an inline image keeps them, plain or up to `~>` through
|
||||
/// `SubFileDecode` and `ASCII85Decode`.
|
||||
#[test]
|
||||
fn image_data_comes_from_the_file_being_run() {
|
||||
let r = read(
|
||||
"currentfile 0 (endstream) /SubFileDecode filter cvx exec\n\
|
||||
30 20 scale 3 2 8 [3 0 0 -2 0 2] currentfile /ASCIIHexDecode filter false 3 colorimage\n\
|
||||
ff0000 00ff00 0000ff 102030 405060 708090>\n\
|
||||
endstream\n",
|
||||
);
|
||||
assert_eq!(pixels(&r, 3, 2), [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [16, 32, 48, 255], [64, 80, 96, 255], [112, 128, 144, 255]]);
|
||||
let r = read(
|
||||
"/ID { 3 1 8 [3 0 0 -1 0 1] currentfile 0 (~>) /SubFileDecode filter /ASCII85Decode filter false 3 colorimage } def\n\
|
||||
currentfile 0 (endstream) /SubFileDecode filter cvx exec\n\
|
||||
30 20 scale ID\n\
|
||||
rr<$!rr<$!rr~>\n\
|
||||
endstream\n",
|
||||
);
|
||||
assert_eq!(pixels(&r, 3, 1), [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255]]);
|
||||
super::tests::check(
|
||||
"/ok false def currentfile 0 (endstream) /SubFileDecode filter cvx exec\n\
|
||||
currentfile 4 string readstring WXYZ pop (WXYZ) eq /ok exch def\n\
|
||||
endstream\nok",
|
||||
);
|
||||
}
|
||||
|
||||
/// A filter waits until it is first read, then reads the file it was made over, wherever the
|
||||
/// program runs by then: one over the program's own file, read in a file being run, and one over
|
||||
/// a file being run, read in a file that one runs.
|
||||
#[test]
|
||||
fn filters_read_the_file_they_were_made_over() {
|
||||
super::tests::check(
|
||||
"/f currentfile /ASCIIHexDecode filter def\n\
|
||||
currentfile 0 (endstream) /SubFileDecode filter cvx exec\n\
|
||||
/s f 3 string readstring pop def\n\
|
||||
endstream\n\
|
||||
616263>\n\
|
||||
s (abc) eq",
|
||||
);
|
||||
super::tests::check(
|
||||
"currentfile 0 (endstream) /SubFileDecode filter cvx exec\n\
|
||||
/g currentfile /ASCIIHexDecode filter def\n\
|
||||
currentfile 0 (endinner) /SubFileDecode filter cvx exec\n\
|
||||
/t g 3 string readstring pop def\n\
|
||||
endinner\n\
|
||||
78797A>\n\
|
||||
endstream\n\
|
||||
t (xyz) eq",
|
||||
);
|
||||
}
|
||||
|
||||
/// CMYK samples keep their ink amounts in a CMYK TIFF: in the operand and dictionary forms, from
|
||||
/// hex and binary data, from one source or one a component, at 4, 8 and 16 bits, read through
|
||||
/// the Decode array. Gray and RGB images stay PNGs.
|
||||
|
||||
@@ -3459,6 +3459,59 @@ fn type_with_a_stacked_art_style_comes_in_as_type_with_that_appearance() {
|
||||
check(&r.document, &r.warnings);
|
||||
}
|
||||
|
||||
/// An art style section with style `Add`: Effect › Pathfinder › Add in the object's chain, over a
|
||||
/// fill and stroke that paint nothing.
|
||||
fn pathfinder_add_style() -> String {
|
||||
let basic = |name: &str, body: &str| {
|
||||
format!("/BasicFilter :\n({name}) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{body}; /Dict ;\n /Part ,\n")
|
||||
};
|
||||
let compound = |name: &str, kids: &[String]| format!("/CompoundFilter :\n({name}) 0 0 /Filter ,\n1 /Visible ,\n{};\n /Part ,\n", kids.concat());
|
||||
let add = basic(
|
||||
"Adobe Pathfinder",
|
||||
"0 /Bool (RemovePoints) ,\n0.5 /Real (Mix) ,\n1 /Bool (ConvertCustom) ,\n0 /Int (Command) ,\n1 /Real (TrapMaxTint) ,\n1 /Real (TrapAspect) ,\n\
|
||||
0.4 /Real (TrapTint) ,\n0.25 /Real (TrapThickness) ,\n0 /Bool (TrapReverse) ,\n10 /Real (Precision) ,\n0 /Bool (TrapConvertCustom) ,\n\
|
||||
0.05 /Real (TrapTintTolerance) ,\n1 /Bool (ExtractUnpainted) ,\n",
|
||||
);
|
||||
let stack = compound(
|
||||
"Stack Style Filter",
|
||||
&[
|
||||
basic("Stroke Style Filter", "/StrokeStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (StrokeStyle) ,\n"),
|
||||
basic("Conduit Filter", ""),
|
||||
basic("Fill Style Filter", "/FillStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (FillStyle) ,\n"),
|
||||
],
|
||||
);
|
||||
format!("%AI9_BeginArtStyles\n/KnownStyle :\n(Add) /Name ,\n/ActiveStyle :\n{}%AI9_EndArtStyles\n", compound("Chain Style Filter", &[add, stack]))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_in_a_group_with_a_pathfinder_effect_stays_type() {
|
||||
// GUARDS: the group's style was not read, and the group came in as its drawn look, the type's
|
||||
// outlines and the square, which can't be retyped.
|
||||
let doc = text_document(&[("Hi\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]);
|
||||
// The look: the square, and the area round where the type lies (its anchor is at (58.5, 61.5)),
|
||||
// in the square's yellow.
|
||||
let drawing = "0 0 1 0 k\n54 56 m\n100 56 L\n100 80 L\n54 80 L\nf";
|
||||
let look = format!("u\n{}\n{drawing}\nU\n9 () XW\n", square(10, 10));
|
||||
let own: String = format!("0 Ae\nu\n{}{}\nU\n", text_object(0), square(10, 10)).lines().map(|l| format!("%_{l}\n")).collect();
|
||||
let art = native_with_text(&(pathfinder_add_style() + &layer("Art", true, &format!("{look}{own}1 (Add) XW\n"))), &doc);
|
||||
let check = |d: &Document, notes: &[String]| {
|
||||
assert_eq!(kinds(&d.layers[0]), ["group[2]"], "{notes:?}");
|
||||
let group = &d.layers[0].children().unwrap()[0];
|
||||
let mut kinds = kinds(group);
|
||||
kinds.sort_unstable();
|
||||
assert_eq!(kinds, ["path", "text"], "{notes:?}");
|
||||
assert_eq!(text_of(group).iter().map(|t| t.plain_text()).collect::<Vec<_>>(), ["Hi"]);
|
||||
let effects: Vec<_> = group.appearance.effects.iter().map(|e| e.id.as_str()).collect();
|
||||
assert_eq!(effects, ["pathfinder.add"], "{notes:?}");
|
||||
assert!(!notes.iter().any(|w| w.contains("drawn look")), "{notes:?}");
|
||||
};
|
||||
let (d, notes) = crate::ai_alone(&private(&art)).unwrap();
|
||||
check(&d, ¬es);
|
||||
let page = format!("{}\n0 0 1 0 setcmykcolor 54 56 moveto 100 56 lineto 100 80 lineto 54 80 lineto closepath fill", page_square(10, 10));
|
||||
let r = import(&eps(&page, &art)).unwrap();
|
||||
check(&r.document, &r.warnings);
|
||||
}
|
||||
|
||||
/// An art style section with style `Bent`: a blue fill over the characters, and effect `name`, its
|
||||
/// dictionary holding `keys`, on the whole object.
|
||||
fn whole_object_style(name: &str, keys: &str) -> String {
|
||||
|
||||
@@ -172,9 +172,11 @@ impl Renderer {
|
||||
/// so the nodes they hold go with them).
|
||||
fn end_frame(&mut self) {
|
||||
let g = self.stamp;
|
||||
if self.geom.len() > 1024 {
|
||||
self.geom.retain(|_, e| g - e.stamp <= 3);
|
||||
}
|
||||
// Swept however few the entries: each keeps its node alive, and an object dragged or
|
||||
// edited makes a new node (with its layer) in every frame. Kept until there were 1,024 of
|
||||
// them, a drag left up to that many old copies of the object alive, each with all its
|
||||
// members (and, for a compound path, its assembled path).
|
||||
self.geom.retain(|_, e| g - e.stamp <= 3);
|
||||
if self.strokes.len() > 1024 {
|
||||
self.strokes.retain(|_, e| g - e.stamp <= 3);
|
||||
}
|
||||
|
||||
@@ -114,7 +114,16 @@ impl Renderer {
|
||||
/// The cached path of path or compound path `n` ([`Self::path_of`]) when the frame is in
|
||||
/// Outline view and `n` is `fx_owner`, else `None`.
|
||||
fn outline_path(&mut self, f: &Frame, n: &Node) -> Option<Arc<BezPath>> {
|
||||
let owner = self.fx_owner.as_ref().filter(|o| f.opts.outline && std::ptr::eq(&***o, n)).cloned()?;
|
||||
if !f.opts.outline {
|
||||
return None;
|
||||
}
|
||||
self.owner_path(f, n)
|
||||
}
|
||||
|
||||
/// The cached path of path or compound path `n` ([`Self::path_of`]) when `n` is `fx_owner`,
|
||||
/// else `None`.
|
||||
fn owner_path(&mut self, f: &Frame, n: &Node) -> Option<Arc<BezPath>> {
|
||||
let owner = self.fx_owner.as_ref().filter(|o| std::ptr::eq(&***o, n)).cloned()?;
|
||||
self.path_of(f.symbols, &owner)
|
||||
}
|
||||
|
||||
@@ -470,17 +479,13 @@ impl Renderer {
|
||||
self.draw_shape(ctx, f, n, &bp, *rule);
|
||||
}
|
||||
}
|
||||
NodeKind::Compound { children, rule } => {
|
||||
if let Some(bp) = self.outline_path(f, n) {
|
||||
return self.draw_shape(ctx, f, n, &bp, *rule);
|
||||
NodeKind::Compound { rule, .. } => {
|
||||
// Its members assembled once and kept with the node in `geom`, as plain paths are
|
||||
// (`path_of`): a compound path of thousands of members is not assembled again in
|
||||
// every frame.
|
||||
if let Some(bp) = self.owner_path(f, n).or_else(|| n.stroke_path().map(Arc::new)) {
|
||||
self.draw_shape(ctx, f, n, &bp, *rule);
|
||||
}
|
||||
let mut bp = BezPath::new();
|
||||
for c in children {
|
||||
if let Some(p) = c.path_data() {
|
||||
bp.extend(p.to_bezpath());
|
||||
}
|
||||
}
|
||||
self.draw_shape(ctx, f, n, &bp, *rule);
|
||||
}
|
||||
NodeKind::Text(t) => self.draw_text(ctx, f, n, t),
|
||||
NodeKind::Image(im) => self.draw_image_in(ctx, f, im, None, images::image_tint(n, f.ink), n.extras().pixelated),
|
||||
|
||||
@@ -2378,3 +2378,47 @@ fn text_runs_draw_their_own_glyphs_from_the_shared_outlines() {
|
||||
}
|
||||
assert!(g.run(7).elements().is_empty());
|
||||
}
|
||||
|
||||
/// A compound path is drawn from the path the renderer keeps for it, as a plain path is: the next
|
||||
/// frame draws the same path, and draws what a new renderer draws.
|
||||
/// Once the compound path changes (each frame of a drag makes a new one), the entries of the old
|
||||
/// one, which keep it alive, go after a few frames, however few entries the renderer holds.
|
||||
#[test]
|
||||
fn compound_paths_draw_from_kept_paths_and_let_old_ones_go() {
|
||||
let _fonts = fonts_steady();
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let layer = d.layers[0].id;
|
||||
let members: Vec<Arc<Node>> = (0..30)
|
||||
.map(|i| {
|
||||
let x = f64::from(i % 6) * 15.0;
|
||||
let y = f64::from(i / 6) * 15.0;
|
||||
let p = vectorcraft_geom::shapes::ellipse(Rect::new(x, y, x + 10.0, y + 10.0));
|
||||
Arc::new(Node::path(d.alloc_id(), p, vectorcraft_doc::Appearance::default()))
|
||||
})
|
||||
.collect();
|
||||
let id = d.alloc_id();
|
||||
let mut compound = Node::new(id, NodeKind::Compound { children: members, rule: vectorcraft_geom::FillRule::EvenOdd });
|
||||
compound.appearance = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).into();
|
||||
d.insert(Some(layer), 0, compound).unwrap();
|
||||
let opts = RenderOptions::default();
|
||||
let kept = |r: &Renderer, d: &Document| {
|
||||
let n = d.layers[0].children().unwrap()[0].clone();
|
||||
r.geom.get(&(Arc::as_ptr(&n) as usize)).and_then(|e| e.path.clone())
|
||||
};
|
||||
let mut r = Renderer::new();
|
||||
let first = r.render(&d, 100, 100, Affine::IDENTITY, &opts).pixels;
|
||||
let path = kept(&r, &d).expect("the compound path's path is kept");
|
||||
assert!(r.render(&d, 100, 100, Affine::IDENTITY, &opts).pixels == first);
|
||||
assert!(kept(&r, &d).is_some_and(|p| Arc::ptr_eq(&p, &path)), "the second frame draws the kept path");
|
||||
assert!(first == Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts).pixels);
|
||||
// Moved: a new compound path (and layer) in each frame.
|
||||
let old = d.layers[0].children().unwrap()[0].clone();
|
||||
let mut moved = d.clone();
|
||||
for _ in 0..5 {
|
||||
moved.node_mut(id).unwrap().transform(Affine::translate((1.0, 0.0)), false);
|
||||
r.render(&moved, 100, 100, Affine::IDENTITY, &opts);
|
||||
}
|
||||
drop(d);
|
||||
assert!(r.geom.len() < 1024);
|
||||
assert_eq!(Arc::strong_count(&old), 1, "the renderer no longer keeps the compound path drawn before the move");
|
||||
}
|
||||
@@ -149,7 +149,7 @@ fn named_made_up_ids(xml: &roxmltree::Document) -> HashSet<usize> {
|
||||
/// * so do objects with attributes in other applications' namespaces ([`foreign`]);
|
||||
/// * so do `<circle>` and `<ellipse>` elements, recorded: usvg makes their arcs into a varying
|
||||
/// number of curves, and they come back as the ellipse VectorCraft draws (not in a file whose
|
||||
/// style sheet has an `[id` selector);
|
||||
/// style sheet has an attribute selector);
|
||||
/// * linked files are read ([`files`]);
|
||||
/// * percentage lengths in a `<symbol>` with a `viewBox` become numbers ([`symbol_units`]);
|
||||
/// * what style sheet rules with a `:not()` set goes in `style` attributes ([`not_rules`]).
|
||||
@@ -164,8 +164,9 @@ pub(super) fn prepass<'s>(svg: &'s str, markers: &str, xml: &roxmltree::Document
|
||||
let not = markers.contains(":not(");
|
||||
let events = SVG_EVENTS.iter().any(|e| markers.contains(e));
|
||||
let foreign_attrs = markers.contains("xmlns:") && has_foreign_attributes(xml);
|
||||
// An id would change what a style sheet's `[id]` selector matches: such files keep usvg's curves.
|
||||
let ellipses = !markers.contains("[id") && ["<circle", ":circle", "<ellipse", ":ellipse"].iter().any(|t| markers.contains(t));
|
||||
let attribute_selectors =
|
||||
xml.descendants().filter(|n| n.is_element() && n.tag_name().name() == "style").filter_map(|n| n.text()).any(|text| text.contains('['));
|
||||
let ellipses = !attribute_selectors && ["<circle", ":circle", "<ellipse", ":ellipse"].iter().any(|t| markers.contains(t));
|
||||
if !css_transform
|
||||
&& !not
|
||||
&& !events
|
||||
|
||||
@@ -20,6 +20,23 @@ fn open(body: &str) -> (Document, Vec<String>) {
|
||||
import_with_report(&svg(body)).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_id_selectors_do_not_recolor_bare_ellipses() {
|
||||
for selector in ["circle[id]", "ellipse[id]", "circle[id]", "ellipse[id]", "circle[ id ]", r"ellipse[\69 d]"] {
|
||||
let source = svg(&format!(
|
||||
"<style>{selector} {{ fill: red }}</style><circle cx=\"40\" cy=\"50\" r=\"20\"/><ellipse cx=\"100\" cy=\"50\" rx=\"20\" ry=\"10\"/><circle id=\"c\" cx=\"40\" cy=\"100\" r=\"8\"/><ellipse id=\"e\" cx=\"100\" cy=\"100\" rx=\"12\" ry=\"8\"/>"
|
||||
));
|
||||
let doc = import(&source).unwrap();
|
||||
let actual = render_artboard(&doc);
|
||||
let expected = resvg_render(&source, 200, 120);
|
||||
assert_eq!((actual.width, actual.height), (expected.width, expected.height));
|
||||
for (x, y) in [(40, 50), (100, 50), (40, 100), (100, 100)] {
|
||||
let at = 4 * (y * actual.width + x) as usize;
|
||||
assert_eq!(&actual.rgba[at..at + 4], &expected.rgba[at..at + 4], "{selector}: ({x}, {y})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// All non-layer nodes in paint order.
|
||||
fn art(d: &Document) -> Vec<&Node> {
|
||||
let mut v = Vec::new();
|
||||
|
||||
@@ -239,6 +239,72 @@ impl FontFace {
|
||||
.map(|a| a as f64)
|
||||
.unwrap_or(self.upem * 0.5)
|
||||
}
|
||||
/// The coordinates of the carets inside ligature glyph `gid`, in font units, in the order the
|
||||
/// font lists them: the font's ligature caret list (`GDEF` `LigCaretList`,
|
||||
/// <https://learn.microsoft.com/en-us/typography/opentype/spec/gdef>), one between each two
|
||||
/// characters the glyph stands for, each an x in horizontal text and a y (up from the baseline)
|
||||
/// in vertical text. A coordinate with a variation index (format 3 in a variable font) takes its
|
||||
/// delta from the `GDEF` item variation store at the face's location; a device table's
|
||||
/// adjustments for pixel sizes are not applied. `None` when the font lists no carets for the
|
||||
/// glyph, lists a number other than `count`, gives one by a contour point, or gives one a
|
||||
/// variation index whose delta can't be read.
|
||||
fn ligature_caret_coordinates(&self, gid: u32, count: usize) -> Option<Vec<f64>> {
|
||||
use skrifa::raw::TableProvider;
|
||||
use skrifa::raw::tables::gdef::CaretValue;
|
||||
use skrifa::raw::tables::layout::DeviceOrVariationIndex;
|
||||
use skrifa::raw::tables::variations::DeltaSetIndex;
|
||||
let font = self.skrifa()?;
|
||||
let gdef = font.gdef().ok()?;
|
||||
let list = gdef.lig_caret_list()?.ok()?;
|
||||
let index = list.coverage().ok()?.get(GlyphId::new(gid))?;
|
||||
let glyph = list.lig_glyphs().get(usize::from(index)).ok()?;
|
||||
if usize::from(glyph.caret_count()) != count {
|
||||
return None;
|
||||
}
|
||||
let carets = glyph
|
||||
.caret_values()
|
||||
.iter()
|
||||
.map(|c| match c.ok()? {
|
||||
CaretValue::Format1(v) => Some(f64::from(v.coordinate())),
|
||||
CaretValue::Format3(v) => {
|
||||
let coordinate = f64::from(v.coordinate());
|
||||
if v.device_offset().is_null() {
|
||||
return Some(coordinate);
|
||||
}
|
||||
match v.device().ok()? {
|
||||
DeviceOrVariationIndex::Device(_) => Some(coordinate),
|
||||
DeviceOrVariationIndex::VariationIndex(ix) => {
|
||||
let store = gdef.item_var_store()?.ok()?;
|
||||
let index = DeltaSetIndex { outer: ix.delta_set_outer_index(), inner: ix.delta_set_inner_index() };
|
||||
Some(coordinate + store.compute_delta(index, self.location.coords()).ok()?.to_f64())
|
||||
}
|
||||
}
|
||||
}
|
||||
CaretValue::Format2(_) => None,
|
||||
})
|
||||
.collect::<Option<Vec<f64>>>()?;
|
||||
(!carets.is_empty()).then_some(carets)
|
||||
}
|
||||
/// The caret positions inside ligature glyph `gid` set across, in font units from its left
|
||||
/// edge, left to right: the x coordinates of the font's ligature caret list. `None` when the
|
||||
/// font lists no carets for the glyph, lists a number other than `count`, gives one by a contour
|
||||
/// point, or gives positions that are not increasing inside the glyph's advance.
|
||||
pub fn ligature_carets(&self, gid: u32, count: usize) -> Option<Vec<f64>> {
|
||||
let carets = self.ligature_caret_coordinates(gid, count)?;
|
||||
let advance = self.advance(gid);
|
||||
let inside = carets.iter().all(|x| *x > 0.0 && *x < advance) && carets.windows(2).all(|w| w[0] < w[1]);
|
||||
inside.then_some(carets)
|
||||
}
|
||||
/// The caret positions inside ligature glyph `gid` standing upright in vertical type, in font
|
||||
/// units down from the top of its cell, top to bottom: the y coordinates of the font's ligature
|
||||
/// caret list, for a cell `cell` long whose top is `top` above the baseline. `None` when the
|
||||
/// font lists no carets for the glyph, lists a number other than `count`, gives one by a contour
|
||||
/// point, or gives positions that are not increasing inside the cell.
|
||||
pub fn vertical_ligature_carets(&self, gid: u32, count: usize, top: f64, cell: f64) -> Option<Vec<f64>> {
|
||||
let carets = self.ligature_caret_coordinates(gid, count)?;
|
||||
let inside = carets.iter().all(|y| *y < top && *y > top - cell) && carets.windows(2).all(|w| w[0] < w[1]);
|
||||
inside.then(|| carets.iter().rev().map(|y| top - y).collect())
|
||||
}
|
||||
/// Glyph `gid` set upright in vertical type, from the font's vertical metrics: (its advance down
|
||||
/// the column, the height above the baseline of its vertical origin, the top of its cell), in
|
||||
/// font units. The origin is the `VORG` table's, else the glyph's top plus its top side bearing.
|
||||
|
||||
@@ -37,7 +37,7 @@ use breaking::tab_advance;
|
||||
#[cfg(test)]
|
||||
use breaking::{break_line, candidates};
|
||||
pub use driver::{decorations, fit_first_line, layout, layout_with, scaled};
|
||||
use vertical::{TcyStyle, stands_upright, tate_chu_yoko, upright_cell, upright_centre, whole_character_widths};
|
||||
use vertical::{TcyStyle, stands_upright, tate_chu_yoko, upright_cell, upright_centre, upright_extent, whole_character_widths};
|
||||
|
||||
const EPS: f64 = 1e-6;
|
||||
|
||||
@@ -47,6 +47,60 @@ fn continues_cluster(prev: Option<&SGlyph>, g: Option<&SGlyph>) -> bool {
|
||||
prev.zip(g).is_some_and(|(a, b)| a.len > 0 && b.len > 0 && a.byte == b.byte)
|
||||
}
|
||||
|
||||
/// The caret stops inside glyph `g` when it alone stands for several characters (grapheme clusters)
|
||||
/// of `text`, a ligature ([`PositionedGlyph::carets`]); `rtl` when its logical leading edge is its
|
||||
/// right edge; `upright` when it stands upright in vertical type, its carets then down its cell
|
||||
/// ([`upright_extent`]). Empty for a glyph of one character.
|
||||
fn ligature_carets(text: &str, g: &SGlyph, rtl: bool, upright: bool) -> Vec<(usize, f64)> {
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
let Some(s) = text.get(g.byte..g.byte + g.len).filter(|_| g.len > 1) else { return Vec::new() };
|
||||
let starts: Vec<usize> = s.grapheme_indices(true).skip(1).map(|(i, _)| g.byte + i).collect();
|
||||
if starts.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let parts = starts.len() + 1;
|
||||
let from_font = if upright {
|
||||
let (cell, top) = upright_extent(g);
|
||||
g.face
|
||||
.vertical_ligature_carets(g.gid, starts.len(), top, cell)
|
||||
.filter(|c| c.len() == starts.len() && cell > 0.0)
|
||||
.map(|c| c.into_iter().map(|d| d / cell).collect::<Vec<f64>>())
|
||||
} else {
|
||||
let advance = g.face.advance(g.gid);
|
||||
g.face
|
||||
.ligature_carets(g.gid, starts.len())
|
||||
.filter(|c| c.len() == starts.len() && advance > 0.0)
|
||||
.map(|c| c.into_iter().map(|x| if rtl { 1.0 - x / advance } else { x / advance }).collect::<Vec<f64>>())
|
||||
};
|
||||
let mut at = from_font.unwrap_or_else(|| (1..parts).map(|j| j as f64 / parts as f64).collect());
|
||||
at.sort_by(f64::total_cmp);
|
||||
starts.into_iter().zip(at).collect()
|
||||
}
|
||||
|
||||
/// Does glyph `g`, standing upright in vertical type, take a cell of its own down the column? Every
|
||||
/// glyph with an advance does, including one whose tracking or kerning makes its advance zero or
|
||||
/// negative; a glyph without a font advance (a mark) does not.
|
||||
fn takes_cell(g: &SGlyph) -> bool {
|
||||
g.adv > 0.0 || g.face.advance(g.gid) > 0.0
|
||||
}
|
||||
|
||||
/// Clear the caret stops of each glyph that shares its cluster with another glyph: only a glyph
|
||||
/// that alone stands for its characters is a ligature.
|
||||
fn keep_lone_ligature_carets(glyphs: &mut [PositionedGlyph]) {
|
||||
if glyphs.iter().all(|g| g.carets.is_empty()) {
|
||||
return;
|
||||
}
|
||||
let mut count: std::collections::HashMap<(usize, usize), usize> = std::collections::HashMap::new();
|
||||
for g in glyphs.iter().filter(|g| g.len > 0) {
|
||||
*count.entry((g.byte, g.len)).or_default() += 1;
|
||||
}
|
||||
for g in glyphs.iter_mut().filter(|g| !g.carets.is_empty()) {
|
||||
if count.get(&(g.byte, g.len)).is_some_and(|n| *n > 1) {
|
||||
g.carets.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Ctx<'a> {
|
||||
on_path: bool,
|
||||
db: &'a FontDb,
|
||||
@@ -278,7 +332,7 @@ impl Ctx<'_> {
|
||||
// the middle of its own cell, not of its advance (tracking and justification add
|
||||
// space after the cell, and must not push the glyph off the centre line).
|
||||
let em = self.style_at(g.byte).size;
|
||||
let cell = if g.adv > 0.0 { upright_cell(g) } else { advance };
|
||||
let cell = if takes_cell(g) { upright_cell(g) } else { advance };
|
||||
// A leading space taken off moves it up the column after the turn (moving the
|
||||
// turning point instead would move it across the column too).
|
||||
let turn = Affine::translate((-g.lead, 0.0))
|
||||
@@ -300,6 +354,29 @@ impl Ctx<'_> {
|
||||
p
|
||||
};
|
||||
let font_id = g.face.id();
|
||||
// Its own width along the baseline: its font advance through its size, scale and the glyph
|
||||
// scaling `pre` adds. In vertical type, an upright glyph's own length down the column is
|
||||
// its cell with the Proportional Metrics change to it, and a tate-chu-yoko glyph takes its
|
||||
// advance, as an inline graphic does.
|
||||
let upright = self.vertical && g.inline.is_none() && g.tcy.is_none() && takes_cell(g) && stands_upright(g);
|
||||
let width = if g.inline.is_some() || (self.vertical && g.tcy.is_some()) {
|
||||
advance
|
||||
} else if upright {
|
||||
let proportional = g.vpal.filter(|_| g.face.vertical_glyph(g.gid).is_some()).map_or(0.0, |a| a.advance);
|
||||
Some(upright_cell(g) + proportional).filter(|w| w.is_finite() && *w > 0.0).unwrap_or(advance)
|
||||
} else {
|
||||
let [a, b, ..] = pre.as_coeffs();
|
||||
Some(g.face.advance(g.gid) * g.sx * a.hypot(b)).filter(|w| w.is_finite()).unwrap_or(advance)
|
||||
};
|
||||
// Where its own width starts along its advance: the shaper's placement, a leading space
|
||||
// taken off and right-to-left manual kerning move the glyph along the line. An upright or
|
||||
// tate-chu-yoko glyph in vertical type starts its cell at the start of its advance.
|
||||
let width_start = if g.inline.is_none() && !upright && !(self.vertical && g.tcy.is_some()) {
|
||||
let [a, b, ..] = pre.as_coeffs();
|
||||
Some((g.kern_shift + g.dx - g.lead) * a.hypot(b)).filter(|s| s.is_finite()).unwrap_or(0.0)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
if let Some(art) = g.inline.as_ref().and_then(|ib| ib.art) {
|
||||
self.out.inlines.push(InlineGlyph { run: g.run, byte: g.byte, glyph: self.out.glyphs.len(), xf: m, bounds: m.transform_rect_bbox(art) });
|
||||
}
|
||||
@@ -323,6 +400,9 @@ impl Ctx<'_> {
|
||||
bend: None,
|
||||
unturned,
|
||||
pivot,
|
||||
carets: if g.inline.is_some() { Vec::new() } else { ligature_carets(self.text, g, g.level.is_rtl() && !self.vertical, upright) },
|
||||
width,
|
||||
width_start,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ use super::ruby::ruby_layout;
|
||||
use super::vertical::{EM_CENTER, QUARTER_TURN, align_vertically, finish_bounds};
|
||||
use super::{
|
||||
Affine, BezPath, CharStyle, Ctx, FontDb, LayoutOptions, OtFeatures, Point, Rect, Shape, TextKind, TextLayout, TextObject, VerticalAlign,
|
||||
keep_lone_ligature_carets,
|
||||
};
|
||||
|
||||
/// Lay out a text object into text-space glyph outlines (default [`LayoutOptions`]).
|
||||
@@ -305,6 +306,7 @@ fn layout_once(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLayout
|
||||
cx.out.vertical = true;
|
||||
cx.out.line_xf = line_xf;
|
||||
}
|
||||
keep_lone_ligature_carets(&mut cx.out.glyphs);
|
||||
finish_bounds(&mut cx.out);
|
||||
cx.out
|
||||
}
|
||||
@@ -369,5 +369,8 @@ fn ruby_glyph(g: &PositionedGlyph, m: Affine, run: usize, byte: usize, line: usi
|
||||
bend: None,
|
||||
unturned: Affine::IDENTITY,
|
||||
pivot: m * g.origin,
|
||||
carets: Vec::new(),
|
||||
width: 0.0,
|
||||
width_start: 0.0,
|
||||
}
|
||||
}
|
||||
@@ -206,6 +206,20 @@ pub(super) fn upright_cell(g: &SGlyph) -> f64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// An upright glyph's cell in font units, as [`upright_cell`] and [`upright_centre`] place it before
|
||||
/// its size: (its length down the column, the height of its top above the baseline). From the
|
||||
/// font's vertical metrics, else at least one em long, centred on the ideographic em box.
|
||||
pub(super) fn upright_extent(g: &SGlyph) -> (f64, f64) {
|
||||
match g.face.vertical_glyph(g.gid) {
|
||||
Some((advance, origin)) => (advance, origin),
|
||||
None => {
|
||||
let em = g.face.units_per_em();
|
||||
let cell = g.face.advance(g.gid).max(em);
|
||||
(cell, EM_CENTER * em + cell * 0.5)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Height above the baseline (line space) of the centre of an upright glyph's `cell`, the point it
|
||||
/// turns about: from the font's vertical metrics, the cell hanging from the glyph's vertical origin;
|
||||
/// else the centre of the ideographic em box ([`EM_CENTER`] of the size `em`).
|
||||
|
||||
+116
-16
@@ -149,6 +149,25 @@ pub struct PositionedGlyph {
|
||||
/// Font units: `xf * pivot` is the point its Character Rotation turns it about, its pen
|
||||
/// position on the baseline moved by its baseline shift.
|
||||
pub pivot: Point,
|
||||
/// A ligature (one glyph that alone stands for several characters, grapheme clusters, of the
|
||||
/// text): the caret stop between each two of them, in logical order, as the byte offset of the
|
||||
/// later character and how far the caret stands along the glyph's own width ([`Self::width`])
|
||||
/// from its logical leading edge, 0 to 1. The font's ligature carets
|
||||
/// ([`FontFace::ligature_carets`], or [`FontFace::vertical_ligature_carets`] for a glyph
|
||||
/// standing upright in vertical type) when it lists one for each stop, else the width divided
|
||||
/// equally among the characters. Empty for any other glyph.
|
||||
pub carets: Vec<(usize, f64)>,
|
||||
/// The glyph's own width along its advance in text space: its font advance at its size,
|
||||
/// Horizontal Scale and glyph scaling, without the tracking, kerning, justification space and
|
||||
/// kashida that [`Self::advance`] includes after it (to its right in horizontal type). The
|
||||
/// advance itself in vertical type.
|
||||
pub width: f64,
|
||||
/// How far right of the left end of its advance the glyph's own width ([`Self::width`]) starts,
|
||||
/// in text space: the font's placement of the glyph (`GPOS` x placement), less a leading space
|
||||
/// taken off, plus the manual kerning of right-to-left text, which moves the glyph right so that
|
||||
/// the space it adds lies on the glyph's left. 0 for a glyph standing upright or set across the
|
||||
/// column in vertical type, and for an inline graphic.
|
||||
pub width_start: f64,
|
||||
}
|
||||
|
||||
/// How a glyph on a path is bent along it: a point of its pen space (x along its advance from its
|
||||
@@ -167,6 +186,57 @@ pub struct GlyphBend {
|
||||
}
|
||||
|
||||
impl PositionedGlyph {
|
||||
/// The glyph's caret stops in logical order: its first byte, its ligature carets
|
||||
/// ([`Self::carets`]) and its end, each with how far along its own width ([`Self::width`]) from
|
||||
/// its logical leading edge the caret stands, 0 to 1.
|
||||
fn width_stops(&self) -> impl Iterator<Item = (usize, f64)> + '_ {
|
||||
std::iter::once((self.byte, 0.0)).chain(self.carets.iter().copied()).chain(std::iter::once((self.byte + self.len, 1.0)))
|
||||
}
|
||||
/// The glyph's caret stops in logical order, each with its distance in text space from the
|
||||
/// logical leading edge of a span `extent` long that holds the glyph (its advance, or its
|
||||
/// cluster's): 0 at its first byte and `extent` at its end. A ligature caret stands at its place
|
||||
/// in the glyph's own width ([`Self::width`]), which starts [`Self::width_start`] right of the
|
||||
/// glyph's left edge; the rest of the space the advance adds lies to the right of that width,
|
||||
/// after the last ligature caret left to right, and before the first one right to left.
|
||||
/// Negative kerning or tracking makes the advance shorter than the width, or zero or negative,
|
||||
/// and a ligature caret then stands past the end of the advance.
|
||||
fn stops_along(&self, extent: f64) -> impl Iterator<Item = (usize, f64)> + '_ {
|
||||
let (width, start) = if self.width > 0.0 && self.width.is_finite() {
|
||||
(self.width, if self.width_start.is_finite() { self.width_start } else { 0.0 })
|
||||
} else {
|
||||
(extent, 0.0)
|
||||
};
|
||||
let ends = (self.byte, self.byte + self.len);
|
||||
self.width_stops().map(move |(b, f)| {
|
||||
if b == ends.0 {
|
||||
(b, 0.0)
|
||||
} else if b == ends.1 {
|
||||
(b, extent)
|
||||
} else if self.rtl {
|
||||
(b, extent - start - (1.0 - f) * width)
|
||||
} else {
|
||||
(b, start + f * width)
|
||||
}
|
||||
})
|
||||
}
|
||||
/// The distance in text space from the logical leading edge of a span `extent` long that holds
|
||||
/// the glyph (its advance, or its cluster's) to the caret for byte `byte`: 0 at its first byte,
|
||||
/// `extent` at its end, a ligature caret's place at that caret's byte ([`Self::stops_along`],
|
||||
/// which can lie outside 0 to `extent`), and in proportion to the bytes between two stops.
|
||||
pub fn caret_offset(&self, byte: usize, extent: f64) -> f64 {
|
||||
if byte <= self.byte || self.len == 0 {
|
||||
return 0.0;
|
||||
}
|
||||
let mut from = (self.byte, 0.0);
|
||||
for (b, d) in self.stops_along(extent).skip(1) {
|
||||
if byte <= b {
|
||||
let span = b.saturating_sub(from.0).max(1) as f64;
|
||||
return from.1 + (d - from.1) * (byte - from.0) as f64 / span;
|
||||
}
|
||||
from = (b, d);
|
||||
}
|
||||
extent
|
||||
}
|
||||
/// The glyph's colour bitmap, and the transform from its pixels to text space.
|
||||
pub fn placed_image(&self) -> Option<(&Arc<GlyphImage>, Affine)> {
|
||||
self.image.as_ref().map(|i| (i, self.xf * i.xf))
|
||||
@@ -436,7 +506,8 @@ fn cluster_extent(layout: &TextLayout, glyphs: &[PositionedGlyph], i: usize) ->
|
||||
}
|
||||
|
||||
/// Caret for byte offset `byte`, as a (top, bottom) segment in text space. In horizontal type, a
|
||||
/// cluster drawn with several glyphs is measured whole ([`cluster_extent`]).
|
||||
/// cluster drawn with several glyphs is measured whole ([`cluster_extent`]). Inside a ligature the
|
||||
/// caret stands at its caret stops ([`PositionedGlyph::carets`]).
|
||||
pub fn caret_position(layout: &TextLayout, byte: usize) -> (Point, Point) {
|
||||
let Some(line) = layout.lines.get(layout.line_of(byte)) else {
|
||||
return (Point::ZERO, Point::ZERO);
|
||||
@@ -444,12 +515,12 @@ pub fn caret_position(layout: &TextLayout, byte: usize) -> (Point, Point) {
|
||||
let glyphs = &layout.glyphs[line.glyph_start..line.glyph_end];
|
||||
let (pos, angle) = if let Some(i) = glyphs.iter().position(|g| g.byte <= byte && g.byte + g.len > byte) {
|
||||
let g = &glyphs[i];
|
||||
let frac = if byte <= g.byte { 0.0 } else { (byte - g.byte) as f64 / g.len.max(1) as f64 };
|
||||
let (origin, advance) = match cluster_extent(layout, glyphs, i) {
|
||||
Some((left, right)) => (Point::new(left, g.origin.y), right - left),
|
||||
None => (g.origin, g.advance),
|
||||
};
|
||||
(origin + dir(g.angle) * (advance * if g.rtl { 1.0 - frac } else { frac }), g.angle)
|
||||
let off = g.caret_offset(byte, advance);
|
||||
(origin + dir(g.angle) * if g.rtl { advance - off } else { off }, g.angle)
|
||||
} else if let Some(g) = glyphs.iter().max_by_key(|g| g.byte + g.len) {
|
||||
(g.origin + dir(g.angle) * if g.rtl { 0.0 } else { g.advance }, g.angle)
|
||||
} else {
|
||||
@@ -464,11 +535,16 @@ pub fn caret_position(layout: &TextLayout, byte: usize) -> (Point, Point) {
|
||||
/// Byte offset nearest to the text-space point `p` (for clicking/dragging with the Type tool).
|
||||
pub fn hit_byte(layout: &TextLayout, p: Point) -> usize {
|
||||
if layout.on_path {
|
||||
let best = layout.glyphs.iter().enumerate().min_by(|(_, a), (_, b)| {
|
||||
let ca = a.origin + dir(a.angle) * (a.advance * 0.5);
|
||||
let cb = b.origin + dir(b.angle) * (b.advance * 0.5);
|
||||
(p - ca).hypot2().total_cmp(&(p - cb).hypot2())
|
||||
});
|
||||
// The distance from `p` to a glyph's middle, or to one of its inner ligature caret stops
|
||||
// when that is nearer (a stop can lie past the glyph's advance).
|
||||
let near = |g: &PositionedGlyph| {
|
||||
let along = dir(g.angle);
|
||||
let mid = (p - (g.origin + along * (g.advance * 0.5))).hypot2();
|
||||
(g.stops_along(g.advance).filter(|(b, _)| *b != g.byte && *b != g.byte + g.len))
|
||||
.map(|(_, d)| (p - (g.origin + along * if g.rtl { g.advance - d } else { d })).hypot2())
|
||||
.fold(mid, f64::min)
|
||||
};
|
||||
let best = layout.glyphs.iter().enumerate().min_by(|(_, a), (_, b)| near(a).total_cmp(&near(b)));
|
||||
let Some((i, g)) = best else { return layout.lines.first().map_or(0, |l| l.start) };
|
||||
// `first` and `last` are the first and last glyphs of the cluster. A click before the middle of
|
||||
// the cluster, measured along the first glyph's direction, goes to the cluster's start.
|
||||
@@ -476,6 +552,14 @@ pub fn hit_byte(layout: &TextLayout, p: Point) -> usize {
|
||||
let first = layout.glyphs[..=i].iter().rev().take_while(same).last().unwrap_or(g);
|
||||
let last = layout.glyphs[i..].iter().take_while(same).last().unwrap_or(g);
|
||||
let along = dir(first.angle);
|
||||
if !g.carets.is_empty() {
|
||||
// A ligature: the nearest of its caret stops, measured along it from its logical
|
||||
// leading edge in text space, within the span its stops cover.
|
||||
let (lo, hi) = g.stops_along(g.advance).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), (_, d)| (lo.min(d), hi.max(d)));
|
||||
let t = (p - g.origin).dot(along);
|
||||
let at = (if g.rtl { g.advance - t } else { t }).max(lo).min(hi);
|
||||
return g.stops_along(g.advance).min_by(|a, b| (a.1 - at).abs().total_cmp(&(b.1 - at).abs())).map_or(g.byte, |s| s.0);
|
||||
}
|
||||
let span = (last.origin + dir(last.angle) * last.advance - first.origin).dot(along);
|
||||
return if ((p - first.origin).dot(along) < span * 0.5) != g.rtl { g.byte } else { g.byte + g.len };
|
||||
}
|
||||
@@ -517,7 +601,8 @@ pub fn byte_in_line(layout: &TextLayout, li: usize, x: f64) -> usize {
|
||||
// a consonant and its reph) has one caret stop at each end of its glyphs taken together. The
|
||||
// tatweels of a kashida have no source length or advance and come after the glyphs of the
|
||||
// letter after the kashida in the text; they belong to that letter's cluster. A list marker's
|
||||
// glyphs (no source length, an advance) are a cluster of their own.
|
||||
// glyphs (no source length, an advance) are a cluster of their own. A ligature also has a stop
|
||||
// at each of its caret stops.
|
||||
let mut clusters: Vec<(f64, f64, &PositionedGlyph)> = Vec::with_capacity(glyphs.len());
|
||||
for g in glyphs {
|
||||
let left = layout.logical_point(g.origin).x;
|
||||
@@ -529,7 +614,7 @@ pub fn byte_in_line(layout: &TextLayout, li: usize, x: f64) -> usize {
|
||||
}
|
||||
let nearest = clusters
|
||||
.iter()
|
||||
.flat_map(|&(left, right, g)| if g.rtl { [(right, g.byte), (left, g.byte + g.len)] } else { [(left, g.byte), (right, g.byte + g.len)] })
|
||||
.flat_map(|&(left, right, g)| g.stops_along(right - left).map(move |(b, d)| (if g.rtl { right - d } else { left + d }, b)))
|
||||
.min_by(|a, b| (a.0 - x).abs().total_cmp(&(b.0 - x).abs()));
|
||||
nearest.map_or(line.start, |(_, byte)| byte)
|
||||
}
|
||||
@@ -562,9 +647,9 @@ fn x_in_line(layout: &TextLayout, li: usize, byte: usize) -> f64 {
|
||||
let glyphs = &layout.glyphs[line.glyph_start..line.glyph_end];
|
||||
if let Some(i) = glyphs.iter().position(|g| g.byte <= byte && g.byte + g.len > byte) {
|
||||
let g = &glyphs[i];
|
||||
let frac = if byte <= g.byte { 0.0 } else { (byte - g.byte) as f64 / g.len.max(1) as f64 };
|
||||
let (left, advance) = cluster_extent(layout, glyphs, i).map_or((layout.logical_point(g.origin).x, g.advance), |(l, r)| (l, r - l));
|
||||
return left + advance * if g.rtl { 1.0 - frac } else { frac };
|
||||
let off = g.caret_offset(byte, advance);
|
||||
return left + if g.rtl { advance - off } else { off };
|
||||
}
|
||||
glyphs.iter().max_by_key(|g| g.byte + g.len).map_or(line.x0, |g| layout.logical_point(g.origin).x + if g.rtl { 0.0 } else { g.advance })
|
||||
}
|
||||
@@ -592,13 +677,25 @@ pub fn selection_quads(layout: &TextLayout, a: usize, b: usize) -> Vec<[Point; 4
|
||||
if a == b {
|
||||
return out;
|
||||
}
|
||||
// The part of glyph `g` that the selection covers, as distances in text space from its left
|
||||
// (its start along a path), the smaller first: all of its advance, or the characters of a
|
||||
// ligature that are selected. A ligature caret past a shortened advance lies outside it.
|
||||
let covered = |g: &PositionedGlyph| {
|
||||
if g.len == 0 {
|
||||
return (g.advance.min(0.0), g.advance.max(0.0));
|
||||
}
|
||||
let (fa, fb) = (g.caret_offset(a.max(g.byte), g.advance), g.caret_offset(b.min(g.byte + g.len), g.advance));
|
||||
let (f0, f1) = if g.rtl { (g.advance - fb, g.advance - fa) } else { (fa, fb) };
|
||||
(f0.min(f1), f0.max(f1))
|
||||
};
|
||||
if layout.on_path {
|
||||
// A list marker's glyphs stand for no characters.
|
||||
for g in layout.glyphs.iter().filter(|g| g.byte >= a && g.byte < b && g.len > 0) {
|
||||
for g in layout.glyphs.iter().filter(|g| g.byte < b && g.byte + g.len > a && g.len > 0) {
|
||||
let li = &layout.lines[0];
|
||||
let d = dir(g.angle);
|
||||
let up = Vec2::new(d.y, -d.x);
|
||||
let (p0, p1) = (g.origin, g.origin + d * g.advance);
|
||||
let (f0, f1) = covered(g);
|
||||
let (p0, p1) = (g.origin + d * f0, g.origin + d * f1);
|
||||
out.push([p0 + up * li.ascent, p1 + up * li.ascent, p1 - up * li.descent, p0 - up * li.descent]);
|
||||
}
|
||||
return out;
|
||||
@@ -609,7 +706,8 @@ pub fn selection_quads(layout: &TextLayout, a: usize, b: usize) -> Vec<[Point; 4
|
||||
for (_, g) in glyphs {
|
||||
let Some(l) = layout.lines.get(g.line) else { continue };
|
||||
let p = layout.logical_point(g.origin);
|
||||
let (x0, x1) = (p.x, p.x + g.advance);
|
||||
let (f0, f1) = covered(g);
|
||||
let (x0, x1) = (p.x + f0, p.x + f1);
|
||||
out.push(
|
||||
[
|
||||
Point::new(x0, l.baseline - l.ascent),
|
||||
@@ -636,6 +734,8 @@ pub fn selection_quads(layout: &TextLayout, a: usize, b: usize) -> Vec<[Point; 4
|
||||
let last = layout.glyphs[l.glyph_start..l.glyph_end].last().map_or(l.x1, |g| layout.logical_point(g.origin).x + g.advance);
|
||||
xb = last.max(l.x1) + (l.ascent + l.descent) * 0.25;
|
||||
}
|
||||
// A ligature caret past the ligature's shortened advance stands right of the glyph's end.
|
||||
let (xa, xb) = (xa.min(xb), xa.max(xb));
|
||||
if xb - xa <= 1e-9 {
|
||||
continue;
|
||||
}
|
||||
@@ -678,7 +778,7 @@ fn caret_horizontal_filtered(layout: &TextLayout, byte: usize, right: bool, vali
|
||||
(layout.logical_point(caret_position(layout, b).0).x, if rtl { -(b as f64) } else { b as f64 })
|
||||
};
|
||||
let (x, order) = stop(byte);
|
||||
let mut stops: Vec<_> = glyphs.iter().flat_map(|g| [g.byte, g.byte + g.len]).collect();
|
||||
let mut stops: Vec<_> = glyphs.iter().flat_map(|g| g.width_stops().map(|(b, _)| b)).collect();
|
||||
stops.sort_unstable();
|
||||
stops.dedup();
|
||||
stops
|
||||
|
||||
@@ -489,6 +489,195 @@ pub fn lam_alef_font(feature: &[u8; 4]) -> Option<Vec<u8>> {
|
||||
Some(builder.build())
|
||||
}
|
||||
|
||||
/// The family of [`ligature_caret_font`].
|
||||
pub const LIGATURE_CARET_FAMILY: &str = "Carettest Sans";
|
||||
|
||||
/// The glyph [`ligature_caret_font`]'s `liga` gives for f + i: W, wider than either letter.
|
||||
pub const LIGATURE_CARET_GLYPH: char = 'W';
|
||||
|
||||
/// A test-only cmap over bundled Source Sans 3 for f, i and the space, whose `GSUB` `liga` joins f +
|
||||
/// i into [`LIGATURE_CARET_GLYPH`]. With `caret`, a `GDEF` ligature caret list puts that glyph's one
|
||||
/// caret at x = `caret` font units; without it the font has no `GDEF` table. `None` when it can't be
|
||||
/// built.
|
||||
pub fn ligature_caret_font(caret: Option<i16>) -> Option<Vec<u8>> {
|
||||
use write_fonts::tables::cmap::Cmap;
|
||||
use write_fonts::tables::gdef::{CaretValue, Gdef, LigCaretList, LigGlyph};
|
||||
use write_fonts::tables::gsub::{Gsub, Ligature, LigatureSet, LigatureSubstFormat1, SubstitutionLookup, SubstitutionLookupList};
|
||||
use write_fonts::tables::layout::{CoverageFormat1, Feature, FeatureList, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord};
|
||||
use write_fonts::types::GlyphId16;
|
||||
|
||||
const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf");
|
||||
let font = skrifa::FontRef::new(BASE).ok()?;
|
||||
let charmap = font.charmap();
|
||||
let mapping = [('f', 'f'), ('i', 'i'), (' ', ' ')];
|
||||
let mappings = mapping.into_iter().map(|(c, source)| Some((c, write_fonts::types::GlyphId::new(charmap.map(source)?.to_u32()))));
|
||||
let cmap = Cmap::from_mappings(mappings.collect::<Option<Vec<_>>>()?).ok()?;
|
||||
let family = LIGATURE_CARET_FAMILY;
|
||||
let name = name_table(&[(1, family), (2, "Regular"), (4, "Carettest Sans Regular"), (6, "CarettestSans-Regular")])?;
|
||||
let mut builder = FontBuilder::new();
|
||||
builder.add_table(&cmap).ok()?;
|
||||
builder.add_raw(Tag::new(b"name"), name);
|
||||
let gid = |c| Some(GlyphId16::new(u16::try_from(charmap.map(c)?.to_u32()).ok()?));
|
||||
let ligature = gid(LIGATURE_CARET_GLYPH)?;
|
||||
let subst = LigatureSubstFormat1::new(
|
||||
CoverageFormat1::new(vec![gid('f')?]).into(),
|
||||
vec![LigatureSet::new(vec![Ligature::new(ligature, vec![gid('i')?])])],
|
||||
);
|
||||
let features = FeatureList::new(vec![FeatureRecord::new(Tag::new(b"liga"), Feature::new(None, vec![0]))]);
|
||||
let lookups = SubstitutionLookupList::new(vec![SubstitutionLookup::Ligature(Lookup::new(Default::default(), vec![subst]))]);
|
||||
let langsys = || Script::new(Some(LangSys::new(vec![0])), vec![]);
|
||||
let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"DFLT"), langsys()), ScriptRecord::new(Tag::new(b"latn"), langsys())]);
|
||||
builder.add_table(&Gsub::new(scripts, features, lookups)).ok()?;
|
||||
if let Some(x) = caret {
|
||||
let carets = LigCaretList::new(CoverageFormat1::new(vec![ligature]).into(), vec![LigGlyph::new(vec![CaretValue::format_1(x)])]);
|
||||
builder.add_table(&Gdef::new(None, None, Some(carets), None)).ok()?;
|
||||
}
|
||||
for r in font.table_directory.table_records() {
|
||||
let tag = Tag::new(&r.tag().to_be_bytes());
|
||||
if tag != Tag::new(b"GDEF") && !builder.contains(tag) {
|
||||
builder.add_raw(tag, font.table_data(r.tag())?.as_bytes());
|
||||
}
|
||||
}
|
||||
Some(builder.build())
|
||||
}
|
||||
|
||||
/// The family of [`vertical_ligature_caret_font`].
|
||||
pub const VERTICAL_LIGATURE_CARET_FAMILY: &str = "Vertical Carettest Sans";
|
||||
|
||||
/// [`ligature_caret_font`] with its one caret at y = `caret` font units, as family
|
||||
/// [`VERTICAL_LIGATURE_CARET_FAMILY`], with vertical metrics (`vhea`, `vmtx` and `VORG`): every glyph
|
||||
/// one em down the column with its vertical origin at 0.88 em. `None` when it can't be built.
|
||||
pub fn vertical_ligature_caret_font(caret: i16) -> Option<Vec<u8>> {
|
||||
let base = ligature_caret_font(Some(caret))?;
|
||||
let font = skrifa::FontRef::new(&base).ok()?;
|
||||
let n = font.maxp().ok()?.num_glyphs();
|
||||
let be16 = |v: &mut Vec<u8>, x: i16| v.extend_from_slice(&x.to_be_bytes());
|
||||
// vmtx: (advance height, top side bearing) for every glyph; VORG gives the origin.
|
||||
let mut vmtx = Vec::with_capacity(4 * usize::from(n));
|
||||
for _ in 0..n {
|
||||
vmtx.extend_from_slice(&1000_u16.to_be_bytes());
|
||||
be16(&mut vmtx, 0);
|
||||
}
|
||||
// vhea 1.1: ascent/descent of the em box across the column, then the metrics' count.
|
||||
let mut vhea = Vec::with_capacity(36);
|
||||
vhea.extend_from_slice(&0x0001_1000_u32.to_be_bytes());
|
||||
for x in [500, -500, 0] {
|
||||
be16(&mut vhea, x);
|
||||
}
|
||||
vhea.extend_from_slice(&1000_u16.to_be_bytes());
|
||||
for x in [0, 0, 1000, 1, 0, 0, 0, 0, 0, 0, 0] {
|
||||
be16(&mut vhea, x);
|
||||
}
|
||||
vhea.extend_from_slice(&n.to_be_bytes());
|
||||
// VORG 1.0: the default origin and no glyph that differs.
|
||||
let mut vorg = Vec::new();
|
||||
for x in [1, 0, 880, 0] {
|
||||
be16(&mut vorg, x);
|
||||
}
|
||||
let family = VERTICAL_LIGATURE_CARET_FAMILY;
|
||||
let name = name_table(&[(1, family), (2, "Regular"), (4, "Vertical Carettest Sans Regular"), (6, "VerticalCarettestSans-Regular")])?;
|
||||
let mut builder = FontBuilder::new();
|
||||
builder.add_raw(Tag::new(b"name"), name);
|
||||
builder.add_raw(Tag::new(b"vhea"), vhea);
|
||||
builder.add_raw(Tag::new(b"vmtx"), vmtx);
|
||||
builder.add_raw(Tag::new(b"VORG"), vorg);
|
||||
for r in font.table_directory.table_records() {
|
||||
let tag = Tag::new(&r.tag().to_be_bytes());
|
||||
if !builder.contains(tag) {
|
||||
builder.add_raw(tag, font.table_data(r.tag())?.as_bytes());
|
||||
}
|
||||
}
|
||||
Some(builder.build())
|
||||
}
|
||||
|
||||
/// The family of [`variable_ligature_caret_font`].
|
||||
pub const VARIABLE_LIGATURE_CARET_FAMILY: &str = "Varicaret Sans";
|
||||
|
||||
/// [`ligature_caret_font`] as a variable font of family [`VARIABLE_LIGATURE_CARET_FAMILY`]: one
|
||||
/// weight axis (400–700, default 400) with the named instances Regular (400) and Bold (700), and a
|
||||
/// `GDEF` ligature caret list whose one caret is a format 3 value at x = `caret` font units with a
|
||||
/// variation index into the `GDEF` item variation store that moves it by `delta` at 700. `None`
|
||||
/// when it can't be built.
|
||||
pub fn variable_ligature_caret_font(caret: i16, delta: i16) -> Option<Vec<u8>> {
|
||||
use write_fonts::tables::gdef::{CaretValue, Gdef, LigCaretList, LigGlyph};
|
||||
use write_fonts::tables::layout::{CoverageFormat1, DeviceOrVariationIndex};
|
||||
use write_fonts::tables::variations::{ItemVariationData, ItemVariationStore, RegionAxisCoordinates, VariationRegion, VariationRegionList};
|
||||
use write_fonts::types::GlyphId16;
|
||||
|
||||
let base = ligature_caret_font(None)?;
|
||||
let font = skrifa::FontRef::new(&base).ok()?;
|
||||
let ligature = GlyphId16::new(source_sans_gid(LIGATURE_CARET_GLYPH)?);
|
||||
let value = CaretValue::format_3(caret, DeviceOrVariationIndex::variation_index(0, 0));
|
||||
let carets = LigCaretList::new(CoverageFormat1::new(vec![ligature]).into(), vec![LigGlyph::new(vec![value])]);
|
||||
let mut gdef = Gdef::new(None, None, Some(carets), None);
|
||||
let region = VariationRegion::new(vec![RegionAxisCoordinates::new(F2Dot14::from_f32(0.0), F2Dot14::from_f32(1.0), F2Dot14::from_f32(1.0))]);
|
||||
// One delta set of one 16-bit delta for the one region.
|
||||
let data = ItemVariationData::new(1, 1, vec![0], delta.to_be_bytes().to_vec());
|
||||
gdef.item_var_store = Some(ItemVariationStore::new(VariationRegionList::new(1, vec![region]), vec![Some(data)])).into();
|
||||
let axis = VariationAxisRecord {
|
||||
axis_tag: Tag::new(b"wght"),
|
||||
min_value: Fixed::from_i32(400),
|
||||
default_value: Fixed::from_i32(400),
|
||||
max_value: Fixed::from_i32(700),
|
||||
flags: 0,
|
||||
axis_name_id: NameId::new(256),
|
||||
};
|
||||
let instance = |name: u16, wght: i32| InstanceRecord {
|
||||
subfamily_name_id: NameId::new(name),
|
||||
flags: 0,
|
||||
coordinates: vec![Fixed::from_i32(wght)],
|
||||
post_script_name_id: None,
|
||||
};
|
||||
let fvar = Fvar::new(AxisInstanceArrays::new(vec![axis], vec![instance(257, 400), instance(258, 700)]));
|
||||
let family = VARIABLE_LIGATURE_CARET_FAMILY;
|
||||
let name = name_table(&[
|
||||
(1, family),
|
||||
(2, "Regular"),
|
||||
(4, "Varicaret Sans Regular"),
|
||||
(6, "VaricaretSans-Regular"),
|
||||
(256, "Weight"),
|
||||
(257, "Regular"),
|
||||
(258, "Bold"),
|
||||
])?;
|
||||
let mut builder = FontBuilder::new();
|
||||
builder.add_raw(Tag::new(b"name"), name);
|
||||
builder.add_table(&gdef).ok()?.add_table(&fvar).ok()?;
|
||||
for r in font.table_directory.table_records() {
|
||||
let tag = Tag::new(&r.tag().to_be_bytes());
|
||||
if !builder.contains(tag) {
|
||||
builder.add_raw(tag, font.table_data(r.tag())?.as_bytes());
|
||||
}
|
||||
}
|
||||
Some(builder.build())
|
||||
}
|
||||
|
||||
/// [`ligature_caret_font`] with its one caret at x = `caret` font units and a `GPOS` `kern` single
|
||||
/// adjustment that places the ligature glyph `x` font units right of its pen position. `None` when
|
||||
/// it can't be built.
|
||||
pub fn placed_ligature_caret_font(caret: i16, x: i16) -> Option<Vec<u8>> {
|
||||
use write_fonts::tables::gpos::{Gpos, PositionLookup, PositionLookupList, SinglePos, ValueRecord};
|
||||
use write_fonts::tables::layout::{CoverageFormat1, Feature, FeatureList, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord};
|
||||
use write_fonts::types::GlyphId16;
|
||||
|
||||
let base = ligature_caret_font(Some(caret))?;
|
||||
let font = skrifa::FontRef::new(&base).ok()?;
|
||||
let ligature = GlyphId16::new(source_sans_gid(LIGATURE_CARET_GLYPH)?);
|
||||
let pos = SinglePos::format_1(CoverageFormat1::new(vec![ligature]).into(), ValueRecord::new().with_x_placement(x));
|
||||
let features = FeatureList::new(vec![FeatureRecord::new(Tag::new(b"kern"), Feature::new(None, vec![0]))]);
|
||||
let lookups = PositionLookupList::new(vec![PositionLookup::Single(Lookup::new(Default::default(), vec![pos]))]);
|
||||
let langsys = || Script::new(Some(LangSys::new(vec![0])), vec![]);
|
||||
let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"DFLT"), langsys()), ScriptRecord::new(Tag::new(b"latn"), langsys())]);
|
||||
let mut builder = FontBuilder::new();
|
||||
builder.add_table(&Gpos::new(scripts, features, lookups)).ok()?;
|
||||
for r in font.table_directory.table_records() {
|
||||
let tag = Tag::new(&r.tag().to_be_bytes());
|
||||
if !builder.contains(tag) {
|
||||
builder.add_raw(tag, font.table_data(r.tag())?.as_bytes());
|
||||
}
|
||||
}
|
||||
Some(builder.build())
|
||||
}
|
||||
|
||||
/// The family of [`pair_kerning_font`].
|
||||
pub const PAIR_KERNING_FAMILY: &str = "Pairtest Sans";
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ mod hang;
|
||||
mod inline;
|
||||
mod joiners;
|
||||
mod justify;
|
||||
mod ligature_carets;
|
||||
mod path_joins;
|
||||
mod ruby;
|
||||
mod scripts;
|
||||
|
||||
@@ -165,6 +165,9 @@ fn lines_of_clusters(lines: &[&[(usize, usize, f64)]], rtl: bool) -> TextLayout
|
||||
bend: None,
|
||||
unturned: Affine::IDENTITY,
|
||||
pivot: Point::new(x, baseline),
|
||||
carets: Vec::new(),
|
||||
width: advance,
|
||||
width_start: 0.0,
|
||||
});
|
||||
x += advance;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,498 @@
|
||||
//! Caret stops inside ligatures: the caret, a click, arrow keys and the selection reach each
|
||||
//! character a ligature glyph stands for, at the font's ligature carets (`GDEF`) or, without them,
|
||||
//! at the glyph's advance divided equally.
|
||||
|
||||
use kurbo::{BezPath, Point, Vec2};
|
||||
use vectorcraft_doc::{CharStyle, TextKind, TextObject};
|
||||
use vectorcraft_geom::PathData;
|
||||
|
||||
use crate::test_fonts::{
|
||||
LIGATURE_CARET_FAMILY, LIGATURE_CARET_GLYPH, VARIABLE_LIGATURE_CARET_FAMILY, VERTICAL_LIGATURE_CARET_FAMILY, lam_alef_family, lam_alef_font,
|
||||
ligature_caret_font, placed_ligature_caret_font, source_sans_gid, variable_ligature_caret_font, vertical_ligature_caret_font,
|
||||
};
|
||||
use crate::*;
|
||||
|
||||
/// A database of the bundled fonts and `font`.
|
||||
fn db_with(font: Option<Vec<u8>>) -> FontDb {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
assert_eq!(db.add_font(font.expect("the test font builds")), 1);
|
||||
db
|
||||
}
|
||||
|
||||
fn point(text: &str, family: &str) -> TextObject {
|
||||
TextObject::point(Point::ZERO, text, CharStyle { font_family: family.into(), size: 100.0, ..CharStyle::default() })
|
||||
}
|
||||
|
||||
/// The caret's x for byte `b`.
|
||||
fn caret_x(l: &TextLayout, b: usize) -> f64 {
|
||||
caret_position(l, b).0.x
|
||||
}
|
||||
|
||||
/// The x of a click at `at` (0 to 1) along glyph `g`'s advance from its left, on its baseline.
|
||||
fn along(g: &PositionedGlyph, at: f64) -> Point {
|
||||
Point::new(g.origin.x + g.advance * at, g.origin.y)
|
||||
}
|
||||
|
||||
/// A font whose caret list for a ligature holds a number of carets other than the one asked for
|
||||
/// gives none.
|
||||
#[test]
|
||||
fn a_caret_list_of_another_length_gives_no_carets() {
|
||||
let db = db_with(ligature_caret_font(Some(150)));
|
||||
let face = db.face(LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added");
|
||||
let gid = u32::from(source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph"));
|
||||
assert_eq!(face.ligature_carets(gid, 1), Some(vec![150.0]));
|
||||
assert_eq!(face.ligature_carets(gid, 2), None);
|
||||
assert_eq!(face.ligature_carets(gid, 0), None);
|
||||
}
|
||||
|
||||
/// A variable font's ligature caret with a variation index moves with the face's axis settings: by
|
||||
/// none at the default weight, by the whole delta at the weight its region peaks at.
|
||||
#[test]
|
||||
fn a_variable_ligature_caret_takes_its_delta() {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
assert_eq!(db.add_font(variable_ligature_caret_font(150, 100).expect("the test font builds")), 2, "Regular and Bold");
|
||||
let gid = u32::from(source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph"));
|
||||
let regular = db.face(VARIABLE_LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added");
|
||||
let bold = db.face(VARIABLE_LIGATURE_CARET_FAMILY, "Bold").expect("the test font is added");
|
||||
assert_eq!(regular.ligature_carets(gid, 1), Some(vec![150.0]));
|
||||
assert_eq!(bold.ligature_carets(gid, 1), Some(vec![250.0]));
|
||||
}
|
||||
|
||||
/// The font's ligature caret is where the caret, a click, arrow keys and the selection stop inside
|
||||
/// the ligature, not the middle of the glyph.
|
||||
#[test]
|
||||
fn the_font_ligature_caret_places_the_inner_stop() {
|
||||
let db = db_with(ligature_caret_font(Some(150)));
|
||||
let face = db.face(LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added");
|
||||
let gid = u32::from(source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph"));
|
||||
let l = layout(&db, &point("fi", LIGATURE_CARET_FAMILY));
|
||||
assert_eq!(l.glyphs.len(), 1, "f + i is one glyph: {:?}", l.glyphs);
|
||||
let g = &l.glyphs[0];
|
||||
assert_eq!((g.gid, g.len), (gid, 2));
|
||||
let at = 150.0 / face.advance(gid);
|
||||
assert!(at < 0.4, "the caret is well left of the middle: {at}");
|
||||
assert_eq!(g.carets.len(), 1);
|
||||
assert_eq!(g.carets[0].0, 1);
|
||||
assert!((g.carets[0].1 - at).abs() < 1e-9, "{:?} against {at}", g.carets);
|
||||
assert!((caret_x(&l, 1) - g.advance * at).abs() < 1e-6);
|
||||
// A click left or right of the caret goes to it rather than to either end.
|
||||
assert_eq!(hit_byte(&l, along(g, at * 0.4)), 0);
|
||||
assert_eq!(hit_byte(&l, along(g, at * 1.4)), 1);
|
||||
assert_eq!(hit_byte(&l, along(g, 0.9)), 2);
|
||||
// Arrow keys stop at it both ways, and the f alone is selected up to it.
|
||||
assert_eq!(caret_horizontal(&l, 0, true), 1);
|
||||
assert_eq!(caret_horizontal(&l, 1, true), 2);
|
||||
assert_eq!(caret_horizontal(&l, 2, false), 1);
|
||||
let q = selection_quads(&l, 0, 1);
|
||||
assert_eq!(q.len(), 1);
|
||||
assert!((q[0][1].x - q[0][0].x - g.advance * at).abs() < 1e-6, "{q:?}");
|
||||
}
|
||||
|
||||
/// The font's placement of a ligature (`GPOS` x placement) moves its caret with the glyph.
|
||||
#[test]
|
||||
fn a_placed_ligature_keeps_its_caret_on_the_glyph() {
|
||||
let at = |font: Option<Vec<u8>>| {
|
||||
let db = db_with(font);
|
||||
let l = layout(&db, &point("fi", LIGATURE_CARET_FAMILY));
|
||||
let g = l.glyphs.iter().find(|g| g.len == 2).expect("f + i is one glyph").clone();
|
||||
(caret_x(&l, 1) - g.origin.x, g.outline.bounding_box().x0 - g.origin.x, g.width_start, hit_byte(&l, Point::new(caret_x(&l, 1) + 1.0, 0.0)))
|
||||
};
|
||||
let (caret, ink, start, _) = at(ligature_caret_font(Some(150)));
|
||||
let (placed_caret, placed_ink, placed_start, hit) = at(placed_ligature_caret_font(150, 100));
|
||||
// 100 units at 100 pt in a 1000-unit em.
|
||||
assert!(start.abs() < 1e-9 && (placed_start - 10.0).abs() < 1e-9, "{start} {placed_start}");
|
||||
assert!((placed_ink - ink - 10.0).abs() < 1e-6, "the glyph moves right: {placed_ink} against {ink}");
|
||||
assert!((placed_caret - caret - 10.0).abs() < 1e-6, "the caret moves with it: {placed_caret} against {caret}");
|
||||
assert_eq!(hit, 1);
|
||||
}
|
||||
|
||||
/// A ligature whose font lists no carets for it divides its advance equally among its characters.
|
||||
#[test]
|
||||
fn a_ligature_without_font_carets_is_divided_equally() {
|
||||
let db = db_with(ligature_caret_font(None));
|
||||
let l = layout(&db, &point("fi", LIGATURE_CARET_FAMILY));
|
||||
assert_eq!(l.glyphs.len(), 1);
|
||||
let g = &l.glyphs[0];
|
||||
assert_eq!(g.carets, vec![(1, 0.5)]);
|
||||
assert!((caret_x(&l, 1) - g.advance * 0.5).abs() < 1e-6);
|
||||
assert_eq!(hit_byte(&l, along(g, 0.4)), 1);
|
||||
assert_eq!(hit_byte(&l, along(g, 0.2)), 0);
|
||||
// A caret value outside the glyph is not used either.
|
||||
let db = db_with(ligature_caret_font(Some(-20)));
|
||||
let l = layout(&db, &point("fi", LIGATURE_CARET_FAMILY));
|
||||
assert_eq!(l.glyphs[0].carets, vec![(1, 0.5)]);
|
||||
}
|
||||
|
||||
/// Tracking adds space after a ligature's own width: the font's caret stays where the font puts it
|
||||
/// in the glyph, and the caret, a click and the selection use that place, left to right and right
|
||||
/// to left.
|
||||
#[test]
|
||||
fn tracking_does_not_move_a_ligature_caret() {
|
||||
let db = db_with(ligature_caret_font(Some(150)));
|
||||
let face = db.face(LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added");
|
||||
let mut t = point("fi", LIGATURE_CARET_FAMILY);
|
||||
t.runs[0].style.tracking = 50.0;
|
||||
let l = layout(&db, &t);
|
||||
assert_eq!(l.glyphs.len(), 1, "f + i stays one glyph at this tracking: {:?}", l.glyphs);
|
||||
let g = &l.glyphs[0];
|
||||
let k = 100.0 / face.units_per_em();
|
||||
let width = face.advance(g.gid) * k;
|
||||
assert!((g.width - width).abs() < 1e-9, "{} against {width}", g.width);
|
||||
assert!((g.advance - width - 5.0).abs() < 1e-9, "the advance takes in 5 pt of tracking: {}", g.advance);
|
||||
let x = g.origin.x + 150.0 * k;
|
||||
assert!((caret_x(&l, 1) - x).abs() < 1e-6, "{} against {x}", caret_x(&l, 1));
|
||||
assert_eq!(hit_byte(&l, Point::new(g.origin.x + 150.0 * k * 0.45, -10.0)), 0);
|
||||
assert_eq!(hit_byte(&l, Point::new(x + 0.3, -10.0)), 1);
|
||||
let q = selection_quads(&l, 0, 1);
|
||||
assert_eq!(q.len(), 1);
|
||||
assert!((q[0][1].x - x).abs() < 1e-6, "{q:?}");
|
||||
// Right to left the tracking lies to the glyph's right, before its first character: the stop
|
||||
// between lam and alef stays in the middle of the glyph's own width.
|
||||
let db = db_with(lam_alef_font(b"rlig"));
|
||||
let mut t = point("\u{0644}\u{0627}", lam_alef_family(b"rlig"));
|
||||
t.runs[0].style.tracking = 50.0;
|
||||
let l = layout(&db, &t);
|
||||
let g = l.glyphs.iter().find(|g| g.len == 4).expect("lam + alef is one glyph");
|
||||
assert!(g.rtl && g.advance > g.width + 4.0, "{} {}", g.advance, g.width);
|
||||
let mid = g.origin.x + g.width * 0.5;
|
||||
assert!((caret_x(&l, 2) - mid).abs() < 1e-6, "{} against {mid}", caret_x(&l, 2));
|
||||
let q = selection_quads(&l, 2, 4);
|
||||
assert_eq!(q.len(), 1, "{q:?}");
|
||||
let (x0, x1) = (q[0][0].x.min(q[0][1].x), q[0][0].x.max(q[0][1].x));
|
||||
assert!((x0 - g.origin.x).abs() < 1e-6 && (x1 - mid).abs() < 1e-6, "{q:?}");
|
||||
}
|
||||
|
||||
/// Negative kerning can end a ligature's advance before its font caret: the caret still stands at
|
||||
/// the font's place, a click at the advance's end goes to the end of the ligature, and the last
|
||||
/// character's selection runs between the two.
|
||||
#[test]
|
||||
fn negative_kerning_keeps_a_ligature_caret_past_the_advance() {
|
||||
let db = db_with(ligature_caret_font(Some(150)));
|
||||
let face = db.face(LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added");
|
||||
let k = 100.0 / face.units_per_em();
|
||||
let gid = u32::from(source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph"));
|
||||
let width = face.advance(gid) * k;
|
||||
// Kerning (thousandths of an em at 100 pt, a tenth of a point each) that leaves an advance of
|
||||
// half the distance to the font caret.
|
||||
let kern = (150.0 * k * 0.5 - width) * 10.0;
|
||||
let mut t = point("fi", LIGATURE_CARET_FAMILY);
|
||||
t.runs[0].style.kerning = Some(kern);
|
||||
let l = layout(&db, &t);
|
||||
assert_eq!(l.glyphs.len(), 1, "f + i stays one glyph with this kerning: {:?}", l.glyphs);
|
||||
let g = &l.glyphs[0];
|
||||
assert!((g.width - width).abs() < 1e-9, "{} against {width}", g.width);
|
||||
assert!((g.advance - 150.0 * k * 0.5).abs() < 1e-6, "the advance ends before the caret: {}", g.advance);
|
||||
let x = g.origin.x + 150.0 * k;
|
||||
let end = g.origin.x + g.advance;
|
||||
assert!((caret_x(&l, 1) - x).abs() < 1e-6, "{} against {x}", caret_x(&l, 1));
|
||||
assert!((caret_x(&l, 2) - end).abs() < 1e-6, "{} against {end}", caret_x(&l, 2));
|
||||
assert_eq!(hit_byte(&l, Point::new(end, -10.0)), 2);
|
||||
assert_eq!(hit_byte(&l, Point::new(x + 0.3, -10.0)), 1);
|
||||
let q = selection_quads(&l, 1, 2);
|
||||
assert_eq!(q.len(), 1, "{q:?}");
|
||||
let (x0, x1) = (q[0][0].x.min(q[0][1].x), q[0][0].x.max(q[0][1].x));
|
||||
assert!((x0 - end).abs() < 1e-6 && (x1 - x).abs() < 1e-6, "{q:?}");
|
||||
// On a path, a click at the advance's end goes to the end of the ligature as well.
|
||||
let mut line = BezPath::new();
|
||||
line.move_to((0.0, 0.0));
|
||||
line.line_to((1000.0, 0.0));
|
||||
t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None };
|
||||
let l = layout(&db, &t);
|
||||
let g = l.glyphs.iter().find(|g| g.len == 2).expect("f + i is one glyph");
|
||||
let d = Vec2::new(g.angle.cos(), g.angle.sin());
|
||||
assert_eq!(hit_byte(&l, g.origin + d * g.advance), 2);
|
||||
assert_eq!(hit_byte(&l, g.origin + d * (g.width * 150.0 / face.advance(gid) + 0.3)), 1);
|
||||
}
|
||||
|
||||
/// On a path, a ligature whose negative kerning ends its advance before its font caret is followed
|
||||
/// by an i that covers the caret: a click at the caret goes to the caret, not to the i.
|
||||
#[test]
|
||||
fn a_click_at_a_ligature_caret_past_the_advance_on_a_path_reaches_it() {
|
||||
let db = db_with(ligature_caret_font(Some(150)));
|
||||
let face = db.face(LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added");
|
||||
let k = 100.0 / face.units_per_em();
|
||||
let gid = u32::from(source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph"));
|
||||
let width = face.advance(gid) * k;
|
||||
let kern = (150.0 * k * 0.5 - width) * 10.0;
|
||||
let mut t = point("fii", LIGATURE_CARET_FAMILY);
|
||||
crate::edit::style_range(&mut t.runs, 0, 2, |st| st.kerning = Some(kern));
|
||||
let mut line = BezPath::new();
|
||||
line.move_to((0.0, 0.0));
|
||||
line.line_to((1000.0, 0.0));
|
||||
t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None };
|
||||
let l = layout(&db, &t);
|
||||
let g = l.glyphs.iter().find(|g| g.len == 2).expect("f + i is one glyph");
|
||||
let i = l.glyphs.iter().find(|h| h.byte == 2).expect("the second i");
|
||||
let d = Vec2::new(g.angle.cos(), g.angle.sin());
|
||||
let caret = g.origin + d * (g.width * 150.0 / face.advance(gid));
|
||||
let mid = |h: &PositionedGlyph| h.origin + d * (h.advance * 0.5);
|
||||
assert!((caret - mid(i)).hypot() < (caret - mid(g)).hypot(), "the i's middle is nearer the caret than the ligature's");
|
||||
assert_eq!(hit_byte(&l, caret + d * 0.3), 1);
|
||||
}
|
||||
|
||||
/// Tracking of -1000 (one em to the left) leaves Source Serif 4's fi ligature, with standard
|
||||
/// ligatures turned on explicitly, an advance of zero or less: the caret, a click and the selection
|
||||
/// still reach the i at its place in the glyph's own width, across and on a path.
|
||||
#[test]
|
||||
fn a_ligature_without_advance_keeps_its_inner_stop() {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let mut t = point("fi", "Source Serif 4");
|
||||
t.runs[0].style.tracking = -1000.0;
|
||||
t.runs[0].style.features = vec!["liga".into()];
|
||||
let l = layout(&db, &t);
|
||||
let g = l.glyphs.iter().find(|g| g.len == 2).expect("f + i is one glyph");
|
||||
assert!(g.advance <= 0.0 && g.width > 0.0, "{} {}", g.advance, g.width);
|
||||
let &[(1, f)] = g.carets.as_slice() else { panic!("one inner stop: {:?}", g.carets) };
|
||||
let x = g.origin.x + g.width * f;
|
||||
let end = g.origin.x + g.advance;
|
||||
assert!((caret_x(&l, 1) - x).abs() < 1e-6, "{} against {x}", caret_x(&l, 1));
|
||||
assert!((caret_x(&l, 2) - end).abs() < 1e-6, "{} against {end}", caret_x(&l, 2));
|
||||
assert_eq!(hit_byte(&l, Point::new(x + 0.3, -10.0)), 1);
|
||||
assert_eq!(hit_byte(&l, Point::new(g.origin.x + 0.3, -10.0)), 0);
|
||||
let q = selection_quads(&l, 0, 1);
|
||||
assert_eq!(q.len(), 1, "{q:?}");
|
||||
let (x0, x1) = (q[0][0].x.min(q[0][1].x), q[0][0].x.max(q[0][1].x));
|
||||
assert!((x0 - g.origin.x).abs() < 1e-6 && (x1 - x).abs() < 1e-6, "{q:?} against {} {x}", g.origin.x);
|
||||
assert_eq!(caret_horizontal(&l, 0, true), 1);
|
||||
// On a path, a click past the inner stop goes to it, and the f alone is selected up to it.
|
||||
let mut line = BezPath::new();
|
||||
line.move_to((0.0, 0.0));
|
||||
line.line_to((1000.0, 0.0));
|
||||
t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None };
|
||||
let l = layout(&db, &t);
|
||||
let g = l.glyphs.iter().find(|g| g.len == 2).expect("f + i is one glyph");
|
||||
assert!(g.advance <= 0.0, "{}", g.advance);
|
||||
let d = Vec2::new(g.angle.cos(), g.angle.sin());
|
||||
assert_eq!(hit_byte(&l, g.origin + d * (g.width * f + 0.3)), 1);
|
||||
assert_eq!(hit_byte(&l, g.origin + d * 0.3), 0);
|
||||
let q = selection_quads(&l, 0, 1);
|
||||
assert_eq!(q.len(), 1, "{q:?}");
|
||||
assert!(((q[0][1] - q[0][0]).hypot() - g.width * f).abs() < 1e-6, "{q:?}");
|
||||
}
|
||||
|
||||
/// Bundled Source Serif 4's fi ligature has a caret stop that a click and the arrow keys reach.
|
||||
#[test]
|
||||
fn source_serif_fi_and_ffi_have_inner_stops() {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
for (s, stops) in [("fi", vec![1]), ("ffi", vec![1, 2])] {
|
||||
let l = layout(&db, &point(s, "Source Serif 4"));
|
||||
let lone: Vec<&PositionedGlyph> = l.glyphs.iter().filter(|g| g.len == s.len()).collect();
|
||||
if lone.is_empty() {
|
||||
// The font has no ligature for these letters (ffi in some versions).
|
||||
assert_ne!(s, "fi", "{:?}", l.glyphs);
|
||||
continue;
|
||||
}
|
||||
let g = lone[0];
|
||||
assert_eq!(g.carets.iter().map(|c| c.0).collect::<Vec<_>>(), stops, "{s}");
|
||||
for &(b, f) in &g.carets {
|
||||
let x = g.origin.x + g.advance * f;
|
||||
assert_eq!(hit_byte(&l, Point::new(x + 0.01, -10.0)), b, "{s} byte {b}");
|
||||
assert!((caret_x(&l, b) - x).abs() < 1e-6);
|
||||
}
|
||||
let mut b = 0;
|
||||
let mut seen = vec![];
|
||||
while b < s.len() {
|
||||
b = caret_horizontal(&l, b, true);
|
||||
seen.push(b);
|
||||
}
|
||||
assert_eq!(seen[..stops.len()], stops[..], "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A right-to-left ligature (lam + alef, two bytes each) has its stop between the two characters,
|
||||
/// never inside a character, and its first character is on its right.
|
||||
#[test]
|
||||
fn a_right_to_left_ligature_stops_between_its_characters() {
|
||||
let db = db_with(lam_alef_font(b"rlig"));
|
||||
let l = layout(&db, &point("\u{0644}\u{0627}", lam_alef_family(b"rlig")));
|
||||
let g = l.glyphs.iter().find(|g| g.len == 4).expect("lam + alef is one glyph");
|
||||
assert!(g.rtl);
|
||||
assert_eq!(g.carets, vec![(2, 0.5)]);
|
||||
// Right of the middle is the lam, left of it the alef.
|
||||
assert_eq!(hit_byte(&l, along(g, 0.9)), 0);
|
||||
assert_eq!(hit_byte(&l, along(g, 0.6)), 2);
|
||||
assert_eq!(hit_byte(&l, along(g, 0.1)), 4);
|
||||
assert!((caret_x(&l, 2) - (g.origin.x + g.advance * 0.5)).abs() < 1e-6);
|
||||
assert!(caret_x(&l, 0) > caret_x(&l, 2) && caret_x(&l, 2) > caret_x(&l, 4));
|
||||
// The lam alone is selected on the right half.
|
||||
let q = selection_quads(&l, 0, 2);
|
||||
assert_eq!(q.len(), 1, "{q:?}");
|
||||
let (x0, x1) = (q[0][0].x.min(q[0][1].x), q[0][0].x.max(q[0][1].x));
|
||||
assert!((x0 - (g.origin.x + g.advance * 0.5)).abs() < 1e-6 && (x1 - (g.origin.x + g.advance)).abs() < 1e-6, "{q:?}");
|
||||
// Arrow keys (visual stops) take the inner stop: right to left, left goes forward.
|
||||
assert_eq!(caret_horizontal_cluster(&l, "\u{0644}\u{0627}", 0, false), 2);
|
||||
assert_eq!(caret_horizontal_cluster(&l, "\u{0644}\u{0627}", 2, false), 4);
|
||||
}
|
||||
|
||||
/// Right to left, manual kerning moves a ligature right and puts its space on the left: the inner
|
||||
/// stop moves with the glyph, and the click, the caret and the selection of each character follow.
|
||||
#[test]
|
||||
fn manual_kerning_moves_a_right_to_left_ligature_stop_with_the_glyph() {
|
||||
let db = db_with(lam_alef_font(b"rlig"));
|
||||
let at = |kern: f64| {
|
||||
let mut t = point("\u{0644}\u{0627}", lam_alef_family(b"rlig"));
|
||||
t.runs[0].style.kerning = Some(kern);
|
||||
let l = layout(&db, &t);
|
||||
let g = l.glyphs.iter().find(|g| g.len == 4).expect("lam + alef is one glyph").clone();
|
||||
assert!(g.rtl);
|
||||
(l, g)
|
||||
};
|
||||
let (plain, p) = at(0.0);
|
||||
let (kerned, k) = at(100.0);
|
||||
// 100/1000 em at 100 pt.
|
||||
assert!((k.width_start - 10.0).abs() < 1e-9 && (k.advance - p.advance - 10.0).abs() < 1e-9, "{} {} {}", k.width_start, k.advance, p.advance);
|
||||
let ink = |g: &PositionedGlyph| g.outline.bounding_box().x0;
|
||||
assert!((ink(&k) - k.origin.x - (ink(&p) - p.origin.x) - 10.0).abs() < 1e-6, "the glyph moves right");
|
||||
let mid = k.origin.x + 10.0 + k.width * 0.5;
|
||||
assert!((caret_x(&kerned, 2) - ink(&k) - (caret_x(&plain, 2) - ink(&p))).abs() < 1e-6, "the stop moves with the glyph");
|
||||
assert!((caret_x(&kerned, 2) - mid).abs() < 1e-6, "{} against {mid}", caret_x(&kerned, 2));
|
||||
assert_eq!(hit_byte(&kerned, Point::new(mid + 1.0, k.origin.y)), 2);
|
||||
assert_eq!(hit_byte(&kerned, Point::new(mid + 4.0, k.origin.y)), 2);
|
||||
assert_eq!(hit_byte(&kerned, Point::new(k.origin.x + k.advance - 1.0, k.origin.y)), 0);
|
||||
let q = selection_quads(&kerned, 0, 2);
|
||||
assert_eq!(q.len(), 1, "{q:?}");
|
||||
let x0 = q[0][0].x.min(q[0][1].x);
|
||||
assert!((x0 - mid).abs() < 1e-6, "the lam alone is selected right of the stop: {q:?}");
|
||||
}
|
||||
|
||||
/// A letter with a combining mark is one character: a glyph for it has no inner stop.
|
||||
#[test]
|
||||
fn a_letter_and_its_mark_has_no_inner_stop() {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let l = layout(&db, &point("e\u{0301}", "Source Sans 3"));
|
||||
assert!(l.glyphs.iter().all(|g| g.carets.is_empty()), "{:?}", l.glyphs);
|
||||
}
|
||||
|
||||
/// On a path, a click on either half of the ligature goes to its nearer stop, and the selection of
|
||||
/// one character covers its part of the glyph.
|
||||
#[test]
|
||||
fn a_ligature_on_a_path_has_its_inner_stop() {
|
||||
let db = db_with(ligature_caret_font(None));
|
||||
let mut line = BezPath::new();
|
||||
line.move_to((0.0, 0.0));
|
||||
line.line_to((1000.0, 0.0));
|
||||
let mut t = point("fi", LIGATURE_CARET_FAMILY);
|
||||
t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None };
|
||||
let l = layout(&db, &t);
|
||||
assert!(l.on_path);
|
||||
let g = l.glyphs.iter().find(|g| g.len == 2).expect("f + i is one glyph");
|
||||
assert_eq!(g.carets, vec![(1, 0.5)]);
|
||||
let at = |f: f64| g.origin + Vec2::new(g.angle.cos(), g.angle.sin()) * (g.advance * f);
|
||||
assert_eq!(hit_byte(&l, at(0.1)), 0);
|
||||
assert_eq!(hit_byte(&l, at(0.4)), 1);
|
||||
assert_eq!(hit_byte(&l, at(0.95)), 2);
|
||||
let q = selection_quads(&l, 1, 2);
|
||||
assert_eq!(q.len(), 1);
|
||||
assert!(((q[0][1] - q[0][0]).hypot() - g.advance * 0.5).abs() < 1e-6, "{q:?}");
|
||||
}
|
||||
|
||||
/// In vertical type, the inner stop of a turned Latin ligature lies down the column between its
|
||||
/// ends.
|
||||
#[test]
|
||||
fn a_ligature_in_vertical_type_has_its_inner_stop() {
|
||||
let db = db_with(ligature_caret_font(None));
|
||||
let mut t = point("fi", LIGATURE_CARET_FAMILY);
|
||||
t.vertical = true;
|
||||
let l = layout(&db, &t);
|
||||
let Some(g) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) };
|
||||
assert_eq!(g.carets, vec![(1, 0.5)]);
|
||||
let y = |b| caret_position(&l, b).0.y;
|
||||
assert!(y(0) < y(1) && y(1) < y(2), "{} {} {}", y(0), y(1), y(2));
|
||||
let mid = caret_position(&l, 1);
|
||||
assert_eq!(hit_byte(&l, mid.0.midpoint(mid.1) + Vec2::new(0.0, 0.01)), 1);
|
||||
}
|
||||
|
||||
/// In vertical type, tracking adds space after a turned ligature's own width as it does across:
|
||||
/// the font's caret stays the same distance down the column from the ligature's start, and the
|
||||
/// last character's selection runs from it to the end of the advance.
|
||||
#[test]
|
||||
fn tracking_does_not_move_a_ligature_caret_in_vertical_type() {
|
||||
let db = db_with(ligature_caret_font(Some(150)));
|
||||
let face = db.face(LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added");
|
||||
let k = 100.0 / face.units_per_em();
|
||||
let at = |tracking: f64| {
|
||||
let mut t = point("fi", LIGATURE_CARET_FAMILY);
|
||||
t.vertical = true;
|
||||
t.runs[0].style.tracking = tracking;
|
||||
let l = layout(&db, &t);
|
||||
let Some(g) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) };
|
||||
let width = face.advance(g.gid) * k;
|
||||
assert!((g.width - width).abs() < 1e-9, "{} against {width}", g.width);
|
||||
let y = |b| caret_position(&l, b).0.y;
|
||||
let q = selection_quads(&l, 1, 2);
|
||||
assert_eq!(q.len(), 1, "{q:?}");
|
||||
let ys = q[0].map(|p| p.y);
|
||||
let (y0, y1) = (ys.iter().copied().fold(f64::INFINITY, f64::min), ys.iter().copied().fold(f64::NEG_INFINITY, f64::max));
|
||||
assert!((y0 - y(1)).abs() < 1e-6 && (y1 - y(2)).abs() < 1e-6, "{q:?} {} {}", y(1), y(2));
|
||||
(y(1) - y(0), y(2) - y(0), g.advance)
|
||||
};
|
||||
let (plain, plain_end, _) = at(0.0);
|
||||
let (tracked, tracked_end, advance) = at(50.0);
|
||||
assert!((plain - 150.0 * k).abs() < 1e-6, "{plain} against {}", 150.0 * k);
|
||||
assert!((tracked - plain).abs() < 1e-6, "{tracked} against {plain}");
|
||||
assert!((tracked_end - advance).abs() < 1e-6 && (tracked_end - plain_end - 5.0).abs() < 1e-6, "{tracked_end} {plain_end} {advance}");
|
||||
}
|
||||
|
||||
/// A ligature standing upright in vertical type (Standard Vertical Roman Alignment) takes its font
|
||||
/// caret as a y coordinate: the stop lies that far below the top of its cell, which runs from its
|
||||
/// vertical origin (0.88 em) one em down the column. A caret above the cell is not used.
|
||||
#[test]
|
||||
fn an_upright_ligature_takes_its_caret_down_its_cell() {
|
||||
let at = |caret: i16| {
|
||||
let db = db_with(vertical_ligature_caret_font(caret));
|
||||
let mut t = point("fi", VERTICAL_LIGATURE_CARET_FAMILY);
|
||||
t.vertical = true;
|
||||
t.runs[0].style.standard_vertical_roman = true;
|
||||
let l = layout(&db, &t);
|
||||
let Some(g) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) };
|
||||
let face = db.face(VERTICAL_LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added");
|
||||
let cell = 1000.0 * 100.0 / face.units_per_em();
|
||||
assert!((g.width - cell).abs() < 1e-9, "the glyph stands upright, one em down the column: {} against {cell}", g.width);
|
||||
let &[(1, f)] = g.carets.as_slice() else { panic!("one inner stop: {:?}", g.carets) };
|
||||
let y = |b| caret_position(&l, b).0.y;
|
||||
assert!(((y(1) - y(0)) - g.width * f).abs() < 1e-6, "{} {} against {f}", y(0), y(1));
|
||||
f
|
||||
};
|
||||
// 0.88 em at the top: y = 280 is 600 units down, y = -50 is 930 units down.
|
||||
assert!((at(280) - 0.6).abs() < 1e-9, "{}", at(280));
|
||||
assert!((at(-50) - 0.93).abs() < 1e-9, "{}", at(-50));
|
||||
assert!((at(900) - 0.5).abs() < 1e-9, "{}", at(900));
|
||||
}
|
||||
|
||||
/// Tracking that makes an upright ligature's advance negative leaves it upright: it keeps its
|
||||
/// caret down its cell, and its cell starts where it does without tracking, with or without the
|
||||
/// font's vertical metrics.
|
||||
#[test]
|
||||
fn an_upright_ligature_with_a_negative_advance_keeps_its_cell() {
|
||||
let at = |font: Option<Vec<u8>>, family: &str, tracking: f64| {
|
||||
let db = db_with(font);
|
||||
let mut t = point("fi", family);
|
||||
t.vertical = true;
|
||||
t.runs[0].style.standard_vertical_roman = true;
|
||||
t.runs[0].style.tracking = tracking;
|
||||
// Ligatures turned on by name stay on at any tracking.
|
||||
t.runs[0].style.features = vec!["+liga".into()];
|
||||
let l = layout(&db, &t);
|
||||
let Some(g) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) };
|
||||
let face = db.face(family, "Regular").expect("the test font is added");
|
||||
assert!(tracking == 0.0 || g.advance <= 0.0, "the tracking makes the advance negative: {}", g.advance);
|
||||
let cell = 1000.0 * 100.0 / face.units_per_em();
|
||||
assert!((g.width - cell).abs() < 1e-9, "the glyph stands upright, one em down the column: {} against {cell}", g.width);
|
||||
let y = |b| caret_position(&l, b).0.y;
|
||||
let &[(1, f)] = g.carets.as_slice() else { panic!("one inner stop: {:?}", g.carets) };
|
||||
assert!(((y(1) - y(0)) - g.width * f).abs() < 1e-6, "{} {} against {f}", y(0), y(1));
|
||||
(f, g.outline.bounding_box().y0 - y(0))
|
||||
};
|
||||
let vertical = |tracking| at(vertical_ligature_caret_font(280), VERTICAL_LIGATURE_CARET_FAMILY, tracking);
|
||||
let (f, top) = vertical(0.0);
|
||||
assert!((f - 0.6).abs() < 1e-9, "{f}");
|
||||
let (tracked, tracked_top) = vertical(-1500.0);
|
||||
assert!((tracked - f).abs() < 1e-9, "the caret is read down the cell: {tracked} against {f}");
|
||||
assert!((tracked_top - top).abs() < 1e-6, "{tracked_top} against {top}");
|
||||
let plain = |tracking| at(ligature_caret_font(None), LIGATURE_CARET_FAMILY, tracking);
|
||||
let (f, top) = plain(0.0);
|
||||
assert!((f - 0.5).abs() < 1e-9, "{f}");
|
||||
let (tracked, tracked_top) = plain(-1500.0);
|
||||
assert!((tracked - f).abs() < 1e-9, "{tracked} against {f}");
|
||||
assert!((tracked_top - top).abs() < 1e-6, "the cell starts where it does without tracking: {tracked_top} against {top}");
|
||||
}
|
||||
@@ -95,12 +95,7 @@ impl Tool for MeasureInspectTool {
|
||||
}
|
||||
PointerKind::Drag | PointerKind::Up if self.dragging => {
|
||||
if let Some((a, _)) = self.line {
|
||||
let b = if ev.mods.shift {
|
||||
a + vectorcraft_geom::constrain_angle_from(ev.pos - a, 45.0, cx.constrain_angle)
|
||||
} else {
|
||||
crate::guides::snap_draw(cx, ev.pos, &[]).0
|
||||
};
|
||||
self.line = Some((a, b));
|
||||
self.line = Some((a, crate::xform::measure_end_point(cx, a, ev.pos, ev.mods.shift)));
|
||||
}
|
||||
self.dragging = ev.kind == PointerKind::Drag;
|
||||
}
|
||||
@@ -213,4 +208,23 @@ mod tests {
|
||||
assert_eq!(t.options(), Value::Null);
|
||||
assert_eq!(area_label(Unit::Points, 2.0), "2.00 pt²");
|
||||
}
|
||||
|
||||
/// A Shift-drag snaps its end point to the grid, then projects it onto its 45° step.
|
||||
#[test]
|
||||
fn shift_drag_snaps_its_end_point() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let mut cx = cx(&d, &s, &p);
|
||||
cx.smart_guides = false;
|
||||
cx.snap_to_grid = true;
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
let mut t = MeasureInspectTool::default();
|
||||
// (37.3, 12.1) snaps to (36, 9) on the 9 pt grid, and Shift keeps it at 0°: (36, 0).
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 37.3, 12.1).with_mods(shift));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 37.3, 12.1).with_mods(shift));
|
||||
let o = t.options();
|
||||
assert!((o["distance"].as_f64().unwrap() - 36.0).abs() < 1e-9, "on the 9 pt grid: {o}");
|
||||
assert!(o["dy"].as_f64().unwrap().abs() < 1e-9, "kept horizontal: {o}");
|
||||
}
|
||||
}
|
||||
@@ -534,6 +534,15 @@ impl Tool for SmartPenTool {
|
||||
}
|
||||
}
|
||||
|
||||
/// A dropped press does not end the path being drawn, as Escape would: the press and its
|
||||
/// marquee are forgotten, so the release does nothing.
|
||||
fn drop_press(&mut self, _cx: &ToolContext) -> Vec<Action> {
|
||||
self.press = None;
|
||||
self.marquee = None;
|
||||
self.snap.clear();
|
||||
vec![]
|
||||
}
|
||||
|
||||
fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool {
|
||||
key == ToolKey::Tab && (self.press.is_some() || self.active(cx).is_some())
|
||||
}
|
||||
|
||||
@@ -184,6 +184,16 @@ impl Tool for CropImageTool {
|
||||
}
|
||||
}
|
||||
|
||||
/// A dropped press puts the box back as it was at the press; earlier changes to it stay.
|
||||
fn drop_press(&mut self, cx: &ToolContext) -> Vec<Action> {
|
||||
if let Some(Drag::Handle(_, from) | Drag::Move(_, from)) = self.drag.take()
|
||||
&& let Some((id, _, _)) = self.current(cx)
|
||||
{
|
||||
self.rect = Some((Some(id), from));
|
||||
}
|
||||
vec![]
|
||||
}
|
||||
|
||||
fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool {
|
||||
matches!(key, ToolKey::Enter | ToolKey::Escape) && self.current(cx).is_some()
|
||||
}
|
||||
@@ -368,6 +378,27 @@ mod tests {
|
||||
assert!(t.overlays(&cx).is_empty() && !t.claims_key(&cx, ToolKey::Enter));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_press_puts_the_box_back_as_it_was_at_the_press() {
|
||||
let (d, s) = doc_with_image((50.0, 60.0));
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut t = CropImageTool::default();
|
||||
drag(&mut t, &cx, (50.0, 60.0), (80.0, 70.0));
|
||||
assert_eq!(t.options()["rect"], json!([80.0, 70.0, 170.0, 90.0]));
|
||||
// A handle pressed and dragged, then the press dropped: the box is the adjusted one.
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 250.0, 160.0));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 200.0, 130.0));
|
||||
assert!(t.drop_press(&cx).is_empty());
|
||||
assert!(!t.busy());
|
||||
assert_eq!(t.options()["rect"], json!([80.0, 70.0, 170.0, 90.0]));
|
||||
// So is a moved box.
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 110.0));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 120.0, 100.0));
|
||||
assert!(t.drop_press(&cx).is_empty());
|
||||
assert_eq!(t.options()["rect"], json!([80.0, 70.0, 170.0, 90.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crop_box_option_requires_exactly_four_finite_numeric_values() {
|
||||
let mut tool = CropImageTool::default();
|
||||
|
||||
@@ -390,6 +390,15 @@ impl Tool for DimensionTool {
|
||||
}
|
||||
vec![]
|
||||
}
|
||||
/// A dropped drag is canceled as by Escape. A dropped click picks nothing, and the points or
|
||||
/// lines earlier clicks picked stay.
|
||||
fn drop_press(&mut self, cx: &ToolContext) -> Vec<Action> {
|
||||
if self.dragging {
|
||||
return self.key(cx, ToolKey::Escape, Mods::default());
|
||||
}
|
||||
self.press = None;
|
||||
vec![]
|
||||
}
|
||||
fn deactivate(&mut self, cx: &ToolContext) -> Vec<Action> {
|
||||
self.key(cx, ToolKey::Escape, Mods::default())
|
||||
}
|
||||
@@ -465,3 +474,37 @@ impl Tool for DimensionTool {
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::testutil::*;
|
||||
use vectorcraft_doc::Selection;
|
||||
|
||||
/// A dropped click picks nothing and keeps the point an earlier click picked. A dropped drag
|
||||
/// out from a segment is canceled as by Escape.
|
||||
#[test]
|
||||
fn a_dropped_press_keeps_the_earlier_picks() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let c = cx(&d, &s, &p);
|
||||
let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y);
|
||||
let mut t = DimensionTool::default();
|
||||
t.pointer(&c, &ev(PointerKind::Down, 400.0, 400.0));
|
||||
t.pointer(&c, &ev(PointerKind::Up, 400.0, 400.0));
|
||||
assert_eq!(t.points.len(), 1);
|
||||
// The engine sends the release after the drop.
|
||||
t.pointer(&c, &ev(PointerKind::Down, 450.0, 420.0));
|
||||
assert!(t.drop_press(&c).is_empty());
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Up, 450.0, 420.0)).is_empty());
|
||||
assert_eq!(t.points.len(), 1, "the earlier pick stays and the dropped click picks nothing");
|
||||
assert!(t.pending.is_none() && t.busy());
|
||||
let mut t = DimensionTool::default();
|
||||
t.pointer(&c, &ev(PointerKind::Down, 150.0, 100.0));
|
||||
let acts = t.pointer(&c, &ev(PointerKind::Drag, 150.0, 60.0));
|
||||
assert!(matches!(acts.first(), Some(Action::Begin(_))), "{acts:?}");
|
||||
assert_eq!(t.drop_press(&c), vec![Action::Cancel]);
|
||||
assert!(!t.busy());
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Up, 150.0, 60.0)).is_empty(), "the release places nothing");
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,7 @@ use crate::bbox::move_delta;
|
||||
use crate::corners::{self, CornerDrag, over_widget};
|
||||
use crate::guides::{HandleSnap, Leave, PointSnap, Targets};
|
||||
use crate::meshedit::{MeshEdit, grid_of};
|
||||
use crate::pathtype::{self, BracketDrag, over_bracket};
|
||||
use crate::pathtype::{self, BracketDrag, near_bracket};
|
||||
use crate::rulerguide::GuideEdit;
|
||||
use crate::select::{MoveSnap, hold_point, is_area_type, is_path_type, matrix_json, release_guide_at};
|
||||
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
|
||||
@@ -227,6 +227,8 @@ pub struct DirectSelectionTool {
|
||||
/// The already selected frame anchor the press landed on without Shift: a click (no drag)
|
||||
/// selects it alone, as a drag moves every selected frame anchor with it.
|
||||
frame_click: Option<(NodeId, AnchorRef)>,
|
||||
/// Where the pointer last hovered: the type on a path bracket under it draws thicker.
|
||||
bracket_hover: Option<Point>,
|
||||
}
|
||||
|
||||
impl DirectSelectionTool {
|
||||
@@ -253,6 +255,7 @@ impl DirectSelectionTool {
|
||||
frame: BTreeMap::new(),
|
||||
frame_revision: (0, 0),
|
||||
frame_click: None,
|
||||
bracket_hover: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -643,6 +646,11 @@ fn segment_at(cx: &ToolContext, id: NodeId, p: Point) -> Option<SegmentHit> {
|
||||
}
|
||||
|
||||
impl Tool for DirectSelectionTool {
|
||||
/// The pointer hovers nothing for the tool: no bracket is highlighted.
|
||||
fn hover_ended(&mut self, _cx: &ToolContext) {
|
||||
self.bracket_hover = None;
|
||||
}
|
||||
|
||||
fn id(&self) -> &'static str {
|
||||
if self.group { "groupSelection" } else { "directSelection" }
|
||||
}
|
||||
@@ -703,6 +711,7 @@ impl Tool for DirectSelectionTool {
|
||||
}
|
||||
}
|
||||
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
|
||||
self.bracket_hover = (ev.kind == PointerKind::Move).then_some(ev.pos);
|
||||
if let Some(out) = self.guide.pointer(cx, ev) {
|
||||
return out;
|
||||
}
|
||||
@@ -727,7 +736,7 @@ impl Tool for DirectSelectionTool {
|
||||
return vec![];
|
||||
}
|
||||
if !over_path_type_anchor(cx, p)
|
||||
&& let Some(b) = BracketDrag::hit(cx, ev)
|
||||
&& let Some(b) = BracketDrag::hit_any(cx, ev)
|
||||
{
|
||||
self.state = State::Bracket(b);
|
||||
return vec![];
|
||||
@@ -915,7 +924,8 @@ impl Tool for DirectSelectionTool {
|
||||
out.extend(self.mesh.overlays(cx, &|id| cx.selection.contains(id)));
|
||||
if !self.group {
|
||||
out.extend(frame_overlays(cx, &self.frame_anchors(cx)));
|
||||
out.extend(pathtype::overlays(cx));
|
||||
let drag = if let State::Bracket(b) = &self.state { Some(b) } else { None };
|
||||
out.extend(pathtype::overlays(cx, self.bracket_hover, drag));
|
||||
}
|
||||
if matches!(self.state, State::Handle { .. } | State::MoveAnchors { .. } | State::MoveObject { .. }) {
|
||||
out.extend(self.guides.iter().cloned());
|
||||
@@ -932,7 +942,7 @@ impl Tool for DirectSelectionTool {
|
||||
if !self.group && (matches!(self.state, State::Corner(_)) || over_widget(cx, p, true)) {
|
||||
return Cursor::CornerRadius;
|
||||
}
|
||||
if !self.group && (matches!(self.state, State::Bracket(_)) || over_bracket(cx, p) && !over_path_type_anchor(cx, p)) {
|
||||
if !self.group && (matches!(self.state, State::Bracket(_)) || near_bracket(cx, p) && !over_path_type_anchor(cx, p)) {
|
||||
return Cursor::PathBracket;
|
||||
}
|
||||
let rest = if self.group { Cursor::GroupSelection } else { Cursor::ArrowHollow };
|
||||
|
||||
@@ -105,6 +105,8 @@ pub struct WidthTool {
|
||||
drag: Option<Drag>,
|
||||
/// Selected width points: the stroke's owner and their positions t.
|
||||
selected: Option<(NodeId, Vec<f64>)>,
|
||||
/// The selected width points when the button went down: a dropped press puts them back.
|
||||
before_press: Option<(NodeId, Vec<f64>)>,
|
||||
}
|
||||
|
||||
/// The object whose stroke path `id` draws with: its compound path, if it is a member of one.
|
||||
@@ -308,6 +310,7 @@ impl Tool for WidthTool {
|
||||
vec![Action::Dialog("widthPoint".into(), json!({"id": spot.owner.0, "index": w.index, "adjustAdjoining": ev.mods.shift}))]
|
||||
}
|
||||
PointerKind::Down => {
|
||||
self.before_press = self.selected.clone();
|
||||
let Some(spot) = Self::spot_at(cx, p) else {
|
||||
if !ev.mods.shift {
|
||||
self.selected = None;
|
||||
@@ -401,6 +404,13 @@ impl Tool for WidthTool {
|
||||
&& self.drag.is_none()
|
||||
&& self.selected.as_ref().is_some_and(|(id, _)| !self.selected_indices(cx, *id).is_empty())
|
||||
}
|
||||
/// A dropped press ends the drag, and the width points selected when the button went down are
|
||||
/// selected again.
|
||||
fn drop_press(&mut self, _cx: &ToolContext) -> Vec<Action> {
|
||||
self.drag = None;
|
||||
self.selected = self.before_press.take();
|
||||
vec![]
|
||||
}
|
||||
fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
|
||||
if key == ToolKey::Escape && self.drag.is_none() {
|
||||
self.selected = None;
|
||||
@@ -691,6 +701,38 @@ mod tests {
|
||||
assert!(t.selected.is_some());
|
||||
}
|
||||
|
||||
/// A dropped press keeps the width points earlier clicks selected: a press away from the
|
||||
/// path, dropped, deselects nothing, and a dropped drag of another point ends with the points
|
||||
/// selected before it, and its release commits nothing.
|
||||
#[test]
|
||||
fn a_dropped_press_keeps_the_selected_width_points() {
|
||||
let (d, id) = doc_three_points();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let c = cx(&d, &s, &p);
|
||||
let mut t = WidthTool::default();
|
||||
let (none, shift) = (Mods::default(), Mods { shift: true, ..Default::default() });
|
||||
t.pointer(&c, &ev(PointerKind::Down, 150.0, 200.0, none));
|
||||
t.pointer(&c, &ev(PointerKind::Up, 150.0, 200.0, none));
|
||||
t.pointer(&c, &ev(PointerKind::Down, 250.0, 200.0, shift));
|
||||
t.pointer(&c, &ev(PointerKind::Up, 250.0, 200.0, shift));
|
||||
assert_eq!(t.selected_indices(&c, id), vec![1, 3]);
|
||||
// The engine sends the release after the drop.
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 450.0, shift)).is_empty());
|
||||
assert!(t.drop_press(&c).is_empty());
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Up, 200.0, 450.0, shift)).is_empty());
|
||||
assert_eq!(t.selected_indices(&c, id), vec![1, 3]);
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 450.0, none)).is_empty());
|
||||
assert!(t.drop_press(&c).is_empty());
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Up, 200.0, 450.0, none)).is_empty());
|
||||
assert_eq!(t.selected_indices(&c, id), vec![1, 3]);
|
||||
assert_eq!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 200.0, none)), vec![Action::Begin("Width Point".into())]);
|
||||
t.pointer(&c, &ev(PointerKind::Drag, 220.0, 200.0, none));
|
||||
assert!(t.drop_press(&c).is_empty());
|
||||
assert!(!t.busy());
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Up, 220.0, 200.0, none)).is_empty(), "the release commits nothing");
|
||||
assert_eq!(t.selected_indices(&c, id), vec![1, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn width_points_show_on_every_subpath() {
|
||||
let (d, c, _) = doc_compound();
|
||||
|
||||
@@ -35,6 +35,9 @@ pub struct CurvatureTool {
|
||||
id: Option<NodeId>,
|
||||
/// The point being dragged, the pointer at the press, and whether the drag began.
|
||||
drag: Option<(Grab, Point, bool)>,
|
||||
/// Where the point of the path being drawn that the press grabbed was at the press, and the
|
||||
/// current point before the press.
|
||||
grabbed: Option<(Point, Option<usize>)>,
|
||||
/// Last touched point of the path being drawn (Backspace removes it).
|
||||
current: Option<usize>,
|
||||
hover: Option<Point>,
|
||||
@@ -564,7 +567,7 @@ impl Tool for CurvatureTool {
|
||||
PointerKind::Down => {
|
||||
if let Some(id) = active {
|
||||
if let Some(i) = self.hit_point(cx, p) {
|
||||
self.current = Some(i);
|
||||
let was_current = self.current.replace(i);
|
||||
if ev.mods.alt {
|
||||
self.pts[i].1 = !self.pts[i].1;
|
||||
return vec![Action::Exec("path.curvature".into(), self.params())];
|
||||
@@ -576,6 +579,7 @@ impl Tool for CurvatureTool {
|
||||
// The point dragged and the curve through it move: the rest pull.
|
||||
hold_targets(&mut self.snap, cx, id, 0, &[i]);
|
||||
self.drag = Some((Grab::Drawn(i), p, false));
|
||||
self.grabbed = self.pts.get(i).map(|pt| (pt.0, was_current));
|
||||
return vec![];
|
||||
}
|
||||
if !self.closed {
|
||||
@@ -650,6 +654,18 @@ impl Tool for CurvatureTool {
|
||||
&& self.drag.is_none()
|
||||
&& if self.active(cx).is_some() { self.pts.len() > 1 } else { current_point(cx).is_some() }
|
||||
}
|
||||
/// A dropped press does not end the path being drawn, as Escape would: a point it grabbed
|
||||
/// goes back to where it was at the press, and the current point to the one before the press.
|
||||
fn drop_press(&mut self, _cx: &ToolContext) -> Vec<Action> {
|
||||
if let (Some((Grab::Drawn(i), _, _)), Some((at, current))) = (self.drag.take(), self.grabbed.take())
|
||||
&& let Some(pt) = self.pts.get_mut(i)
|
||||
{
|
||||
pt.0 = at;
|
||||
self.current = current;
|
||||
}
|
||||
self.snap.clear();
|
||||
vec![]
|
||||
}
|
||||
fn key(&mut self, cx: &ToolContext, key: ToolKey, _m: Mods) -> Vec<Action> {
|
||||
match key {
|
||||
ToolKey::Escape | ToolKey::Enter => {
|
||||
|
||||
@@ -370,6 +370,34 @@ fn a_press_on_a_point_selects_it_and_a_drag_moves_it() {
|
||||
assert_eq!(press(&mut t, &cx, 100.0, 0.0, false).len(), 1);
|
||||
}
|
||||
|
||||
/// A dropped drag of a point of the path being drawn puts the point back where it was at the
|
||||
/// press, and the path goes on: the next click adds a point to it.
|
||||
#[test]
|
||||
fn a_dropped_drag_puts_the_point_back_and_keeps_drawing() {
|
||||
let (d, id) = doc_with(SubPath::polyline(&[pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)], false));
|
||||
let (s, p) = (selected(id, None), paint());
|
||||
let cx = quiet(&d, &s, &p);
|
||||
let mut t = CurvatureTool {
|
||||
pts: vec![(pt(100.0, 100.0), false), (pt(200.0, 100.0), false), (pt(300.0, 100.0), false)],
|
||||
id: Some(id),
|
||||
current: Some(2),
|
||||
..Default::default()
|
||||
};
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.0, 100.0));
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 220.0, 160.0));
|
||||
assert_eq!(a[0], Action::Begin("Curvature".into()));
|
||||
assert_eq!(t.pts[1].0, pt(220.0, 160.0));
|
||||
assert!(t.drop_press(&cx).is_empty(), "the engine has undone the preview");
|
||||
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 0.0, 0.0)), vec![]);
|
||||
assert_eq!(t.pts[1].0, pt(200.0, 100.0), "the point is back");
|
||||
assert_eq!(t.current, Some(2), "the current point is the one before the press");
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 400.0, 200.0));
|
||||
assert!(
|
||||
matches!(&a[0], Action::Exec(_, v) if v["id"] == id.0 && v["points"][1]["y"] == 100.0 && v["points"].as_array().unwrap().len() == 4),
|
||||
"{a:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// #2120: the dragged end of a slanted straight path keeps to its extension (Smart Guides).
|
||||
#[test]
|
||||
fn a_dragged_end_of_a_straight_path_keeps_to_its_extension() {
|
||||
|
||||
@@ -124,6 +124,12 @@ pub trait Tool: Send {
|
||||
fn key(&mut self, _cx: &ToolContext, _key: ToolKey, _mods: Mods) -> Vec<Action> {
|
||||
vec![]
|
||||
}
|
||||
/// The press in progress is dropped (a long touch, a canceled touch, a second finger): the
|
||||
/// engine has undone its interaction and sends a release after this. By default the tool takes
|
||||
/// Escape, as during a drag.
|
||||
fn drop_press(&mut self, cx: &ToolContext) -> Vec<Action> {
|
||||
self.key(cx, ToolKey::Escape, Mods::default())
|
||||
}
|
||||
fn overlays(&self, _cx: &ToolContext) -> Vec<Overlay> {
|
||||
vec![]
|
||||
}
|
||||
|
||||
@@ -48,6 +48,9 @@ pub struct BlendTool {
|
||||
first: Option<Pick>,
|
||||
/// A blend was just made: the next click adds to it (the selected blend).
|
||||
chained: bool,
|
||||
/// `first` and `chained` when the button went down: a dropped press puts them back, unless
|
||||
/// the press picked an object or made a blend.
|
||||
before_press: Option<(Option<Pick>, bool)>,
|
||||
}
|
||||
|
||||
/// The anchor of the first subpath of path or compound path `id` (its first member's) nearest
|
||||
@@ -98,25 +101,32 @@ impl Tool for BlendTool {
|
||||
match ev.kind {
|
||||
PointerKind::DoubleClick => options(self),
|
||||
PointerKind::Down if ev.mods.alt => options(self),
|
||||
PointerKind::Down => match (self.first(cx), pick(cx, ev.pos)) {
|
||||
(_, None) => {
|
||||
(self.first, self.chained) = (None, false);
|
||||
vec![]
|
||||
}
|
||||
(None, Some((top, start))) => {
|
||||
self.first = Some((top, start));
|
||||
vec![Action::Exec("select.set".into(), json!({"ids": [top.0]}))]
|
||||
}
|
||||
(Some((a, sa)), Some((b, sb))) if a != b && cx.doc.node(a).is_some() => {
|
||||
(self.first, self.chained) = (None, true);
|
||||
let mut p = json!({"ids": [a.0, b.0]});
|
||||
if sa.is_some() || sb.is_some() {
|
||||
p["starts"] = json!([sa, sb]);
|
||||
PointerKind::Down => {
|
||||
self.before_press = Some((self.first, self.chained));
|
||||
match (self.first(cx), pick(cx, ev.pos)) {
|
||||
(_, None) => {
|
||||
(self.first, self.chained) = (None, false);
|
||||
vec![]
|
||||
}
|
||||
vec![Action::Exec("object.blend.make".into(), p)]
|
||||
(None, Some((top, start))) => {
|
||||
(self.first, self.before_press) = (Some((top, start)), None);
|
||||
vec![Action::Exec("select.set".into(), json!({"ids": [top.0]}))]
|
||||
}
|
||||
(Some((a, sa)), Some((b, sb))) if a != b && cx.doc.node(a).is_some() => {
|
||||
(self.first, self.chained, self.before_press) = (None, true, None);
|
||||
let mut p = json!({"ids": [a.0, b.0]});
|
||||
if sa.is_some() || sb.is_some() {
|
||||
p["starts"] = json!([sa, sb]);
|
||||
}
|
||||
vec![Action::Exec("object.blend.make".into(), p)]
|
||||
}
|
||||
(Some(_), Some(_)) => vec![],
|
||||
}
|
||||
(Some(_), Some(_)) => vec![],
|
||||
},
|
||||
}
|
||||
PointerKind::Up => {
|
||||
self.before_press = None;
|
||||
vec![]
|
||||
}
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
@@ -151,6 +161,15 @@ impl Tool for BlendTool {
|
||||
}
|
||||
vec![]
|
||||
}
|
||||
/// A dropped press puts back the object picked first and the blend being added to as they
|
||||
/// were when the button went down, so the picks of earlier clicks stay. An object the press
|
||||
/// picked stays picked and selected, and a blend the press made stays made.
|
||||
fn drop_press(&mut self, _cx: &ToolContext) -> Vec<Action> {
|
||||
if let Some((first, chained)) = self.before_press.take() {
|
||||
(self.first, self.chained) = (first, chained);
|
||||
}
|
||||
vec![]
|
||||
}
|
||||
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
|
||||
(self.first, self.chained) = (None, false);
|
||||
vec![]
|
||||
@@ -354,7 +373,7 @@ mod tests {
|
||||
let mut s = Selection::default();
|
||||
s.set([g]);
|
||||
let c = cx(&d, &s, &p);
|
||||
let mut t = BlendTool { first: None, chained: true };
|
||||
let mut t = BlendTool { first: None, chained: true, ..Default::default() };
|
||||
assert!(t.first(&c).is_some());
|
||||
assert!(t.chosen_again(&c).is_empty());
|
||||
assert!(t.first(&c).is_none(), "choosing the tool again ends adding to the blend just made");
|
||||
@@ -385,7 +404,7 @@ mod tests {
|
||||
// After a blend is made, a click while the selected blend is gone picks the object it hits.
|
||||
let mut s = Selection::default();
|
||||
s.set([NodeId(9999)]);
|
||||
let mut t = BlendTool { first: None, chained: true };
|
||||
let mut t = BlendTool { first: None, chained: true, ..Default::default() };
|
||||
let acts = t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 320.0, 120.0));
|
||||
assert_eq!(acts, vec![Action::Exec("select.set".into(), json!({"ids": [b.0]}))]);
|
||||
}
|
||||
@@ -432,7 +451,7 @@ mod tests {
|
||||
d.insert(Some(l), 1, blend).unwrap();
|
||||
let mut s = Selection::default();
|
||||
let p = paint();
|
||||
let mut t = BlendTool { first: None, chained: true };
|
||||
let mut t = BlendTool { first: None, chained: true, ..Default::default() };
|
||||
s.set([g]);
|
||||
let c = cx(&d, &s, &p);
|
||||
let acts = t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0));
|
||||
@@ -477,7 +496,7 @@ mod tests {
|
||||
let mut s = Selection::default();
|
||||
s.set([g]);
|
||||
let c = cx(&d, &s, &p);
|
||||
let mut t = BlendTool { first: None, chained: true };
|
||||
let mut t = BlendTool { first: None, chained: true, ..Default::default() };
|
||||
assert!(t.first(&c).is_some());
|
||||
assert!(t.key(&c, crate::ToolKey::Escape, Mods::default()).is_empty());
|
||||
assert!(t.first(&c).is_none(), "Escape ends adding to the blend just made");
|
||||
@@ -485,6 +504,51 @@ mod tests {
|
||||
assert!(esc(&mut BlendTool::default()).is_empty(), "nothing to drop");
|
||||
}
|
||||
|
||||
/// A dropped press (a long touch, a canceled touch) keeps the pick an earlier click made and
|
||||
/// keeps adding to the blend just made: the next click blends with them. A dropped press
|
||||
/// that picked an object keeps that pick, as the object stays selected.
|
||||
#[test]
|
||||
fn a_dropped_press_keeps_the_blend_tools_first_pick() {
|
||||
let (mut d, a) = doc_with_rect();
|
||||
let l = d.layers[0].id;
|
||||
let (b, g) = (d.alloc_id(), d.alloc_id());
|
||||
let r = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(300.0, 100.0, 350.0, 150.0));
|
||||
d.insert(Some(l), 1, vectorcraft_doc::Node::path(b, r, vectorcraft_doc::Appearance::default_art())).unwrap();
|
||||
let (k1, k2) = (d.alloc_id(), d.alloc_id());
|
||||
let key = |id: NodeId, x: f64| {
|
||||
let r = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x, 300.0, x + 20.0, 320.0));
|
||||
std::sync::Arc::new(vectorcraft_doc::Node::path(id, r, vectorcraft_doc::Appearance::default_art()))
|
||||
};
|
||||
let blend = vectorcraft_doc::Node::new(g, NodeKind::Blend { children: vec![key(k1, 0.0), key(k2, 100.0)], spec: Default::default() });
|
||||
d.insert(Some(l), 2, blend).unwrap();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let c = cx(&d, &s, &p);
|
||||
let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y);
|
||||
// The engine sends the release after the drop.
|
||||
let dropped = |t: &mut BlendTool, c: &ToolContext, x: f64, y: f64| {
|
||||
t.pointer(c, &ev(PointerKind::Down, x, y));
|
||||
assert!(t.drop_press(c).is_empty());
|
||||
assert!(t.pointer(c, &ev(PointerKind::Up, x, y)).is_empty());
|
||||
};
|
||||
let mut t = BlendTool::default();
|
||||
assert_eq!(t.pointer(&c, &ev(PointerKind::Down, 150.0, 150.0)), vec![Action::Exec("select.set".into(), json!({"ids": [a.0]}))]);
|
||||
assert!(t.drop_press(&c).is_empty());
|
||||
t.pointer(&c, &ev(PointerKind::Up, 150.0, 150.0));
|
||||
assert_eq!(t.first(&c), Some((a, None)), "a dropped first press keeps the object it picked and selected");
|
||||
// A second press on a, and a press on empty canvas, each dropped.
|
||||
dropped(&mut t, &c, 151.0, 151.0);
|
||||
dropped(&mut t, &c, 450.0, 450.0);
|
||||
assert_eq!(t.first(&c), Some((a, None)), "the pick stays");
|
||||
assert_eq!(t.pointer(&c, &ev(PointerKind::Down, 320.0, 120.0)), vec![Action::Exec("object.blend.make".into(), json!({"ids": [a.0, b.0]}))]);
|
||||
// After a blend is made, a dropped press on empty canvas keeps adding to it.
|
||||
let mut s = Selection::default();
|
||||
s.set([g]);
|
||||
let c = cx(&d, &s, &p);
|
||||
let mut t = BlendTool { first: None, chained: true, ..Default::default() };
|
||||
dropped(&mut t, &c, 450.0, 450.0);
|
||||
assert_eq!(t.first(&c), Some((g, None)), "the blend just made is still added to");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_tool_click_path_creates_mesh() {
|
||||
let (d, a) = doc_with_rect();
|
||||
|
||||
@@ -11,10 +11,21 @@
|
||||
//! previewed while dragging and kept as one undo step on release. Shift turns in steps of 15°, and
|
||||
//! Escape cancels the drag.
|
||||
//!
|
||||
//! Behavior: <https://helpx.adobe.com/illustrator/using/objects-on-path.html>.
|
||||
//! The Space widget: with one Objects on Path group of two or more objects selected, the same
|
||||
//! tools show a square handle beyond the group's last object, ahead along the path. Dragging it
|
||||
//! along the path sets the distance between the objects' attachment points
|
||||
//! (`object.objectsOnPath.options` with `spacing` and `start`): the first object stays where it is
|
||||
//! and the others move toward or away from it. With Alt (Option on macOS) the objects spread from
|
||||
//! both ends toward or away from the center of an open path, or of the first anchor of a closed
|
||||
//! one. The distance shows next to the pointer in the document's units, the drag is previewed and
|
||||
//! kept as one undo step on release, and Escape cancels it.
|
||||
//!
|
||||
//! Behavior: <https://helpx.adobe.com/illustrator/using/objects-on-path.html>,
|
||||
//! <https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rearrange-and-edit-objects-on-a-path.html>.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::objects_on_path::{CENTER, attachable_path, is_objects_on_path, stops};
|
||||
use vectorcraft_doc::blend::Spine;
|
||||
use vectorcraft_doc::objects_on_path::{CENTER, ObjectsOnPath, attachable_path, is_objects_on_path, layout, nth_length, path_length, stop};
|
||||
use vectorcraft_doc::{Document, NodeId, Selection};
|
||||
use vectorcraft_geom::{BezPath, Point, Vec2};
|
||||
|
||||
@@ -33,6 +44,35 @@ const ROTATE_ALL_HIT_PX: f64 = 6.0;
|
||||
/// The step (degrees) a Shift-drag of the Rotate All widget turns by.
|
||||
const ROTATE_ALL_STEP: f64 = 15.0;
|
||||
|
||||
/// The Space widget's center sits this far (screen px) beyond the last object, ahead along the path.
|
||||
const SPACE_OFFSET_PX: f64 = 16.0;
|
||||
/// Half the side of the Space widget's square (screen px), as the canvas draws it.
|
||||
pub const SPACE_HALF_PX: f32 = 3.5;
|
||||
/// How near (screen px) the pointer must be to hit the Space widget.
|
||||
const SPACE_HIT_PX: f64 = 6.0;
|
||||
|
||||
/// The Objects on Path group the widgets show for at `zoom` (screen px per document point), with
|
||||
/// its record, its children and its path: only when the selection is that one editable group, on
|
||||
/// a path with length, and no anchors are Direct-Selected.
|
||||
fn one_group<'a>(
|
||||
doc: &'a Document,
|
||||
selection: &Selection,
|
||||
zoom: f64,
|
||||
) -> Option<(NodeId, &'a ObjectsOnPath, &'a [std::sync::Arc<vectorcraft_doc::Node>], &'a vectorcraft_geom::PathData)> {
|
||||
if !selection.anchors.is_empty() || !zoom.is_finite() || zoom <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let [group] = selection.objects.as_slice() else { return None };
|
||||
if !doc.editable()(*group) {
|
||||
return None;
|
||||
}
|
||||
let n = doc.node(*group)?;
|
||||
let rec = n.extras().objects_on_path.as_deref()?;
|
||||
let children = n.children()?;
|
||||
let path = attachable_path(children.iter().find(|c| c.id == rec.path)?)?;
|
||||
Some((*group, rec, children.as_slice(), path))
|
||||
}
|
||||
|
||||
/// The Rotate All widget of a selected Objects on Path group.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct RotateAllWidget {
|
||||
@@ -50,20 +90,9 @@ impl RotateAllWidget {
|
||||
/// selection is one editable Objects on Path group with at least one object on a path with
|
||||
/// length, and no anchors are Direct-Selected.
|
||||
pub fn of(doc: &Document, selection: &Selection, zoom: f64) -> Option<Self> {
|
||||
if !selection.anchors.is_empty() || !zoom.is_finite() || zoom <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let [group] = selection.objects.as_slice() else { return None };
|
||||
if !doc.editable()(*group) {
|
||||
return None;
|
||||
}
|
||||
let n = doc.node(*group)?;
|
||||
let rec = n.extras().objects_on_path.as_deref()?;
|
||||
let children = n.children()?;
|
||||
let path = attachable_path(children.iter().find(|c| c.id == rec.path)?)?;
|
||||
let (group, rec, children, path) = one_group(doc, selection, zoom)?;
|
||||
let first = rec.members.first()?;
|
||||
// The first object attaches at the path's start, whatever the number of objects.
|
||||
let (pivot, _) = *stops(path, 1)?.first()?;
|
||||
let (pivot, _) = stop(path, rec.members.len(), rec.spacing, rec.start, 0)?;
|
||||
let art = children.iter().find(|c| c.id == first.id)?;
|
||||
let b = art.geometric_bounds_with(&doc.symbol_boxes())?;
|
||||
// The object's top is the -y direction of the frame it is drawn in (the document's y axis
|
||||
@@ -80,7 +109,7 @@ impl RotateAllWidget {
|
||||
let reach = corners.iter().map(|c| (*c - pivot).dot(up)).fold(0.0, f64::max);
|
||||
let at = pivot + up * (reach + ROTATE_ALL_OFFSET_PX / zoom);
|
||||
let finite = at.x.is_finite() && at.y.is_finite() && pivot.x.is_finite() && pivot.y.is_finite();
|
||||
finite.then_some(Self { group: *group, pivot, at, rotate: rec.rotate })
|
||||
finite.then_some(Self { group, pivot, at, rotate: rec.rotate })
|
||||
}
|
||||
|
||||
/// The widget of `cx` when `p` is within reach of it.
|
||||
@@ -166,6 +195,205 @@ impl RotateAllDrag {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Space widget of a selected Objects on Path group.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct SpaceWidget {
|
||||
pub group: NodeId,
|
||||
/// The last object's attachment point, in the document.
|
||||
pub last: Point,
|
||||
/// The distance along the path to the last object's attachment point (points).
|
||||
pub last_length: f64,
|
||||
/// The widget's center in the document.
|
||||
pub at: Point,
|
||||
/// The path's direction at the last object's attachment point: a unit vector in the
|
||||
/// document's axes, in which the widget sits beyond the object.
|
||||
pub dir: Vec2,
|
||||
/// The length of the path (points).
|
||||
pub len: f64,
|
||||
/// Is the path closed?
|
||||
pub closed: bool,
|
||||
/// The number of objects on the path: 2 or more.
|
||||
pub count: usize,
|
||||
/// Where the first object attaches along the path (points from its first anchor), as drawn.
|
||||
pub start: f64,
|
||||
/// The distance along the path between neighboring objects' attachment points (points), as drawn.
|
||||
pub gap: f64,
|
||||
/// The group's Space value (`None`: Auto) and start, as saved: more than is drawn when the path
|
||||
/// is too short for them.
|
||||
pub saved: (Option<f64>, f64),
|
||||
}
|
||||
|
||||
impl SpaceWidget {
|
||||
/// The widget of the selection at `zoom` (screen px per document point): only when the
|
||||
/// selection is one editable Objects on Path group with two or more objects on a path with
|
||||
/// length, and no anchors are Direct-Selected. It sits beyond the last object's bounds, ahead
|
||||
/// along the path's direction there.
|
||||
pub fn of(doc: &Document, selection: &Selection, zoom: f64) -> Option<Self> {
|
||||
let (group, rec, children, path) = one_group(doc, selection, zoom)?;
|
||||
let count = rec.members.len();
|
||||
if count < 2 {
|
||||
return None;
|
||||
}
|
||||
let (len, closed) = path_length(path)?;
|
||||
let (start, gap) = layout(len, closed, count, rec.spacing, rec.start);
|
||||
let (last, angle) = stop(path, count, rec.spacing, rec.start, count - 1)?;
|
||||
let dir = Vec2::new(angle.cos(), angle.sin());
|
||||
let m = rec.members.last()?;
|
||||
let b = children.iter().find(|c| c.id == m.id)?.geometric_bounds_with(&doc.symbol_boxes())?;
|
||||
let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)];
|
||||
let reach = corners.iter().map(|c| (*c - last).dot(dir)).fold(0.0, f64::max);
|
||||
let at = last + dir * (reach + SPACE_OFFSET_PX / zoom);
|
||||
let finite = at.x.is_finite() && at.y.is_finite() && last.x.is_finite() && last.y.is_finite();
|
||||
let last_length = nth_length(len, closed, start, gap, count - 1);
|
||||
finite.then_some(Self { group, last, last_length, at, dir, len, closed, count, start, gap, saved: (rec.spacing, rec.start) })
|
||||
}
|
||||
|
||||
/// The widget of `cx` when `p` is within reach of it.
|
||||
fn at_point(cx: &ToolContext, p: Point) -> Option<Self> {
|
||||
Self::of(cx.doc, cx.selection, cx.zoom).filter(|w| w.at.distance(p) <= cx.tol(SPACE_HIT_PX))
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `p` over the Space widget?
|
||||
pub fn over_space(cx: &ToolContext, p: Point) -> bool {
|
||||
SpaceWidget::at_point(cx, p).is_some()
|
||||
}
|
||||
|
||||
/// The distance along the path of the Objects on Path group of `w` in `doc` to the point nearest
|
||||
/// `p` ([`Spine::nearest`]: past the ends of an open path, along the lines of its end segments),
|
||||
/// staying near `from` when the pointer is following the path from there. The line from the last
|
||||
/// object's attachment point through the widget counts as the path too, as far as the pointer is
|
||||
/// ahead of that object along it, so a widget beyond a corner measures from where it is. The flag
|
||||
/// says whether the point is on that line, where the distance runs on past the end of a closed path
|
||||
/// instead of round it.
|
||||
fn length_near(doc: &Document, w: &SpaceWidget, p: Point, from: Option<f64>) -> Option<(f64, bool)> {
|
||||
let n = doc.node(w.group)?;
|
||||
let rec = n.extras().objects_on_path.as_deref()?;
|
||||
let path = attachable_path(n.children()?.iter().find(|c| c.id == rec.path)?)?;
|
||||
let spine = Spine::new(path)?;
|
||||
let bias = |s: f64| from.filter(|f| f.is_finite()).map_or(0.0, |f| spine.apart(s, f) / 2.0);
|
||||
let ahead = (p - w.last).dot(w.dir);
|
||||
let line = (ahead >= 0.0).then(|| {
|
||||
let s = w.last_length + ahead;
|
||||
((p - w.last).cross(w.dir).abs() + bias(s), s)
|
||||
});
|
||||
let (s, on_line) = match (spine.nearest(p, from), line) {
|
||||
(Some(on), Some(line)) if line.0 < on.0 => (line.1, true),
|
||||
(Some(on), _) => (on.1, false),
|
||||
(None, line) => (line?.1, true),
|
||||
};
|
||||
s.is_finite().then_some((s, on_line))
|
||||
}
|
||||
|
||||
/// Dragging the Space widget: the distance the pointer moves along the path moves the last object
|
||||
/// along it as far, and the objects between follow evenly. With Alt the first object moves the
|
||||
/// other way as far, so the objects spread from both ends.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SpaceDrag {
|
||||
widget: SpaceWidget,
|
||||
start: Point,
|
||||
began: bool,
|
||||
/// The distance along the path to the point nearest the pointer at the last drag (points).
|
||||
last: f64,
|
||||
/// The distance the pointer has moved along the path since the press (points).
|
||||
along: f64,
|
||||
/// The distance between neighboring objects the drag sets (points).
|
||||
gap: f64,
|
||||
at: Point,
|
||||
}
|
||||
|
||||
impl SpaceDrag {
|
||||
/// The drag has left the click: the distance is changing.
|
||||
pub fn adjusting(&self) -> bool {
|
||||
self.began
|
||||
}
|
||||
|
||||
/// Start a drag when the press `ev` is on the Space widget.
|
||||
pub fn hit(cx: &ToolContext, ev: &PointerEvent) -> Option<Self> {
|
||||
let widget = SpaceWidget::at_point(cx, ev.pos)?;
|
||||
let (last, _) = length_near(cx.doc, &widget, ev.pos, None)?;
|
||||
Some(Self { widget, start: ev.pos, began: false, last, along: 0.0, gap: widget.gap, at: ev.pos })
|
||||
}
|
||||
|
||||
/// The pointer moved to `p` from `self.at`: add the distance it moved along the path. On the
|
||||
/// line through the widget, from a point ahead of the last object, that is how far it moved
|
||||
/// along the line; otherwise it takes the shorter way round a closed path.
|
||||
fn follow(&mut self, doc: &Document, p: Point) {
|
||||
let w = &self.widget;
|
||||
let Some((t, on_line)) = length_near(doc, w, p, Some(self.last)) else { return };
|
||||
let before = (self.at - w.last).dot(w.dir);
|
||||
let step = if on_line && before >= 0.0 {
|
||||
(p - w.last).dot(w.dir) - before
|
||||
} else if w.closed {
|
||||
(t - self.last + w.len / 2.0).rem_euclid(w.len) - w.len / 2.0
|
||||
} else {
|
||||
t - self.last
|
||||
};
|
||||
if step.is_finite() {
|
||||
self.along += step;
|
||||
self.last = t;
|
||||
}
|
||||
}
|
||||
|
||||
/// The Space and start the drag sets: without `alt` the first object stays and the last one goes
|
||||
/// no further than the end of an open path; with `alt` the objects are centered on an open path,
|
||||
/// or on the first anchor of a closed one, and spread over the whole path at most. On a closed
|
||||
/// path the objects go no more than once around.
|
||||
fn spacing_at(&self, alt: bool) -> (f64, f64) {
|
||||
let w = &self.widget;
|
||||
let k = (w.count - 1) as f64;
|
||||
let along = self.along;
|
||||
let round = w.len / w.count as f64;
|
||||
if alt {
|
||||
let most = if w.closed { round } else { w.len / k };
|
||||
let gap = (w.gap + 2.0 * along / k).clamp(0.0, most);
|
||||
let span = gap * k;
|
||||
(gap, if w.closed { (-span / 2.0).rem_euclid(w.len) } else { (w.len - span) / 2.0 })
|
||||
} else {
|
||||
let most = if w.closed { round } else { (w.len - w.start) / k };
|
||||
((w.gap + along / k).clamp(0.0, most.max(0.0)), w.start)
|
||||
}
|
||||
}
|
||||
|
||||
/// The pointer moved to `p`; `alt` spreads the objects from both ends.
|
||||
pub fn drag(&mut self, cx: &ToolContext, p: Point, alt: bool) -> Vec<Action> {
|
||||
let mut out = vec![];
|
||||
if !self.began {
|
||||
if p.distance(self.start) < cx.tol(3.0) {
|
||||
return out;
|
||||
}
|
||||
self.began = true;
|
||||
out.push(Action::Begin("Objects on Path Options".into()));
|
||||
}
|
||||
self.follow(cx.doc, p);
|
||||
let (gap, start) = self.spacing_at(alt);
|
||||
self.gap = gap;
|
||||
self.at = p;
|
||||
// Where the objects stay as they are drawn, the group keeps its saved values: Auto, or a
|
||||
// Space value the path is too short for.
|
||||
let w = &self.widget;
|
||||
let (spacing, start) = if (gap - w.gap).abs() < 1e-9 && (start - w.start).abs() < 1e-9 {
|
||||
(w.saved.0.map_or_else(|| json!("auto"), |g| json!(g)), json!(w.saved.1))
|
||||
} else {
|
||||
(json!(gap), json!(start))
|
||||
};
|
||||
out.push(Action::Preview("object.objectsOnPath.options".into(), json!({ "ids": [w.group.0], "spacing": spacing, "start": start })));
|
||||
out
|
||||
}
|
||||
|
||||
pub fn finish(self) -> Vec<Action> {
|
||||
if self.began { vec![Action::Commit] } else { vec![] }
|
||||
}
|
||||
|
||||
/// The distance between the objects next to the pointer, in the document's units.
|
||||
pub fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
|
||||
if !self.began || !cx.measurement_labels {
|
||||
return vec![];
|
||||
}
|
||||
vec![Overlay::Measure { p: self.at, text: cx.len(self.gap) }]
|
||||
}
|
||||
}
|
||||
|
||||
/// The path a click at `p` attaches the selected objects to: the path object hit there, when it can
|
||||
/// take objects, is in no Objects on Path group, is not a clipping path or part of a compound path,
|
||||
/// blend, envelope, repeat or Intertwine group ([`vectorcraft_doc::objects_on_path::held`]), and
|
||||
@@ -190,6 +418,8 @@ pub struct ObjectsOnPathTool {
|
||||
press: Option<Point>,
|
||||
/// The Rotate All widget drag, while the button is down after a press on the widget.
|
||||
rotating: Option<RotateAllDrag>,
|
||||
/// The Space widget drag, while the button is down after a press on the widget.
|
||||
spacing: Option<SpaceDrag>,
|
||||
/// The reference point of each object attached next (0-8, row by row from the top left).
|
||||
pivot: u8,
|
||||
/// The angle of each object attached next, in degrees counter-clockwise from upright on the path.
|
||||
@@ -198,7 +428,7 @@ pub struct ObjectsOnPathTool {
|
||||
|
||||
impl Default for ObjectsOnPathTool {
|
||||
fn default() -> Self {
|
||||
Self { hover: None, press: None, rotating: None, pivot: CENTER, rotate: 0.0 }
|
||||
Self { hover: None, press: None, rotating: None, spacing: None, pivot: CENTER, rotate: 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,9 +446,16 @@ impl Tool for ObjectsOnPathTool {
|
||||
_ => vec![],
|
||||
};
|
||||
}
|
||||
if let Some(d) = &mut self.spacing {
|
||||
return match ev.kind {
|
||||
PointerKind::Drag => d.drag(cx, p, ev.mods.alt),
|
||||
PointerKind::Up => self.spacing.take().map(SpaceDrag::finish).unwrap_or_default(),
|
||||
_ => vec![],
|
||||
};
|
||||
}
|
||||
match ev.kind {
|
||||
PointerKind::Move => {
|
||||
self.hover = if over_rotate_all(cx, p) { None } else { target(cx, p) };
|
||||
self.hover = if over_rotate_all(cx, p) || over_space(cx, p) { None } else { target(cx, p) };
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Down => {
|
||||
@@ -227,6 +464,11 @@ impl Tool for ObjectsOnPathTool {
|
||||
self.hover = None;
|
||||
return vec![];
|
||||
}
|
||||
if let Some(d) = SpaceDrag::hit(cx, ev) {
|
||||
self.spacing = Some(d);
|
||||
self.hover = None;
|
||||
return vec![];
|
||||
}
|
||||
self.press = Some(p);
|
||||
vec![]
|
||||
}
|
||||
@@ -247,12 +489,17 @@ impl Tool for ObjectsOnPathTool {
|
||||
if let Some(d) = &self.rotating {
|
||||
o.extend(d.overlays(cx));
|
||||
}
|
||||
if let Some(d) = &self.spacing {
|
||||
o.extend(d.overlays(cx));
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
fn cursor(&self, cx: &ToolContext, p: Point, _mods: Mods) -> Cursor {
|
||||
if self.rotating.is_some() || over_rotate_all(cx, p) {
|
||||
if self.rotating.is_some() || (self.spacing.is_none() && over_rotate_all(cx, p)) {
|
||||
Cursor::Rotate
|
||||
} else if self.spacing.is_some() || over_space(cx, p) {
|
||||
Cursor::ArrowHollow
|
||||
} else if target(cx, p).is_some() {
|
||||
Cursor::ObjectsOnPath
|
||||
} else {
|
||||
@@ -261,12 +508,14 @@ impl Tool for ObjectsOnPathTool {
|
||||
}
|
||||
|
||||
/// Escape while the button is down cancels the click, so the release attaches nothing, or the
|
||||
/// Rotate All drag, so the objects go back to the Rotate they had.
|
||||
/// Rotate All or Space drag, so the objects go back to the Rotate or Space they had.
|
||||
fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
|
||||
if key == ToolKey::Escape {
|
||||
self.press = None;
|
||||
self.hover = None;
|
||||
if self.rotating.take().is_some_and(|d| d.adjusting()) {
|
||||
let rotated = self.rotating.take().is_some_and(|d| d.adjusting());
|
||||
let spaced = self.spacing.take().is_some_and(|d| d.adjusting());
|
||||
if rotated || spaced {
|
||||
return vec![Action::Cancel];
|
||||
}
|
||||
}
|
||||
@@ -296,11 +545,11 @@ impl Tool for ObjectsOnPathTool {
|
||||
}
|
||||
|
||||
fn busy(&self) -> bool {
|
||||
self.press.is_some() || self.rotating.is_some()
|
||||
self.press.is_some() || self.rotating.is_some() || self.spacing.is_some()
|
||||
}
|
||||
|
||||
fn transforming(&self) -> bool {
|
||||
self.rotating.as_ref().is_some_and(RotateAllDrag::adjusting)
|
||||
self.rotating.as_ref().is_some_and(RotateAllDrag::adjusting) || self.spacing.as_ref().is_some_and(SpaceDrag::adjusting)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -602,4 +851,228 @@ mod tests {
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Up, p.0, p.1)).is_empty(), "a click on {what} attaches nothing");
|
||||
}
|
||||
}
|
||||
|
||||
/// [`group_doc`] with the group's Space `spacing` from `start`, its objects placed again.
|
||||
fn spaced_doc(spacing: Option<f64>, start: f64) -> (Document, NodeId, Selection) {
|
||||
let (mut d, g, sel) = group_doc(0.0);
|
||||
let empty = Document::new(1.0, 1.0);
|
||||
let symbols = empty.symbol_boxes();
|
||||
let n = d.node_mut(g).unwrap();
|
||||
let rec = n.extras().objects_on_path.as_deref().cloned().unwrap();
|
||||
n.extras_mut().objects_on_path = Some(Box::new(vectorcraft_doc::objects_on_path::ObjectsOnPath { spacing, start, ..rec }));
|
||||
vectorcraft_doc::objects_on_path::place(n, &symbols);
|
||||
(d, g, sel)
|
||||
}
|
||||
|
||||
/// The Space and start a drag's last action previews, to 1/1,000,000 pt.
|
||||
fn spaced(acts: &[Action]) -> Option<(f64, f64)> {
|
||||
let round = |v: f64| (v * 1e6).round() / 1e6 + 0.0;
|
||||
match acts.last() {
|
||||
Some(Action::Preview(cmd, p)) if cmd == "object.objectsOnPath.options" => {
|
||||
Some((round(p["spacing"].as_f64()?), round(p["start"].as_f64()?)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn alt(kind: PointerKind, x: f64, y: f64) -> PointerEvent {
|
||||
PointerEvent { mods: Mods { alt: true, ..Mods::default() }, ..ev(kind, x, y) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_space_widget_sits_beyond_the_last_object_ahead_along_the_path() {
|
||||
// Auto: the second square sits on the end (400, 300) and spans 390 to 410.
|
||||
let (d, g, sel) = group_doc(0.0);
|
||||
let w = SpaceWidget::of(&d, &sel, 1.0).unwrap();
|
||||
assert_eq!((w.group, w.count, w.closed), (g, 2, false));
|
||||
assert!(near(w.last, Point::new(400.0, 300.0)) && near(w.at, Point::new(426.0, 300.0)), "{w:?}");
|
||||
assert!((w.len - 400.0).abs() < 1e-9 && w.start == 0.0 && (w.gap - 400.0).abs() < 1e-9, "{w:?}");
|
||||
assert!(near(SpaceWidget::of(&d, &sel, 2.0).unwrap().at, Point::new(418.0, 300.0)));
|
||||
// With a Space set it follows the last object, and Rotate All follows the first one.
|
||||
let (d, _, sel) = spaced_doc(Some(100.0), 50.0);
|
||||
let w = SpaceWidget::of(&d, &sel, 1.0).unwrap();
|
||||
assert!(near(w.last, Point::new(150.0, 300.0)) && near(w.at, Point::new(176.0, 300.0)), "{w:?}");
|
||||
assert!(near(RotateAllWidget::of(&d, &sel, 1.0).unwrap().pivot, Point::new(50.0, 300.0)));
|
||||
// No widget for an object in the group, or for a locked group.
|
||||
let children: Vec<NodeId> = d.node(sel.objects[0]).and_then(|n| n.children()).unwrap().iter().map(|c| c.id).collect();
|
||||
let mut one = Selection::default();
|
||||
one.set([children[1]]);
|
||||
assert!(SpaceWidget::of(&d, &one, 1.0).is_none());
|
||||
let (mut d, g, sel) = group_doc(0.0);
|
||||
if let Some(n) = d.node_mut(g) {
|
||||
n.locked = true;
|
||||
}
|
||||
assert!(SpaceWidget::of(&d, &sel, 1.0).is_none());
|
||||
}
|
||||
|
||||
/// Dragging the widget 100 pt back along the path brings the last object 100 pt nearer the
|
||||
/// first one, which stays; with Alt the first one comes as far the other way. Switching Alt
|
||||
/// during the drag works from where the drag began.
|
||||
#[test]
|
||||
fn dragging_the_space_widget_spaces_the_objects_from_the_first_one() {
|
||||
let (d, g, sel) = group_doc(0.0);
|
||||
let paint = paint();
|
||||
let c = cx(&d, &sel, &paint);
|
||||
let at = SpaceWidget::of(&d, &sel, 1.0).unwrap().at;
|
||||
let tools: [Box<dyn Tool>; 2] = [Box::new(crate::select::SelectionTool::default()), Box::new(ObjectsOnPathTool::default())];
|
||||
for mut t in tools {
|
||||
let id = t.id();
|
||||
assert_eq!(t.cursor(&c, at, Mods::default()), Cursor::ArrowHollow, "{id}");
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)).is_empty(), "{id}");
|
||||
let a = t.pointer(&c, &ev(PointerKind::Drag, at.x - 100.0, at.y + 30.0));
|
||||
assert_eq!(a.first(), Some(&Action::Begin("Objects on Path Options".into())), "{id}");
|
||||
assert!(matches!(a.last(), Some(Action::Preview(_, p)) if p["ids"] == json!([g.0])), "{a:?}");
|
||||
assert_eq!(spaced(&a), Some((300.0, 0.0)), "{id}: the first object stays");
|
||||
assert!(t.transforming() && t.cursor(&c, at, Mods::default()) == Cursor::ArrowHollow, "{id}");
|
||||
let label = c.len(300.0);
|
||||
assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if *text == label)), "{id}");
|
||||
assert_eq!(spaced(&t.pointer(&c, &alt(PointerKind::Drag, at.x - 100.0, at.y))), Some((200.0, 100.0)), "{id}: from both ends");
|
||||
assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, at.x - 100.0, at.y))), Some((300.0, 0.0)), "{id}: Alt let go");
|
||||
// No further than the end, where the objects are as drawn and the group stays Auto; and no
|
||||
// less than 0.
|
||||
let a = t.pointer(&c, &ev(PointerKind::Drag, at.x + 50.0, at.y));
|
||||
assert!(matches!(a.last(), Some(Action::Preview(_, p)) if p["spacing"] == "auto" && p["start"] == 0.0), "{id}: {a:?}");
|
||||
assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, at.x - 900.0, at.y))), Some((0.0, 0.0)), "{id}");
|
||||
assert_eq!(spaced(&t.pointer(&c, &alt(PointerKind::Drag, at.x - 900.0, at.y))), Some((0.0, 200.0)), "{id}");
|
||||
assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at.x, at.y)), vec![Action::Commit], "{id}");
|
||||
assert!(!t.busy(), "{id}");
|
||||
// A click on the widget that does not move changes nothing.
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)).is_empty());
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Up, at.x, at.y)).is_empty(), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A Space value the path is too short for stays when a drag leaves the objects where they are
|
||||
/// drawn, and a drag that moves them sets the drawn value.
|
||||
#[test]
|
||||
fn a_drag_that_leaves_the_objects_as_drawn_keeps_the_saved_space() {
|
||||
let (d, _, sel) = spaced_doc(Some(1000.0), 0.0);
|
||||
let paint = paint();
|
||||
let c = cx(&d, &sel, &paint);
|
||||
let w = SpaceWidget::of(&d, &sel, 1.0).unwrap();
|
||||
assert_eq!((w.gap, w.saved), (400.0, (Some(1000.0), 0.0)), "drawn to the end of the 400 pt path");
|
||||
let mut t = ObjectsOnPathTool::default();
|
||||
t.pointer(&c, &ev(PointerKind::Down, w.at.x, w.at.y));
|
||||
assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, w.at.x + 50.0, w.at.y))), Some((1000.0, 0.0)));
|
||||
assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, w.at.x - 50.0, w.at.y))), Some((350.0, 0.0)));
|
||||
assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, w.at.x, w.at.y))), Some((1000.0, 0.0)), "back where it began");
|
||||
}
|
||||
|
||||
/// On a closed path the objects go no more than once around, and Alt centers them on the
|
||||
/// first anchor.
|
||||
#[test]
|
||||
fn dragging_the_space_widget_on_a_closed_path_wraps_at_the_first_anchor() {
|
||||
let w = SpaceWidget {
|
||||
group: NodeId(1),
|
||||
last: Point::ZERO,
|
||||
last_length: 300.0,
|
||||
at: Point::ZERO,
|
||||
dir: Vec2::new(1.0, 0.0),
|
||||
len: 400.0,
|
||||
closed: true,
|
||||
count: 4,
|
||||
start: 0.0,
|
||||
gap: 100.0,
|
||||
saved: (None, 0.0),
|
||||
};
|
||||
let moved = |along| SpaceDrag { widget: w, start: Point::ZERO, began: true, last: 0.0, along, gap: w.gap, at: Point::ZERO };
|
||||
assert_eq!(moved(30.0).spacing_at(false), (100.0, 0.0), "a quarter of the way round at most");
|
||||
assert_eq!(moved(-60.0).spacing_at(false), (80.0, 0.0));
|
||||
assert_eq!(moved(-60.0).spacing_at(true), (60.0, 310.0), "the span of 180 centered on the first anchor");
|
||||
}
|
||||
|
||||
/// An Objects on Path group of two 20 × 20 squares on an L: 400 pt to the right from (0, 300),
|
||||
/// then 300 pt up, with Space `spacing`; and a selection of the group.
|
||||
fn corner_doc(spacing: Option<f64>) -> (Document, Selection) {
|
||||
let points = [Point::new(0.0, 300.0), Point::new(400.0, 300.0), Point::new(400.0, 0.0)];
|
||||
path_doc(vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&points, false)), spacing)
|
||||
}
|
||||
|
||||
/// An Objects on Path group of two 20 × 20 squares on `path`, with Space `spacing`; and a
|
||||
/// selection of the group.
|
||||
fn path_doc(path: vectorcraft_geom::PathData, spacing: Option<f64>) -> (Document, Selection) {
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let l = d.layers[0].id;
|
||||
let (line, a, b, g) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let line = Node::path(line, path, Appearance::default_art());
|
||||
let a = Node::path(a, shapes::rectangle(Rect::new(50.0, 50.0, 70.0, 70.0)), Appearance::default_art());
|
||||
let b = Node::path(b, shapes::rectangle(Rect::new(100.0, 50.0, 120.0, 70.0)), Appearance::default_art());
|
||||
let rec = vectorcraft_doc::objects_on_path::ObjectsOnPath::new(line.id, &[&a, &b], CENTER, 0.0);
|
||||
let rec = vectorcraft_doc::objects_on_path::ObjectsOnPath { spacing, ..rec };
|
||||
let mut group = Node::new(g, NodeKind::Group { children: vec![Arc::new(line), Arc::new(a), Arc::new(b)], clip: false });
|
||||
group.extras_mut().objects_on_path = Some(Box::new(rec));
|
||||
vectorcraft_doc::objects_on_path::place(&mut group, &Document::new(1.0, 1.0).symbol_boxes());
|
||||
d.insert(Some(l), 0, group).unwrap();
|
||||
let mut sel = Selection::default();
|
||||
sel.set([g]);
|
||||
(d, sel)
|
||||
}
|
||||
|
||||
/// On an L-shaped path the drag counts the distance along the path, round the corner.
|
||||
#[test]
|
||||
fn a_space_drag_follows_the_path_round_a_corner() {
|
||||
let (d, sel) = corner_doc(None);
|
||||
let paint = paint();
|
||||
let c = cx(&d, &sel, &paint);
|
||||
// The path is 700 pt long; the second object sits on its end (400, 0), and the widget above it.
|
||||
let w = SpaceWidget::of(&d, &sel, 1.0).unwrap();
|
||||
assert!(near(w.last, Point::new(400.0, 0.0)) && (w.gap - 700.0).abs() < 1e-9, "{w:?}");
|
||||
let mut t = ObjectsOnPathTool::default();
|
||||
t.pointer(&c, &ev(PointerKind::Down, w.at.x, w.at.y));
|
||||
// The press, 26 pt beyond the end, is 726 pt along. Down the upright leg to 500 pt along,
|
||||
// then round the corner onto the level one at 300 pt along.
|
||||
assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, 400.0, 200.0))), Some((474.0, 0.0)));
|
||||
assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, 300.0, 310.0))), Some((274.0, 0.0)));
|
||||
}
|
||||
|
||||
/// With the last object just short of the corner, the widget sits past the corner; the drag
|
||||
/// measures from the widget, so the objects follow the pointer from the start.
|
||||
#[test]
|
||||
fn a_space_widget_past_a_corner_measures_from_where_it_is() {
|
||||
let (d, sel) = corner_doc(Some(390.0));
|
||||
let paint = paint();
|
||||
let c = cx(&d, &sel, &paint);
|
||||
let w = SpaceWidget::of(&d, &sel, 1.0).unwrap();
|
||||
assert!(near(w.last, Point::new(390.0, 300.0)) && near(w.at, Point::new(416.0, 300.0)) && w.last_length == 390.0, "{w:?}");
|
||||
let mut t = ObjectsOnPathTool::default();
|
||||
t.pointer(&c, &ev(PointerKind::Down, w.at.x, w.at.y));
|
||||
assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, 396.0, 300.0))), Some((370.0, 0.0)), "20 pt back");
|
||||
assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, 386.0, 300.0))), Some((360.0, 0.0)));
|
||||
}
|
||||
|
||||
/// On a closed path, a drag far ahead along the line through the widget spreads the objects
|
||||
/// apart, however far the pointer goes at once.
|
||||
#[test]
|
||||
fn a_long_drag_ahead_on_a_closed_path_spreads_the_objects() {
|
||||
// The square's outline is 800 pt round, from (100, 100) to the right.
|
||||
let (d, sel) = path_doc(shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 300.0)), Some(100.0));
|
||||
let paint = paint();
|
||||
let c = cx(&d, &sel, &paint);
|
||||
let w = SpaceWidget::of(&d, &sel, 1.0).unwrap();
|
||||
assert!(near(w.last, Point::new(200.0, 100.0)) && near(w.at, Point::new(226.0, 100.0)), "{w:?}");
|
||||
let mut t = ObjectsOnPathTool::default();
|
||||
t.pointer(&c, &ev(PointerKind::Down, w.at.x, w.at.y));
|
||||
assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, 236.0, 100.0))), Some((110.0, 0.0)));
|
||||
assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, 1000.0, 100.0))), Some((400.0, 0.0)), "half way round at most");
|
||||
}
|
||||
|
||||
/// Escape during a Space drag cancels it: the readout is removed, and the release keeps
|
||||
/// nothing.
|
||||
#[test]
|
||||
fn escape_cancels_a_space_drag() {
|
||||
let (d, _, sel) = group_doc(0.0);
|
||||
let paint = paint();
|
||||
let c = cx(&d, &sel, &paint);
|
||||
let at = SpaceWidget::of(&d, &sel, 1.0).unwrap().at;
|
||||
let tools: [Box<dyn Tool>; 2] = [Box::new(crate::select::SelectionTool::default()), Box::new(ObjectsOnPathTool::default())];
|
||||
for mut t in tools {
|
||||
t.pointer(&c, &ev(PointerKind::Down, at.x, at.y));
|
||||
assert!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, at.x - 40.0, at.y))).is_some());
|
||||
assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel], "{}", t.id());
|
||||
assert!(!t.busy() && !t.transforming(), "{}", t.id());
|
||||
assert!(!t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { .. })), "{}", t.id());
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Drag, at.x, at.y)).is_empty(), "{}", t.id());
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Up, at.x, at.y)).is_empty(), "{}: the release keeps nothing", t.id());
|
||||
}
|
||||
}
|
||||
}
|
||||
+160
-25
@@ -3,8 +3,12 @@
|
||||
//! type begins or ends along its path; dragging the centre bracket slides the type along the path
|
||||
//! (its brackets with it) and, dragged across the path, flips the type to the other side
|
||||
//! (Cmd/Ctrl held: it only slides). Each drag is one undo step of `type.pathOptions`. The tools
|
||||
//! draw the brackets from the same geometry they hit-test. With more than 10,000 type on a path
|
||||
//! objects selected, they neither draw nor hit-test any bracket.
|
||||
//! draw the brackets from the same geometry they hit-test. A press within [`HIT_PX`] of a bracket
|
||||
//! takes the nearest one, and the bracket a press would take draws thicker under the pointer. In
|
||||
//! the Selection tool, which loads text from ports, the nearer of a bracket and a text port takes a
|
||||
//! press (and the highlight); Direct Selection has no ports, so a bracket within reach always takes
|
||||
//! it there. With more than 10,000 type on a path objects selected, they neither draw nor hit-test
|
||||
//! any bracket.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind, TextKind};
|
||||
@@ -20,6 +24,10 @@ const DOWN_PX: f64 = 4.0;
|
||||
const FOOT_PX: f64 = 4.0;
|
||||
/// How far past the path (screen px) the centre bracket goes before the type flips.
|
||||
const FLIP_PX: f64 = 6.0;
|
||||
/// How near (screen px) a press must be to a bracket to take it.
|
||||
const HIT_PX: f64 = 8.0;
|
||||
/// The stroke width (screen px) of the bracket under the pointer; the others are hairlines.
|
||||
const HOT_WIDTH: f32 = 2.5;
|
||||
/// The most points the tools draw for the brackets of a selection, the same number as the canvas's
|
||||
/// limit on the anchor points it outlines (`OVERLAY_MAX_ANCHORS` in `crates/ui-egui/src/canvas.rs`).
|
||||
/// Past it the tools neither draw nor hit-test any bracket.
|
||||
@@ -107,9 +115,14 @@ impl Brackets {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bracket within `tol` (document units) of `p`.
|
||||
fn hit(&self, p: Point, zoom: f64, tol: f64) -> Option<Bracket> {
|
||||
Bracket::ALL.into_iter().find(|b| self.lines(*b, zoom).iter().any(|(a, c)| Line::new(*a, *c).nearest(p, 1e-9).distance_sq <= tol * tol))
|
||||
/// How far (document units) bracket `b` is from `p`.
|
||||
fn distance(&self, b: Bracket, p: Point, zoom: f64) -> f64 {
|
||||
self.lines(b, zoom).into_iter().map(|(a, c)| Line::new(a, c).nearest(p, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min)
|
||||
}
|
||||
|
||||
/// The bracket nearest `p` within `tol` (document units), and how far it is.
|
||||
fn hit(&self, p: Point, zoom: f64, tol: f64) -> Option<(Bracket, f64)> {
|
||||
Bracket::ALL.into_iter().map(|b| (b, self.distance(b, p, zoom))).filter(|(_, d)| *d <= tol).min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
}
|
||||
|
||||
/// The fraction of the path's length nearest document point `p`.
|
||||
@@ -125,29 +138,64 @@ fn too_many(cx: &ToolContext) -> bool {
|
||||
cx.selection.objects.iter().filter(on_path).nth(MAX_POINTS / POINTS_EACH).is_some()
|
||||
}
|
||||
|
||||
/// The selected type on a path's bracket under `p`, if any.
|
||||
fn bracket_at(cx: &ToolContext, p: Point) -> Option<(Brackets, Bracket)> {
|
||||
Brackets::of(cx).into_iter().find_map(|b| {
|
||||
let which = b.hit(p, cx.zoom, cx.tol(5.0))?;
|
||||
Some((b, which))
|
||||
})
|
||||
/// The selected type on a path's bracket nearest `p` within [`HIT_PX`], and how far it is.
|
||||
fn bracket_at(cx: &ToolContext, p: Point) -> Option<(Brackets, Bracket, f64)> {
|
||||
Brackets::of(cx)
|
||||
.into_iter()
|
||||
.filter_map(|b| {
|
||||
let (which, d) = b.hit(p, cx.zoom, cx.tol(HIT_PX))?;
|
||||
Some((b, which, d))
|
||||
})
|
||||
.min_by(|a, b| a.2.total_cmp(&b.2))
|
||||
}
|
||||
|
||||
/// Is `p` over a bracket of the selected type on a path?
|
||||
/// How far (document units) the bracket of the selected type on a path under `p` is from it; None
|
||||
/// when no bracket is within reach.
|
||||
pub fn bracket_distance(cx: &ToolContext, p: Point) -> Option<f64> {
|
||||
if too_many(cx) {
|
||||
return None;
|
||||
}
|
||||
bracket_at(cx, p).map(|(_, _, d)| d)
|
||||
}
|
||||
|
||||
/// Is `p` within reach of a bracket of the selected type on a path, ports or not (Direct
|
||||
/// Selection, which takes no clicks on ports)?
|
||||
pub fn near_bracket(cx: &ToolContext, p: Point) -> bool {
|
||||
bracket_distance(cx, p).is_some()
|
||||
}
|
||||
|
||||
/// Is `p` over a bracket of the selected type on a path, nearer than any text port (a start
|
||||
/// bracket and an in port sit side by side: the nearer takes the press)? For the Selection tool,
|
||||
/// which loads text from ports.
|
||||
pub fn over_bracket(cx: &ToolContext, p: Point) -> bool {
|
||||
!too_many(cx) && bracket_at(cx, p).is_some()
|
||||
bracket_distance(cx, p).is_some_and(|d| crate::text::port_near(cx, p).is_none_or(|(_, _, port)| d <= port))
|
||||
}
|
||||
|
||||
/// The brackets of the selected type on a path, in their layer's colour.
|
||||
pub fn overlays(cx: &ToolContext) -> Vec<Overlay> {
|
||||
/// The brackets of the selected type on a path, in their layer's colour: the one under `hover`
|
||||
/// thicker (the caller passes only a hover that would take the bracket), or the one `drag` moves.
|
||||
pub fn overlays(cx: &ToolContext, hover: Option<Point>, drag: Option<&BracketDrag>) -> Vec<Overlay> {
|
||||
if too_many(cx) {
|
||||
return vec![];
|
||||
}
|
||||
let hot = match drag {
|
||||
Some(d) => Some((d.brackets.id, d.which)),
|
||||
None => hover.and_then(|p| bracket_at(cx, p)).map(|(b, which, _)| (b.id, which)),
|
||||
};
|
||||
let mut out = vec![];
|
||||
for b in Brackets::of(cx) {
|
||||
let color = cx.doc.layer_color(b.id);
|
||||
for which in Bracket::ALL {
|
||||
out.extend(b.lines(which, cx.zoom).into_iter().map(|(a, b)| Overlay::Line { a, b, color, dashed: false }));
|
||||
let lines = b.lines(which, cx.zoom);
|
||||
if hot == Some((b.id, which)) {
|
||||
let mut path = vectorcraft_geom::kurbo::BezPath::new();
|
||||
for (a, c) in lines {
|
||||
path.move_to(a);
|
||||
path.line_to(c);
|
||||
}
|
||||
out.push(Overlay::Path { path, color, width: HOT_WIDTH, dashed: false });
|
||||
} else {
|
||||
out.extend(lines.into_iter().map(|(a, b)| Overlay::Line { a, b, color, dashed: false }));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -165,12 +213,22 @@ pub struct BracketDrag {
|
||||
}
|
||||
|
||||
impl BracketDrag {
|
||||
/// Start a drag when the press `ev` is on a bracket of the selected type on a path.
|
||||
/// Start a drag when the press `ev` is on a bracket of the selected type on a path, nearer than
|
||||
/// any text port (the Selection tool, [`over_bracket`]).
|
||||
pub fn hit(cx: &ToolContext, ev: &PointerEvent) -> Option<Self> {
|
||||
if !over_bracket(cx, ev.pos) {
|
||||
return None;
|
||||
}
|
||||
Self::hit_any(cx, ev)
|
||||
}
|
||||
|
||||
/// Start a drag when the press `ev` is within reach of a bracket, ports or not (Direct
|
||||
/// Selection, [`near_bracket`]).
|
||||
pub fn hit_any(cx: &ToolContext, ev: &PointerEvent) -> Option<Self> {
|
||||
if too_many(cx) {
|
||||
return None;
|
||||
}
|
||||
let (brackets, which) = bracket_at(cx, ev.pos)?;
|
||||
let (brackets, which, _) = bracket_at(cx, ev.pos)?;
|
||||
let grab = brackets.fraction_at(ev.pos)?;
|
||||
Some(Self { brackets, which, start: ev.pos, grab, began: false })
|
||||
}
|
||||
@@ -271,12 +329,13 @@ mod tests {
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let b = Brackets::of(&cx).pop().unwrap();
|
||||
assert_eq!(b.hit(Point::new(160.0, 290.0), 1.0, 2.0), Some(Bracket::Start));
|
||||
assert_eq!(b.hit(Point::new(280.0, 290.0), 1.0, 2.0), Some(Bracket::Centre));
|
||||
assert_eq!(b.hit(Point::new(400.0, 290.0), 1.0, 2.0), Some(Bracket::End));
|
||||
assert_eq!(b.hit(Point::new(220.0, 290.0), 1.0, 2.0), None);
|
||||
let which = |p: Point| b.hit(p, 1.0, 2.0).map(|(w, _)| w);
|
||||
assert_eq!(which(Point::new(160.0, 290.0)), Some(Bracket::Start));
|
||||
assert_eq!(which(Point::new(280.0, 290.0)), Some(Bracket::Centre));
|
||||
assert_eq!(which(Point::new(400.0, 290.0)), Some(Bracket::End));
|
||||
assert_eq!(which(Point::new(220.0, 290.0)), None);
|
||||
// Drawn over the type's side of the path, with feet pointing into the span.
|
||||
let o = overlays(&cx);
|
||||
let o = overlays(&cx, None, None);
|
||||
assert_eq!(o.len(), 5);
|
||||
assert!(o.contains(&Overlay::Line { a: Point::new(160.0, 286.0), b: Point::new(164.0, 286.0), color: d.layer_color(id), dashed: false }));
|
||||
// Nothing for unselected or other type.
|
||||
@@ -316,13 +375,13 @@ mod tests {
|
||||
};
|
||||
{
|
||||
let cx = cx(&d, &s, &p);
|
||||
assert_eq!(overlays(&cx).len(), 50_000);
|
||||
assert_eq!(overlays(&cx, None, None).len(), 50_000);
|
||||
assert!(over_bracket(&cx, at) && BracketDrag::hit(&cx, &press).is_some());
|
||||
assert_eq!(tools(&cx), vec![(50_000, Cursor::PathBracket); 2]);
|
||||
}
|
||||
add(&mut d, &mut s, 1);
|
||||
let cx = cx(&d, &s, &p);
|
||||
assert!(overlays(&cx).is_empty());
|
||||
assert!(overlays(&cx, None, None).is_empty());
|
||||
assert!(!over_bracket(&cx, at) && BracketDrag::hit(&cx, &press).is_none());
|
||||
for (n, cursor) in tools(&cx) {
|
||||
assert_eq!(n, 0);
|
||||
@@ -364,4 +423,80 @@ mod tests {
|
||||
let v = preview(&drag(&cx, Point::new(400.0, 295.0), Point::new(110.0, 300.0), Mods::default())).clone();
|
||||
assert!((v["end"].as_f64().unwrap() - 0.2).abs() < 1e-6, "{v}");
|
||||
}
|
||||
|
||||
/// A press takes a bracket within 8 screen px at any zoom, and not further.
|
||||
#[test]
|
||||
fn brackets_are_hit_within_eight_screen_pixels_at_any_zoom() {
|
||||
let (d, id) = doc_with_path_type();
|
||||
let s = selected(id);
|
||||
let p = paint();
|
||||
for zoom in [0.25, 1.0, 8.0] {
|
||||
let mut cx = cx(&d, &s, &p);
|
||||
cx.zoom = zoom;
|
||||
let px = 1.0 / zoom;
|
||||
// The start bracket's stem stands at x 160, from 4 px below the path to 14 px above it.
|
||||
let near = |dx: f64| near_bracket(&cx, Point::new(160.0 - dx * px, 300.0 - 7.0 * px));
|
||||
assert!(near(7.5), "7.5 px beside the stem at zoom {zoom}");
|
||||
assert!(!near(9.0), "9 px beside the stem at zoom {zoom}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The bracket a press would take draws thicker under the pointer; elsewhere they are all
|
||||
/// hairlines.
|
||||
#[test]
|
||||
fn the_hovered_bracket_draws_thicker() {
|
||||
let (d, id) = doc_with_path_type();
|
||||
let s = selected(id);
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let hot = |o: &[Overlay]| o.iter().filter(|o| matches!(o, Overlay::Path { width, .. } if *width == HOT_WIDTH)).count();
|
||||
assert_eq!(hot(&overlays(&cx, Some(Point::new(400.0, 293.0)), None)), 1);
|
||||
assert_eq!(hot(&overlays(&cx, Some(Point::new(220.0, 250.0)), None)), 0);
|
||||
let mut t = crate::select::SelectionTool::default();
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 400.0, 293.0));
|
||||
assert_eq!(hot(&t.overlays(&cx)), 1);
|
||||
t.hover_ended(&cx);
|
||||
assert_eq!(hot(&t.overlays(&cx)), 0, "the highlight goes with the hover");
|
||||
}
|
||||
|
||||
/// A press on a bracket takes it rather than moving the type; where the in port sits beside the
|
||||
/// start bracket, the Selection tool gives a press nearer the port to the port (no bracket drag,
|
||||
/// cursor or highlight), while Direct Selection, which has no ports, takes the bracket.
|
||||
#[test]
|
||||
fn the_nearer_of_a_bracket_and_a_port_takes_a_selection_press() {
|
||||
let (d, id) = doc_with_path_type();
|
||||
let s = selected(id);
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut t = crate::select::SelectionTool::default();
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 280.0, 296.0));
|
||||
let out = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 310.0, 296.0));
|
||||
assert!(out.iter().any(|a| matches!(a, Action::Preview(c, _) if c == "type.pathOptions")), "{out:?}");
|
||||
// A point nearer the in port with the start bracket in reach.
|
||||
let mut between = None;
|
||||
for i in 0..400 {
|
||||
for j in 0..120 {
|
||||
let q = Point::new(130.0 + i as f64 * 0.1, 282.0 + j as f64 * 0.2);
|
||||
let Some((_, crate::text::Port::In, port)) = crate::text::port_near(&cx, q) else { continue };
|
||||
if bracket_distance(&cx, q).is_some_and(|b| port < b) {
|
||||
between = Some(q);
|
||||
}
|
||||
}
|
||||
}
|
||||
let q = between.expect("a point nearer the in port with the start bracket in reach");
|
||||
let down = PointerEvent::new(PointerKind::Down, q.x, q.y);
|
||||
let hot = |o: &[Overlay]| o.iter().any(|o| matches!(o, Overlay::Path { width, .. } if *width == HOT_WIDTH));
|
||||
assert!(!over_bracket(&cx, q) && BracketDrag::hit(&cx, &down).is_none());
|
||||
let mut select = crate::select::SelectionTool::default();
|
||||
select.pointer(&cx, &PointerEvent::new(PointerKind::Move, q.x, q.y));
|
||||
assert!(!hot(&select.overlays(&cx)));
|
||||
assert_ne!(select.cursor(&cx, q, Mods::default()), Cursor::PathBracket);
|
||||
let mut direct = crate::direct::DirectSelectionTool::new(false);
|
||||
assert_eq!(direct.cursor(&cx, q, Mods::default()), Cursor::PathBracket);
|
||||
direct.pointer(&cx, &PointerEvent::new(PointerKind::Move, q.x, q.y));
|
||||
assert!(hot(&direct.overlays(&cx)));
|
||||
direct.pointer(&cx, &down);
|
||||
let out = direct.pointer(&cx, &PointerEvent::new(PointerKind::Drag, q.x + 30.0, q.y));
|
||||
assert!(out.iter().any(|a| matches!(a, Action::Preview(c, _) if c == "type.pathOptions")), "{out:?}");
|
||||
}
|
||||
}
|
||||
@@ -445,6 +445,15 @@ impl Tool for PenTool {
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
/// A dropped press drops only the anchor it was placing, a handle it was dragging or the
|
||||
/// close it was making: the path being drawn goes on with the next click.
|
||||
fn drop_press(&mut self, _cx: &ToolContext) -> Vec<Action> {
|
||||
self.drag = None;
|
||||
self.handle = None;
|
||||
self.convert = None;
|
||||
self.snap.clear();
|
||||
vec![]
|
||||
}
|
||||
/// Deactivate the pen tool, committing in-flight operations and restoring compound path selection.
|
||||
fn deactivate(&mut self, cx: &ToolContext) -> Vec<Action> {
|
||||
let path = self.path;
|
||||
|
||||
@@ -47,7 +47,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
use crate::bbox::{Handle, hit_handle, in_rotate_zone, move_delta, rotate_for_drag, scale_for_drag};
|
||||
use crate::corners::{self, CornerDrag, over_widget};
|
||||
use crate::guides::{PointSnap, Targets, distance_guides, hold_on_path};
|
||||
use crate::objects_on_path::{RotateAllDrag, over_rotate_all};
|
||||
use crate::objects_on_path::{RotateAllDrag, SpaceDrag, over_rotate_all, over_space};
|
||||
use crate::pathtype::{self, BracketDrag, over_bracket};
|
||||
use crate::pie::{self, PieDrag};
|
||||
use crate::rulerguide::GuideEdit;
|
||||
@@ -107,6 +107,8 @@ enum State {
|
||||
Pie(PieDrag),
|
||||
/// Dragging an Objects on Path group's Rotate All widget.
|
||||
RotateAll(RotateAllDrag),
|
||||
/// Dragging an Objects on Path group's Space widget.
|
||||
Space(SpaceDrag),
|
||||
/// Move or rotate a live mirror axis.
|
||||
Mirror(crate::mirror::MirrorDrag),
|
||||
/// Drag a grid repeat's row, column or corner handle or a spacing slider.
|
||||
@@ -150,6 +152,11 @@ pub struct SelectionTool {
|
||||
/// The last hover had Alt held: what it measures depends on what lies under the pointer
|
||||
/// ([`Tool::wants_rehover`]).
|
||||
alt_hover: bool,
|
||||
/// The text the pointer was loaded with when the button went down: a dropped press loads it
|
||||
/// again.
|
||||
loaded_at_press: Option<(NodeId, bool)>,
|
||||
/// Where the pointer last hovered: the type on a path bracket under it draws thicker.
|
||||
bracket_hover: Option<Point>,
|
||||
}
|
||||
|
||||
/// What Distance Guides measure the selection to.
|
||||
@@ -556,6 +563,21 @@ impl SelectionTool {
|
||||
})
|
||||
}
|
||||
|
||||
/// On a press, notes the text the pointer is loaded with ([`Self::loaded_at_press`]); a
|
||||
/// release clears it.
|
||||
fn note_loaded_at_press(&mut self, kind: PointerKind) {
|
||||
match kind {
|
||||
PointerKind::Down => {
|
||||
self.loaded_at_press = match self.state {
|
||||
State::Loaded { from, before, .. } => Some((from, before)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
PointerKind::Up => self.loaded_at_press = None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pointer loaded with the text of area type or type on a path `from` ([`State::Loaded`]):
|
||||
/// a press starts placing it, and its release threads it (`text.thread.add`), into a frame put
|
||||
/// `before` `from` or after it. None when `from` can no longer thread: the press is an
|
||||
@@ -622,7 +644,7 @@ impl Tool for SelectionTool {
|
||||
|
||||
/// E during a marquee drag switches the marquee between the objects it touches and only the
|
||||
/// objects inside it. Escape during a drag (a move or an Alt-drag copy, a bounding-box scale or
|
||||
/// rotation, a marquee, a corner widget, a pie widget, the Rotate All widget, the brackets of type on a path, a mirror
|
||||
/// rotation, a marquee, a corner widget, a pie widget, the Rotate All or Space widget, the brackets of type on a path, a mirror
|
||||
/// axis, a grid repeat's handles, a ruler guide) cancels it: what it changed goes back, no copy
|
||||
/// is left, and the tool waits for the next press. With the pointer loaded with text, Escape
|
||||
/// drops the text.
|
||||
@@ -669,6 +691,18 @@ impl Tool for SelectionTool {
|
||||
if key == ToolKey::Escape { self.guide.cancel() } else { vec![] }
|
||||
}
|
||||
|
||||
/// A dropped press is canceled as by Escape, so a dropped press on a port loads no text. With
|
||||
/// the pointer loaded with text, the press threads nothing and the text stays loaded for the
|
||||
/// next click, a press on the port that loaded it included.
|
||||
fn drop_press(&mut self, cx: &ToolContext) -> Vec<Action> {
|
||||
let loaded = self.loaded_at_press.take();
|
||||
let out = if matches!(self.state, State::Loaded { press: Some(_), .. }) { vec![] } else { self.key(cx, ToolKey::Escape, Mods::default()) };
|
||||
if let Some((from, before)) = loaded {
|
||||
self.state = State::Loaded { from, before, press: None };
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
|
||||
match self.state {
|
||||
State::Marquee { .. } => key == ToolKey::Letter('e'),
|
||||
@@ -683,6 +717,7 @@ impl Tool for SelectionTool {
|
||||
self.hover = None;
|
||||
self.distance = None;
|
||||
self.alt_hover = false;
|
||||
self.bracket_hover = None;
|
||||
}
|
||||
|
||||
fn wants_rehover(&self) -> bool {
|
||||
@@ -695,6 +730,7 @@ impl Tool for SelectionTool {
|
||||
State::Corner(c) => c.adjusting(),
|
||||
State::Pie(d) => d.adjusting(),
|
||||
State::RotateAll(d) => d.adjusting(),
|
||||
State::Space(d) => d.adjusting(),
|
||||
State::Bracket(b) => b.adjusting(),
|
||||
State::Mirror(d) => d.adjusting(),
|
||||
State::GridRepeat(d) => d.adjusting(),
|
||||
@@ -703,7 +739,9 @@ impl Tool for SelectionTool {
|
||||
}
|
||||
|
||||
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
|
||||
self.note_loaded_at_press(ev.kind);
|
||||
let hovering = ev.kind == PointerKind::Move && matches!(self.state, State::Idle);
|
||||
self.bracket_hover = hovering.then_some(ev.pos);
|
||||
self.alt_hover = hovering && ev.mods.alt;
|
||||
self.distance = hovering.then(|| distance_target(cx, ev.pos, ev.mods)).flatten();
|
||||
if let State::Loaded { from, before, press } = self.state
|
||||
@@ -856,6 +894,15 @@ impl Tool for SelectionTool {
|
||||
self.state = State::Idle;
|
||||
d.finish()
|
||||
}
|
||||
(PointerKind::Drag, State::Space(mut d)) => {
|
||||
let out = d.drag(cx, p, m.alt);
|
||||
self.state = State::Space(d);
|
||||
out
|
||||
}
|
||||
(PointerKind::Up, State::Space(d)) => {
|
||||
self.state = State::Idle;
|
||||
d.finish()
|
||||
}
|
||||
(PointerKind::Drag, State::Bracket(mut b)) => {
|
||||
let out = b.drag(cx, p, m.cmd);
|
||||
self.state = State::Bracket(b);
|
||||
@@ -899,7 +946,9 @@ impl Tool for SelectionTool {
|
||||
}
|
||||
|
||||
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
|
||||
let mut o = pathtype::overlays(cx);
|
||||
// Highlighted only where a press would take the bracket, not a nearer port.
|
||||
let drag = if let State::Bracket(b) = &self.state { Some(b) } else { None };
|
||||
let mut o = pathtype::overlays(cx, self.bracket_hover.filter(|p| over_bracket(cx, *p)), drag);
|
||||
if let Some(source) = cx.isolation.and_then(|id| cx.doc.node(id)).filter(|n| n.name.as_deref() == Some(vectorcraft_doc::shaper::SOURCES)) {
|
||||
for n in source.children().into_iter().flatten() {
|
||||
if let Some(path) = n.path_data() {
|
||||
@@ -912,6 +961,7 @@ impl Tool for SelectionTool {
|
||||
State::Corner(c) => o.extend(c.overlays(cx)),
|
||||
State::Pie(d) => o.extend(d.overlays(cx)),
|
||||
State::RotateAll(d) => o.extend(d.overlays(cx)),
|
||||
State::Space(d) => o.extend(d.overlays(cx)),
|
||||
State::Loaded { press: Some((start, cur)), .. } => o.push(Overlay::Marquee(Rect::from_points(*start, *cur))),
|
||||
_ => {}
|
||||
}
|
||||
@@ -960,6 +1010,7 @@ impl Tool for SelectionTool {
|
||||
State::Corner(_) => return Cursor::CornerRadius,
|
||||
State::Pie(_) => return Cursor::ArrowHollow,
|
||||
State::RotateAll(_) => return Cursor::Rotate,
|
||||
State::Space(_) => return Cursor::ArrowHollow,
|
||||
State::Bracket(_) => return Cursor::PathBracket,
|
||||
State::Loaded { .. } => return Cursor::LoadedText,
|
||||
_ => {}
|
||||
@@ -976,6 +1027,9 @@ impl Tool for SelectionTool {
|
||||
if over_rotate_all(cx, p) {
|
||||
return Cursor::Rotate;
|
||||
}
|
||||
if over_space(cx, p) {
|
||||
return Cursor::ArrowHollow;
|
||||
}
|
||||
if over_bracket(cx, p) {
|
||||
return Cursor::PathBracket;
|
||||
}
|
||||
@@ -1314,11 +1368,11 @@ impl SelectionTool {
|
||||
fn press_widgets(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point) -> Option<Vec<Action>> {
|
||||
// 0. A port of selected area type or type on a path: the pointer takes its text,
|
||||
// to thread on from the out port or back from the in port.
|
||||
if let Some((from, port)) = crate::text::port_at(cx, p) {
|
||||
if let Some((from, port)) = crate::text::port_at(cx, p).filter(|_| !over_bracket(cx, p)) {
|
||||
self.state = State::Loaded { from, before: port == crate::text::Port::In, press: None };
|
||||
return Some(vec![]);
|
||||
}
|
||||
// 1. Live Corners widgets, pie widgets, the Rotate All widget and type on a path's brackets, then the
|
||||
// 1. Live Corners widgets, pie widgets, the Rotate All and Space widgets and type on a path's brackets, then the
|
||||
// bounding-box handles of the current selection.
|
||||
if let Some(c) = CornerDrag::hit(cx, ev, false) {
|
||||
self.state = State::Corner(c);
|
||||
@@ -1332,6 +1386,10 @@ impl SelectionTool {
|
||||
self.state = State::RotateAll(d);
|
||||
return Some(vec![]);
|
||||
}
|
||||
if let Some(d) = SpaceDrag::hit(cx, ev) {
|
||||
self.state = State::Space(d);
|
||||
return Some(vec![]);
|
||||
}
|
||||
if let Some(b) = BracketDrag::hit(cx, ev) {
|
||||
self.state = State::Bracket(b);
|
||||
return Some(vec![]);
|
||||
|
||||
@@ -1871,6 +1871,41 @@ fn escape_drops_the_loaded_text() {
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 30.0, 420.0)), vec![Action::Exec("select.none".into(), json!({}))]);
|
||||
}
|
||||
|
||||
/// A dropped press with the pointer loaded with text threads nothing, and the text stays loaded:
|
||||
/// the next click threads it. A dropped press on the port loads no text.
|
||||
#[test]
|
||||
fn a_dropped_press_keeps_the_text_loaded() {
|
||||
let (d, id, _, port) = overflowing_area_type();
|
||||
let mut s = Selection::default();
|
||||
s.set([id]);
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut t = SelectionTool::default();
|
||||
t.pointer(&cx, &ev(PointerKind::Down, port.x, port.y));
|
||||
t.drop_press(&cx);
|
||||
t.pointer(&cx, &ev(PointerKind::Up, port.x, port.y));
|
||||
assert_ne!(t.cursor(&cx, Point::new(30.0, 420.0), Mods::default()), Cursor::LoadedText, "the dropped press loads no text");
|
||||
t.pointer(&cx, &ev(PointerKind::Down, port.x, port.y));
|
||||
t.pointer(&cx, &ev(PointerKind::Up, port.x, port.y));
|
||||
// The engine sends the release after the drop.
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 20.0, 20.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 80.0, 90.0));
|
||||
assert!(t.drop_press(&cx).is_empty());
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Up, 80.0, 90.0)).is_empty(), "the release threads nothing");
|
||||
assert!(!t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Marquee(_))), "the new frame's outline is removed");
|
||||
assert_eq!(t.cursor(&cx, Point::new(30.0, 420.0), Mods::default()), Cursor::LoadedText);
|
||||
// A press on the port that loaded the text puts it down; dropped, it leaves the text loaded.
|
||||
t.pointer(&cx, &ev(PointerKind::Down, port.x, port.y));
|
||||
assert!(t.drop_press(&cx).is_empty());
|
||||
t.pointer(&cx, &ev(PointerKind::Up, port.x, port.y));
|
||||
assert_eq!(t.cursor(&cx, Point::new(30.0, 420.0), Mods::default()), Cursor::LoadedText, "a dropped press on the port");
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 30.0, 420.0));
|
||||
assert_eq!(
|
||||
t.pointer(&cx, &ev(PointerKind::Up, 30.0, 420.0)),
|
||||
vec![Action::Exec("text.thread.add".into(), json!({"from": id.0, "at": [30.0, 420.0]}))]
|
||||
);
|
||||
}
|
||||
|
||||
/// [`doc_with_area_type`], its text fitting its frame; where its in and out ports are.
|
||||
fn fitting_area_type() -> (vectorcraft_doc::Document, NodeId, Point, Point) {
|
||||
let (d, id) = doc_with_area_type();
|
||||
|
||||
@@ -51,8 +51,8 @@ mod tool;
|
||||
use plain::char_range_to_bytes;
|
||||
use plain::common_affixes;
|
||||
pub use plain::step_key;
|
||||
pub(crate) use ports::port_at;
|
||||
pub use ports::{PORT_RISE_PX, PORTS_MAX, Port, PortMarks, PortState, port_centre, port_states, ported, ports_shown, push_port, thread_ports};
|
||||
pub(crate) use ports::{port_at, port_near};
|
||||
|
||||
/// Which of the Type tools this is.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -189,6 +189,9 @@ pub struct TypeTool {
|
||||
snap: DrawSnap,
|
||||
/// The press landed in the edited text: dragging selects.
|
||||
selecting: bool,
|
||||
/// The caret and anchor from before a press in type, kept until its release; a dropped press
|
||||
/// puts them back.
|
||||
before_press: Option<(usize, usize)>,
|
||||
/// Click counting for double/triple click (position of the last click, count).
|
||||
clicks: (Option<Point>, u8),
|
||||
/// Styled copy of the last copied range (pasting the same plain text keeps its styles).
|
||||
|
||||
@@ -145,15 +145,25 @@ pub fn ports_shown(d: &vectorcraft_doc::Document, selected: &[NodeId]) -> bool {
|
||||
/// on the in port to thread into one before it. Every such frame has both ports, threaded,
|
||||
/// overflowing or not, while their ports show ([`PORTS_MAX`]).
|
||||
pub(crate) fn port_at(cx: &ToolContext, p: Point) -> Option<(NodeId, Port)> {
|
||||
port_near(cx, p).map(|(id, port, _)| (id, port))
|
||||
}
|
||||
|
||||
/// [`port_at`], with how far (document units) the port's centre is from `p`: the nearest port
|
||||
/// within reach, of every selected frame (ports of overlapping frames can both be in reach).
|
||||
pub(crate) fn port_near(cx: &ToolContext, p: Point) -> Option<(NodeId, Port, f64)> {
|
||||
if !ports_shown(cx.doc, &cx.selection.objects) {
|
||||
return None;
|
||||
}
|
||||
let h = cx.tol(PORT_HALF_PX + 1.0);
|
||||
let near = |c: Point| (c.x - p.x).abs() <= h && (c.y - p.y).abs() <= h;
|
||||
cx.selection.objects.iter().find_map(|id| {
|
||||
let t = ported(cx.doc, *id)?;
|
||||
[Port::Out, Port::In].into_iter().find(|port| port_centre(t, *port, cx.tol(1.0)).is_some_and(near)).map(|port| (*id, port))
|
||||
})
|
||||
cx.selection
|
||||
.objects
|
||||
.iter()
|
||||
.filter_map(|id| ported(cx.doc, *id).map(|t| (*id, t)))
|
||||
.flat_map(|(id, t)| [Port::Out, Port::In].into_iter().filter_map(move |port| port_centre(t, port, cx.tol(1.0)).map(|c| (id, port, c))))
|
||||
.filter(|(_, _, c)| near(*c))
|
||||
.map(|(id, port, c)| (id, port, c.distance(p)))
|
||||
.min_by(|a, b| a.2.total_cmp(&b.2))
|
||||
}
|
||||
|
||||
/// Which selected text overflows, for [`thread_ports`]: each text object's layout verdict kept
|
||||
|
||||
@@ -603,6 +603,41 @@ fn a_drag_across_type_not_being_edited_selects_its_text() {
|
||||
assert_eq!((tool.editing, tool.sel()), (Some(id), (7, 7)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_press_keeps_the_type_in_editing() {
|
||||
let (d, id, mut tool) = editing("Hello world");
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let c = cx(&d, &sel, &p);
|
||||
let t = TypeTool::text(&c, id).unwrap().clone();
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
let pt = |i: usize| {
|
||||
let (a, b) = vectorcraft_text::caret_position(&lay, i);
|
||||
t.xf * a.midpoint(b)
|
||||
};
|
||||
let (at, to) = (pt(3), pt(7));
|
||||
tool.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x + 0.1, at.y));
|
||||
tool.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x + 0.1, to.y));
|
||||
assert!(tool.busy());
|
||||
assert_eq!(tool.sel(), (3, 7));
|
||||
// The press is dropped: the caret and selection are as they were before it.
|
||||
let out = tool.drop_press(&c);
|
||||
assert!(!out.iter().any(|a| matches!(a, Action::SwitchTool(_))));
|
||||
assert!(!tool.busy());
|
||||
assert_eq!((tool.editing, tool.sel()), (Some(id), (0, 0)));
|
||||
// The dropped press does not count toward a double or triple click.
|
||||
assert_eq!(tool.clicks, (None, 0));
|
||||
tool.pointer(&c, &PointerEvent::new(PointerKind::Up, at.x + 0.1, at.y));
|
||||
assert_eq!((tool.editing, tool.sel()), (Some(id), (0, 0)));
|
||||
// A Shift-press that extends the selection, dropped, leaves the caret where a click put it.
|
||||
tool.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x + 0.1, at.y));
|
||||
tool.pointer(&c, &PointerEvent::new(PointerKind::Up, at.x + 0.1, at.y));
|
||||
assert_eq!(tool.sel(), (3, 3));
|
||||
tool.pointer(&c, &PointerEvent { mods: SHIFT, ..PointerEvent::new(PointerKind::Down, to.x + 0.1, to.y) });
|
||||
assert_eq!(tool.sel(), (3, 7));
|
||||
tool.drop_press(&c);
|
||||
assert_eq!((tool.editing, tool.sel()), (Some(id), (3, 3)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_all_and_styled_paste() {
|
||||
let (d, _, mut tool) = editing("abc");
|
||||
|
||||
@@ -29,6 +29,20 @@ impl Tool for TypeTool {
|
||||
fn claims_key(&self, _: &ToolContext, key: ToolKey) -> bool {
|
||||
key == ToolKey::Escape && self.editing.is_some()
|
||||
}
|
||||
/// A dropped press drops only the selection drag or the type it was placing: the type being
|
||||
/// edited stays in editing, with the caret and selection it had before the press.
|
||||
fn drop_press(&mut self, _cx: &ToolContext) -> Vec<Action> {
|
||||
if let Some((caret, anchor)) = self.before_press.take() {
|
||||
(self.caret, self.anchor) = (caret, anchor);
|
||||
}
|
||||
self.selecting = false;
|
||||
self.clicks = (None, 0);
|
||||
self.press = None;
|
||||
self.held = None;
|
||||
self.drag = None;
|
||||
self.snap.clear();
|
||||
vec![]
|
||||
}
|
||||
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
|
||||
match ev.kind {
|
||||
PointerKind::Down => {
|
||||
@@ -36,6 +50,7 @@ impl Tool for TypeTool {
|
||||
let same = self.clicks.0.is_some_and(|q| (q - ev.pos).hypot() <= cx.tol(4.0));
|
||||
let n = if same { self.clicks.1 + 1 } else { 1 };
|
||||
self.clicks = (Some(ev.pos), n);
|
||||
self.before_press = Some((self.caret, self.anchor));
|
||||
let out = self.move_to(byte, ev.mods.shift);
|
||||
self.goal_x = None;
|
||||
if n >= 3 {
|
||||
@@ -51,6 +66,7 @@ impl Tool for TypeTool {
|
||||
// as it does in the type being edited.
|
||||
if let Some(out) = self.edit_at(cx, ev.pos) {
|
||||
self.selecting = true;
|
||||
self.before_press = Some((self.caret, self.anchor));
|
||||
return out;
|
||||
}
|
||||
self.press = Some((ev.pos, self.snap.press(cx, ev.pos, self.editing.as_slice(), None)));
|
||||
@@ -71,6 +87,7 @@ impl Tool for TypeTool {
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Up => {
|
||||
self.before_press = None;
|
||||
if self.selecting {
|
||||
self.selecting = false;
|
||||
return vec![];
|
||||
|
||||
@@ -22,6 +22,7 @@ pub use artboard::ArtboardTool;
|
||||
pub use eyedropper::EyedropperTool;
|
||||
pub use free::{DistortMode, FreeTransformTool};
|
||||
pub use gradient::GradientTool;
|
||||
pub(crate) use measure::end_point as measure_end_point;
|
||||
pub use measure::{MeasureTool, measure};
|
||||
pub use transform::{TransformKind, TransformTool};
|
||||
pub use wand::{LassoTool, MagicWandTool};
|
||||
|
||||
@@ -274,10 +274,11 @@ pub(super) fn release(cx: &ToolContext, a: Option<&Annotator>, g: Gesture, lines
|
||||
}
|
||||
}
|
||||
|
||||
/// Escape during a drag: the point a drag-out deselected is selected again.
|
||||
/// Escape during a drag: the point a drag-out deselected is selected again, also when the drag
|
||||
/// came back inside the object.
|
||||
pub(super) fn cancel(g: &Gesture) -> Vec<Action> {
|
||||
match g.grab {
|
||||
Grab::Point(i) if g.out => vec![Action::Cancel, select(Some(i))],
|
||||
Grab::Point(i) if g.left => vec![Action::Cancel, select(Some(i))],
|
||||
_ => vec![Action::Cancel],
|
||||
}
|
||||
}
|
||||
@@ -451,6 +452,31 @@ mod tests {
|
||||
assert!(!t.claims_key(&cx, ToolKey::Escape));
|
||||
}
|
||||
|
||||
/// A dropped click adds no point and leaves the line being drawn open: the next click still
|
||||
/// joins it. A dropped drag of a point is canceled as by Escape.
|
||||
#[test]
|
||||
fn a_dropped_click_keeps_the_line_open() {
|
||||
let (d, s) = doc(FreeformMode::Lines);
|
||||
let p = paint();
|
||||
let mut cx = cx(&d, &s, &p);
|
||||
let mut t = GradientTool::default();
|
||||
let add = |x: f64, y: f64, line: bool| Action::Exec("paint.freeform.addPoint".into(), json!({"at": [x, y], "line": line, "stroke": false}));
|
||||
assert_eq!(click(&mut t, &cx, 140.0, 150.0), vec![add(140.0, 150.0, false)]);
|
||||
cx.freeform_point = Some(2);
|
||||
assert!(t.claims_key(&cx, ToolKey::Escape));
|
||||
// The engine sends the release after the drop.
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 170.0, 160.0));
|
||||
assert!(t.drop_press(&cx).is_empty());
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Up, 170.0, 160.0)).is_empty(), "the dropped click adds no point");
|
||||
assert!(t.claims_key(&cx, ToolKey::Escape), "the line stays open");
|
||||
assert_eq!(click(&mut t, &cx, 160.0, 140.0), vec![add(160.0, 140.0, true)]);
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 120.0, 121.0));
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Drag, 130.0, 140.0))[0], Action::Begin("Gradient".into()));
|
||||
assert_eq!(t.drop_press(&cx), vec![Action::Cancel]);
|
||||
assert!(!t.busy());
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Up, 130.0, 140.0)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_dragged_out_of_the_object_is_removed() {
|
||||
let (d, s) = doc(FreeformMode::Points);
|
||||
@@ -474,6 +500,11 @@ mod tests {
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 120.0, 120.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 60.0, 60.0));
|
||||
assert_eq!(t.key(&cx, ToolKey::Escape, Default::default()), vec![Action::Cancel, select(Some(0))]);
|
||||
// Also after the drag came back inside.
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 120.0, 120.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 60.0, 60.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 110.0, 110.0));
|
||||
assert_eq!(t.key(&cx, ToolKey::Escape, Default::default()), vec![Action::Cancel, select(Some(0))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Loaded 100 of 178 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user