diff --git a/ASSETS.md b/ASSETS.md index db2a978163..aa3bfeda0f 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -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 | diff --git a/Cargo.lock b/Cargo.lock index 72b06a51a6..137e9a2be7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -970,17 +970,17 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1003,7 +1003,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "egui", "serde", @@ -1013,7 +1013,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1024,9 +1024,10 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "craft-winprint-gdi", + "log", "miniz_oxide 0.9.1", "roxmltree 0.21.2", "tempfile", @@ -1037,7 +1038,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1095,7 +1096,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "egui", "objc2 0.6.5", @@ -2205,7 +2206,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "brotli", "hayro-postscript", @@ -2214,7 +2215,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -2232,7 +2233,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -2250,12 +2251,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "flate2", "hayro-ccitt", @@ -2863,7 +2864,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=fb08be5fa19eee8d37e624397fcdc96df6035e92#fb08be5fa19eee8d37e624397fcdc96df6035e92" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "base64 0.22.1", "bumpalo", @@ -6072,7 +6073,7 @@ dependencies = [ [[package]] name = "vectorcraft" -version = "0.20.0" +version = "0.21.0" dependencies = [ "arboard", "block2 0.6.2", @@ -6117,7 +6118,7 @@ dependencies = [ [[package]] name = "vectorcraft-affinity" -version = "0.20.0" +version = "0.21.0" dependencies = [ "crc32fast", "flate2", @@ -6128,7 +6129,7 @@ dependencies = [ [[package]] name = "vectorcraft-brush" -version = "0.20.0" +version = "0.21.0" dependencies = [ "kurbo 0.13.1", "serde", @@ -6140,7 +6141,7 @@ dependencies = [ [[package]] name = "vectorcraft-cad" -version = "0.20.0" +version = "0.21.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6156,7 +6157,7 @@ dependencies = [ [[package]] name = "vectorcraft-cli" -version = "0.20.0" +version = "0.21.0" dependencies = [ "log", "objc2-core-foundation", @@ -6178,7 +6179,7 @@ dependencies = [ [[package]] name = "vectorcraft-color" -version = "0.20.0" +version = "0.21.0" dependencies = [ "kurbo 0.13.1", "moxcms", @@ -6190,7 +6191,7 @@ dependencies = [ [[package]] name = "vectorcraft-doc" -version = "0.20.0" +version = "0.21.0" dependencies = [ "chrono", "hayro-ccitt", @@ -6209,7 +6210,7 @@ dependencies = [ [[package]] name = "vectorcraft-effects" -version = "0.20.0" +version = "0.21.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6225,7 +6226,7 @@ dependencies = [ [[package]] name = "vectorcraft-engine" -version = "0.20.0" +version = "0.21.0" dependencies = [ "cfb", "chrono", @@ -6267,7 +6268,7 @@ dependencies = [ [[package]] name = "vectorcraft-eps" -version = "0.20.0" +version = "0.21.0" dependencies = [ "fax", "flate2", @@ -6291,7 +6292,7 @@ dependencies = [ [[package]] name = "vectorcraft-format" -version = "0.20.0" +version = "0.21.0" dependencies = [ "craft-vectorcraft-format", "flate2", @@ -6307,7 +6308,7 @@ dependencies = [ [[package]] name = "vectorcraft-geom" -version = "0.20.0" +version = "0.21.0" dependencies = [ "kurbo 0.13.1", "proptest", @@ -6319,7 +6320,7 @@ dependencies = [ [[package]] name = "vectorcraft-mcp" -version = "0.20.0" +version = "0.21.0" dependencies = [ "image", "log", @@ -6338,7 +6339,7 @@ dependencies = [ [[package]] name = "vectorcraft-metafile" -version = "0.20.0" +version = "0.21.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6352,7 +6353,7 @@ dependencies = [ [[package]] name = "vectorcraft-pathops" -version = "0.20.0" +version = "0.21.0" dependencies = [ "kurbo 0.13.1", "linesweeper", @@ -6364,7 +6365,7 @@ dependencies = [ [[package]] name = "vectorcraft-pdf" -version = "0.20.0" +version = "0.21.0" dependencies = [ "aes", "chrono", @@ -6396,7 +6397,7 @@ dependencies = [ [[package]] name = "vectorcraft-plugins" -version = "0.20.0" +version = "0.21.0" dependencies = [ "serde", "serde_json", @@ -6410,7 +6411,7 @@ dependencies = [ [[package]] name = "vectorcraft-render" -version = "0.20.0" +version = "0.21.0" dependencies = [ "flate2", "gif 0.14.2", @@ -6440,14 +6441,14 @@ dependencies = [ [[package]] name = "vectorcraft-scriptcheck" -version = "0.20.0" +version = "0.21.0" dependencies = [ "proptest", ] [[package]] name = "vectorcraft-svg" -version = "0.20.0" +version = "0.21.0" dependencies = [ "craft-docpath", "flate2", @@ -6457,6 +6458,7 @@ dependencies = [ "resvg", "serde", "serde_json", + "simplecss", "skrifa 0.47.0", "svgtypes 0.16.1", "thiserror 2.0.21", @@ -6472,7 +6474,7 @@ dependencies = [ [[package]] name = "vectorcraft-testkit" -version = "0.20.0" +version = "0.21.0" dependencies = [ "fax", "image", @@ -6490,7 +6492,7 @@ dependencies = [ [[package]] name = "vectorcraft-text" -version = "0.20.0" +version = "0.21.0" dependencies = [ "harfrust 0.13.3", "icu_segmenter", @@ -6511,7 +6513,7 @@ dependencies = [ [[package]] name = "vectorcraft-three-d" -version = "0.20.0" +version = "0.21.0" dependencies = [ "vectorcraft-geom", "vectorcraft-pathops", @@ -6519,7 +6521,7 @@ dependencies = [ [[package]] name = "vectorcraft-tools" -version = "0.20.0" +version = "0.21.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6536,7 +6538,7 @@ dependencies = [ [[package]] name = "vectorcraft-trace" -version = "0.20.0" +version = "0.21.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6548,7 +6550,7 @@ dependencies = [ [[package]] name = "vectorcraft-ui-egui" -version = "0.20.0" +version = "0.21.0" dependencies = [ "bytemuck", "craft-keymap", @@ -6586,7 +6588,7 @@ dependencies = [ [[package]] name = "vectorcraft-web" -version = "0.20.0" +version = "0.21.0" dependencies = [ "eframe", "egui", @@ -6753,12 +6755,12 @@ dependencies = [ [[package]] name = "wasm-encoder" -version = "0.262.0" +version = "0.263.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +checksum = "0b883a26aea02eaabe2d2c3fba7eb039ef5cdcb5d5201ae5551e73d5e251a81f" dependencies = [ "leb128fmt", - "wasmparser 0.262.0", + "wasmparser 0.263.0", ] [[package]] @@ -6813,9 +6815,9 @@ dependencies = [ [[package]] name = "wasmparser" -version = "0.262.0" +version = "0.263.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +checksum = "4f5fa0a054ae153606df820eb0a84213e28cda41bbe04ba2628e71b6ba100fcb" dependencies = [ "bitflags 2.13.2", "indexmap", @@ -6824,9 +6826,9 @@ dependencies = [ [[package]] name = "wast" -version = "262.0.0" +version = "263.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30612a0c29249b5f185888a107e8a519d920226b7d07f9d351fd094e9f75eb23" +checksum = "69d90bcf581b501aa1c358bc5dc0faa979cd375796908860ebcb6d1d70b907c7" dependencies = [ "bumpalo", "leb128fmt", @@ -6837,9 +6839,9 @@ dependencies = [ [[package]] name = "wat" -version = "1.262.0" +version = "1.263.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e228027f2b07bbaf946980ebbe2437fca73be6f54c40c2a8d4f42f277075f8d1" +checksum = "bbc9c5aca783b3f1838be89f3f9937c528b90ec5faa6fb62d809726c16a7d8f7" dependencies = [ "wast", ] @@ -7717,7 +7719,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.20.0" +version = "0.21.0" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index fe54598299..1af59ddfe4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,21 +4,21 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"] [workspace.package] -version = "0.20.0" +version = "0.21.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", default-features = false, features = ["interpret", "write"] } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] } -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", default-features = false, features = ["interpret", "write"] } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["serde"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } # Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["egui"] } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "14d5dbb50c317b8747a9cf9eb35ab8a22515f137" } # craft-update: app-specific pretend versions apply to startup and manual checks. @@ -147,14 +147,12 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -# The PDF writer takes craft-libs#417 (CMYK, gray and spot colors keep their exact inks); the other -# craft-libs crates stay at 92d392cf. craft-pdf's sources are the same at both revisions. -krilla = { git = "https://github.com/storytold/craft-libs", rev = "fb08be5fa19eee8d37e624397fcdc96df6035e92" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/NOTICE b/NOTICE index 0d0758820e..002fa016ac 100644 --- a/NOTICE +++ b/NOTICE @@ -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. diff --git a/ROADMAP.md b/ROADMAP.md index 8ebfd65222..6cf80d3628 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,5 +1,7 @@ # VectorCraft Roadmap +- Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged. + - PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document. - PDF.W1: PDF export and print composition use the shared optional writer for configuration, metadata, font preparation and guarded finalization; drawing and output policy remain app-owned. @@ -9,7 +11,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Color Effects add-on's Find Nearest Swatch; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -129,6 +131,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923). - 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). @@ -137,6 +140,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. +- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. - 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged. @@ -214,6 +218,8 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. | +| 2026-11-02 | minor | Closed font-family fields accept wheel input for selected text in Character, Properties and Control (#5253); scores and estimates unchanged. | | 2026-11-01 | minor | Progress log row for the Color Effects add-on's Find Nearest Swatch (#4923); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for the Path Precision Tools add-on's Expand Dashes into Paths (#4922); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Randomize Opacity (#4925); headline numbers unchanged. | diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index cec7fca1fb..59b30b7649 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -157,6 +157,10 @@ fn copied_file(paths: Vec, mimes: &[&'static str]) -> Option { None if vectorcraft_engine::file_access::current().is_none() => {} None => return None, } + // A device or pipe may never end: only a regular file is read whole. + if !std::fs::metadata(&path).ok()?.is_file() { + return None; + } let mut head = Vec::with_capacity(FILE_HEAD); std::fs::File::open(&path).ok()?.take(FILE_HEAD as u64).read_to_end(&mut head).ok()?; let mime = file_flavour(&path.to_string_lossy(), &head, mimes)?; diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index e25332b61a..16fe1d469c 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -151,6 +151,22 @@ fn reveal_command(path: &str) -> std::process::Command { c } +/// Read a whole file. A device or pipe may never end: only a regular file is read. +fn read_file(path: &str) -> Result, String> { + if !std::fs::metadata(path).map_err(|e| e.to_string())?.is_file() { + return Err(format!("{path}: not a file")); + } + std::fs::read(path).map_err(|e| e.to_string()) +} + +#[cfg(test)] +#[test] +fn read_file_refuses_what_is_not_a_regular_file() { + assert!(read_file(&std::env::temp_dir().to_string_lossy()).is_err()); + #[cfg(unix)] + assert!(read_file("/dev/zero").is_err()); +} + /// Write a file the safe way: a failed write keeps the old file ([`fileio::write_atomic`]). fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> { fileio::write_atomic(std::path::Path::new(path), bytes).map_err(|e| e.to_string()) @@ -277,7 +293,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { // Windows reads it from the pen's pointer messages (`windows_stylus`). #[cfg(windows)] stylus: Some(windows_stylus::start()), - read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), + read: Some(Box::new(read_file)), write: Some(Box::new(write_file)), exists: Some(Box::new(|p: &str| std::path::Path::new(p).exists())), // Background Save and Export write from a worker thread. @@ -300,6 +316,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { reveal: Some(Box::new(reveal)), // Links panel: Edit Original; Package: Show Package. Relink to Folder and Package pick folders. open_file: Some(Box::new(open_file)), + // Edit Original of a raster image with Use System Defaults for Edit Original off (#5236). + open_in_photocraft: Some(Box::new(open_in_photocraft)), pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())), // Sample Color from Screen: the system's color sampler. #[cfg(target_os = "macos")] @@ -334,3 +352,281 @@ fn open_file(path: &str) -> Result<(), String> { c.arg(path); c.spawn().map(|_| ()).map_err(|e| format!("can't open {path}: {e}")) } + +/// Edit Original with Preferences › File Handling › Use System Defaults for Edit Original off +/// (#5236): open the raster image `path` in PhotoCraft, found only where it installs +/// ([`find_photocraft`]); `Ok(false)` when it isn't installed. PhotoCraft gets the path as its only +/// argument and is never started through a shell. +fn open_in_photocraft(path: &str) -> Result { + explorer_safe(path)?; + let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(std::path::PathBuf::from); + let Some(app) = find_photocraft(home.as_deref(), std::env::var_os("PATH").as_deref()) else { return Ok(false) }; + #[cfg(target_os = "macos")] + let mut c = { + let mut c = std::process::Command::new("open"); + c.arg("-a").arg(&app).arg(path); + c + }; + #[cfg(not(target_os = "macos"))] + let mut c = { + let mut c = std::process::Command::new(&app); + c.arg(path); + c + }; + // macOS: `open` returns once Launch Services has the request, so a short wait reports an app + // it can't open (a folder named `.app` that isn't a bundle). The wait is capped so a stalled + // `open` never holds the window: past it, the launch is left to run. Elsewhere the editor + // itself runs: waiting would last until it closes. + #[cfg(target_os = "macos")] + { + const WAIT: std::time::Duration = std::time::Duration::from_secs(2); + let fail = |why: String| format!("can't open {path} in {}: {why}", app.display()); + let mut child = c.stderr(std::process::Stdio::piped()).spawn().map_err(|e| fail(e.to_string()))?; + let started = std::time::Instant::now(); + loop { + match child.try_wait() { + Ok(Some(status)) if status.success() => return Ok(true), + Ok(Some(status)) => { + let mut why = String::new(); + if let Some(mut err) = child.stderr.take() { + // Best effort: without its message the exit status says why. + let _ = std::io::Read::read_to_string(&mut err, &mut why); + } + let why = why.trim().to_string(); + return Err(fail(if why.is_empty() { status.to_string() } else { why })); + } + Ok(None) if started.elapsed() < WAIT => std::thread::sleep(std::time::Duration::from_millis(20)), + Ok(None) => { + // Reaped off the UI thread once it ends. + std::thread::spawn(move || { + let _ = child.wait(); + }); + return Ok(true); + } + Err(e) => return Err(fail(e.to_string())), + } + } + } + #[cfg(not(target_os = "macos"))] + c.spawn().map(|_| true).map_err(|e| format!("can't open {path} in {}: {e}", app.display())) +} + +/// PhotoCraft where it is installed: the first of [`photocraft_candidates`] that is an application. +pub(crate) fn find_photocraft(home: Option<&std::path::Path>, path_var: Option<&std::ffi::OsStr>) -> Option { + photocraft_candidates(home, path_var).into_iter().find(|p| check_app(p).is_ok()) +} + +/// Where PhotoCraft may be installed: the Applications folders on macOS; on Windows where its +/// installer puts it ([`windows_candidates`]); else a `photocraft` program on the `PATH`. +pub(crate) fn photocraft_candidates(home: Option<&std::path::Path>, path_var: Option<&std::ffi::OsStr>) -> Vec { + if cfg!(target_os = "macos") { + let mut v = vec![std::path::PathBuf::from("/Applications/PhotoCraft.app")]; + v.extend(home.map(|h| h.join("Applications/PhotoCraft.app"))); + return v; + } + let name = if cfg!(windows) { "photocraft.exe" } else { "photocraft" }; + let on_path = path_var.map(|p| std::env::split_paths(p).map(|dir| dir.join(name)).collect()).unwrap_or_default(); + if cfg!(windows) { + let folders: Vec = [ + std::env::var_os("LOCALAPPDATA").map(|d| std::path::PathBuf::from(d).join("Programs")), + std::env::var_os("ProgramW6432").map(std::path::PathBuf::from), + std::env::var_os("ProgramFiles").map(std::path::PathBuf::from), + ] + .into_iter() + .flatten() + .collect(); + return windows_candidates(registered_photocraft(), &folders, on_path); + } + on_path +} + +/// Windows: PhotoCraft's installer puts it in `ArtCraft\PhotoCraft` under a folder of +/// `program_folders` (for the current user `%LOCALAPPDATA%\Programs`, for everyone Program Files) +/// and registers its path under App Paths, which also covers a folder chosen in setup. So: the +/// `registered` paths first, then those folders, then `on_path`. +pub(crate) fn windows_candidates( + registered: Vec, + program_folders: &[std::path::PathBuf], + on_path: Vec, +) -> Vec { + let mut v = registered; + for f in program_folders { + let p = f.join("ArtCraft").join("PhotoCraft").join("photocraft.exe"); + if !v.contains(&p) { + v.push(p); + } + } + v.extend(on_path); + v +} + +/// The paths PhotoCraft's installer registers under App Paths, for the current user and then for +/// everyone (`reg query`, so no extra dependency; a hidden console window). +#[cfg(windows)] +fn registered_photocraft() -> Vec { + use std::os::windows::process::CommandExt as _; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + // reg.exe by its full path, so nothing named `reg` in the app's folder or on PATH runs instead. + let root = std::env::var_os("SystemRoot").map(std::path::PathBuf::from).unwrap_or_else(|| r"C:\Windows".into()); + ["HKCU", "HKLM"] + .into_iter() + .filter_map(|hive| { + let key = format!(r"{hive}\Software\Microsoft\Windows\CurrentVersion\App Paths\photocraft.exe"); + let out = std::process::Command::new(root.join("System32").join("reg.exe")) + .args(["query", &key, "/ve"]) + .creation_flags(CREATE_NO_WINDOW) + .output() + .ok()?; + registered_path(&String::from_utf8_lossy(&out.stdout)) + }) + .collect() +} + +#[cfg(not(windows))] +fn registered_photocraft() -> Vec { + Vec::new() +} + +/// The path in `reg query … /ve` output like +/// ` (Default) REG_SZ C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe`. +#[cfg_attr(not(any(windows, test)), allow(dead_code))] +pub(crate) fn registered_path(text: &str) -> Option { + text.lines().find_map(|l| l.split_once("REG_SZ")).map(|(_, v)| v.trim().trim_matches('"')).filter(|v| !v.is_empty()).map(std::path::PathBuf::from) +} + +/// Is `app` an application Edit Original may start: an `.app` bundle on macOS, an `.exe` on +/// Windows, an executable file elsewhere? Anything else (a document, a folder, a script on +/// Windows) found where PhotoCraft installs is not taken for it. +pub(crate) fn check_app(app: &std::path::Path) -> Result<(), String> { + let ext = app.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); + let ok = if cfg!(target_os = "macos") { + ext == "app" && app.is_dir() + } else if cfg!(windows) { + ext == "exe" && app.is_file() + } else { + executable_file(app) + }; + if ok { Ok(()) } else { Err(format!("{} isn't an application Edit Original can open files in", app.display())) } +} + +#[cfg(unix)] +fn executable_file(p: &std::path::Path) -> bool { + use std::os::unix::fs::PermissionsExt as _; + std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) +} + +#[cfg(not(unix))] +fn executable_file(p: &std::path::Path) -> bool { + p.is_file() +} + +#[cfg(test)] +mod open_with_tests { + use super::{check_app, find_photocraft, photocraft_candidates, registered_path, windows_candidates}; + + /// A fresh, empty folder under the system's temporary folder. + fn scratch(name: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("vc-open-with-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + /// #5236: only an application counts as PhotoCraft, never a document, a folder or a missing + /// path. + #[test] + fn only_applications_are_started() { + let d = scratch("check"); + let doc = d.join("notes.txt"); + std::fs::write(&doc, "hi").unwrap(); + assert!(check_app(&doc).is_err(), "a document"); + assert!(check_app(&d).is_err(), "a folder"); + assert!(check_app(&d.join("Missing.app")).is_err(), "a missing path"); + if cfg!(target_os = "macos") { + let app = d.join("Editor.app"); + std::fs::create_dir_all(&app).unwrap(); + assert!(check_app(&app).is_ok(), "an .app bundle"); + } + #[cfg(all(unix, not(target_os = "macos")))] + { + use std::os::unix::fs::PermissionsExt as _; + let tool = d.join("editor"); + std::fs::write(&tool, "#!/bin/sh\n").unwrap(); + assert!(check_app(&tool).is_err(), "not executable yet"); + std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert!(check_app(&tool).is_ok(), "an executable file"); + } + let _ = std::fs::remove_dir_all(&d); + } + + /// PhotoCraft is looked for only where it installs. + #[test] + fn photocraft_is_found_where_it_installs() { + let d = scratch("find"); + if cfg!(target_os = "macos") { + let candidates = photocraft_candidates(Some(&d), None); + assert_eq!(candidates.first().map(|p| p.to_string_lossy().into_owned()).as_deref(), Some("/Applications/PhotoCraft.app")); + assert!(candidates.contains(&d.join("Applications/PhotoCraft.app")), "{candidates:?}"); + std::fs::create_dir_all(d.join("Applications/PhotoCraft.app")).unwrap(); + assert!(find_photocraft(Some(&d), None).unwrap().ends_with("PhotoCraft.app")); + } else { + let bin = d.join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + let path_var = std::env::join_paths([&bin]).unwrap(); + // On Windows an installed PhotoCraft (registered, or in a program folder) comes first, so + // there only the `PATH` candidate is checked. + if !cfg!(windows) { + assert!(find_photocraft(None, Some(&path_var)).is_none(), "not installed"); + } + let exe = bin.join(if cfg!(windows) { "photocraft.exe" } else { "photocraft" }); + std::fs::write(&exe, "").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + if cfg!(windows) { + assert_eq!(photocraft_candidates(None, Some(&path_var)).last(), Some(&exe)); + assert!(check_app(&exe).is_ok()); + } else { + assert_eq!(find_photocraft(None, Some(&path_var)), Some(exe)); + } + } + let _ = std::fs::remove_dir_all(&d); + } + + /// #5327 review: on Windows PhotoCraft is looked for where its installer puts it: the path it + /// registers, then `ArtCraft\PhotoCraft` in the per-user and per-machine program folders, then + /// the `PATH`. + #[test] + fn windows_looks_where_the_photocraft_installer_puts_it() { + use std::path::PathBuf; + let registered = vec![PathBuf::from("D:/Tools/PhotoCraft/photocraft.exe")]; + let folders = [PathBuf::from("C:/Users/me/AppData/Local/Programs"), PathBuf::from("C:/Program Files"), PathBuf::from("C:/Program Files")]; + let on_path = vec![PathBuf::from("C:/bin/photocraft.exe")]; + let exe = |f: &str| PathBuf::from(f).join("ArtCraft").join("PhotoCraft").join("photocraft.exe"); + assert_eq!( + windows_candidates(registered, &folders, on_path), + [ + PathBuf::from("D:/Tools/PhotoCraft/photocraft.exe"), + exe("C:/Users/me/AppData/Local/Programs"), + exe("C:/Program Files"), + PathBuf::from("C:/bin/photocraft.exe"), + ] + ); + } + + /// The registered path is read from `reg query … /ve` output, spaces and quotes included; + /// no value, no path. + #[test] + fn the_registered_path_is_read_from_reg_query() { + let out = "\r\nHKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\photocraft.exe\r\n (Default) REG_SZ C:\\Program Files\\ArtCraft\\PhotoCraft\\photocraft.exe\r\n"; + assert_eq!(registered_path(out), Some(std::path::PathBuf::from(r"C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe"))); + assert_eq!( + registered_path(" (Standard) REG_SZ \"C:\\A B\\photocraft.exe\""), + Some(std::path::PathBuf::from(r"C:\A B\photocraft.exe")) + ); + assert_eq!(registered_path("ERROR: The system was unable to find the specified registry key or value."), None); + assert_eq!(registered_path(" (Default) REG_SZ "), None); + } +} diff --git a/apps/vectorcraft/src/portal_save.rs b/apps/vectorcraft/src/portal_save.rs index b6dd3cc8e9..0357829aec 100644 --- a/apps/vectorcraft/src/portal_save.rs +++ b/apps/vectorcraft/src/portal_save.rs @@ -96,6 +96,12 @@ fn answer(code: u32, results: &HashMap) -> Result) = v.try_clone().ok()?.try_into().ok()?; Some(label) @@ -103,9 +109,9 @@ fn answer(code: u32, results: &HashMap) -> Result Option { +/// `file:///home/me/A%20b.svg` → `/home/me/A b.svg` (its bytes); `None` for a file elsewhere +/// (`file://host/`) or another scheme. +fn file_uri_path(uri: &str) -> Option> { let rest = uri.strip_prefix("file://")?; let rest = rest.strip_prefix("localhost").unwrap_or(rest); if !rest.starts_with('/') { @@ -126,8 +132,7 @@ fn file_uri_path(uri: &str) -> Option { } } } - // `show_dialog` makes rfd's path a string with `to_string_lossy` too. - Some(String::from_utf8_lossy(&out).into_owned()) + Some(out) } /// `saved` as the answer of the save dialog for `request`: the path, then the first extension of @@ -406,6 +411,7 @@ mod tests { #[test] fn file_uris_become_local_paths() { + let file_uri_path = |uri: &str| super::file_uri_path(uri).map(|b| String::from_utf8(b).unwrap()); assert_eq!(file_uri_path("file:///home/me/Untitled-1.vectorcraft").as_deref(), Some("/home/me/Untitled-1.vectorcraft")); assert_eq!(file_uri_path("file:///home/me/A%20b%C3%A9.svg").as_deref(), Some("/home/me/A bé.svg")); assert_eq!(file_uri_path("file://localhost/tmp/x.pdf").as_deref(), Some("/tmp/x.pdf")); @@ -413,6 +419,9 @@ mod tests { assert_eq!(file_uri_path("file:///tmp/100%+1%2").as_deref(), Some("/tmp/100%+1%2")); assert_eq!(file_uri_path("file://host/x.svg"), None); assert_eq!(file_uri_path("sftp://host/x.svg"), None); + // Not UTF-8: the bytes as they are, which `answer` refuses rather than changing them. + assert_eq!(super::file_uri_path("file:///tmp/a%FF.svg"), Some(b"/tmp/a\xff.svg".to_vec())); + assert!(matches!(answer(0, &results("file:///tmp/a%FF.svg", None)), Ok(None))); } #[test] diff --git a/apps/vectorcraft/src/prefs.rs b/apps/vectorcraft/src/prefs.rs index cf4e59b28d..a6daacb83a 100644 --- a/apps/vectorcraft/src/prefs.rs +++ b/apps/vectorcraft/src/prefs.rs @@ -62,7 +62,12 @@ pub(crate) fn keep_prefs_copy(path: &std::path::Path, bytes: &[u8], stem: &str) use std::io::Write as _; for n in 1..100u32 { let name = if n == 1 { format!("{stem}.json") } else { format!("{stem}-{n}.json") }; - match std::fs::OpenOptions::new().write(true).create_new(true).open(path.with_file_name(name)) { + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + // The preferences hold recent document paths: the copy is owner-only, whatever the umask. + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + match options.open(path.with_file_name(name)) { Ok(mut file) => { if file.write_all(bytes).is_ok() { return; @@ -312,6 +317,8 @@ pub(crate) fn prefs_bytes(app: &VectorcraftApp) -> serde_json::Result> { /// [`prefs_bytes`] as JSON. fn prefs_value(app: &VectorcraftApp) -> serde_json::Result { let mut ui = app.ui.clone(); + // An open dialog is never restored, and its fields can hold passwords (PDF import and save). + ui.dialog = None; ui.engine_prefs = app.session.prefs.to_json(); serde_json::to_value(&ui) } @@ -324,6 +331,19 @@ mod tests { /// Two windows open at once (#4625): the one that saves last keeps the other's changes and /// adds its own, instead of putting back the preferences it started from. + #[cfg(unix)] + #[test] + fn a_kept_preferences_copy_is_owner_only() { + use std::os::unix::fs::PermissionsExt as _; + let dir = std::env::temp_dir().join(format!("vc-prefs-copy-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + super::keep_prefs_copy(&dir.join("ui.json"), b"{}", "ui.unreadable"); + let mode = std::fs::metadata(dir.join("ui.unreadable.json")).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn a_window_saves_only_what_it_changed_over_another_windows_save() { let base = json!({"workspace": "Essentials", "toolbar": true, "engine_prefs": {"uiAccent": "blue", "uiScaling": 1.0}}); diff --git a/apps/vectorcraft/src/profile.rs b/apps/vectorcraft/src/profile.rs index 4030d0aeae..8ef0355831 100644 --- a/apps/vectorcraft/src/profile.rs +++ b/apps/vectorcraft/src/profile.rs @@ -149,6 +149,15 @@ fn copy_dir(from: &Path, to: &Path) -> Result<(), String> { } } +/// Make folder `dir`, owner-only on Unix. +fn private_dir(dir: &Path) -> std::io::Result<()> { + let mut builder = std::fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] + std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700); + builder.create(dir) +} + fn copy_dir_into(from: &Path, to: &Path, skip: &mut impl FnMut(String)) { let entries = match std::fs::read_dir(from) { Ok(entries) => entries, @@ -165,7 +174,12 @@ fn copy_dir_into(from: &Path, to: &Path, skip: &mut impl FnMut(String)) { let (src, dst) = (entry.path(), to.join(entry.file_name())); // A symbolic link is copied as what it points to, or skipped when that is a folder. let copied = match entry.file_type() { - Ok(kind) if kind.is_dir() => std::fs::create_dir_all(&dst).map(|()| copy_dir_into(&src, &dst, skip)), + // The copy keeps the folder's permissions (a private recovery folder stays private): + // owner-only while it fills, then the source's. + Ok(kind) if kind.is_dir() => private_dir(&dst).and_then(|()| { + copy_dir_into(&src, &dst, skip); + std::fs::set_permissions(&dst, std::fs::metadata(&src)?.permissions()) + }), Ok(_) => std::fs::copy(&src, &dst).map(|_| ()), Err(e) => Err(e), }; @@ -387,4 +401,19 @@ mod tests { let _ = std::fs::remove_dir_all(&from); let _ = std::fs::remove_dir_all(&to); } + + #[cfg(unix)] + #[test] + fn a_copied_folder_keeps_its_permissions() { + use std::os::unix::fs::PermissionsExt as _; + let from = temp("copy-mode-from"); + let to = temp("copy-mode-to"); + std::fs::create_dir_all(from.join("recovery")).unwrap(); + std::fs::write(from.join("recovery/copy.vectorcraft"), b"unsaved").unwrap(); + std::fs::set_permissions(from.join("recovery"), std::fs::Permissions::from_mode(0o700)).unwrap(); + copy_dir(&from, &to).unwrap(); + assert_eq!(std::fs::metadata(to.join("recovery")).unwrap().permissions().mode() & 0o777, 0o700); + let _ = std::fs::remove_dir_all(&from); + let _ = std::fs::remove_dir_all(&to); + } } diff --git a/contributors/people.toml b/contributors/people.toml index f3c8629b71..db94e2a890 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -189,3 +189,7 @@ sync_github_name = false [people.WadahBadawi] display_name = "Wadah Badawi" sync_github_name = true + +[people.JonRC] +real_name = "Jonathan Cardoso" +display_name = "Jonathan Cardoso" diff --git a/crates/affinity/src/container.rs b/crates/affinity/src/container.rs index 6b1df95103..f26948e919 100644 --- a/crates/affinity/src/container.rs +++ b/crates/affinity/src/container.rs @@ -15,6 +15,13 @@ const DOCUMENT_KIND: &[u8; 4] = b"nsrP"; /// A save appends one table; real files have one to a few hundred. const MAX_TABLES: usize = 4096; +/// Allocation records read over the whole table chain. Each save lists every entry again, so a +/// document with a few hundred saves of a few thousand entries stays far below; tables whose +/// record regions overlap (or a table chain of thousands of huge tables) can't multiply the work. +const MAX_INDEX_RECORDS: usize = 1 << 22; +/// Bytes of entry names kept by the index (after lossy UTF-8 decoding, which can triple a name). +/// Real names (`doc.dat`, `d/12`) are a few bytes each. +const MAX_INDEX_NAME_BYTES: usize = 16 << 20; /// zstd window ceiling: real documents use a few MiB; this stops a header from reserving gigabytes. const MAX_ZSTD_WINDOW: u64 = 64 << 20; @@ -75,6 +82,9 @@ pub struct Archive<'a> { pub revisions: usize, extracted: usize, limits: Limits, + /// Entries whose extraction failed after their size was charged: asked again, they fail + /// again without being decompressed again. + failed: HashMap, } pub(crate) struct Cursor<'a> { @@ -157,7 +167,15 @@ pub fn header(bytes: &[u8]) -> Result { impl<'a> Archive<'a> { pub fn open(bytes: &'a [u8], limits: Limits) -> Result { + Self::open_within(bytes, limits, MAX_INDEX_RECORDS, MAX_INDEX_NAME_BYTES) + } + + /// [`Archive::open`] reading at most `max_records` allocation records and keeping at most + /// `max_name_bytes` bytes of entry names, both over the whole table chain. + pub(crate) fn open_within(bytes: &'a [u8], limits: Limits, max_records: usize, max_name_bytes: usize) -> Result { let header = header(bytes)?; + let mut records_left = max_records; + let mut name_bytes_left = max_name_bytes; // Newest record per id: (table date, table index, record). let mut latest: HashMap)> = HashMap::new(); let mut names: HashMap = HashMap::new(); @@ -189,6 +207,7 @@ impl<'a> Archive<'a> { let dirs = c.u16()?; c.take(1)?; for _ in 0..files { + records_left = records_left.checked_sub(1).ok_or(Error::Limit("too many archive entries"))?; let id = c.u32()?; let flag = c.u8()?; let mut record = None; @@ -224,8 +243,13 @@ impl<'a> Archive<'a> { } if flag == 0 { let len = usize::from(c.u16()?); - let name = String::from_utf8_lossy(c.take(len)?).into_owned(); - names.entry(id).or_insert(name); + let raw = c.take(len)?; + // Only the first name of an id is kept: later ones are not even decoded. + if let std::collections::hash_map::Entry::Vacant(slot) = names.entry(id) { + let name = String::from_utf8_lossy(raw); + name_bytes_left = name_bytes_left.checked_sub(name.len()).ok_or(Error::Limit("archive entry names too long"))?; + slot.insert(name.into_owned()); + } } // Equal dates: the first table in the chain (the newest) wins, as in afread. let replace = latest.get(&id).is_none_or(|(d, _, _)| date > *d); @@ -234,6 +258,7 @@ impl<'a> Archive<'a> { } } for _ in 0..dirs { + records_left = records_left.checked_sub(1).ok_or(Error::Limit("too many archive entries"))?; let len = usize::from(c.u16()?); c.take(10)?; c.take(len)?; @@ -241,12 +266,12 @@ impl<'a> Archive<'a> { } let mut entries = HashMap::new(); for (id, (_, _, record)) in latest { - if let (Some(mut e), Some(name)) = (record, names.get(&id)) { - e.name = name.clone(); + if let (Some(mut e), Some(name)) = (record, names.remove(&id)) { + e.name = name; entries.insert(e.name.clone(), e); } } - Ok(Self { bytes, header, entries, revisions: tables, extracted: 0, limits }) + Ok(Self { bytes, header, entries, revisions: tables, extracted: 0, limits, failed: HashMap::new() }) } pub fn entry(&self, name: &str) -> Option<&Entry> { @@ -279,7 +304,10 @@ impl<'a> Archive<'a> { } pub fn read(&mut self, name: &str) -> Result, Error> { - let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?.clone(); + if let Some(e) = self.failed.get(name) { + return Err(*e); + } + let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?; let size = usize::try_from(e.size).map_err(|_| Error::Limit("archive entry too large"))?; if size > self.limits.max_entry { return Err(Error::Limit("archive entry too large")); @@ -288,30 +316,41 @@ impl<'a> Archive<'a> { if total > self.limits.max_total { return Err(Error::Limit("document too large")); } - let mut c = Cursor::new(self.bytes, offset(e.offset)?); - if c.take(4)? != b"#Fil" { - return Err(Error::Malformed("archive entry has no data block")); - } - let method = e.compression & 3; - let stored_len = if matches!(method, 1 | 2) { e.compressed } else { e.size }; - let data = c.take(offset(stored_len)?)?; - let mut out = match method { - 1 => inflate(data, size)?, - 2 => unzstd(data, size)?, - _ => data.to_vec(), - }; - if out.len() != size { - return Err(Error::Malformed("archive entry size mismatch")); - } - unpredict(&mut out, e.compression)?; - if crc32fast::hash(&out) != e.crc { - return Err(Error::Malformed("archive entry checksum mismatch")); - } + // Charged before the work, and kept when it fails: an entry that fails its checksum + // can't be decompressed over and over for free. self.extracted = total; - Ok(out) + let result = extract(self.bytes, e, size); + if let Err(err) = result { + self.failed.insert(name.to_owned(), err); + } + result } } +/// Decompress entry `e` of `bytes` (declared `size` bytes), undo its predictor and check its CRC. +fn extract(bytes: &[u8], e: &Entry, size: usize) -> Result, Error> { + let mut c = Cursor::new(bytes, offset(e.offset)?); + if c.take(4)? != b"#Fil" { + return Err(Error::Malformed("archive entry has no data block")); + } + let method = e.compression & 3; + let stored_len = if matches!(method, 1 | 2) { e.compressed } else { e.size }; + let data = c.take(offset(stored_len)?)?; + let mut out = match method { + 1 => inflate(data, size)?, + 2 => unzstd(data, size)?, + _ => data.to_vec(), + }; + if out.len() != size { + return Err(Error::Malformed("archive entry size mismatch")); + } + unpredict(&mut out, e.compression)?; + if crc32fast::hash(&out) != e.crc { + return Err(Error::Malformed("archive entry checksum mismatch")); + } + Ok(out) +} + /// Read at most `size + 1` bytes so a stream that decodes past its declared size is caught /// without unbounded allocation. fn read_bounded(mut r: impl Read, size: usize) -> Result, Error> { diff --git a/crates/affinity/src/overlay.rs b/crates/affinity/src/overlay.rs index 170c50ec38..80f54f68e9 100644 --- a/crates/affinity/src/overlay.rs +++ b/crates/affinity/src/overlay.rs @@ -332,7 +332,7 @@ fn pixels(img: &mut Image, o: &Overlay) -> bool { }; let to_unit = match o.source { Source::Gradient(g) => match invert(g.transform) { - Some(m) => Some((img.transform.then(m), g)), + Some(m) => Some((img.transform.then(m), g, stop_reach(g))), None => return false, }, Source::Solid(_) => None, @@ -343,9 +343,9 @@ fn pixels(img: &mut Image, o: &Overlay) -> bool { } let (s, sa) = match (solid, &to_unit) { (Some(s), _) => s, - (None, Some((m, g))) => { + (None, Some((m, g, reach))) => { let q = m.apply(Point { x: (i % width) as f64 + 0.5, y: (i / width) as f64 + 0.5 }); - let c = sample(g, q); + let c = sample(g, reach, q); (rgb(c), c.alpha()) } (None, None) => continue, @@ -376,8 +376,22 @@ fn decode(bytes: &[u8], width: u32, height: u32) -> Option> { Some(reader.decode().ok()?.into_rgba8().into_raw()) } -/// The gradient's colour at unit-space point `q`. -fn sample(g: &Gradient, q: Point) -> Color { +/// For each pair of neighbouring stops (`k`, `k + 1`), the largest offset of stops `1..=k + 1`: +/// the first pair whose end offset a `t` doesn't pass is the first whose reach it doesn't pass, and +/// reaches never decrease, so [`sample`] finds it by binary search, sorted stops or not. +fn stop_reach(g: &Gradient) -> Vec { + g.stops + .iter() + .skip(1) + .scan(f64::NEG_INFINITY, |m, s| { + *m = m.max(s.offset); + Some(*m) + }) + .collect() +} + +/// The gradient's colour at unit-space point `q` (`reach`: [`stop_reach`] of `g`). +fn sample(g: &Gradient, reach: &[f64], q: Point) -> Color { let t = match g.kind { GradientKind::Linear => q.x, GradientKind::Radial => q.x.hypot(q.y), @@ -388,18 +402,16 @@ fn sample(g: &Gradient, q: Point) -> Color { if t <= first.offset { return first.color; } - for w in g.stops.windows(2) { - let [a, b] = [&w[0], &w[1]]; - if t <= b.offset { - let span = b.offset - a.offset; - let u = if span > 1e-9 { (t - a.offset) / span } else { 1.0 }; - // Affinity's midpoint bias (see `Stop::half_point`). - let k = 1.0 + 8.0 * (a.bias - 0.5).abs(); - let u = if a.bias >= 0.5 { u.powf(k) } else { 1.0 - (1.0 - u).powf(k) }; - let (x, y) = (rgb(a.color), rgb(b.color)); - let [r, g, bl] = [0, 1, 2].map(|i| x[i] + (y[i] - x[i]) * u); - return Color::Rgb { r, g, b: bl, a: a.color.alpha() + (b.color.alpha() - a.color.alpha()) * u }; - } + let k = reach.partition_point(|r| *r < t); + if let (Some(a), Some(b)) = (g.stops.get(k), g.stops.get(k + 1)) { + let span = b.offset - a.offset; + let u = if span > 1e-9 { (t - a.offset) / span } else { 1.0 }; + // Affinity's midpoint bias (see `Stop::half_point`). + let k = 1.0 + 8.0 * (a.bias - 0.5).abs(); + let u = if a.bias >= 0.5 { u.powf(k) } else { 1.0 - (1.0 - u).powf(k) }; + let (x, y) = (rgb(a.color), rgb(b.color)); + let [r, g, bl] = [0, 1, 2].map(|i| x[i] + (y[i] - x[i]) * u); + return Color::Rgb { r, g, b: bl, a: a.color.alpha() + (b.color.alpha() - a.color.alpha()) * u }; } last.color } diff --git a/crates/affinity/src/shapes.rs b/crates/affinity/src/shapes.rs index c5d1b31e0e..a2503539f4 100644 --- a/crates/affinity/src/shapes.rs +++ b/crates/affinity/src/shapes.rs @@ -13,8 +13,7 @@ const MAX_SIDES: i64 = 10_000; /// The last value of a tag: a shape changed from one kind to another keeps a stale first block. fn last<'a>(r: &'a Reader, id: ObjId, tag: &[u8; 4]) -> Option<&'a Value> { - let t = Tag::of(tag); - r.s.object(id)?.fields.iter().rev().find(|(k, _)| *k == t).map(|(_, v)| v) + r.s.object(id)?.get_last(Tag::of(tag)) } fn num(r: &Reader, id: ObjId, tag: &[u8; 4]) -> Option { @@ -51,12 +50,13 @@ pub(crate) fn shape(r: &mut Reader, shape: ObjId, b: [f64; 4], world: Affine) -> let class = r.s.class(shape)?; let sub = match &class.0.to_be_bytes() { b"ShNR" | b"ShRR" => { - let types = match last(r, shape, b"CTyp") { - Some(Value::Array(a)) => a.iter().map(|t| if let Value::Enum { id, .. } = t { Some(*id) } else { None }).collect(), + // Only the four corners' entries can matter: longer arrays are read no further. + let types: Vec> = match last(r, shape, b"CTyp") { + Some(Value::Array(a)) => a.iter().take(4).map(|t| if let Value::Enum { id, .. } = t { Some(*id) } else { None }).collect(), _ => Vec::new(), }; - let radii = match last(r, shape, b"ShCR") { - Some(Value::Floats(v)) => v.iter().map(|f| if f.is_finite() && *f > 0.0 { *f } else { 0.0 }).collect(), + let radii: Vec = match last(r, shape, b"ShCR") { + Some(Value::Floats(v)) => v.iter().take(4).map(|f| if f.is_finite() && *f > 0.0 { *f } else { 0.0 }).collect(), _ => Vec::new(), }; // Corners follow the first one (top left) unless they were unlocked; then each has diff --git a/crates/affinity/src/stream.rs b/crates/affinity/src/stream.rs index 7a3010251f..9d31f35e70 100644 --- a/crates/affinity/src/stream.rs +++ b/crates/affinity/src/stream.rs @@ -73,11 +73,67 @@ pub struct Object { pub chain: Vec, /// Fields in stream order; positional fields have tag 0. pub fields: Vec<(Tag, Value)>, + /// For objects with many fields: each tag with the positions of its first and last field, + /// sorted by tag, so a lookup isn't a scan of every field (a shared object is looked up + /// again on every visit). Built by [`Object::index`]; empty for small objects. + index: Vec<(Tag, u32, u32)>, } +/// Objects with more fields than this get an [`Object::index`]; fewer are scanned. +const INDEXED_FIELDS: usize = 16; + impl Object { + pub fn new(class: Tag, kind: Kind, chain: Vec, fields: Vec<(Tag, Value)>) -> Self { + let mut o = Self { class, kind, chain, fields, index: Vec::new() }; + o.index(); + o + } + + /// (Re)build the tag index after `fields` changed. + fn index(&mut self) { + self.index.clear(); + if self.fields.len() <= INDEXED_FIELDS { + return; + } + let mut index: Vec<(Tag, u32, u32)> = Vec::new(); + if index.try_reserve_exact(self.fields.len()).is_err() { + return; + } + // Fields beyond u32 positions are impossible: a stream holds at most MAX_VALUES values. + index.extend(self.fields.iter().enumerate().filter_map(|(i, (t, _))| u32::try_from(i).ok().map(|i| (*t, i, i)))); + // Stable: equal tags stay in stream order, so the run of a tag starts at its first field. + index.sort_by_key(|(t, _, _)| *t); + index.dedup_by(|later, first| { + if later.0 == first.0 { + first.2 = later.2; + true + } else { + false + } + }); + index.shrink_to_fit(); + self.index = index; + } + + fn position(&self, tag: Tag, last: bool) -> Option { + if self.index.is_empty() { + let mut fields = self.fields.iter().enumerate(); + let hit = if last { fields.rev().find(|(_, (t, _))| *t == tag) } else { fields.find(|(_, (t, _))| *t == tag) }; + return hit.map(|(i, _)| i); + } + let at = self.index.binary_search_by_key(&tag, |(t, _, _)| *t).ok()?; + let (_, first, end) = self.index.get(at)?; + usize::try_from(if last { *end } else { *first }).ok() + } + + /// The first field tagged `tag`. pub fn get(&self, tag: Tag) -> Option<&Value> { - self.fields.iter().find(|(t, _)| *t == tag).map(|(_, v)| v) + self.fields.get(self.position(tag, false)?).map(|(_, v)| v) + } + + /// The last field tagged `tag` (a shape changed from one kind to another keeps a stale first one). + pub fn get_last(&self, tag: Tag) -> Option<&Value> { + self.fields.get(self.position(tag, true)?).map(|(_, v)| v) } } @@ -124,10 +180,11 @@ pub fn parse(bytes: &[u8]) -> Result { c.u32()?; } let mut p = Parser { c, objects: Vec::new(), shared: std::collections::HashMap::new(), depth: 0, values: 0 }; - let root = p.push(Object { class, kind: Kind::Root, chain: vec![class], fields: Vec::new() })?; + let root = p.push(Object::new(class, Kind::Root, vec![class], Vec::new()))?; let fields = p.fields(true, class)?; if let Some(o) = p.objects.get_mut(root) { o.fields = fields; + o.index(); } Ok(Stream { root, objects: p.objects }) } @@ -252,7 +309,7 @@ impl Parser<'_> { } 0x30 => { let fields = self.fields(false, class)?; - let id = self.push(Object { class, kind: Kind::Positional, chain: Vec::new(), fields })?; + let id = self.push(Object::new(class, Kind::Positional, Vec::new(), fields))?; Value::Obj(Some(id)) } 0x31 | 0x32 if !tagged => return Err(Error::Malformed("object without a field tag")), @@ -354,7 +411,7 @@ impl Parser<'_> { } }; let fields = self.fields(true, class)?; - let id = self.push(Object { class, kind: Kind::Inline, chain: vec![class], fields })?; + let id = self.push(Object::new(class, Kind::Inline, vec![class], fields))?; Ok(Value::Obj(Some(id))) } @@ -373,7 +430,7 @@ impl Parser<'_> { return Err(Error::Malformed("object defined twice")); } // Register before the fields: an object's own fields may refer back to it. - let id = self.push(Object { class: Tag(0), kind: Kind::Shared, chain: Vec::new(), fields: Vec::new() })?; + let id = self.push(Object::new(Tag(0), Kind::Shared, Vec::new(), Vec::new()))?; self.shared.insert(key, id); let mut chain = Vec::new(); let mut fields = Vec::new(); @@ -399,8 +456,36 @@ impl Parser<'_> { let class = chain.first().copied().unwrap_or(Tag(0)); fields.extend(self.fields(true, class)?); if let Some(o) = self.objects.get_mut(id) { - *o = Object { class, kind: Kind::Shared, chain, fields }; + *o = Object::new(class, Kind::Shared, chain, fields); } Ok(Value::Obj(Some(id))) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lookups_in_a_large_object_find_the_first_and_last_fields_of_a_tag() { + let tag = |i: u32| Tag(0x4100_0000 + i); + let mut fields: Vec<(Tag, Value)> = (0..1000).map(|i| (tag(i % 300), Value::UInt(u64::from(i)))).collect(); + fields.push((tag(7), Value::Str("last".into()))); + let o = Object::new(Tag::of(b"Grup"), Kind::Shared, Vec::new(), fields.clone()); + assert!(!o.index.is_empty()); + // The index has one entry per distinct tag, not per field. + assert_eq!(o.index.len(), 300); + for t in 0..300 { + let first = fields.iter().find(|(k, _)| *k == tag(t)).map(|(_, v)| v); + let last = fields.iter().rev().find(|(k, _)| *k == tag(t)).map(|(_, v)| v); + assert_eq!(o.get(tag(t)), first); + assert_eq!(o.get_last(tag(t)), last); + } + assert_eq!(o.get(tag(300)), None); + assert_eq!(o.get_last(tag(7)), Some(&Value::Str("last".into()))); + let small = Object::new(Tag::of(b"Grup"), Kind::Shared, Vec::new(), vec![(tag(1), Value::Bool(true)), (tag(1), Value::Bool(false))]); + assert!(small.index.is_empty()); + assert_eq!(small.get(tag(1)), Some(&Value::Bool(true))); + assert_eq!(small.get_last(tag(1)), Some(&Value::Bool(false))); + } +} diff --git a/crates/affinity/src/tests.rs b/crates/affinity/src/tests.rs index eeb709d34d..75b6b7b146 100644 --- a/crates/affinity/src/tests.rs +++ b/crates/affinity/src/tests.rs @@ -261,6 +261,34 @@ mod archive { assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_)))); } + #[test] + fn an_entry_that_fails_its_checksum_is_charged_once_and_not_decompressed_again() { + let d = doc(); + let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None); + let mut broken = file.clone(); + broken[90] ^= 0x55; + let mut a = Archive::open(&broken, Limits::default()).unwrap(); + let first = a.read("doc.dat").unwrap_err(); + // The work was done, so it counts against the import even though it failed. + assert_eq!(a.extracted(), d.len()); + assert_eq!(a.read("doc.dat").unwrap_err(), first); + assert_eq!(a.extracted(), d.len()); + // A budget that only covers one attempt is not exceeded by asking again. + let mut a = Archive::open(&broken, Limits { max_entry: usize::MAX, max_total: d.len() }).unwrap(); + assert!(a.read("doc.dat").is_err()); + assert_eq!(a.read("doc.dat").unwrap_err(), first); + } + + #[test] + fn the_table_index_has_a_budget_for_records_and_names() { + let d = doc(); + let long = "n".repeat(300); + let file = synth::container(&[("doc.dat", &d, Method::Stored), (&long, b"tile", Method::Stored)], None); + Archive::open_within(&file, Limits::default(), 2, 307).unwrap(); + assert_eq!(Archive::open_within(&file, Limits::default(), 1, 1 << 20).unwrap_err(), Error::Limit("too many archive entries")); + assert_eq!(Archive::open_within(&file, Limits::default(), 2, 306).unwrap_err(), Error::Limit("archive entry names too long")); + } + // Regression test for #1710: ruzstd 0.9.0 let a block decompress to more than its frame's // window allows (RUSTSEC-2026-0344), so a crafted entry made the decoder produce far more than // the format permits for a block. 0.9.1 refuses it. diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 60e8a0234d..093ce531a9 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -781,10 +781,9 @@ pub fn unique_name(lib: &[Brush], base: &str) -> String { return base.to_string(); } // At most `lib.len()` names are taken, so one of the first `lib.len() + 1` candidates is free. - (2..=lib.len() + 2) - .map(|i| format!("{base} {i}")) - .find(|n| !lib.iter().any(|b| &b.name == n)) - .unwrap_or_else(|| format!("{base} {}", lib.len() + 2)) + // Each is looked up in a set: scanning the library per candidate is quadratic in its size. + let taken: std::collections::HashSet<&str> = lib.iter().map(|b| b.name.as_str()).collect(); + (2..=lib.len() + 2).map(|i| format!("{base} {i}")).find(|n| !taken.contains(n.as_str())).unwrap_or_else(|| format!("{base} {}", lib.len() + 2)) } // ---------- geometry ---------- @@ -849,9 +848,15 @@ fn draws_brushed(doc: &Document, def: Named<'_>, known: &mut Known) -> bool { }; // Without recursion, each one looked at once: they may use one another without end. let (mut seen, mut stack) = (std::collections::HashSet::from([key.clone()]), art(def)); + // A brush name the library lacks draws a plain stroke ([`node_pieces`]), which runs no brush. + let mut names: Option> = None; + let mut resolves = |n: &Node| { + let names = names.get_or_insert_with(|| library(doc).into_iter().map(|b| b.name).collect()); + n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.visible && s.brush.as_ref().is_some_and(|b| names.contains(b)))) + }; let mut answer = false; while let Some(n) = stack.pop() { - if has_brush(n) { + if has_brush(n) && resolves(n) { answer = true; break; } @@ -884,7 +889,16 @@ fn leave_out_brushed(doc: &Document, nodes: &mut Vec, 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); diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 6e8113f14a..7871b61af6 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -1301,6 +1301,7 @@ fn pieces_leave_out_what_draws_a_brushed_stroke_by_name() { }; let art = Node::group(NodeId(0), [instance("plain"), instance("brushed"), painted("plain"), painted("brushed")].map(std::sync::Arc::new).into()); let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) }; + store(&mut doc, std::slice::from_ref(&b)); let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 100.0, 0.0), &stroke(1.0)); assert!(!out.is_empty()); for piece in &out { @@ -1316,6 +1317,46 @@ fn pieces_leave_out_what_draws_a_brushed_stroke_by_name() { } } +/// A symbol instance at the root of an opacity mask is filtered like one among the children: when +/// its symbol draws a brushed stroke the mask goes (it would run the brush again from inside the +/// mask, without end), and a mask whose root symbol is plain stays. +#[test] +fn pieces_leave_out_a_mask_whose_root_draws_a_brushed_stroke() { + use vectorcraft_doc::{OpacityMask, Symbol}; + let mut doc = Document::new(100.0, 100.0); + let mut brushed = rect_art(10.0, 4.0); + brushed.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(StrokeLayer { brush: Some("s".into()), ..stroke(1.0) })); + // A brush the library lacks draws a plain stroke: its mask stays. + let mut unresolved = rect_art(10.0, 4.0); + unresolved.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(StrokeLayer { brush: Some("missing".into()), ..stroke(1.0) })); + for (name, art) in [("plain", rect_art(10.0, 4.0)), ("brushed", brushed), ("unresolved", unresolved)] { + doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: std::sync::Arc::new(art) }); + } + let instance = |symbol: &str| Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY }); + let masked = |symbol: &str| { + let mut n = rect_art(10.0, 4.0); + n.extras_mut().mask = Some(Box::new(OpacityMask::new(instance(symbol), true))); + n + }; + let art = Node::group(NodeId(0), [masked("plain"), masked("brushed"), masked("unresolved")].map(std::sync::Arc::new).into()); + let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) }; + store(&mut doc, std::slice::from_ref(&b)); + let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 100.0, 0.0), &stroke(1.0)); + assert!(!out.is_empty()); + for piece in &out { + let roots: Vec> = piece + .children() + .unwrap() + .iter() + .map(|c| match c.extras().mask.as_ref().map(|m| &m.art.kind) { + Some(NodeKind::SymbolInstance { symbol, .. }) => Some(symbol.as_str()), + _ => None, + }) + .collect(); + assert_eq!(roots, [Some("plain"), None, Some("unresolved")], "the plain and unresolved masks stay and the brushed one goes"); + } +} + /// Anchors a brushed stroke emitted, which is what the output budget counts. fn anchors(nodes: &[Node]) -> usize { nodes diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index 6857c2a175..eb24859f12 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -23,10 +23,19 @@ const PT_PER_MM: f64 = 72.0 / 25.4; const THINNEST: f64 = 0.25; /// The most objects an import makes. const MAX_NODES: usize = 2_000_000; -/// The most block visits (one per insert copy) an import makes, whatever they produce. -const MAX_VISITS: usize = 10_000_000; +/// The most block work an import does, whatever it produces: one per insert copy drawn, and one +/// per item of the block looked at for it (art on hidden layers too). +const MAX_VISITS: usize = if cfg!(test) { 1_000_000 } else { 20_000_000 }; /// The most path elements an import makes (blocks drawn as art are copied for every placement). const MAX_ELEMENTS: usize = if cfg!(test) { 1_000_000 } else { 4_000_000 }; +/// The most dash lengths an import keeps (every dashed path holds its own copy of its pattern). +const MAX_DASH_VALUES: usize = if cfg!(test) { 1_000 } else { 4_000_000 }; +/// The most bytes of text, font names and symbol names an import copies into objects (a block's +/// text and name are copied for every placement). +const MAX_TEXT_BYTES: usize = if cfg!(test) { 64 << 10 } else { 64 << 20 }; +/// The longest font family a text style may name; a longer one is not a font, and is set in the +/// default. +const MAX_FAMILY_BYTES: usize = 256; /// How far from the origin art may lie (points): the canvas. pub(crate) const MAX_EXTENT: f64 = 4.0e6; @@ -34,6 +43,9 @@ const NESTED: &str = "blocks nested more than 8 deep, or inside themselves, are const XREFS: &str = "blocks referencing other drawings (external references) are left out"; const TOO_MANY: &str = "the drawing has more than 2,000,000 objects: the rest are left out"; const TOO_MANY_POINTS: &str = "the drawing has more than 4,000,000 path points: the rest are left out"; +const TOO_MUCH_BLOCK_WORK: &str = "the drawing's blocks take too much work to place: the rest are left out"; +const TOO_MANY_DASHES: &str = "the drawing has more dashed lines than can be kept: the rest are drawn solid"; +const TOO_MUCH_TEXT: &str = "the drawing has more than 64 MB of text and block names: the rest are left out"; /// What a block's art takes from the insert that places it: its colour, lineweight, linetype /// and opacity where the art says "by block", and its layer for art on layer 0. @@ -71,6 +83,9 @@ pub(crate) struct Build<'d, 'a> { visits: usize, /// Path elements made so far. elements: usize, + /// Dash lengths and text bytes kept so far. + dash_values: usize, + text_bytes: usize, warnings: Vec, } @@ -128,6 +143,8 @@ impl<'d, 'a> Build<'d, 'a> { nodes: 0, visits: 0, elements: 0, + dash_values: 0, + text_bytes: 0, warnings: vec![], } } @@ -138,6 +155,20 @@ impl<'d, 'a> Build<'d, 'a> { } } + /// Take `bytes` of text from [`MAX_TEXT_BYTES`]; false (with a warning) when they don't fit. + fn charge_text(&mut self, bytes: usize) -> bool { + match self.text_bytes.checked_add(bytes).filter(|t| *t <= MAX_TEXT_BYTES) { + Some(t) => { + self.text_bytes = t; + true + } + None => { + self.warn(TOO_MUCH_TEXT); + false + } + } + } + /// Import `layout`; `natural` and `ratio` are points per drawing unit in the drawing's own /// unit and at the scale asked for (fitting computes its own). pub fn run(mut self, layout: &LayoutDef, natural: f64, ratio: f64) -> Result<(Document, Vec), String> { @@ -469,6 +500,9 @@ impl<'d, 'a> Build<'d, 'a> { super::curve::bounds(&bp)?; let paint = Paint::solid(rgb_color(self.rgb(p, inh))); let scale = map.determinant().abs().sqrt(); + let path = PathData::from_bezpath(&bp); + // A compound path's loops each keep a copy of its appearance, beside its own. + let copies = if path.subpaths.len() > 1 { path.subpaths.len() + 1 } else { 1 }; let appearance = if fill { Appearance::basic(paint, Paint::None, 0.0) } else { @@ -484,15 +518,20 @@ impl<'d, 'a> Build<'d, 'a> { if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut() && let Some((dash, dots)) = self.dash(&self.linetype(p, inh), p, scale) { - s.dash = Some(dash); - if dots { - s.cap = LineCap::Round; + match dash.pattern.len().checked_mul(copies).and_then(|v| self.dash_values.checked_add(v)).filter(|n| *n <= MAX_DASH_VALUES) { + Some(n) => { + self.dash_values = n; + s.dash = Some(dash); + if dots { + s.cap = LineCap::Round; + } + } + None => self.warn(TOO_MANY_DASHES), } } ap }; let rule = if fill { FillRule::EvenOdd } else { FillRule::NonZero }; - let path = PathData::from_bezpath(&bp); let kind = |path: PathData| NodeKind::Path { path, rule, live: None, clipping: false, guide: false }; let mut n = if path.subpaths.len() > 1 { // Several loops (a hatch with islands) paint as one compound path. Each loop is an @@ -527,10 +566,15 @@ impl<'d, 'a> Build<'d, 'a> { if !(s > 1e-12 && s.is_finite()) { return None; } - let family = t.family.clone().or_else(|| self.d.styles.get(&t.style).filter(|f| !f.is_empty()).cloned()); + let d = self.d; + let family = t.family.as_deref().or_else(|| d.styles.get(&t.style).map(String::as_str).filter(|f| !f.is_empty())); + let family = family.filter(|f| f.len() <= MAX_FAMILY_BYTES); + if !self.charge_text(t.text.len().saturating_add(family.map_or(0, str::len))) { + return None; + } let default = CharStyle::default(); let style = CharStyle { - font_family: family.unwrap_or(default.font_family.clone()), + font_family: family.map_or_else(|| default.font_family.clone(), str::to_string), size: t.height / CAP_HEIGHT * s, h_scale: t.width * 100.0, leading: t.leading.map(|l| l * s), @@ -558,6 +602,13 @@ impl<'d, 'a> Build<'d, 'a> { for cell in &ins.cells { let node = match &symbol { Some(name) => { + if self.nodes >= MAX_NODES { + self.warn(TOO_MANY); + break; + } + if !self.charge_text(name.len()) { + break; + } let xf = map * *cell * self.symbol_map.inverse(); self.nodes += 1; Some(Node::new(self.doc.alloc_id(), NodeKind::SymbolInstance { symbol: name.clone(), xf })) @@ -581,14 +632,19 @@ impl<'d, 'a> Build<'d, 'a> { /// The art of block `name` drawn by `map`, as one object. fn art(&mut self, name: &str, map: Affine, inh: &Inherit, depth: u32) -> Option { - self.visits += 1; - if self.visits > MAX_VISITS { - if self.visits == MAX_VISITS + 1 { - self.warn(TOO_MANY); - } + if self.visits >= MAX_VISITS { + self.warn(TOO_MUCH_BLOCK_WORK); return None; } - let items = self.block(name)?; + let items = self.block(name); + // Each placement looks at every item of the block, drawn or not (art on a hidden layer + // makes nothing, so the node budget doesn't bound it). + self.visits = self.visits.saturating_add(1 + items.as_ref().map_or(0, |i| i.len())); + if self.visits > MAX_VISITS { + self.warn(TOO_MUCH_BLOCK_WORK); + return None; + } + let items = items?; if !self.enter(name, depth) { return None; } @@ -618,12 +674,16 @@ impl<'d, 'a> Build<'d, 'a> { let base = self.d.blocks.get(name).map_or(Point::ZERO, |b| b.base); let map = self.symbol_map * Affine::translate(-base.to_vec2()); let art = self.art(name, map, &key.1, depth); - let made = art.map(|art| { + let made = art.and_then(|art| { let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str()); + // The symbol keeps its name: text, as its instances' copies of it are. + if !self.charge_text(label.len()) { + return None; + } let symbol = unique(label, &mut self.next_suffix, &self.symbol_names); self.symbol_names.insert(symbol.clone()); self.doc.symbols.push(Symbol { dynamic: false, name: symbol.clone(), art: Arc::new(art) }); - symbol + Some(symbol) }); self.symbols.insert(key, made.clone()); made diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index 6bd3d1c106..d28a48553d 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -814,7 +814,7 @@ fn nested_array_inserts_of_nothing_stop_at_the_work_budget() { blocks.extend(block("*C", None)); let top = [(0, "INSERT"), (2, "*A"), (10, "0"), (20, "0"), (70, "300"), (44, "1")]; let r = open(&drawing(&[], &[], &blocks, &top), &points()); - assert!(r.warnings.iter().any(|w| w.contains("more than")), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings); } #[test] @@ -1177,3 +1177,173 @@ fn many_array_inserts_of_a_missing_block_stay_bounded() { assert!(total <= 2_000_000 + 3000, "total cells materialised: {total}"); assert!(conv.warnings.iter().any(|w| w.contains("array inserts")), "{:?}", conv.warnings); } + +#[test] +fn dashed_lines_past_the_dash_budget_are_drawn_solid() { + // 600 lines of a two-length linetype: 1,200 dash lengths, past the 1,000 tests import with. + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + let line = [(0, "LINE"), (6, "DASHED"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]; + let e: Vec<(i32, &str)> = (0..600).flat_map(|_| line).collect(); + let r = open(&drawing(&[], &tables, &[], &e), &points()); + let (mut dashed, mut solid, mut kept) = (0, 0, 0); + r.document.walk(|n| { + if let NodeKind::Path { .. } = n.kind { + match n.appearance.stroke().and_then(|s| s.dash.as_ref()) { + Some(d) => { + dashed += 1; + kept += d.pattern.len(); + } + None => solid += 1, + } + } + }); + assert_eq!(dashed + solid, 600); + assert!(dashed > 0 && solid > 0, "{dashed} dashed, {solid} solid"); + assert!(kept <= 1_000, "{kept} dash lengths kept"); + assert!(r.warnings.iter().any(|w| w.contains("drawn solid")), "{:?}", r.warnings); +} + +/// The bytes of text in the document's text objects. +fn text_bytes(doc: &Document) -> usize { + let mut bytes = 0; + doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + bytes += t.runs.iter().map(|r| r.text.len()).sum::(); + } + }); + bytes +} + +#[test] +fn text_copied_into_array_cells_stops_at_the_text_budget() { + // 1,000 characters of text in an anonymous block placed 10 × 10: 100 KB of copies, past the + // 64 KB tests import with. + let long = "x".repeat(1000); + let blocks = + [(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0"), (0, "TEXT"), (10, "0"), (20, "0"), (40, "1"), (1, long.as_str()), (0, "ENDBLK")]; + let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "10"), (71, "10"), (44, "1"), (45, "1")]; + let r = open(&drawing(&[], &[], &blocks, &insert), &points()); + let bytes = text_bytes(&r.document); + assert!(bytes > 0, "some copies are kept"); + assert!(bytes <= 64 << 10, "{bytes} bytes of text"); + assert!(r.warnings.iter().any(|w| w.contains("64 MB of text")), "{:?}", r.warnings); +} + +#[test] +fn a_text_style_naming_an_overlong_font_family_takes_the_default() { + let family = "F".repeat(10_000); + let tables = [(0, "TABLE"), (2, "STYLE"), (0, "STYLE"), (2, "Big"), (3, "x.ttf"), (1001, "ACAD"), (1000, family.as_str()), (0, "ENDTAB")]; + let e = [(0, "TEXT"), (10, "0"), (20, "0"), (40, "1"), (1, "Hi"), (7, "Big")]; + let doc = open(&drawing(&[], &tables, &[], &e), &points()).document; + let mut families = vec![]; + doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + families.extend(t.runs.iter().map(|r| r.style.font_family.clone())); + } + }); + assert_eq!(families, [vectorcraft_doc::CharStyle::default().font_family]); +} + +#[test] +fn symbol_instances_of_a_long_block_name_stop_at_the_text_budget() { + // A 1,000-byte block name placed 10 × 10: each instance keeps its own copy of the name. + let name = "N".repeat(1000); + let blocks = [(0, "BLOCK"), (2, name.as_str()), (10, "0"), (20, "0"), (0, "LINE"), (10, "0"), (20, "0"), (11, "1"), (21, "0"), (0, "ENDBLK")]; + let insert = [(0, "INSERT"), (2, name.as_str()), (10, "0"), (20, "0"), (70, "10"), (71, "10"), (44, "2"), (45, "2")]; + let r = open(&drawing(&[], &[], &blocks, &insert), &points()); + let mut instances = 0; + r.document.walk(|n| { + if let NodeKind::SymbolInstance { .. } = n.kind { + instances += 1; + } + }); + assert!(instances > 0 && instances < 100, "{instances} instances"); + assert!(r.warnings.iter().any(|w| w.contains("64 MB of text")), "{:?}", r.warnings); +} + +#[test] +fn arrays_of_blocks_of_hidden_art_stop_at_the_work_budget() { + // 500 lines on a hidden layer in an anonymous block placed 50 × 50: they make nothing, but + // each placement looks at all of them (1,250,000 items, past the 1,000,000 tests import with). + let tables = [(0, "TABLE"), (2, "LAYER"), (0, "LAYER"), (2, "Off"), (70, "0"), (62, "-1"), (0, "ENDTAB")]; + let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")]; + for _ in 0..500 { + blocks.extend([(0, "LINE"), (8, "Off"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + } + blocks.push((0, "ENDBLK")); + let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "50"), (71, "50"), (44, "1"), (45, "1")]; + let r = open(&drawing(&[], &tables, &blocks, &insert), &points()); + assert!(r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings); +} + +#[test] +fn dashed_compound_paths_charge_every_copy_of_their_pattern() { + // 100 pattern hatches of 9 loops in a two-length linetype: each keeps its dashes on the + // compound path and on each loop, 2,000 dash lengths, past the 1,000 tests import with. + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + let corners = ["0", "10", "20", "30", "40", "50", "60", "70", "80", "90"]; + let mut hatch = vec![(0, "HATCH"), (6, "DASHED"), (10, "0"), (20, "0"), (30, "0"), (2, "ANSI31"), (70, "0"), (71, "0"), (91, "9")]; + for i in 0..9 { + let (a, b) = (corners[i], corners[i + 1]); + hatch.extend([ + (92, "2"), + (72, "0"), + (73, "1"), + (93, "4"), + (10, a), + (20, "0"), + (10, b), + (20, "0"), + (10, b), + (20, "5"), + (10, a), + (20, "5"), + (97, "0"), + ]); + } + hatch.extend([(75, "0"), (76, "1"), (98, "0")]); + let e: Vec<(i32, &str)> = (0..100).flat_map(|_| hatch.iter().copied()).collect(); + let r = open(&drawing(&[], &tables, &[], &e), &points()); + let (mut compounds, mut kept) = (0, 0); + r.document.walk(|n| { + compounds += usize::from(matches!(n.kind, NodeKind::Compound { .. })); + kept += n.appearance.stroke().and_then(|s| s.dash.as_ref()).map_or(0, |d| d.pattern.len()); + }); + assert_eq!(compounds, 100, "{:?}", r.warnings); + assert!(kept > 0 && kept <= 1_000, "{kept} dash lengths kept"); + assert!(r.warnings.iter().any(|w| w.contains("drawn solid")), "{:?}", r.warnings); +} + +#[test] +fn symbols_of_a_long_block_name_stop_at_the_text_budget() { + // A 1,000-byte block name inserted in 100 colours its art takes: a symbol per colour, each + // keeping its own copy of the name, past the 64 KB tests import with. + let name = "N".repeat(1000); + let blocks = [ + (0, "BLOCK"), + (2, name.as_str()), + (10, "0"), + (20, "0"), + (0, "LINE"), + (8, "0"), + (62, "0"), + (10, "0"), + (20, "0"), + (11, "1"), + (21, "0"), + (0, "ENDBLK"), + ]; + let colours: Vec = (1..=100).map(|c| c.to_string()).collect(); + let inserts: Vec<(i32, &str)> = + colours.iter().flat_map(|c| [(0, "INSERT"), (2, name.as_str()), (62, c.as_str()), (10, "0"), (20, "0")]).collect(); + let r = open(&drawing(&[], &[], &blocks, &inserts), &points()); + let mut bytes: usize = r.document.symbols.iter().map(|s| s.name.len()).sum(); + r.document.walk(|n| { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { + bytes += symbol.len(); + } + }); + assert!(!r.document.symbols.is_empty()); + assert!(bytes <= 64 << 10, "{bytes} bytes of symbol names"); + assert!(r.warnings.iter().any(|w| w.contains("64 MB of text")), "{:?}", r.warnings); +} diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index b7aeb5c6c2..d7e20654a1 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -271,7 +271,11 @@ const MAX_ENTITIES: u32 = 10_000_000; /// The largest x or y a path may have to be flattened, and the most points its polygons keep. const MAX_COORD: f64 = 1e9; -const MAX_POINTS: usize = 4_000_000; +const MAX_POINTS: usize = if cfg!(test) { 100_000 } else { 4_000_000 }; +/// The most segments flattening one path makes, kept or not (repeats of a point are dropped). +const MAX_FLATTEN_SEGMENTS: usize = 4 * MAX_POINTS; + +const SYMBOLS_LEFT_OUT: &str = "symbols placed inside symbols hold too many objects for DXF: the instances past that were left out"; /// Do the dashes of `d` start at the start of their pattern, as a linetype's do? A pattern of /// odd length repeats twice in its linetype. @@ -296,14 +300,19 @@ fn polygons(bp: &BezPath) -> Vec> { } let mut out: Vec> = vec![]; let mut cur: Vec = vec![]; - let mut points = 0usize; - let mut push = |p: Point, cur: &mut Vec| { - if points < MAX_POINTS && cur.last().is_none_or(|q| q.distance(p) > 1e-9) { - points += 1; + // Points kept, and segments made: once either budget is spent, no further curve is flattened. + let points = std::cell::Cell::new(0usize); + let segments = std::cell::Cell::new(0usize); + let push = |p: Point, cur: &mut Vec| { + segments.set(segments.get() + 1); + if points.get() < MAX_POINTS && cur.last().is_none_or(|q| q.distance(p) > 1e-9) { + points.set(points.get() + 1); cur.push(p); } }; - kurbo::flatten(bp.iter(), FLATNESS, |el| match el { + let elements = bp.iter().take_while(|_| points.get() < MAX_POINTS && segments.get() < MAX_FLATTEN_SEGMENTS); + // Each curve is flattened into a bounded number of segments, however large it is. + vectorcraft_geom::flatten(elements, FLATNESS, |el| match el { PathEl::MoveTo(p) => { out.push(std::mem::take(&mut cur)); push(p, &mut cur); @@ -412,6 +421,9 @@ pub(crate) struct Scene<'a> { opacity: f32, /// Symbols and brush art being written inside one another. nest: u32, + /// Objects the symbol instances written held, together + /// ([`vectorcraft_doc::MAX_SYMBOL_NODES`]). + symbol_nodes: u64, } impl<'a> Scene<'a> { @@ -441,6 +453,8 @@ impl<'a> Scene<'a> { extents: None, opacity: 1.0, nest: 0, + // Tests spend all but a million of it up front. + symbol_nodes: if cfg!(test) { vectorcraft_doc::MAX_SYMBOL_NODES - 1_000_000 } else { 0 }, } } @@ -542,13 +556,36 @@ impl<'a> Scene<'a> { NodeKind::Text(t) => self.text(n, t), NodeKind::Image(im) => self.image(im), NodeKind::SymbolInstance { symbol, xf } => { - if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol) + let doc = self.doc; + if self.symbol_nodes >= vectorcraft_doc::MAX_SYMBOL_NODES { + // Spent: no more instances are looked at, so what's left costs nothing. + self.warn(SYMBOLS_LEFT_OUT); + } else if let Some(sym) = doc.symbols.iter().find(|s| &s.name == symbol) && self.nest < MAX_NEST - && let Some(art) = self.doc.place_symbol_art_unclipped(symbol, &vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n), *xf) { - self.nest += 1; - self.node(&art, true); - self.nest -= 1; + // Symbols holding instances of symbols are written in full for each instance, + // empty or not: every instance's art counts against one budget for the export. + let art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n); + let count = art.count_with_masks() as u64; + // Counted as `place_symbol_art_unclipped` places it: no clip groups. + let most = doc.symbol_slice_map(symbol, *xf).map_or(count, |m| m.most_placed_unclipped(&art, doc)); + let placed = vectorcraft_doc::charge_symbol_art(&mut self.symbol_nodes, most, || { + let placed = doc.place_symbol_art_unclipped(symbol, &art, *xf); + let n = placed.as_ref().map_or(0, |a| a.count_with_masks() as u64); + (placed, n) + }); + match placed { + Some(Some(art)) => { + self.nest += 1; + self.node(&art, true); + self.nest -= 1; + } + Some(None) => {} + None => { + self.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES; + self.warn(SYMBOLS_LEFT_OUT); + } + } } } // Live blends, envelopes, meshes and repeats are written as their evaluated art. @@ -1262,3 +1299,47 @@ fn first_solid(n: &Node) -> Option { }); own.or_else(|| n.children().into_iter().flatten().find_map(|c| first_solid(c))) } + +#[cfg(test)] +mod budget_tests { + use super::*; + + #[test] + fn flattening_a_path_of_huge_curves_stops_at_its_budget() { + // Each curve, a hundred million points across, flattens to thousands of segments at + // FLATNESS; a small square after them is past the budget and left out. + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + for i in 0..20_000 { + let y = if i % 2 == 0 { 1e8 } else { -1e8 }; + bp.curve_to((1e8, y), (-1e8, y), (0.0, 0.0)); + } + bp.move_to((10.0, 10.0)); + bp.line_to((20.0, 10.0)); + bp.line_to((20.0, 20.0)); + bp.close_path(); + let polys = polygons(&bp); + let points: usize = polys.iter().map(Vec::len).sum(); + assert!(points <= MAX_POINTS, "{points} points"); + assert!(!polys.iter().any(|p| p.contains(&Point::new(20.0, 20.0))), "the square past the budget is left out"); + } + + #[test] + fn flattening_a_path_of_repeated_points_stops_at_its_segment_budget() { + // Repeats of a point are dropped, so these keep one point but still count as segments: + // the segment budget, not the point budget, leaves out the square after them. + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + for _ in 0..MAX_FLATTEN_SEGMENTS { + bp.line_to((0.0, 0.0)); + } + bp.move_to((10.0, 10.0)); + bp.line_to((20.0, 10.0)); + bp.line_to((20.0, 20.0)); + bp.close_path(); + let polys = polygons(&bp); + let points: usize = polys.iter().map(Vec::len).sum(); + assert!(points < MAX_POINTS, "{points} points"); + assert!(!polys.iter().any(|p| p.contains(&Point::new(20.0, 20.0))), "the square past the budget is left out"); + } +} diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index f1b537b70b..e4984c3332 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1007,3 +1007,22 @@ fn crop_keeps_an_instance_whose_art_reaches_the_region() { let o = DxfOptions { crop: true, ..opts(&d) }; assert!(!kinds(&export(&d, &o).unwrap()).is_empty()); } + +#[test] +fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() { + // Five levels of 100 instances of the level below, ending in an empty symbol: 10^10 empty + // instances, which write no entities, past the million objects tests export with. + let mut d = doc_with(|d| vec![Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "L5".into(), xf: Affine::IDENTITY })]); + let empty = Node::group(d.alloc_id(), vec![]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "L0".into(), art: Arc::new(empty) }); + for level in 1..=5 { + let below = format!("L{}", level - 1); + let children = + (0..100).map(|_| Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: below.clone(), xf: Affine::IDENTITY }))).collect(); + let art = Node::group(d.alloc_id(), children); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("L{level}"), art: Arc::new(art) }); + } + let out = export(&d, &opts(&d)).unwrap(); + assert!(entities(&out).is_empty()); + assert!(out.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", out.warnings); +} diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index 64f42f25b9..0b09062b84 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -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 { + 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; diff --git a/crates/color/src/cms/tests_icc.rs b/crates/color/src/cms/tests_icc.rs index 46e44cd760..1d312c09c3 100644 --- a/crates/color/src/cms/tests_icc.rs +++ b/crates/color/src/cms/tests_icc.rs @@ -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] diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 402cf3ae26..652db3340b 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -175,6 +175,40 @@ fn between(a: &GradientStop, b: &GradientStop, t: f32, mix: &impl Fn(&Color, &Co (mix(&a.color, &b.color, v), a.opacity + (b.opacity - a.opacity) * v) } +/// For each pair of neighbouring stops (`k`, `k + 1`), the largest offset among stops `1..=k + 1`. +/// [`Gradient::sample_with`] picks the first pair whose end offset `t` doesn't pass; that is the +/// first pair whose reach `t` doesn't pass, and the reaches never decrease, so the pair is found by +/// binary search whether or not the stops are in order. +struct StopReach(Vec); + +impl StopReach { + fn new(stops: &[GradientStop]) -> Self { + // `f32::max` skips a NaN offset, which `t <= offset` never chooses either. + let reach = stops.iter().skip(1).scan(f32::NEG_INFINITY, |m, s| { + *m = m.max(s.offset); + Some(*m) + }); + Self(reach.collect()) + } + + /// What [`Gradient::sample_with`] gives at `t` for `stops`, the stops this was built from. + fn sample_with(&self, stops: &[GradientStop], t: f32, mix: &impl Fn(&Color, &Color, f32) -> Color) -> (Color, f32) { + let Some(first) = stops.first() else { return (Color::BLACK, 1.0) }; + if t <= first.offset { + return (first.color, first.opacity); + } + let last = || stops.last().map_or((Color::BLACK, 1.0), |l| (l.color, l.opacity)); + if t.is_nan() { + return last(); + } + let k = self.0.partition_point(|r| *r < t); + match (stops.get(k), stops.get(k + 1)) { + (Some(a), Some(b)) => between(a, b, t, mix), + _ => last(), + } + } +} + fn one() -> f32 { 1.0 } @@ -211,6 +245,12 @@ impl Gradient { pub fn sample(&self, t: f32) -> (Color, f32) { self.sample_with(t, |a, b, v| self.method.mix(a, b, v)) } + /// [`Self::sample`] for many points in no order (a gradient drawn pixel by pixel): the stops + /// are prepared once, so each sample costs a binary search rather than a scan of the stops. + pub fn sampler(&self) -> impl Fn(f32) -> (Color, f32) + '_ { + let reach = StopReach::new(&self.stops); + move |t| reach.sample_with(&self.stops, t, &|a, b, v| self.method.mix(a, b, v)) + } /// [`Self::sample`], a Classic gradient's neighbouring stop colours of one model mixed in it /// (CMYK stays CMYK; [`Color::lerp_keep_model`]) rather than in display RGB, a Perceptual /// gradient's as [`Self::sample`] mixes them. @@ -245,9 +285,11 @@ impl Gradient { /// the one before it stopped, so the work is the samples plus the stops, not their product. pub fn sample_increasing_with(&self, ts: impl IntoIterator, mix: impl Fn(&Color, &Color, f32) -> Color) -> Vec<(Color, f32)> { let stops = &self.stops; - // The shared index assumes ordered stops; others (a file's, unsorted) sample one by one. + // The shared cursor assumes ordered stops; others (a file's, unsorted) look each sample up + // in a [`StopReach`], so they cost a binary search each rather than a scan of the stops. if stops.windows(2).any(|w| w[1].offset < w[0].offset) { - return ts.into_iter().map(|t| self.sample_with(t, &mix)).collect(); + let reach = StopReach::new(stops); + return ts.into_iter().map(|t| reach.sample_with(stops, t, &mix)).collect(); } let mut j = 0; ts.into_iter() @@ -284,6 +326,9 @@ impl Gradient { fn expanded_with_stops(&self) -> impl Iterator, Option)> + '_ { // Direct interpolation matches `sample` only for strictly increasing offsets. let increasing = self.stops.windows(2).all(|w| w[0].offset < w[1].offset); + // Otherwise (repeated or unsorted offsets) each midpoint is looked up as `sample` would + // find it, but by binary search: a scan of all the stops per midpoint cost their square. + let reach = if increasing || !self.method.is_classic() { None } else { Some(StopReach::new(&self.stops)) }; self.stops.iter().enumerate().flat_map(move |(i, s)| { let next = self.stops.get(i + 1); let off_centre = (s.midpoint - 0.5).abs() > 1e-3; @@ -293,7 +338,10 @@ impl Gradient { // Mixed from the two stops it lies between, as `sample` would: searching all the // stops again for each midpoint made many stops cost their square. let mix = |a: &Color, b: &Color, v| self.method.mix(a, b, v); - let (c, o) = if increasing { between(s, n, t, &mix) } else { self.sample_with(t, mix) }; + let (c, o) = match &reach { + Some(reach) => reach.sample_with(&self.stops, t, &mix), + None => between(s, n, t, &mix), + }; (t, c, o, Some(s.midpoint), None) }); // Perceptual: stops along the mix (`v`) where a straight line would stray from it, the diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index 2248030758..1e75feb335 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -23,6 +23,64 @@ fn increasing_samples_match_single_samples() { assert_eq!(g.sample_increasing_with(ts, Color::lerp_keep_model), one_by_one); } +/// The prepared sampler gives what sampling each position alone does, out-of-order stops included. +#[test] +fn the_sampler_matches_single_samples() { + let stop = |offset: f32, hex: &str| GradientStop::new(offset, Color::from_hex(hex).unwrap()); + let g = Gradient::new( + GradientKind::Linear, + vec![stop(0.1, "#ff0000"), stop(0.4, "#00ff00"), stop(0.4, "#0000ff"), stop(0.2, "#ffff00"), stop(0.9, "#000000")], + ); + let sample = g.sampler(); + for k in (0..=40).rev() { + let t = k as f32 / 40.0; + assert_eq!(sample(t), g.sample(t), "{t}"); + } +} + +/// Looking stops up by their reach finds what scanning them does, for any order of offsets, +/// repeated, out-of-order and NaN ones included, and for positions outside and between them. +#[test] +fn stop_reach_matches_scanning_the_stops() { + let colors = ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#00ffff", "#000000"]; + let offsets: [&[f32]; 5] = [ + &[0.1, 0.4, 0.4, 0.2, 0.9, 0.5], + &[0.5, 0.5, 0.5, 0.5], + &[0.9, 0.1, 0.8, 0.2, 0.7, 0.3], + &[0.2, f32::NAN, 0.6, 0.1, f32::NAN, 1.0], + &[f32::NAN, 0.3, 0.3, 0.8], + ]; + for offsets in offsets { + let stops: Vec = offsets + .iter() + .zip(colors.iter().cycle()) + .map(|(&o, hex)| GradientStop { midpoint: 0.3, ..GradientStop::new(o, Color::from_hex(hex).unwrap()) }) + .collect(); + let g = Gradient::new(GradientKind::Linear, stops); + let reach = StopReach::new(&g.stops); + for t in (-4..=44).map(|k| k as f32 / 40.0).chain([f32::NAN, f32::INFINITY, f32::NEG_INFINITY]) { + // Compared as printed: a NaN offset mixes NaN colours, which are equal only so. + let (got, want) = (reach.sample_with(&g.stops, t, &Color::lerp_keep_model), g.sample_with(t, Color::lerp_keep_model)); + assert_eq!(format!("{got:?}"), format!("{want:?}"), "{offsets:?} at {t}"); + } + } +} + +/// Repeated offsets turn off the direct midpoint mix, and the midpoints still come out as +/// `sample` gives them, with work that stays near linear in the stops (thousands of stops at one +/// offset used to scan them all for each midpoint). +#[test] +fn expanded_with_repeated_offsets_samples_midpoints() { + let stop = |offset: f32, hex: &str| GradientStop { midpoint: 0.25, ..GradientStop::new(offset, Color::from_hex(hex).unwrap()) }; + let g = Gradient::new(GradientKind::Linear, vec![stop(0.0, "#ff0000"), stop(0.5, "#00ff00"), stop(0.5, "#0000ff"), stop(1.0, "#000000")]); + for (t, c, o, mid) in g.expanded().filter(|e| e.3.is_some()) { + assert_eq!(mid, Some(0.25)); + assert_eq!((c, o), g.sample(t), "midpoint at {t}"); + } + let many = Gradient::new(GradientKind::Linear, (0..200_000).map(|i| stop(if i == 0 { 0.0 } else { 0.5 }, "#808080")).collect()); + assert_eq!(many.expanded().count(), 2 * 200_000 - 1); +} + #[test] fn midpoint_shifts() { let mut g = Gradient::default(); diff --git a/crates/color/src/recolor.rs b/crates/color/src/recolor.rs index e7cf22c41f..5117f16a36 100644 --- a/crates/color/src/recolor.rs +++ b/crates/color/src/recolor.rs @@ -433,10 +433,11 @@ pub fn cluster(colors: &[Color], weights: &[f32], n: usize) -> Vec> { .collect(); let w = |i: usize| weights.get(i).copied().unwrap_or(1.0).max(1e-6); let d2 = |a: &[f32; 3], b: &[f32; 3]| (a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2); - let n = n.max(1); if pts.is_empty() { return vec![]; } + // No more rows than colours: each colour seeds one at most. + let n = n.clamp(1, pts.len()); // Seeds: the heaviest colour, then each time the one farthest from every seed so far. let first = (0..pts.len()).fold(0, |best, i| if w(i) > w(best) { i } else { best }); let mut centres = vec![pts[first]]; @@ -447,6 +448,8 @@ pub fn cluster(colors: &[Color], weights: &[f32], n: usize) -> Vec> { break; } centres.push(pts[i]); + // Picked: a colour whose distances aren't finite (an infinite coordinate) stays farthest. + near[i] = 0.0; for (j, p) in pts.iter().enumerate() { near[j] = near[j].min(d2(p, &pts[i])); } @@ -670,6 +673,12 @@ mod tests { assert!(matches!(shaded(lab[0], 0.5), Color::Lab { .. })); } + #[test] + fn clustering_seeds_each_colour_once_even_unbounded() { + let colors = [Color::lab(f32::INFINITY, 0.0, 0.0), Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)]; + assert!(cluster(&colors, &[], usize::MAX).len() <= colors.len()); + } + #[test] fn clustering_reduces_to_n_rows_of_similar_colours() { let colors = diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index ce20d29cd8..8bca517ee1 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -862,6 +862,52 @@ impl Spine { pub fn anchor_length(&self, i: usize) -> Option { 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 { + 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) -> 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()) diff --git a/crates/doc/src/depth.rs b/crates/doc/src/depth.rs index 6f10da9b7a..5abba9c63b 100644 --- a/crates/doc/src/depth.rs +++ b/crates/doc/src/depth.rs @@ -107,15 +107,21 @@ fn nested_deeper(now: &[Arc], depth: usize) -> bool { /// an opacity mask too deep are left out); what it held stays hidden or locked as it was. Returns /// whether anything changed. Recurses no deeper than the cap. fn limit(nodes: &mut Vec>, depth: usize) -> bool { - let mut changed = false; - let mut i = 0; - while let Some(n) = nodes.get_mut(i) { - if !nested_deeper(std::slice::from_ref(n), depth) { - i += 1; + if !nested_deeper(nodes, depth) { + return false; + } + // The list is rebuilt in order rather than spliced in place: replacing one container of many + // by what it holds would move all the siblings after it each time. + let mut out = Vec::with_capacity(nodes.len()); + // What is left to look at, the next one last. + let mut left: Vec> = std::mem::take(nodes); + left.reverse(); + while let Some(mut a) = left.pop() { + if !nested_deeper(std::slice::from_ref(&a), depth) { + out.push(a); continue; } - changed = true; - let n = Arc::make_mut(n); + let n = Arc::make_mut(&mut a); if n.extras().mask.as_ref().is_some_and(|m| nested_deeper(std::slice::from_ref(&m.art), depth + 1)) { n.extras_mut().mask = None; } @@ -123,7 +129,7 @@ fn limit(nodes: &mut Vec>, depth: usize) -> bool { if let Some(ch) = n.children_mut() { limit(ch, depth + 1); } - i += 1; + out.push(a); continue; } let clip = matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. }); @@ -140,9 +146,10 @@ fn limit(nodes: &mut Vec>, depth: usize) -> bool { } } // What it held takes its place, and is looked at in its turn. - nodes.splice(i..=i, held); + left.extend(held.into_iter().rev()); } - changed + *nodes = out; + true } /// A symbol (`false`) or a pattern (`true`) of the document, by name: what art draws by name, an @@ -439,6 +446,24 @@ mod tests { } } + #[test] + fn many_containers_at_the_cap_are_merged_in_order() { + // A group just above the cap holding many groups of two paths each: every group is + // replaced by its two paths, in order (in time linear in their number). + const PAIRS: u64 = 50_000; + let path = |id| Arc::new(Node::path(NodeId(id), Default::default(), Default::default())); + let pairs = (0..PAIRS).map(|i| Arc::new(Node::group(NodeId(1_000_000 + i), vec![path(2 * i + 1), path(2 * i + 2)]))).collect(); + let mut art = Arc::new(Node::group(NodeId(500_000), pairs)); + for i in 0..MAX_DEPTH - 3 { + art = Arc::new(Node::group(NodeId(600_000 + i as u64), vec![art])); + } + let mut d = doc(art); + assert!(d.limit_depth()); + assert!(!d.too_deep(None)); + let holder = d.node(NodeId(500_000)).and_then(Node::children).map(|c| c.iter().map(|c| c.id.0).collect::>()); + assert_eq!(holder, Some((1..=2 * PAIRS).collect())); + } + #[test] fn a_clipping_path_and_a_mask_too_deep_are_left_out_and_hidden_art_stays_hidden() { let mut inner = Node::new(NodeId(9000), NodeKind::Group { children: vec![nested(0), nested(0)], clip: true }); diff --git a/crates/doc/src/document_ext.rs b/crates/doc/src/document_ext.rs index b52e850c76..c9a6c5f56a 100644 --- a/crates/doc/src/document_ext.rs +++ b/crates/doc/src/document_ext.rs @@ -2,8 +2,8 @@ use super::graphic_style::GraphicStyle; use super::limits::MAX_NEXT_ID; use super::records::{ImageBlob, SavedSelection, SavedView}; use super::{ - Arc, Document, ImageObject, Node, NodeKind, SYMBOL_EXPORT_TYPE, SYMBOL_NINE_SLICE, SYMBOL_REGISTRATION, SymbolExportType, SymbolNineSlice, - SymbolRegistration, + Arc, Document, EnvelopeKind, ImageObject, LiveShape, Node, NodeKind, Point, SYMBOL_EXPORT_TYPE, SYMBOL_NINE_SLICE, SYMBOL_REGISTRATION, + SymbolExportType, SymbolNineSlice, SymbolRegistration, placed_document, }; impl Document { @@ -120,6 +120,112 @@ impl Document { d.drop_edit_modes(); std::borrow::Cow::Owned(d) } + + /// Round every path's anchors and handles to `decimals` decimal places: path objects (with + /// Live Corners' uncut outlines), blend spines, envelopes' top-object outlines and Intertwine + /// areas, in the layers, symbol definitions, graph designs, pattern swatches (the one being + /// edited included), opacity masks and the brushes kept as foreign data. Colors, transforms, + /// opacity, live shapes' own sizes, meshes and type (its frames and paths included) are left + /// as they are. + pub fn round_geometry(&mut self, decimals: u8) { + let scale = 10f64.powi(i32::from(decimals)); + let round = |v: f64| { + let r = (v * scale).round() / scale; + if !r.is_finite() { + v + } else if r == 0.0 { + // `-0.0` is written as `0.0`. + 0.0 + } else { + r + } + }; + let round_path = |path: &mut vectorcraft_geom::PathData| { + for a in path.subpaths.iter_mut().flat_map(|s| s.anchors.iter_mut()) { + for p in [&mut a.p, &mut a.h_in, &mut a.h_out] { + *p = Point::new(round(p.x), round(p.y)); + } + } + }; + let mut fix = |n: &mut Node| { + match &mut n.kind { + NodeKind::Path { path, live, .. } => { + round_path(path); + // Live Corners' uncut outline. + if let Some(LiveShape::Path { base, .. }) = live.as_deref_mut() { + round_path(base); + } + } + NodeKind::Blend { spec, .. } => { + if let Some(spine) = &mut spec.spine { + round_path(spine); + } + } + NodeKind::Envelope { kind, .. } => { + if let EnvelopeKind::TopObject { path } = kind.as_mut() { + round_path(path); + } + } + _ => {} + } + if let Some(e) = n.extras_if_any() { + for area in e.intertwine.as_deref_mut().into_iter().chain(e.intertwine_tiers.iter_mut()) { + round_path(area); + } + } + }; + let roots = self + .layers + .iter_mut() + .chain(self.symbols.iter_mut().map(|s| &mut s.art)) + .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) + .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); + for root in roots { + placed_document::each_mut(Arc::make_mut(root), &mut fix); + } + if self.unknown.contains_key("brushes") + && let Some(brushes) = self.unknown.get_mut("brushes") + { + round_json_paths(brushes, &round); + } + } +} + +/// Round with `round` the anchors of the paths in `v`, nodes in their file form kept as JSON: every +/// `{"subpaths": [{"anchors": [{"p", "in", "out"}]}]}` outside type (`{"type": "text"}`), as +/// [`Document::round_geometry`] rounds the nodes it holds. +fn round_json_paths(v: &mut serde_json::Value, round: &impl Fn(f64) -> f64) { + use serde_json::Value; + match v { + Value::Object(o) => { + if o.get("type").and_then(Value::as_str) == Some("text") { + return; + } + if let Some(subpaths) = o.get_mut("subpaths").and_then(Value::as_array_mut) { + let anchors = subpaths.iter_mut().filter_map(|s| s.get_mut("anchors").and_then(Value::as_array_mut)).flatten(); + for a in anchors.filter_map(Value::as_object_mut) { + let points = a.iter_mut().filter(|(k, _)| matches!(k.as_str(), "p" | "in" | "out")).filter_map(|(_, v)| v.as_array_mut()); + for xy in points { + for n in xy.iter_mut().filter(|n| n.is_f64()) { + if let Some(r) = n.as_f64().and_then(|x| serde_json::Number::from_f64(round(x))) { + *n = Value::Number(r); + } + } + } + } + } + for c in o.values_mut() { + round_json_paths(c, round); + } + } + Value::Array(a) => { + for c in a { + round_json_paths(c, round); + } + } + _ => {} + } } /// Graphic styles. diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index d20c1ffe4e..cb972b94f8 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -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 { + 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], p: Point, tol: f64) -> vectorcraft_geom::BezPath { + let near = |b: Rect| b.x0 - tol <= p.x && p.x <= b.x1 + tol && b.y0 - tol <= p.y && p.y <= b.y1 + tol; + let mut bp = vectorcraft_geom::BezPath::new(); + for pd in children.iter().filter_map(|m| m.path_data()) { + if pd.control_bounds().is_some_and(near) { + bp.extend(pd.to_bezpath()); + } + } + bp } /// Is the first child of `n` the isolated container `scope`? @@ -710,12 +744,23 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio } None } - NodeKind::Compound { rule, .. } => { - let bp = n.stroke_path()?; - if let Some(k) = hit_stroke(n, &bp, *rule, p, opt) { - return Some(k); + NodeKind::Compound { children, rule } => { + // Painted strokes follow the whole compound path (alignment, dashes, width profiles): + // they are measured along all of it, as before. + if !opt.outline && n.appearance.painted_strokes().next().is_some() { + let bp = n.stroke_path()?; + if n.appearance.stroke_hit(&bp, *rule, p, opt.tol) { + return Some(HitKind::Stroke); + } } - (!opt.outline && !opt.path_only && fill_contains(&bp, *rule, p)).then_some(HitKind::Fill) + // The outline and the fill only need the members near `p`. (Measured without + // `stroke_contains`'s box check: the box of the members near `p` is smaller than the + // whole path's, and its far edges would turn away points exactly `tol` away.) + let near = compound_members_near(children, p, opt.tol); + if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol { + return Some(HitKind::Outline); + } + (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill) } // The type path lies within the bounds: they rule out the rest before it is measured. NodeKind::Text(t) if opt.type_path_only => { @@ -835,6 +880,16 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option { /// clipping mask counts only when the marquee meets the region its clipping path clips to, and then /// only within that region's bounds. pub fn marquee(doc: &Document, r: Rect, scope: Option, leaves: bool) -> Vec { + marquee_with(doc, r, scope, leaves, false) +} + +/// Candidates for whole-object enclosure by a loop bounded by `r`. Eligibility and group +/// traversal follow [`marquee`]; compounds contribute the complete path they paint. +pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option) -> Vec { + marquee_with(doc, r, scope, true, true) +} + +fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, whole_compounds: bool) -> Vec { let mut out = Vec::new(); // `tops` pairs each object with the part of `r` in which the marquee can touch it. let tops: Vec<(&std::sync::Arc, Rect)> = match scope.and_then(|s| doc.node(s)) { @@ -879,13 +934,19 @@ pub fn marquee(doc: &Document, r: Rect, scope: Option, leaves: bool) -> /// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched /// by the copies it draws, as clicks hit them. Objects of every other kind except paths, /// compound paths, layers and groups are touched by their box. - fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option) -> bool { + fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool) -> bool { match &n.kind { NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r), - NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => marquee_in(n, r) - .is_some_and(|r| children.iter().enumerate().any(|(i, c)| c.visible && !shaper_hides(n, i, scope) && touches(c, s, r, scope))), - NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope)), - NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope)), + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => { + marquee_in(n, r).is_some_and(|r| { + children.iter().enumerate().any(|(i, c)| c.visible && !shaper_hides(n, i, scope) && touches(c, s, r, scope, whole_compounds)) + }) + } + NodeKind::Compound { children, .. } if whole_compounds => { + children.iter().filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r)) + } + NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds)), + NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds)), // A box with no width or no height (an instance of a symbol that draws a straight // line) is touched where the marquee crosses it. _ => n.geometric_bounds_with(s).is_some_and(|b| { @@ -894,18 +955,18 @@ pub fn marquee(doc: &Document, r: Rect, scope: Option, leaves: bool) -> }), } } - fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, out: &mut Vec) { + fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, out: &mut Vec) { match &n.kind { NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => { let Some(r) = marquee_in(n, r) else { return }; for (i, c) in children.iter().enumerate() { if c.visible && !c.locked && !shaper_hides(n, i, scope) { - collect_leaves(c, s, r, scope, out); + collect_leaves(c, s, r, scope, whole_compounds, out); } } } _ => { - if touches(n, s, r, scope) { + if touches(n, s, r, scope, whole_compounds) { out.push(n.id); } } @@ -918,8 +979,8 @@ pub fn marquee(doc: &Document, r: Rect, scope: Option, leaves: bool) -> continue; } if leaves { - collect_leaves(t, &symbols, r, scope, &mut out); - } else if touches(t, &symbols, r, scope) { + collect_leaves(t, &symbols, r, scope, whole_compounds, &mut out); + } else if touches(t, &symbols, r, scope, whole_compounds) { out.push(t.id); } } diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index c4d6c565e0..452055a8f2 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -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) { + 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 { + 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 { + 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 = (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> = [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); +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c836390e19..b59f661c21 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -29,7 +29,10 @@ mod symbol_registration; pub use inline::{SYMBOL_HALF, SYMBOL_SIZES}; pub use shared::Shared; pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType}; -pub use symbol_nine_slice::{MAX_SLICE_GROWTH, NineSliceMap, PAINTED_EFFECTS, SYMBOL_NINE_SLICE, SymbolNineSlice, charge_symbol_art}; +pub use symbol_nine_slice::{ + EditedNineSlice, MAX_SLICE_GROWTH, MIN_CENTER_BAND, NineSliceGuide, NineSliceMap, PAINTED_EFFECTS, SYMBOL_NINE_SLICE, SymbolNineSlice, + charge_symbol_art, +}; pub use symbol_overrides::SymbolOverride; pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration}; pub mod links; diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index b5ae03e8b1..07899196c2 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -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 { diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index df675580e2..1669de1a27 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -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 = + (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()); +} diff --git a/crates/doc/src/objects_on_path.rs b/crates/doc/src/objects_on_path.rs index 779e2eced3..67c9c0ee87 100644 --- a/crates/doc/src/objects_on_path.rs +++ b/crates/doc/src/objects_on_path.rs @@ -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, + /// 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, Option)> { + 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 { + 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) { 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> { - 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, 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, start: f64) -> Option> { + 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, 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 = 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, start: f64) -> Vec { + 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::::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] diff --git a/crates/doc/src/pattern.rs b/crates/doc/src/pattern.rs index a0b19b844c..2a98df62ce 100644 --- a/crates/doc/src/pattern.rs +++ b/crates/doc/src/pattern.rs @@ -522,7 +522,28 @@ pub struct RepeatSpec { /// many as one 500 × 500 grid, the budget [`PatternDef::offsets_covering`] also keeps. const MAX_REPEAT_INSTANCES: usize = 250_000; -/// Counts the instances Repeats make in all, following symbol instances into their symbol's art +/// Most nodes and anchors a Repeat copies in all, those of the Repeats nested in its source and +/// of the opacity masks in it included: each instance copies the whole source, so a large source +/// keeps fewer instances than [`MAX_REPEAT_INSTANCES`] allows (a 500 × 500 grid of a shape of up +/// to 39 anchors keeps them all). +const MAX_REPEAT_COPIES: usize = 10_000_000; + +/// What the Repeats in some art make in all ([`NestedCount::nodes`]). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Cost { + /// Instances the Repeats make (0 when there are none). + instances: usize, + /// Nodes and path anchors drawn, each Repeat's source counted once per instance it keeps. + copies: usize, +} + +impl Cost { + fn plus(self, o: Cost) -> Cost { + Cost { instances: self.instances.saturating_add(o.instances), copies: self.copies.saturating_add(o.copies) } + } +} + +/// Counts the instances Repeats make, and the nodes they copy, in all, following symbol instances into their symbol's art /// in `doc`: each symbol's art is counted once, and a missing symbol, or an instance of a symbol /// inside its own art, counts as none. /// @@ -549,21 +570,27 @@ impl<'a> NestedCount<'a> { } let Some(sym) = self.doc.and_then(|d| d.symbols.iter().find(|s| s.name == name)) else { return 0 }; self.symbols.borrow_mut().insert(name.to_owned(), None); - let n = self.nodes(std::slice::from_ref(&sym.art)); + let n = self.nodes(std::slice::from_ref(&sym.art)).instances; self.symbols.borrow_mut().insert(name.to_owned(), Some(n)); n } - /// Instances the Repeats in `nodes` make in all (0 when there are none). - fn nodes(&self, nodes: &[Arc]) -> usize { - let mut sum = 0usize; + /// What the Repeats in `nodes` make in all, in the art of their enabled opacity masks too + /// (drawn again with each copy of the object they mask). + fn nodes(&self, nodes: &[Arc]) -> Cost { + let mut sum = Cost::default(); for n in nodes { - sum = sum.saturating_add(match (&n.kind, n.children()) { - (NodeKind::Repeat(r), _) => r.instances_in_all(self), - (NodeKind::SymbolInstance { symbol, .. }, _) => self.symbol(symbol), - (_, Some(c)) => self.nodes(c), - _ => 0, - }); + let own = match (&n.kind, n.children()) { + (NodeKind::Repeat(r), _) => r.in_all(self), + (NodeKind::SymbolInstance { symbol, .. }, _) => Cost { instances: self.symbol(symbol), copies: 1 }, + (NodeKind::Path { path, .. }, _) => Cost { instances: 0, copies: path.anchor_count().saturating_add(1) }, + (_, Some(c)) => self.nodes(c).plus(Cost { instances: 0, copies: 1 }), + _ => Cost { instances: 0, copies: 1 }, + }; + sum = sum.plus(own); + if let Some(m) = n.extras().mask.as_ref().filter(|m| !m.disabled) { + sum = sum.plus(self.nodes(std::slice::from_ref(&m.art))); + } } sum } @@ -643,21 +670,22 @@ impl RepeatSpec { v.truncate(self.kept(NestedCount::new(doc).nodes(&self.source))); v } - /// How many of its instances this Repeat keeps when each makes `nested` instances of the - /// Repeats in its source: as many as fit in [`MAX_REPEAT_INSTANCES`], at least one. - fn kept(&self, nested: usize) -> usize { - self.kind.count().min(MAX_REPEAT_INSTANCES / nested.max(1)).max(1) + /// How many of its instances this Repeat keeps when its source costs `nested`: as many as fit + /// in [`MAX_REPEAT_INSTANCES`] and [`MAX_REPEAT_COPIES`], at least one. + fn kept(&self, nested: Cost) -> usize { + self.kind.count().min(MAX_REPEAT_INSTANCES / nested.instances.max(1)).min(MAX_REPEAT_COPIES / nested.copies.max(1)).max(1) } /// How many instances this Repeat draws ([`Self::transforms`] for `doc`): as many as its /// options make, fewer when the Repeats in its source would take it past - /// [`MAX_REPEAT_INSTANCES`]. + /// [`MAX_REPEAT_INSTANCES`], or the copies of its source past [`MAX_REPEAT_COPIES`]. pub fn instances(&self, doc: Option<&Document>) -> usize { self.kept(NestedCount::new(doc).nodes(&self.source)) } - /// Instances made in all, those of the Repeats nested in the source included. - fn instances_in_all(&self, count: &NestedCount) -> usize { + /// Instances made and nodes copied in all, those of the Repeats nested in the source included. + fn in_all(&self, count: &NestedCount) -> Cost { let nested = count.nodes(&self.source); - self.kept(nested).saturating_mul(nested.max(1)) + let kept = self.kept(nested); + Cost { instances: kept.saturating_mul(nested.instances.max(1)), copies: kept.saturating_mul(nested.copies).saturating_add(1) } } /// Evaluated instances: one group of the (transformed) source per instance (ids 0), as many /// as [`Self::transforms`] keeps for `doc`. @@ -1005,6 +1033,42 @@ mod tests { assert_eq!(made(&small), 18); } + #[test] + fn repeats_in_opacity_masks_share_the_instance_budget() { + let grid = |source: Arc| { + let mut g = RepeatSpec::grid(vec![source], 0.0, 0.0); + if let RepeatKind::Grid { rows, cols, .. } = &mut g.kind { + *rows = 500; + *cols = 500; + } + g + }; + // A shape masked by a 500 × 500 grid draws the grid again for each copy. + let inner = Node::new(NodeId(3), NodeKind::Repeat(grid(sq(0.0, 0.0, 1.0)))); + let mut masked = (*sq(0.0, 0.0, 1.0)).clone(); + masked.extras_mut().mask = Some(Box::new(crate::node::OpacityMask::new(inner, true))); + let outer = grid(Arc::new(masked.clone())); + assert_eq!(outer.transforms(None).len(), 1); + // A disabled mask is not drawn, so it costs nothing. + if let Some(m) = &mut masked.extras_mut().mask { + m.disabled = true; + } + assert_eq!(grid(Arc::new(masked)).transforms(None).len(), 250_000); + } + + #[test] + fn a_large_source_keeps_fewer_copies() { + let mut g = RepeatSpec::grid((0..1000).map(|i| sq(i as f64, 0.0, 1.0)).collect(), 0.0, 0.0); + if let RepeatKind::Grid { rows, cols, .. } = &mut g.kind { + *rows = 500; + *cols = 500; + } + // Each copy is 1000 paths of 4 anchors: far fewer than 250 000 of them fit. + let kept = g.transforms(None).len(); + assert!(kept.saturating_mul(5000) <= MAX_REPEAT_COPIES, "{kept} copies kept"); + assert!(kept > 1); + } + #[test] fn serde_roundtrip() { let mut def = PatternDef::new("Dots", vec![sq(0.0, 0.0, 10.0)]); diff --git a/crates/doc/src/placed_document.rs b/crates/doc/src/placed_document.rs index 310d7b784f..33eccb178a 100644 --- a/crates/doc/src/placed_document.rs +++ b/crates/doc/src/placed_document.rs @@ -559,6 +559,9 @@ impl Document { reads += usize::from(read_full && depth > 0); let full = if read_full { full_bytes(&p, &blob) } else { None }; if full.and_then(|b| read(&p, &b)).is_none() { + // A full read cached for another caller (one allowed to read the file) must not + // stand in for the one refused or not tried here: the preview shows instead. + cache().entries.remove(&(p.key.clone(), false)); let preview = if blob.is_proxy() { Some(blob.bytes.clone()) } else { blob.proxy.clone() }; if let Some(bytes) = preview { read_preview(&p, &bytes); diff --git a/crates/doc/src/range.rs b/crates/doc/src/range.rs index 87db16f206..7162709bc8 100644 --- a/crates/doc/src/range.rs +++ b/crates/doc/src/range.rs @@ -17,7 +17,9 @@ pub fn parse_range(s: &str, count: usize) -> Result, String> { .ok_or_else(|| format!("range `{s}`: `{t}` is not a number from 1 to {count}")) }; let mut out = vec![]; - let mut seen = std::collections::HashSet::new(); + // Past each run of indices picked so far, the index after it: an interval skips the runs it + // overlaps instead of walking them again, so repeating `1-` costs no more than writing it once. + let mut next = std::collections::HashMap::new(); for part in s.split(',').map(str::trim).filter(|p| !p.is_empty()) { let (a, b) = match part.replace('\u{2013}', "-").split_once('-') { Some((a, b)) if a.trim().is_empty() && b.trim().is_empty() => return Err(format!("range `{s}`: `{part}` names no number")), @@ -30,10 +32,11 @@ pub fn parse_range(s: &str, count: usize) -> Result, String> { if a > b { return Err(format!("range `{s}`: `{part}` runs backwards")); } - for i in a - 1..b { - if seen.insert(i) { - out.push(i); - } + let mut i = unpicked(&mut next, a - 1); + while i < b { + out.push(i); + next.insert(i, i + 1); + i = unpicked(&mut next, i + 1); } } if out.is_empty() { @@ -42,6 +45,23 @@ pub fn parse_range(s: &str, count: usize) -> Result, String> { Ok(out) } +/// The first index from `i` on not picked yet, `next` linking each picked index onward (the links +/// followed are then pointed straight at it). +fn unpicked(next: &mut std::collections::HashMap, i: usize) -> usize { + let mut end = i; + while let Some(&j) = next.get(&end) { + end = j; + } + let mut at = i; + while at != end { + match next.insert(at, end) { + Some(j) => at = j, + None => break, + } + } + end +} + #[cfg(test)] mod tests { use super::parse_range; @@ -53,4 +73,20 @@ mod tests { assert!(parse_range("-+2", 5).is_err()); assert_eq!(parse_range("1-3, 5", 5), Ok(vec![0, 1, 2, 4])); } + + #[test] + fn repeats_and_overlaps_are_dropped_in_order() { + assert_eq!(parse_range("3-5, 1-4, 2, 6-, -1", 7), Ok(vec![2, 3, 4, 0, 1, 5, 6])); + assert_eq!(parse_range("2,2,1-2", 4), Ok(vec![1, 0])); + assert_eq!(parse_range("4, 2, 1-", 5), Ok(vec![3, 1, 0, 2, 4])); + } + + #[test] + fn a_range_repeated_many_times_is_read_once() { + // 100 000 pages named 50 000 times: walking the pages for each would take billions of steps. + let s = "1-,".repeat(50_000); + let pages = parse_range(&s, 100_000).unwrap(); + assert_eq!(pages.len(), 100_000); + assert!(pages.iter().enumerate().all(|(i, p)| i == *p)); + } } diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 95978bd8d2..528e33e3e3 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -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, &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, key: &str, f: &mut LinkFn) -> bool { + let Some(value) = attrs.get_mut(key) else { return false }; + let Ok(mut paint) = serde_json::from_value::(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>)) { diff --git a/crates/doc/src/symbol_nine_slice.rs b/crates/doc/src/symbol_nine_slice.rs index a37b92eef6..8d7c108ab5 100644 --- a/crates/doc/src/symbol_nine_slice.rs +++ b/crates/doc/src/symbol_nine_slice.rs @@ -71,6 +71,79 @@ impl SymbolNineSlice { } } +/// One of the four 9-slice guides. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NineSliceGuide { + Left, + Top, + Right, + Bottom, +} + +impl NineSliceGuide { + pub const ALL: [Self; 4] = [Self::Left, Self::Top, Self::Right, Self::Bottom]; +} + +/// The narrowest center band a guide dragged toward the opposite guide leaves, as a fraction of +/// the art's width or height (VectorCraft's own rule). +pub const MIN_CENTER_BAND: f64 = 0.001; + +/// The 9-slice guides of the symbol edited in symbol editing mode, over its art on the editing +/// layer ([`Document::edited_nine_slice`]). +#[derive(Clone, Debug, PartialEq)] +pub struct EditedNineSlice { + /// The symbol's name. + pub symbol: String, + pub guides: SymbolNineSlice, + /// The art's geometric box at its natural size. + art: Rect, + /// The art at its natural size → the document. + to_doc: Affine, +} + +impl EditedNineSlice { + /// Guide `g` as a line across the art's box, from one edge to the other, in the document. + pub fn line(&self, g: NineSliceGuide) -> (Point, Point) { + let (b, s) = (self.art, self.guides); + let (a, c) = match g { + NineSliceGuide::Left | NineSliceGuide::Right => { + let x = if g == NineSliceGuide::Left { b.x0 + s.left * b.width() } else { b.x1 - s.right * b.width() }; + (Point::new(x, b.y0), Point::new(x, b.y1)) + } + NineSliceGuide::Top | NineSliceGuide::Bottom => { + let y = if g == NineSliceGuide::Top { b.y0 + s.top * b.height() } else { b.y1 - s.bottom * b.height() }; + (Point::new(b.x0, y), Point::new(b.x1, y)) + } + }; + (self.to_doc * a, self.to_doc * c) + } + + /// The four guides' lines: left, top, right, bottom. + pub fn lines(&self) -> [(NineSliceGuide, Point, Point); 4] { + NineSliceGuide::ALL.map(|g| { + let (a, b) = self.line(g); + (g, a, b) + }) + } + + /// The guides with guide `g` moved across its axis to document point `p`. The guide stays + /// within the art's box, and [`MIN_CENTER_BAND`] short of the opposite guide, or where it is + /// when the guides are already closer than that. A point that is not finite leaves the guides + /// as they are. + pub fn moved(&self, g: NineSliceGuide, p: Point) -> SymbolNineSlice { + let (b, mut out) = (self.art, self.guides); + let q = self.to_doc.inverse() * p; + let fit = |v: f64, other: f64, now: f64| if v.is_finite() { v.clamp(0.0, (1.0 - other - MIN_CENTER_BAND).max(now)) } else { now }; + match g { + NineSliceGuide::Left => out.left = fit((q.x - b.x0) / b.width(), out.right, out.left), + NineSliceGuide::Right => out.right = fit((b.x1 - q.x) / b.width(), out.left, out.right), + NineSliceGuide::Top => out.top = fit((q.y - b.y0) / b.height(), out.bottom, out.top), + NineSliceGuide::Bottom => out.bottom = fit((b.y1 - q.y) / b.height(), out.top, out.bottom), + } + out + } +} + /// The most objects [`NineSliceMap::place`] makes for each object of the art it places: an /// object drawn in nine cells becomes a group of nine clip groups, each a clip path and a copy. pub const MAX_SLICE_GROWTH: u64 = 28; @@ -364,6 +437,11 @@ impl NineSliceMap { self.most_at(art, &boxes, 0) } + /// [`Self::most_placed`] for [`Self::place_unclipped`]: the most objects it makes of `art`. + pub fn most_placed_unclipped(&self, art: &Node, doc: &Document) -> u64 { + Self { clips: false, ..*self }.most_placed(art, doc) + } + /// [`Self::most_placed`] for `n` at nesting depth `depth`, following [`Self::place_at`]. fn most_at(&self, n: &Node, boxes: &SymbolBoxes, depth: u32) -> u64 { let whole = n.count_with_masks() as u64; @@ -638,14 +716,30 @@ impl Document { } } + /// The 9-slice guides of the symbol being edited in symbol editing mode, over its art on the + /// editing layer: `None` outside the mode, when the symbol has no guides, or when its art has + /// no width or height. + pub fn edited_nine_slice(&self) -> Option { + let se = self.symbol_edit.as_ref()?; + let guides = self.symbol_nine_slice(&se.symbol)?; + let sym = self.symbols.iter().find(|s| s.name == se.symbol)?; + let art = self.symbol_boxes().quick().art_bounds(&se.symbol).or_else(|| sym.art.geometric_bounds())?; + let natural = self.symbol_natural_xf(&se.symbol); + let b = natural.transform_rect_bbox(art); + if !finite(b) || b.width() <= 1e-9 || b.height() <= 1e-9 || natural.determinant().abs() < 1e-18 { + return None; + } + let to_doc = se.xf * natural.inverse(); + let det = to_doc.determinant(); + let usable = to_doc.as_coeffs().into_iter().all(f64::is_finite) && det.is_finite() && det.abs() > 1e-18; + usable.then(|| EditedNineSlice { symbol: se.symbol.clone(), guides, art: b, to_doc }) + } + /// [`Self::place_symbol_art`] for writers that do not apply clipping /// ([`NineSliceMap::place_unclipped`]). pub fn place_symbol_art_unclipped(&self, name: &str, art: &Node, xf: Affine) -> Option { match self.symbol_slice_map(name, xf) { - Some(m) => { - let m = NineSliceMap { clips: false, ..m }; - (m.most_placed(art, self) <= MAX_SYMBOL_NODES).then(|| m.place(art, self)) - } + Some(m) => (m.most_placed_unclipped(art, self) <= MAX_SYMBOL_NODES).then(|| m.place_unclipped(art, self)), None => Some(transformed(art, xf)), } } @@ -1072,6 +1166,9 @@ mod tests { let bar = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 40.0, 100.0, 60.0)), Appearance::basic(gradient, Paint::None, 0.0)); assert_eq!(m.most_placed(&bar, &d), 10); assert_eq!(m.place(&bar, &d).count(), 10); + // Unclipped, as DXF writes it, the bar is cut at the guides and stays one path. + assert_eq!(m.most_placed_unclipped(&bar, &d), 1); + assert_eq!(m.place_unclipped(&bar, &d).count(), 1); // Art nested past the depth limit, clipped in all nine cells. let mut deep = square(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0); for _ in 0..=MAX_SLICE_DEPTH { @@ -1279,4 +1376,76 @@ mod tests { let v = inst.visual_bounds_with(&d.symbol_boxes()); assert!(v.is_some_and(|b| near(b, whole)), "{v:?}"); } + + /// Symbol "S" of [`markers`] edited in symbol editing mode, its art placed by `xf`. + fn editing(guides: Option, xf: Affine) -> Document { + let mut d = markers(guides); + let layer = d.layers[0].id; + d.symbol_edit = Some(crate::SymbolEdit { + symbol: "S".into(), + layer, + instance: None, + xf, + group: true, + changed: false, + back_isolation: None, + back_layer: None, + }); + d + } + + fn near_point(a: Point, b: Point) -> bool { + (a - b).hypot() < 1e-9 + } + + /// While a symbol with guides is edited, its four guides cross its art's box from edge to edge + /// where the art shows on the editing layer: here at 25 % in, the art doubled and moved. + #[test] + fn the_edited_symbols_guides_cross_its_art_where_the_editing_layer_shows_it() { + let xf = Affine::translate((10.0, 20.0)) * Affine::scale(2.0); + let e = editing(Some(SymbolNineSlice::default()), xf).edited_nine_slice().unwrap(); + assert_eq!(e.symbol, "S"); + let want = [ + (NineSliceGuide::Left, Point::new(60.0, 20.0), Point::new(60.0, 220.0)), + (NineSliceGuide::Top, Point::new(10.0, 70.0), Point::new(210.0, 70.0)), + (NineSliceGuide::Right, Point::new(160.0, 20.0), Point::new(160.0, 220.0)), + (NineSliceGuide::Bottom, Point::new(10.0, 170.0), Point::new(210.0, 170.0)), + ]; + for ((g, a, b), (wg, wa, wb)) in e.lines().into_iter().zip(want) { + assert!(g == wg && near_point(a, wa) && near_point(b, wb), "{g:?} {a:?} {b:?}"); + } + // Outside the mode, without guides, or for a symbol that is gone: no guides. + assert!(markers(Some(SymbolNineSlice::default())).edited_nine_slice().is_none()); + assert!(editing(None, xf).edited_nine_slice().is_none()); + let mut d = editing(Some(SymbolNineSlice::default()), xf); + d.symbols.clear(); + assert!(d.edited_nine_slice().is_none()); + } + + /// Moving a guide changes that guide alone, follows the pointer across its axis only, stays + /// within the art's box and stops short of the opposite guide. + #[test] + fn a_moved_guide_stays_in_the_art_and_short_of_the_opposite_guide() { + let xf = Affine::translate((10.0, 20.0)) * Affine::scale(2.0); + let e = editing(Some(SymbolNineSlice::default()), xf).edited_nine_slice().unwrap(); + let q = SymbolNineSlice { left: 0.25, top: 0.25, right: 0.25, bottom: 0.25 }; + assert_eq!(e.moved(NineSliceGuide::Left, Point::new(30.0, 999.0)), SymbolNineSlice { left: 0.1, ..q }); + assert_eq!(e.moved(NineSliceGuide::Bottom, Point::new(-50.0, 180.0)), SymbolNineSlice { bottom: 0.2, ..q }); + assert_eq!(e.moved(NineSliceGuide::Top, Point::new(0.0, -500.0)), SymbolNineSlice { top: 0.0, ..q }); + assert_eq!(e.moved(NineSliceGuide::Right, Point::new(1e6, 0.0)), SymbolNineSlice { right: 0.0, ..q }); + let crossed = e.moved(NineSliceGuide::Left, Point::new(200.0, 50.0)); + assert!((crossed.left - (0.75 - MIN_CENTER_BAND)).abs() < 1e-12, "{crossed:?}"); + assert!(SymbolNineSlice::new(crossed.left, crossed.top, crossed.right, crossed.bottom).is_some()); + assert_eq!(e.moved(NineSliceGuide::Top, Point::new(f64::NAN, f64::NAN)), q); + // Saved guides closer than the minimum center band keep their place when a drag does not + // move them closer. + let narrow = SymbolNineSlice::new(0.00005, 0.25, 0.9999, 0.25).unwrap(); + let e = editing(Some(narrow), xf).edited_nine_slice().unwrap(); + assert_eq!(e.moved(NineSliceGuide::Left, Point::new(200.0, 50.0)), narrow); + assert_eq!(e.moved(NineSliceGuide::Left, Point::new(0.0, 50.0)), SymbolNineSlice { left: 0.0, ..narrow }); + // A mirrored placement measures along the symbol's own axes. + let e = editing(Some(SymbolNineSlice::default()), Affine::scale_non_uniform(-1.0, 1.0)).edited_nine_slice().unwrap(); + assert!(near_point(e.line(NineSliceGuide::Left).0, Point::new(-25.0, 0.0))); + assert_eq!(e.moved(NineSliceGuide::Left, Point::new(-10.0, 0.0)), SymbolNineSlice { left: 0.1, ..q }); + } } diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index 035b92e349..5461f005ec 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -93,6 +93,10 @@ pub struct CharStyle { /// them. #[serde(default, rename = "charDirection", skip_serializing_if = "Option::is_none")] pub char_direction: Option, + /// Character panel menu › Kashidas: whether these characters may receive a kashida when + /// their paragraph is justified with Insert Kashidas. On by default, including old documents. + #[serde(default = "crate::yes", skip_serializing_if = "crate::skip::is_true")] + pub kashidas: bool, /// Proportional Metrics (Character panel menu, East Asian options): full-width glyphs take the /// font's own proportional widths, OpenType `palt` (#966); in vertical type upright glyphs take /// its proportional heights, `vpal`. @@ -405,6 +409,7 @@ impl Default for CharStyle { position: CharPosition::Normal, char_align: CharAlign::RomanBaseline, char_direction: None, + kashidas: true, proportional_metrics: false, tate_chu_yoko: false, tcy_up_down: 0.0, diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index 5ba5669e62..c6a22a29c4 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -435,12 +435,16 @@ impl crate::Document { st.h_scale = num("h_scale").unwrap_or(st.h_scale); st.v_scale = num("v_scale").unwrap_or(st.v_scale); st.baseline_shift = num("baseline_shift").unwrap_or(st.baseline_shift); + st.tcy_up_down = num("tcyUpDown").unwrap_or(st.tcy_up_down); + st.tcy_left_right = num("tcyLeftRight").unwrap_or(st.tcy_left_right); st.keep_dimensions_in_range(); let kept = [ ("size", Some(st.size)), ("h_scale", Some(st.h_scale)), ("v_scale", Some(st.v_scale)), ("baseline_shift", Some(st.baseline_shift)), + ("tcyUpDown", Some(st.tcy_up_down)), + ("tcyLeftRight", Some(st.tcy_left_right)), ("leading", st.leading), ]; for (k, v) in kept { diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index 7c9f649c7a..b67279bbb4 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -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 { diff --git a/crates/effects/src/stroke/dash.rs b/crates/effects/src/stroke/dash.rs index 5c47c07439..689c88dae1 100644 --- a/crates/effects/src/stroke/dash.rs +++ b/crates/effects/src/stroke/dash.rs @@ -57,6 +57,10 @@ pub fn dash(bp: &BezPath, d: &Dash) -> Option { pat.extend_from_within(..); } let period: f64 = pat.iter().sum(); + // Finite entries can still sum to infinity, which would never leave the phase loop below. + if !period.is_finite() { + return None; + } let plans: Vec = subpaths(bp) .into_iter() .map(|(r, closed)| { diff --git a/crates/effects/src/stroke/tests.rs b/crates/effects/src/stroke/tests.rs index 067064950a..1da14b334e 100644 --- a/crates/effects/src/stroke/tests.rs +++ b/crates/effects/src/stroke/tests.rs @@ -21,6 +21,11 @@ fn stroke(width: f64, f: impl FnOnce(&mut StrokeLayer)) -> StrokeLayer { st } +#[test] +fn dash_period_overflowing_to_infinity_is_solid() { + assert!(dash(&line(0.0, 60.0), &dashed(&[f64::MAX, f64::MAX], -1.0)).is_none()); +} + fn dashed(pattern: &[f64], offset: f64) -> Dash { Dash { pattern: pattern.to_vec(), offset, align_corners: false } } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 285604af5c..1af3693ca5 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -611,6 +611,26 @@ pub(crate) fn unique_name(base: &str, taken: impl Fn(&str) -> bool) -> String { (2..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_else(|| base.to_string()) } +/// [`unique_name`] for names given one after another (an import): `next` keeps, per base (in +/// any case), the number after the last one tried, so a run of one name doesn't count up from 2 +/// again for each copy. Names only become taken meanwhile, so the result is the same. +pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap, taken: impl Fn(&str) -> bool) -> String { + if !taken(base) { + return base.to_string(); + } + let i = next.entry(base.to_lowercase()).or_insert(2); + loop { + let n = format!("{base} {i}"); + *i += 1; + if !taken(&n) { + return n; + } + } +} + +/// The most presets one presets file imports: each is looked up among the saved ones. +pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; + pub(crate) use edit::{settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use vectorcraft_doc::range::parse_range; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 21d73cc4f8..02f8864423 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -7,6 +7,7 @@ mod color; mod document; mod pathtools; mod pen; +mod typetools; use super::CommandSpec; @@ -18,5 +19,6 @@ pub fn specs() -> Vec { v.extend(document::specs()); v.extend(pathtools::specs()); v.extend(pen::specs()); + v.extend(typetools::specs()); v } diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs new file mode 100644 index 0000000000..0cd8e21ea1 --- /dev/null +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -0,0 +1,165 @@ +//! Type Tools (`addon.type.*`), a built-in add-on: Text Tweaker gives one character attribute to +//! the selected characters letter by letter, from a start value to an end value along a shape +//! (straight, eased, a bow, a spike, or at random), while the text stays live. Values are set as +//! the Character panel sets them (`text.setRangeStyle`), in its units and ranges +//! (). Its submenu +//! (Object › Plug-ins › Type Tools) and dialog are the UI's. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_color::recolor::Rng; +use vectorcraft_doc::{NodeId, TextRun}; +use vectorcraft_text::edit; + +use super::super::menucmds::whole_or; +use super::super::object::choice; +use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges}; +use super::super::typecmd::refresh_bounds; +use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or}; +use crate::{EngineError, Result, Session}; + +/// An attribute Text Tweaker sets: its `text.setRangeStyle` param, the values it takes and its +/// default start and end. +type Attribute = (&'static str, (f64, f64), (f64, f64)); + +/// The attributes Text Tweaker sets. +pub const ATTRIBUTES: [Attribute; 8] = [ + ("size", (0.1, 1296.0), (12.0, 36.0)), + ("baselineShift", (-1296.0, 1296.0), (0.0, 12.0)), + ("rotation", (-360.0, 360.0), (0.0, 30.0)), + ("hScale", (1.0, 10000.0), (100.0, 150.0)), + ("vScale", (1.0, 10000.0), (100.0, 150.0)), + ("tracking", (-1000.0, 10000.0), (0.0, 200.0)), + ("leading", (0.1, 5000.0), (12.0, 36.0)), + ("strokeWidth", (0.0, 1000.0), (0.0, 2.0)), +]; +/// The shapes the values follow from the first character to the last. +pub const SHAPES: [&str; 5] = ["straight", "ease", "bow", "spike", "random"]; +/// The most characters one run changes. +const MAX_CHARS: usize = 100_000; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.type.textTweaker", + "Text Tweaker", + ["Object", "Plug-ins", "Type Tools"], + None, + "{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}", + has_selection, + text_tweaker + )] +} + +/// Where along `shape` (0 at `from`, 1 at `to`) character `i` of `n` lands; `random` for the +/// random shape. +fn amount(shape: &str, i: usize, n: usize, random: f64) -> f64 { + let t = if n > 1 { i as f64 / (n - 1) as f64 } else { 0.0 }; + match shape { + "ease" => t * t * (3.0 - 2.0 * t), + "bow" => (std::f64::consts::PI * t).sin(), + "spike" => 1.0 - (2.0 * t - 1.0).abs(), + "random" => random, + _ => t, + } +} + +/// A random number from 0 to 1. +fn unit(rng: &mut Rng) -> f64 { + (rng.next_u64() >> 11) as f64 / (1u64 << 53) as f64 +} + +fn text_tweaker(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.type.textTweaker"; + let attribute = choice(p, C, "attribute", &ATTRIBUTES.map(|a| a.0))?.unwrap_or("size"); + let Some(&(key, (lo, hi), (from0, to0))) = ATTRIBUTES.iter().find(|a| a.0 == attribute) else { + return Err(bad(C, format!("unknown attribute `{attribute}`"))); + }; + let mut ends = [0.0; 2]; + for (end, (k, default)) in ends.iter_mut().zip([("from", from0), ("to", to0)]) { + let v = number_or(p, k, default, C)?; + if !(lo..=hi).contains(&v) { + return Err(bad(C, format!("`{k}` must be from {lo} to {hi} for {key}"))); + } + *end = v; + } + let [from, to] = ends; + let shape = choice(p, C, "shape", &SHAPES)?.unwrap_or("straight"); + let mut rng = Rng::new(whole_or(p, "seed", 0, C)?); + let skip = switch_or(p, "skipSpaces", true, C)?; + let setup = s.doc()?.doc.setup.clone(); + // At a caret, all of the object's text. + let ranges = type_ranges(s, p, C, |text, _| Some((0, text.len())))?; + // Each object's changed characters: (byte, its change), worked out before the edit. + let mut plans: Vec<(NodeId, Vec<(usize, CharChange)>)> = vec![]; + let mut count = 0; + for (id, a, b, _) in ranges { + let t = text_ref(s, id)?; + let text = t.plain_text(); + let chars: Vec = + text.char_indices().filter(|&(i, c)| (a..b).contains(&i) && !(skip && (c.is_whitespace() || c.is_control()))).map(|(i, _)| i).collect(); + count += chars.len(); + if count > MAX_CHARS { + return Err(bad(C, format!("too many characters: at most {MAX_CHARS}"))); + } + let n = chars.len(); + let mut changes = Vec::with_capacity(n); + for (i, at) in chars.into_iter().enumerate() { + let random = if shape == "random" { unit(&mut rng) } else { 0.0 }; + let value = from + (to - from) * amount(shape, i, n, random); + let mut change = CharChange::parse(&json!({ key: value }), C, &setup)?; + change.localize(&t, C)?; + changes.push((at, change)); + } + if !changes.is_empty() { + plans.push((id, changes)); + } + } + if plans.is_empty() { + return Ok(json!({ "count": 0, "ids": [] })); + } + let ids: Vec = plans.iter().map(|(id, _)| id.0).collect(); + s.edit("Text Tweaker", |d, _| { + for (id, changes) in &plans { + let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?; + t.runs = tweak(std::mem::take(&mut t.runs), changes); + refresh_bounds(t); + } + Ok(()) + })?; + Ok(json!({ "count": count, "ids": ids })) +} + +/// `runs` with each character at a byte of `changes` (in order) changed: its run split into +/// characters, the changes applied, and runs that came out alike merged again. +fn tweak(runs: Vec, changes: &[(usize, CharChange)]) -> Vec { + let mut out = Vec::with_capacity(runs.len() + changes.len() * 2); + let mut next = changes.iter().peekable(); + let mut off = 0; + for r in runs { + let end = off + r.text.len(); + if r.inline.is_some() || next.peek().is_none_or(|(at, _)| *at >= end) { + // An inline graphic is one character: its style changes whole. + if let Some((_, change)) = next.next_if(|(at, _)| (off..end).contains(at)) { + let mut r = r; + change.apply(&mut r.style); + out.push(r); + } else { + out.push(r); + } + off = end; + continue; + } + for (i, c) in r.text.char_indices() { + let mut piece = TextRun::new(c.to_string(), r.style.clone()); + if let Some((_, change)) = next.next_if(|(at, _)| *at == off + i) { + change.apply(&mut piece.style); + } + out.push(piece); + } + off = end; + } + edit::normalize(&mut out); + out +} diff --git a/crates/engine/src/cmd/addons/typetools/tests.rs b/crates/engine/src/cmd/addons/typetools/tests.rs new file mode 100644 index 0000000000..47a1b92b9d --- /dev/null +++ b/crates/engine/src/cmd/addons/typetools/tests.rs @@ -0,0 +1,195 @@ +//! Text Tweaker: the values each shape gives each character, what it skips and changes, one undo +//! step, and bad params refused without a change. + +use serde_json::json; +use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextObject}; + +use super::amount; +use crate::Session; + +const C: &str = "addon.type.textTweaker"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +fn text(s: &mut Session, words: &str) -> NodeId { + NodeId(s.execute("text.create", &json!({"x": 40, "y": 100, "text": words, "size": 20})).unwrap()["id"].as_u64().unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.select(|_, sel| sel.set(ids.iter().copied())).unwrap(); +} + +fn obj(s: &Session, id: NodeId) -> TextObject { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("not text"), + } +} + +/// Each character of `id` with its style. +fn styles(s: &Session, id: NodeId) -> Vec<(char, CharStyle)> { + obj(s, id).runs.iter().flat_map(|r| r.text.chars().map(|c| (c, r.style.clone())).collect::>()).collect() +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn near(a: &[f64], b: &[f64]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9) +} + +#[test] +fn the_shapes_run_from_the_start_value_to_the_end_value() { + let at = |shape, n| (0..n).map(|i| amount(shape, i, n, 0.5)).collect::>(); + assert!(near(&at("straight", 5), &[0.0, 0.25, 0.5, 0.75, 1.0])); + assert!(near(&at("ease", 5), &[0.0, 0.15625, 0.5, 0.84375, 1.0]), "slow at both ends"); + let bow = at("bow", 5); + assert!(near(&[bow[0], bow[2], bow[4]], &[0.0, 1.0, 0.0]) && (bow[1] - 0.5f64.sqrt()).abs() < 1e-9, "a smooth arc"); + assert!(near(&at("spike", 5), &[0.0, 0.5, 1.0, 0.5, 0.0]), "straight up and down"); + assert!(near(&at("random", 3), &[0.5; 3])); + assert!(near(&at("straight", 1), &[0.0]), "one character takes the start value"); +} + +#[test] +fn a_straight_ramp_sizes_each_letter_and_skips_spaces() { + let mut s = session(); + let id = text(&mut s, "ab cd"); + select(&mut s, &[id]); + let n = steps(&s); + let out = s.execute(C, &json!({"attribute": "size", "from": 10, "to": 40})).unwrap(); + assert_eq!(out, json!({"count": 4, "ids": [id.0]})); + assert_eq!(steps(&s), n + 1, "one undo step"); + let sizes: Vec<(char, f64)> = styles(&s, id).into_iter().map(|(c, st)| (c, st.size)).collect(); + assert_eq!(sizes, [('a', 10.0), ('b', 20.0), (' ', 20.0), ('c', 30.0), ('d', 40.0)], "the space keeps its size"); + assert_eq!(obj(&s, id).plain_text(), "ab cd", "the text stays live"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(styles(&s, id).iter().all(|(_, st)| st.size == 20.0), "undone"); +} + +#[test] +fn spaces_can_count_too() { + let mut s = session(); + let id = text(&mut s, "a b"); + select(&mut s, &[id]); + s.execute(C, &json!({"attribute": "baselineShift", "from": 0, "to": 10, "skipSpaces": false})).unwrap(); + let shifts: Vec = styles(&s, id).iter().map(|(_, st)| st.baseline_shift).collect(); + assert_eq!(shifts, [0.0, 5.0, 10.0]); +} + +#[test] +fn every_attribute_is_set_as_the_character_panel_sets_it() { + let mut s = session(); + for (attribute, get) in [ + ("size", (|st: &CharStyle| st.size) as fn(&CharStyle) -> f64), + ("baselineShift", |st| st.baseline_shift), + ("rotation", |st| st.rotation), + ("hScale", |st| st.h_scale), + ("vScale", |st| st.v_scale), + ("tracking", |st| st.tracking), + ("leading", |st| st.leading.unwrap_or(-1.0)), + ("strokeWidth", |st| st.stroke_width), + ] { + let id = text(&mut s, "xyz"); + select(&mut s, &[id]); + s.execute(C, &json!({"attribute": attribute, "from": 2, "to": 6})).unwrap(); + let got: Vec = styles(&s, id).iter().map(|(_, st)| get(st)).collect(); + assert!(near(&got, &[2.0, 4.0, 6.0]), "{attribute}: {got:?}"); + } +} + +#[test] +fn each_object_gets_its_own_ramp() { + let mut s = session(); + let (a, b) = (text(&mut s, "abc"), text(&mut s, "de")); + select(&mut s, &[a, b]); + let out = s.execute(C, &json!({"attribute": "rotation", "from": 0, "to": 30})).unwrap(); + assert_eq!(out["count"], json!(5)); + let turns = |id| styles(&s, id).iter().map(|(_, st)| st.rotation).collect::>(); + assert_eq!((turns(a), turns(b)), (vec![0.0, 15.0, 30.0], vec![0.0, 30.0])); +} + +#[test] +fn a_range_changes_only_its_characters() { + let mut s = session(); + let id = text(&mut s, "abcde"); + s.execute(C, &json!({"id": id.0, "start": 1, "end": 4, "attribute": "tracking", "from": 100, "to": 300})).unwrap(); + let tracking: Vec = styles(&s, id).iter().map(|(_, st)| st.tracking).collect(); + assert_eq!(tracking, [0.0, 100.0, 200.0, 300.0, 0.0]); +} + +#[test] +fn random_values_stay_in_range_and_repeat_with_the_seed() { + let mut s = session(); + let id = text(&mut s, "randomness"); + select(&mut s, &[id]); + let run = |s: &mut Session, seed| { + s.execute(C, &json!({"attribute": "vScale", "from": 50, "to": 150, "shape": "random", "seed": seed})).unwrap(); + styles(s, id).iter().map(|(_, st)| st.v_scale).collect::>() + }; + let first = run(&mut s, 7); + assert!(first.iter().all(|v| (50.0..=150.0).contains(v)), "{first:?}"); + assert!(first.windows(2).any(|w| w[0] != w[1]), "values vary"); + assert_eq!(run(&mut s, 7), first, "same seed, same values"); + assert_ne!(run(&mut s, 8), first, "another seed, other values"); +} + +#[test] +fn values_follow_the_text_transform_as_the_character_panel_does() { + let mut s = session(); + let id = text(&mut s, "ab"); + select(&mut s, &[id]); + s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap(); + s.execute(C, &json!({"attribute": "size", "from": 20, "to": 40})).unwrap(); + let sizes: Vec = styles(&s, id).iter().map(|(_, st)| st.size).collect(); + // Shown sizes are the asked ones: stored sizes are half, the text being scaled twice. + let scale = obj(&s, id).style_scale().unwrap().points; + assert!(near(&sizes.iter().map(|v| v * scale).collect::>(), &[20.0, 40.0]), "{sizes:?} at {scale}"); +} + +#[test] +fn empty_text_and_only_spaces_change_nothing() { + let mut s = session(); + let id = text(&mut s, " "); + select(&mut s, &[id]); + let n = steps(&s); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"count": 0, "ids": []})); + assert_eq!(steps(&s), n, "no step"); +} + +#[test] +fn bad_params_are_refused_without_a_change() { + let mut s = session(); + let id = text(&mut s, "abc"); + select(&mut s, &[id]); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + for p in [ + json!({"attribute": "colour"}), + json!({"attribute": 3}), + json!({"shape": "zigzag"}), + json!({"attribute": "size", "from": 0}), + json!({"attribute": "size", "to": 5000}), + json!({"attribute": "hScale", "from": -1}), + json!({"from": "big"}), + json!({"to": f64::MAX}), + json!({"seed": -1}), + json!({"skipSpaces": "yes"}), + json!({"ids": [999_999]}), + ] { + assert!(s.execute(C, &p).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().doc, before, "{p}"); + assert_eq!(steps(&s), n, "{p}"); + } +} + +#[test] +fn it_needs_a_selection() { + let mut s = session(); + text(&mut s, "abc"); + select(&mut s, &[]); + assert!(s.execute(C, &json!({})).is_err()); +} diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 04498111c9..8f36e16f61 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -107,10 +107,14 @@ impl BrushLibrary { /// `name`: the brushes and every resource their art uses. pub fn from_document(src: &Document, names: &[String], name: String) -> std::result::Result { let all = brush::library(src); - if let Some(n) = names.iter().find(|n| !all.iter().any(|b| b.name == **n)) { + // Names looked up in sets: scanning the lists for each brush made a library of N brushes + // cost N² comparisons. + let have: HashSet<&str> = all.iter().map(|b| b.name.as_str()).collect(); + if let Some(n) = names.iter().find(|n| !have.contains(n.as_str())) { return Err(format!("no brush `{n}`")); } - let picked = all.iter().filter(|b| names.is_empty() || names.contains(&b.name)); + let wanted: HashSet<&str> = names.iter().map(String::as_str).collect(); + let picked = all.iter().filter(|b| names.is_empty() || wanted.contains(b.name.as_str())); let clip = Clipboard::gather(src, picked.map(|b| stroke(&b.name)).collect()); let mut doc = clip.to_document(); for l in &mut doc.layers { @@ -120,7 +124,8 @@ impl BrushLibrary { } // The brushes picked and those their art paints with, in the panel order of the document // they came from. - let brushes: Vec = all.into_iter().filter(|b| clip.brushes.iter().any(|c| c.name == b.name)).collect(); + let kept: HashSet<&str> = clip.brushes.iter().map(|c| c.name.as_str()).collect(); + let brushes: Vec = all.iter().filter(|b| kept.contains(b.name.as_str())).cloned().collect(); brush::store(&mut doc, &brushes); doc.title = name.clone(); Ok(Self { name, brushes, doc }) diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index ec2722197d..29933309e9 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -161,10 +161,19 @@ impl Clipboard { d.para_styles = self.para_styles.clone().into(); if !self.brushes.is_empty() { let mut lib = vectorcraft_brush::library(&d); + // Each brush's place in the library by name: finding it by scanning the growing list + // made a library of N brushes cost N² comparisons. + let mut at: std::collections::HashMap = std::collections::HashMap::new(); + for (i, b) in lib.iter().enumerate() { + at.entry(b.name.clone()).or_insert(i); + } for b in &self.brushes { - match lib.iter_mut().find(|x| x.name == b.name) { + match at.get(&b.name).and_then(|&i| lib.get_mut(i)) { Some(x) => *x = b.clone(), - None => lib.push(b.clone()), + None => { + at.insert(b.name.clone(), lib.len()); + lib.push(b.clone()); + } } } vectorcraft_brush::store(&mut d, &lib); diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index 8d9fe0b3fd..b2e1114e1a 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -125,6 +125,10 @@ pub struct Flavour { /// Longest side (px) of the PNG Copy offers: larger art is scaled down to fit. const COPY_PNG_SIDE: f64 = 4096.0; +/// The smallest scale (pixels a point) the PNG encoder renders at. +const MIN_COPY_PNG_SCALE: f64 = 0.01; +/// What Copy says when the art is too large for its PNG. +const TOO_LARGE_FOR_PNG: &str = "The art is too large to copy as a picture: other apps get no PNG of it"; /// Most bytes of text `clipboard.importText` takes. const MAX_TEXT: usize = 1 << 20; /// Most bytes of images the SVG markup may embed and still go out as plain text. A paste reads the @@ -288,12 +292,24 @@ impl Clipboard { let text = (svg && self.image_bytes() <= COPY_TEXT_IMAGE_BYTES) || self.nodes.iter().all(type_only); // Art without an area (a lone guide-like line) has no page or picture. let area = self.bounds().is_some_and(|b| b.width() > 0.0 && b.height() > 0.0); - [(TEXT, text), (SVG, svg), (PDF, pdf && area), (PNG, area)].into_iter().filter_map(|(m, on)| on.then_some(m)).collect() + [(TEXT, text), (SVG, svg), (PDF, pdf && area), (PNG, area && self.png_scale().is_some())] + .into_iter() + .filter_map(|(m, on)| on.then_some(m)) + .collect() + } + + /// The scale (pixels a point) of the PNG Copy offers: at most [`COPY_PNG_SIDE`] pixels a side, + /// and `None` when even [`MIN_COPY_PNG_SCALE`], the encoder's smallest, can't bring it that small + /// (rather than a PNG of up to a gigabyte of pixels). + fn png_scale(&self) -> Option { + let side = self.bounds().map_or(1.0, |b| b.width().max(b.height())); + Some((COPY_PNG_SIDE / side).min(1.0)).filter(|s| *s >= MIN_COPY_PNG_SCALE) } /// What Copy offers other apps, best first, with Include SVG Code (`svg`) and On Copy: PDF /// (`pdf`) as given (see `clipboard.flavours`). A [`Flavour`] that can't be made (art too large - /// to render) is left out; the PNG is scaled down to at most [`COPY_PNG_SIDE`] pixels a side. + /// to render) is left out; the PNG is scaled down to at most [`COPY_PNG_SIDE`] pixels a side, and + /// left out when even [`MIN_COPY_PNG_SCALE`] can't bring it that small. pub fn flavours(&self, svg: bool, pdf: bool) -> Vec { self.flavours_with_warnings(svg, pdf).0 } @@ -305,6 +321,9 @@ impl Clipboard { let svg = types.contains(&SVG).then(|| self.svg()).flatten(); let mut out = vec![]; let mut warnings: Vec = vec![]; + if !self.is_empty() && self.png_scale().is_none() { + warnings.push(TOO_LARGE_FOR_PNG.to_string()); + } let mut keep = |(bytes, notes): (Vec, Vec)| { for w in notes { if !warnings.contains(&w) { @@ -318,11 +337,10 @@ impl Clipboard { TEXT => self.text().or_else(|| svg.clone()).map(String::into_bytes), SVG => svg.clone().map(String::into_bytes), PDF => self.pdf().inspect_err(|e| log::warn!("clipboard PDF: {e}")).ok().flatten().map(&mut keep), - _ => { - let side = self.bounds().map_or(1.0, |b| b.width().max(b.height())); - let scale = (COPY_PNG_SIDE / side).clamp(0.01, 1.0); - self.png(scale).inspect_err(|e| log::warn!("clipboard PNG: {e}")).ok().flatten().map(|(png, _, _, notes)| keep((png, notes))) - } + _ => self + .png_scale() + .and_then(|scale| self.png(scale).inspect_err(|e| log::warn!("clipboard PNG: {e}")).ok().flatten()) + .map(|(png, _, _, notes)| keep((png, notes))), }; out.extend(data.map(|data| Flavour { mime, data })); } diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index e6bd96371b..6a436ab31d 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -14,7 +14,7 @@ //! uses its resources as they are now. use std::cell::OnceCell; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::sync::Arc; use serde_json::{Map, Value, json}; @@ -149,6 +149,39 @@ struct Defs<'a> { char_styles: &'a [TextStyleDef], para_styles: &'a [TextStyleDef], brushes: Brushes<'a>, + /// Where each name is defined, built the first time a kind is followed. + index: DefIndex, +} + +/// The positions of a kind's definitions by name. +type NameIndex = HashMap>; + +/// [`Defs`]' definitions by name (graphic styles by id), each kind indexed the first time a +/// reference to it is followed: finding a name's definitions by scanning them all made a +/// document or library of N definitions that use each other cost N² comparisons. +#[derive(Default)] +struct DefIndex { + swatches: OnceCell, + symbols: OnceCell, + patterns: OnceCell, + styles: OnceCell>>, + char_styles: OnceCell, + para_styles: OnceCell, + brushes: OnceCell, +} + +/// The items of `list` named `name`, in order, `index` holding their positions (built from +/// `list` the first time). +fn named<'l, T>(index: &OnceCell, list: &'l [T], name_of: impl Fn(&T) -> &str, name: &str) -> impl Iterator { + let index = index.get_or_init(|| { + let mut by: NameIndex = HashMap::new(); + for (i, item) in list.iter().enumerate() { + by.entry(name_of(item).to_string()).or_default().push(i); + } + by + }); + let at: &[usize] = index.get(name).map_or(&[], Vec::as_slice); + at.iter().filter_map(move |&i| list.get(i)) } /// The brushes references lead to: a document's library, read the first time a brush is used @@ -178,6 +211,7 @@ impl<'a> Defs<'a> { char_styles: &d.char_styles, para_styles: &d.para_styles, brushes: Brushes::Lazy(d, brushes), + index: DefIndex::default(), } } } @@ -219,8 +253,16 @@ impl Used { fn note<'a>(&mut self, defs: &Defs<'a>, r: Ref<'_>, todo: &mut Vec>) { let (res, name) = match r { Ref::Style(id) => { - if self.styles.insert(id) { - todo.extend(defs.styles.iter().filter(|g| g.id != 0 && g.id == id).map(|g| Source::Appearance(&g.appearance))); + if self.styles.insert(id) && id != 0 { + let index = defs.index.styles.get_or_init(|| { + let mut by: HashMap> = HashMap::new(); + for (i, g) in defs.styles.iter().enumerate() { + by.entry(g.id).or_default().push(i); + } + by + }); + let at = index.get(&id).map_or(&[][..], Vec::as_slice); + todo.extend(at.iter().filter_map(|&i| defs.styles.get(i)).map(|g| Source::Appearance(&g.appearance))); } return; } @@ -237,15 +279,16 @@ impl Used { return; } set.insert(name.to_string()); + let ix = &defs.index; match res { // A tint swatch's base, a gradient swatch's linked stops. - Res::Swatch => todo.extend(defs.swatches.iter().filter(|w| w.name == name).map(|w| Source::Paint(&w.paint))), - Res::Symbol => todo.extend(defs.symbols.iter().filter(|s| s.name == name).map(|s| Source::Node(&s.art))), - Res::Pattern => todo.extend(defs.patterns.iter().filter(|p| p.name == name).flat_map(|p| p.art.iter().map(|a| Source::Node(a)))), - Res::CharStyle => todo.extend(defs.char_styles.iter().filter(|s| s.name == name).map(|s| Source::Attrs(&s.attrs))), - Res::ParaStyle => todo.extend(defs.para_styles.iter().filter(|s| s.name == name).map(|s| Source::Attrs(&s.attrs))), + Res::Swatch => todo.extend(named(&ix.swatches, &defs.swatches, |w| &w.name, name).map(|w| Source::Paint(&w.paint))), + Res::Symbol => todo.extend(named(&ix.symbols, defs.symbols, |s| &s.name, name).map(|s| Source::Node(&s.art))), + Res::Pattern => todo.extend(named(&ix.patterns, defs.patterns, |p| &p.name, name).flat_map(|p| p.art.iter().map(|a| Source::Node(a)))), + Res::CharStyle => todo.extend(named(&ix.char_styles, defs.char_styles, |s| &s.name, name).map(|s| Source::Attrs(&s.attrs))), + Res::ParaStyle => todo.extend(named(&ix.para_styles, defs.para_styles, |s| &s.name, name).map(|s| Source::Attrs(&s.attrs))), // A scatter or art brush's art, a pattern brush's tiles. - Res::Brush => todo.extend(defs.brushes.get().iter().filter(|b| b.name == name).flat_map(|b| b.art().into_iter().map(Source::Node))), + Res::Brush => todo.extend(named(&ix.brushes, defs.brushes.get(), |b| &b.name, name).flat_map(|b| b.art().into_iter().map(Source::Node))), _ => {} } } @@ -649,6 +692,7 @@ impl Clipboard { char_styles: &self.char_styles, para_styles: &self.para_styles, brushes: Brushes::Ready(&self.brushes), + index: DefIndex::default(), }; Used::of(&defs, &self.nodes) } @@ -671,7 +715,7 @@ impl Clipboard { self.import_swatches(d, &used, choices, same_doc, &mut out); // Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art // they may brush; the others once those are in. - let mut added_brushes = self.import_brushes(d, &used, same_doc, false, &mut out); + let mut added_brushes: HashSet = self.import_brushes(d, &used, same_doc, false, &mut out).into_iter().collect(); // Character and paragraph styles (their colours relinked first). for (r, mine, theirs) in [(Res::CharStyle, &self.char_styles, &mut d.char_styles), (Res::ParaStyle, &self.para_styles, &mut d.para_styles)] { for def in mine.iter().filter(|s| used.has(r, &s.name)) { @@ -683,14 +727,14 @@ impl Clipboard { } // Symbols and patterns, compared once relinked. Those added are relinked at the end, when // every new name and graphic style id is known. - let mut added_symbols = vec![]; + let mut added_symbols = HashSet::new(); for def in self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)) { let r = &out.relink; let p = place(&mut d.symbols, def, same_doc, |a, b| same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))); added_symbols.extend(p.new_name(&def.name)); out.placed(Res::Symbol, &def.name, &p); } - let mut added_patterns = vec![]; + let mut added_patterns = HashSet::new(); for def in self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)) { // Tile options alike, and the art once relinked. let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() }; diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index 7131dd9d4d..260b981d27 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -1,7 +1,7 @@ //! Document Info panel data, its categories and the text report (Document Info › Save…, File → //! Package), and Object → Make Pixel Perfect. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashSet}; use serde_json::{Value, json}; use vectorcraft_color::Paint; @@ -293,8 +293,14 @@ fn info(s: &mut Session, p: &Value) -> Result { // `repeats` and `repeat_rows` hold the `repeatObjects` entries and the rows of the Repeat objects that the walk visits, in walk order. let mut repeats: Vec = vec![]; let mut repeat_rows: Vec<(String, String)> = vec![]; + // The objects the walk has visited: a selection can hold a group and objects inside it, and each object counts once. + // The set holds each object's address, so two objects that share an id (as a damaged file can hold) count as two. + let mut seen: HashSet<*const Node> = HashSet::new(); for r in roots { r.walk(&mut |n| { + if !seen.insert(std::ptr::from_ref(n)) { + return; + } let k = match &n.kind { NodeKind::Layer { .. } => None, NodeKind::Group { clip: true, .. } => Some("clipGroups"), @@ -337,13 +343,15 @@ fn info(s: &mut Session, p: &Value) -> Result { if let Some(k) = k { *counts.entry(k).or_default() += 1; } + // The paint kinds this object's fills and strokes use, each once. + let mut kinds = BTreeSet::new(); for item in &n.appearance.items { let paint = match item { vectorcraft_doc::AppearanceItem::Fill(f) => &f.paint, vectorcraft_doc::AppearanceItem::Stroke(s) => &s.paint, }; if let Some(k) = paint_kind(paint) { - *counts.entry(k).or_default() += 1; + kinds.insert(k); } if let Paint::Pattern { pattern, .. } = paint { patterns.insert(pattern.clone()); @@ -354,6 +362,9 @@ fn info(s: &mut Session, p: &Value) -> Result { spot.insert(name.clone()); } } + for k in kinds { + *counts.entry(k).or_default() += 1; + } if n.extras().mask.is_some() { *counts.entry("opacityMasks").or_default() += 1; } @@ -552,7 +563,7 @@ mod tests { /// Document Info › Repeat Objects lists each Repeat object by name with its kind and the number /// of instances it makes (for a grid, its rows and columns, followed by the number it draws when /// that is fewer), one in a group included. With Selection Only it lists the Repeat objects in - /// the selection. + /// the selection, each once when the selection holds a group and a Repeat object inside it. #[test] fn info_lists_the_repeat_objects() { let mut s = Session::new(); @@ -590,6 +601,11 @@ mod tests { }; s.execute("select.set", &json!({"ids": [grid, group]})).unwrap(); assert_eq!(names(&mut s), ["Tiles", ""]); + // A selection that holds the group and the Repeat object inside it lists that object once. + for ids in [json!([group, mirror]), json!([mirror, group])] { + s.execute("select.set", &json!({"ids": ids})).unwrap(); + assert_eq!(names(&mut s), [""], "{ids}"); + } s.execute("select.set", &json!({"ids": [radial]})).unwrap(); assert_eq!(names(&mut s), [""]); s.execute("select.set", &json!({"ids": [d]})).unwrap(); @@ -618,6 +634,64 @@ mod tests { assert_eq!(i["sections"][0]["rows"][0], json!(["", "Grid Repeat, 500 rows × 500 columns, 125000 instances"])); } + /// Document Info › Objects counts an object with a gradient or a pattern on both its fill and + /// its stroke once, and with Selection Only a selection that holds a group and an object inside + /// it counts that object once. + #[test] + fn info_counts_each_object_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let square = + |s: &mut Session, x: f64| s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + let tile = square(&mut s, 0.0); + s.execute("object.pattern.make", &json!({"ids": [tile], "name": "Dots", "edit": false})).unwrap(); + let (g, p) = (square(&mut s, 100.0), square(&mut s, 200.0)); + let gradient = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}); + s.execute("paint.setFill", &json!({"ids": [g], "gradient": gradient})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [g], "gradient": gradient})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [p], "swatch": "Dots"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [p], "swatch": "Dots"})).unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + assert_eq!((i["objects"]["gradients"].as_u64(), i["objects"]["patterns"].as_u64()), (Some(1), Some(1)), "{}", i["objects"]); + // A group of the two squares, selected together with one of them. + s.execute("select.set", &json!({"ids": [g, p]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].clone(); + for ids in [json!([group, p]), json!([p, group])] { + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let i = s.execute("document.info", &json!({"selectionOnly": true})).unwrap(); + let o = &i["objects"]; + assert_eq!( + (o["paths"].as_u64(), o["groups"].as_u64(), o["gradients"].as_u64(), o["patterns"].as_u64()), + (Some(2), Some(1), Some(1), Some(1)), + "{ids}: {o}" + ); + assert!((i["pathLength"].as_f64().unwrap() - 80.0).abs() < 1e-6, "{ids}: {}", i["pathLength"]); + } + } + + /// Document Info › Objects counts two objects that share an id (as a damaged file can hold) as + /// two, in the whole document and in a selected group that holds both. + #[test] + fn info_counts_objects_that_share_an_id() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let square = |s: &mut Session, x: f64| { + s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (square(&mut s, 0.0), square(&mut s, 100.0)); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].clone(); + s.execute("select.set", &json!({"ids": [group]})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.node_mut(NodeId(b)).unwrap().id = NodeId(a); + for p in [json!({}), json!({"selectionOnly": true})] { + let i = s.execute("document.info", &p).unwrap(); + let o = &i["objects"]; + assert_eq!((o["paths"].as_u64(), o["groups"].as_u64()), (Some(2), Some(1)), "{p}: {o}"); + assert!((i["pathLength"].as_f64().unwrap() - 80.0).abs() < 1e-6, "{p}: {}", i["pathLength"]); + } + } + #[test] fn embedding_permissions_read_from_fs_type() { assert_eq!(embedding_label(0), "embedding allowed"); diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index dc6d2a6559..58d5daf17a 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -66,6 +66,15 @@ pub fn specs() -> Vec { "select.same.textStrokeColor", |a, b| a.stroke == b.stroke )), + cmd!( + "select.same.textFillAndStrokeColor", + "Text Fill & Stroke Color", + ["Select", "Same"], + None, + "{} select the type objects with characters whose fill and stroke both match the first character of the first selected type → {count}", + has_selection, + |s, _| same_text(s, "select.same.textFillAndStrokeColor", |a, b| a.fill == b.fill && a.stroke == b.stroke) + ), cmd!( "select.object.directionHandles", "Direction Handles", @@ -316,7 +325,7 @@ fn first_text_style(s: &Session) -> Option { fn same_text(s: &mut Session, cmd: &str, eq: fn(&CharStyle, &CharStyle) -> bool) -> Result { 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) diff --git a/crates/engine/src/cmd/fileio/affinity/master_copies.rs b/crates/engine/src/cmd/fileio/affinity/master_copies.rs index 91b0ce53ce..f0ab8bd404 100644 --- a/crates/engine/src/cmd/fileio/affinity/master_copies.rs +++ b/crates/engine/src/cmd/fileio/affinity/master_copies.rs @@ -1,7 +1,8 @@ use super::nodes::MAX_DEPTH; use super::{Kind, af}; -/// What copying a subtree takes: its nodes, characters and table cells (`work`), and its pixels. +/// What copying a subtree takes: its nodes, characters, table cells and path segments (`work`), +/// and its pixels. #[derive(Clone, Copy, Debug, Default)] pub(super) struct CopyCost { pub(super) work: u64, @@ -40,8 +41,58 @@ pub(super) fn copy_cost(n: &af::Node, depth: usize) -> CopyCost { let own = match &n.kind { Kind::Text(t) => CopyCost { work: 1 + len(&t.runs), pixels: 0 }, Kind::Table(t) => CopyCost { work: 1 + t.cells.iter().map(|c| 1 + len(&c.runs)).sum::(), pixels: 0 }, - Kind::Image(img) => CopyCost { work: 1, pixels: u64::from(img.width) * u64::from(img.height) }, + Kind::Image(img) => CopyCost { work: 1, pixels: pixels(img) }, + // Each copy builds its own path: a curve of many segments costs them all. + Kind::Shape { path, .. } | Kind::Artboard { path, .. } => CopyCost { work: 1 + segments(path), pixels: 0 }, _ => CopyCost { work: 1, pixels: 0 }, }; - n.children.iter().fold(own, |c, ch| c.plus(copy_cost(ch, depth + 1))) + // A vector mask is a path of its own, and a pixel mask an image of its own, in every copy. + let mask = + CopyCost { work: n.mask.as_ref().map_or(0, segments) + u64::from(n.pixel_mask.is_some()), pixels: n.pixel_mask.as_ref().map_or(0, pixels) }; + n.children.iter().fold(own.plus(mask), |c, ch| c.plus(copy_cost(ch, depth + 1))) +} + +/// The subpaths and segments of `p`. +fn segments(p: &af::Path) -> u64 { + p.subpaths.iter().map(|s| 1 + s.segments.len() as u64).sum() +} + +fn pixels(img: &af::Image) -> u64 { + u64::from(img.width) * u64::from(img.height) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn node(kind: Kind, mask: Option) -> af::Node { + af::Node { + class: vectorcraft_affinity::stream::Tag::of(b"ShpN"), + name: String::new(), + visible: true, + locked: false, + opacity: 1.0, + blend: af::Blend::Normal, + kind, + mask, + pixel_mask: None, + effects: vec![], + children: vec![], + } + } + + fn path(n: usize) -> af::Path { + let p = af::Point { x: 0.0, y: 0.0 }; + af::Path { subpaths: vec![af::SubPath { start: p, segments: vec![[p; 3]; n], closed: false }] } + } + + /// A curve, and a vector mask, cost every segment each copy rebuilds: a shape of a million + /// segments shown on many pages can't pass as one object. + #[test] + fn paths_and_masks_cost_their_segments() { + let shape = |n| Kind::Shape { path: path(n), fills: vec![], strokes: vec![], even_odd: false }; + assert!(copy_cost(&node(shape(1_000_000), None), 0).work > 1_000_000); + assert!(copy_cost(&node(Kind::Group, Some(path(1_000_000))), 0).work > 1_000_000); + assert!(copy_cost(&node(shape(3), None), 0).work < 10); + } } diff --git a/crates/engine/src/cmd/fileio/affinity/nodes.rs b/crates/engine/src/cmd/fileio/affinity/nodes.rs index 2e93342279..36734dbe39 100644 --- a/crates/engine/src/cmd/fileio/affinity/nodes.rs +++ b/crates/engine/src/cmd/fileio/affinity/nodes.rs @@ -11,6 +11,15 @@ pub(super) fn affine(a: af::Affine) -> Affine { Affine::new(a.0) } +/// Are all of `p`'s points, mapped by `to_doc`, finite and within `MAX_COORD` of the origin? +pub(super) fn path_in_range(p: &af::Path, to_doc: Affine) -> bool { + let ok = |q: &af::Point| { + let d = to_doc * kurbo::Point::new(q.x, q.y); + [d.x, d.y].iter().all(|v| v.is_finite() && v.abs() <= crate::MAX_COORD) + }; + p.subpaths.iter().all(|s| ok(&s.start) && s.segments.iter().flatten().all(ok)) +} + impl Builder { pub(super) fn layer_with(&mut self, name: Option<&str>, children: Vec>) -> Arc { let id = self.doc.alloc_id(); @@ -107,6 +116,12 @@ impl Builder { return None; } } + // So must its vector mask, which becomes a clipping path: every control point, not just + // the finite ones a bounding box takes. + if n.mask.as_ref().is_some_and(|m| !path_in_range(m, to_doc)) { + self.warn("objects beyond the document range VectorCraft supports (left out)"); + return None; + } let n = &*self.overlaid(n); // Register before descending so nested artboards keep their document order. Inside an // embedded document an artboard is just its content's frame. @@ -252,3 +267,25 @@ impl Builder { Some(Arc::new(out)) } } + +#[cfg(test)] +mod tests { + use super::*; + + fn path(points: &[(f64, f64)]) -> af::Path { + let p = |&(x, y): &(f64, f64)| af::Point { x, y }; + let start = p(&points[0]); + let segments = points[1..].iter().map(|q| [start, p(q), p(q)]).collect(); + af::Path { subpaths: vec![af::SubPath { start, segments, closed: true }] } + } + + /// A mask's control points are checked as mapped into the document, NaN ones included. + #[test] + fn mask_paths_must_stay_in_the_document_range() { + let k = Affine::scale(0.75); + assert!(path_in_range(&path(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)]), k)); + assert!(!path_in_range(&path(&[(0.0, 0.0), (1.0e7, 0.0)]), k)); + assert!(!path_in_range(&path(&[(0.0, 0.0), (f64::NAN, 0.0)]), k)); + assert!(!path_in_range(&path(&[(0.0, 0.0), (1.0, 1.0)]), Affine::scale(1.0e9))); + } +} diff --git a/crates/engine/src/cmd/fileio/naming.rs b/crates/engine/src/cmd/fileio/naming.rs index e701a03d05..12cf26ca0b 100644 --- a/crates/engine/src/cmd/fileio/naming.rs +++ b/crates/engine/src/cmd/fileio/naming.rs @@ -70,9 +70,11 @@ pub fn render(template: &str, p: &NameParts<'_>) -> String { let mut out = String::with_capacity(t.len() + 16); let mut rest = t; while let Some(c) = rest.chars().next() { - // Bracketed tokens; an unknown one stays as written, with `-` for its brackets. + // Bracketed tokens; an unknown one stays as written, with `-` for its brackets. A token's + // name has no `<`, so the search for its `>` stops at the next `<`: each part of the + // pattern is searched once, not once for every `<` before it. if c == '<' - && let Some(end) = rest.find('>') + && let Some(end) = rest.get(1..).and_then(|r| r.find(['<', '>'])).map(|i| i + 1).filter(|&i| rest.as_bytes().get(i) == Some(&b'>')) && let Some(value) = rest.get(1..end).and_then(|name| token(name, p)) { out.push_str(&value); @@ -155,6 +157,16 @@ mod tests { assert_eq!(render("#", &NameParts { counter: 12345, ..parts() }), "12345"); } + /// Many `<` without a `>`, or before one far away, are each looked at once. + #[test] + fn unmatched_brackets_are_read_in_one_pass() { + let p = parts(); + let n = 200_000; + assert_eq!(render(&"<".repeat(n), &p), "-".repeat(n)); + assert_eq!(render(&format!("{}", "<".repeat(n)), &p), format!("{}Dark", "-".repeat(n))); + assert_eq!(render(">", &p), "-aDark-"); + } + #[test] fn dates_are_strict_about_hyphens_and_days() { for bad in ["2026-1-011", "2-0-2-6-1-0-1-6", "2026--10--16", "2026-02-31", "2026-10-16-", "202610-16"] { diff --git a/crates/engine/src/cmd/fileio/native.rs b/crates/engine/src/cmd/fileio/native.rs index 948556c7a6..6c2b002580 100644 --- a/crates/engine/src/cmd/fileio/native.rs +++ b/crates/engine/src/cmd/fileio/native.rs @@ -35,6 +35,12 @@ pub const OPTIONS: &[FormatOption] = &[ default: "false", description: "embed a PNG preview of the first artboard (at most 256 pixels on its longer side) for file browsers", }, + FormatOption { + name: "precision", + ty: "integer", + default: "null", + description: "round path anchors and handles to this many decimal places, 0 to 9 (a smaller file; colors, transforms and type are kept exactly); null writes them exactly. Only the save that gives it rounds", + }, SEPARATE_ARTBOARDS, SEPARATE_RANGE, INCLUDE_LINKED, @@ -131,6 +137,7 @@ struct NativeOptions { compress: Option, version: Option, preview: bool, + precision: Option, include_linked: bool, embed_profiles: Option, pdf_compatible: bool, @@ -151,6 +158,7 @@ pub(super) fn save_options(cmd: &str, f: &Format, doc: &Document, p: &Value) -> compress: o.compress.unwrap_or(false), version: o.version.unwrap_or(vectorcraft_format::VERSION), include_linked: o.include_linked, + precision: o.precision.map(|v| precision(cmd, &v)).transpose()?, ..SaveOptions::default() }; if o.embed_profiles.unwrap_or(true) { @@ -160,6 +168,20 @@ pub(super) fn save_options(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Ok((so, Extras { preview: o.preview, pdf: o.pdf_compatible })) } +/// The `precision` option `v`: a whole number of decimal places, 0 to +/// [`vectorcraft_format::MAX_PRECISION`]. Any other value, a string included, gets the range message. +fn precision(cmd: &str, v: &Value) -> Result { + let (key, min, max) = ("precision", 0u8, vectorcraft_format::MAX_PRECISION); + if let Some(x) = v.as_f64() + && x.fract() == 0.0 + && (f64::from(min)..=f64::from(max)).contains(&x) + { + return Ok(x as u8); + } + let x = v.as_f64().map_or_else(|| v.to_string(), |x| x.to_string()); + Err(bad(cmd, format!("`{key}` must be a whole number between {min} and {max} (got {x})"))) +} + /// The `.vectorcraft` file of `doc` with the options in `p`. pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result> { let mut out = Vec::new(); @@ -177,13 +199,19 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp } else { std::borrow::Cow::Borrowed(doc) }; + // With a precision, the preview and PDF show the rounded art the file holds. + let drawn = match so.precision { + Some(decimals) if extras.preview || extras.pdf => Cow::Owned(rounded(&full, so.version, decimals)), + _ => Cow::Borrowed(full.as_ref()), + }; if extras.preview { - so.preview = preview_png(&full)?; + so.preview = preview_png(&drawn)?; } if extras.pdf { // Every artboard as PDF pages (no editing data: the file is the native document). - so.pdf = Some(super::pdf::encode(cmd, &full, &json!({ "range": "all", "preserveEditing": false }))?.0); + so.pdf = Some(super::pdf::encode(cmd, &drawn, &json!({ "range": "all", "preserveEditing": false }))?.0); } + drop(drawn); let native = match full { Cow::Owned(full) if so.include_linked && so.version >= vectorcraft_format::VERSION => { // Include available bytes without replacing missing, relinkable placed objects. @@ -197,6 +225,20 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp vectorcraft_format::save_to(&native, &so, w).map_err(|e| bad(cmd, e.to_string())) } +/// `doc` with its path geometry rounded to `decimals` places, as [`vectorcraft_format::save_to`] +/// writes it for `version`: placed documents become groups of their art for older versions. +fn rounded(doc: &Document, version: u32, decimals: u8) -> Document { + let mut d = if version < vectorcraft_format::VERSION && doc.has_placed() { + let mut d = doc.with_placed_art().into_owned(); + d.placed_as_groups(); + d + } else { + doc.clone() + }; + d.round_geometry(decimals.min(vectorcraft_format::MAX_PRECISION)); + d +} + /// The ICC files of the profiles `doc` is tagged with that were loaded from files (the built-in /// ones are there wherever VectorCraft runs). fn embedded_profiles(doc: &Document) -> BTreeMap> { @@ -230,8 +272,8 @@ pub(super) fn ai_options(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Re let mut q = p.clone(); if let Some(o) = q.as_object_mut() { // AI carries the current native format without a separate preview. Its compression - // and PDF-content flags are still validated as booleans. - o.retain(|k, _| !matches!(k.as_str(), "version" | "preview")); + // and PDF-content flags are still validated as booleans. Its coordinates are written exactly. + o.retain(|k, _| !matches!(k.as_str(), "version" | "preview" | "precision")); if o.get("pdfCompatible").is_some_and(Value::is_null) { o.remove("pdfCompatible"); } diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index a38c4b93ce..de67968dad 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -134,8 +134,9 @@ pub fn templates_folder(prefs: &Prefs) -> Option { pub fn templates_dialog_folder(prefs: &Prefs) -> Option { let folder = std::path::PathBuf::from(templates_folder(prefs)?); if !folder.is_dir() { - // Best effort: a folder that can't be made leaves the nearest one that exists. - let _ = std::fs::create_dir_all(&folder); + // Best effort: a folder that can't be made (or automation may not write) leaves the + // nearest one that exists. + let _ = super::create_dir(&folder.to_string_lossy()); } folder.ancestors().find(|a| a.is_dir()).map(|a| a.to_string_lossy().into_owned()).or_else(home_folder) } @@ -265,7 +266,7 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result { given = svg; } else { // So do PDF options (as the Save PDF dialog and document.exportPdf name them) and the - // native ones (compress, version, preview). + // native ones (compress, version, preview, precision). if let Some(o) = p.as_object() { given.extend( o.iter().filter(|(k, v)| !v.is_null() && k.as_str() != "path" && reads_option(format, k)).map(|(k, v)| (k.clone(), v.clone())), @@ -296,7 +297,7 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result { } /// The native save options, which a save also takes beside the path. -const NATIVE_OPTIONS: [&str; 3] = ["compress", "version", "preview"]; +const NATIVE_OPTIONS: [&str; 4] = ["compress", "version", "preview", "precision"]; /// The first option `p` gives both beside the path and in `options` with different values, as /// `(key, top-level value, options value)`. For an SVG save (`svg`), an SVG option's value on @@ -839,6 +840,8 @@ impl SaveJob { st.path = Some(path); st.format = self.plan.format.id; st.save_options = self.plan.options; + // A later save rounds only when it gives `precision` too. + st.save_options.remove("precision"); st.save_artboards = self.snapshot.artboards.iter().map(|a| a.id).collect(); st.converted = false; st.recovered = false; @@ -869,7 +872,7 @@ impl SaveJob { let saved = self.plan.retargets() && self.plan.path.is_some(); if saved && self.plan.format.id == "vectorcraft" { let mut last = self.plan.options.clone(); - last.retain(|k, _| !ARTBOARD_PARAMS.contains(&k.as_str()) && !matches!(k.as_str(), "separateArtboards" | "compress")); + last.retain(|k, _| !ARTBOARD_PARAMS.contains(&k.as_str()) && !matches!(k.as_str(), "separateArtboards" | "compress" | "precision")); s.prefs.native_save_options = last; } // The other open documents that place this one show the new version. @@ -964,7 +967,7 @@ pub(super) fn specs() -> Vec { "Save Document", [], None, - "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version or preview given flat), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: false for native (also carry a PDF of every artboard) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly; separateArtboards writes more files, one per artboard. EPS saves the chosen artboard (first by default), retaining its page margins and the whole editable document; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified", + "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: false for native (also carry a PDF of every artboard) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly; separateArtboards writes more files, one per artboard. EPS saves the chosen artboard (first by default), retaining its page margins and the whole editable document; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified", has_doc, |s, p| save(s, SaveMode::Save, p) ), @@ -973,7 +976,7 @@ pub(super) fn specs() -> Vec { "Save As…", ["File"], Some("Cmd+Shift+S"), - "{…as document.save} {path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own; ait, a .ait template, is written by file.saveAsTemplate), options?, svg?, modified?} the document takes on the new path, name and format (except a template, which is always a copy) → {path, format, bytes, warnings}; no path → {dataBase64, format, name, folder?, warnings}", + "{…as document.save} {path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own; ait, a .ait template, is written by file.saveAsTemplate), options?, svg?, precision?, modified?} the document takes on the new path, name and format (except a template, which is always a copy) → {path, format, bytes, warnings}; no path → {dataBase64, format, name, folder?, warnings}", has_doc, |s, p| save(s, SaveMode::SaveAs, p) ), @@ -982,7 +985,7 @@ pub(super) fn specs() -> Vec { "Save a Copy…", ["File"], Some("Cmd+Alt+S"), - "{…as document.save} {path?, format?, options?} write a copy; the document keeps its path, title and modified state → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \" copy.\", folder?, warnings}", + "{…as document.save} {path?, format?, options?, precision?} write a copy; the document keeps its path, title and modified state → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \" copy.\", folder?, warnings}", has_doc, |s, p| save(s, SaveMode::Copy, p) ), @@ -991,7 +994,7 @@ pub(super) fn specs() -> Vec { "Save as Template…", ["File"], None, - "{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \" template.\", folder: the Templates folder (preference templatesFolder), warnings}", + "{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?, precision?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \" template.\", folder: the Templates folder (preference templatesFolder), warnings}", has_doc, |s, p| save(s, SaveMode::Template, p) ), @@ -1072,6 +1075,13 @@ mod tests_folders { std::fs::write(base.join("blocked"), b"x").unwrap(); prefs.templates_folder = base.join("blocked").join("Templates").to_string_lossy().into_owned(); assert_eq!(super::templates_dialog_folder(&prefs).map(PathBuf::from), Some(base.clone())); + // Automation that may not write there makes no folder. + let outside = base.join("Outside").join("Templates"); + prefs.templates_folder = outside.to_string_lossy().into_owned(); + std::fs::create_dir_all(base.join("Allowed")).unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[&base], &[&base.join("Allowed")]).unwrap().unwrap(); + crate::file_access::confine(Some(&roots), || super::templates_dialog_folder(&prefs)); + assert!(!outside.exists(), "not made"); let _ = std::fs::remove_dir_all(&base); } } diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 384f731aa3..26737e158c 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -521,6 +521,11 @@ struct Output { folders: std::collections::HashMap, /// Sub-folders already made, by their [`fold`]ed names. made: HashSet, + /// For each [`fold`]ed name asked for, the number to try next: many files given one name + /// would otherwise try `-2`, `-3`… from the start each time. + next: std::collections::HashMap, + /// Each [`fold`]ed name asked for with the file (`key`) that got a name from it. + claimed: HashSet<(String, String)>, /// `(relative name, bytes)` kept to return or zip (empty when written to a folder). kept: Vec<(String, Vec)>, /// The paths written. @@ -540,8 +545,14 @@ impl Output { } None => name.to_string(), }; + let asked = (fold(&name), key.to_string()); + // The same file under the same name again: it has its name already. + if self.claimed.contains(&asked) { + return None; + } let (base, ext) = name.rsplit_once('.').map_or((name.as_str(), ""), |(b, e)| (b, e)); - for n in 1.. { + let start = self.next.get(&asked.0).copied().unwrap_or(1); + for n in start.. { let candidate = if n == 1 { name.to_string() } else if ext.is_empty() { @@ -554,6 +565,8 @@ impl Output { Some(_) => continue, None => { self.taken.insert(fold(&candidate), key.to_string()); + self.next.insert(asked.0.clone(), n + 1); + self.claimed.insert(asked); return Some(candidate); } } @@ -685,6 +698,8 @@ fn preset_settings(s: &Session, cmd: &str, given: &Map) -> Result // Refuse what an export would refuse, now rather than when the preset is used. check_settings(s, &Value::Object(settings.clone())).map_err(|e| bad(cmd, e.to_string()))?; Folders::of(&ScreenParams::of(&Value::Object(settings.clone()))?).map_err(|e| bad(cmd, e.to_string()))?; + let mut settings = settings; + remove_passwords(&mut settings); Ok(settings) } @@ -912,6 +927,7 @@ pub(crate) fn with_export_preset(s: &Session, cmd: &str, settings: &mut Map Result { + check_passwords(p)?; let o = ScreenParams::of(p)?; let rows = rows_of(s, p, o.preset.as_deref())?; o.one_source()?; @@ -1262,9 +1278,61 @@ fn remember(s: &mut Session, p: &Value) { let _ = store_settings(s, settings); } +/// The PDF passwords an export may be given (`security` of a PDF row or of `settings.pdf`). +const PASSWORD_KEYS: [&str; 2] = ["openPassword", "permissionsPassword"]; + +/// Left where [`remove_passwords`] took a password out: an export of these settings is refused +/// until a password is given again ([`check_passwords`]), rather than written unprotected. +const PASSWORD_REQUIRED: &str = "passwordRequired"; + +/// `settings` without the PDF passwords anywhere in them: settings kept in the document (which +/// native saves write) or in the preferences hold the export's choices, never its secrets, as +/// the PDF settings themselves are saved without them. Where one was given, [`PASSWORD_REQUIRED`] +/// says so. +fn remove_passwords(settings: &mut Map) { + let mut removed = false; + for key in PASSWORD_KEYS { + removed |= settings.remove(key).is_some_and(|v| v.as_str().is_none_or(|p| !p.is_empty())); + } + if removed { + settings.insert(PASSWORD_REQUIRED.into(), Value::Bool(true)); + } + for v in settings.values_mut() { + remove_passwords_in(v); + } +} + +/// Refuse export params `v` that hold settings whose PDF passwords were left out +/// ([`PASSWORD_REQUIRED`]) without a password given again. +fn check_passwords(v: &Value) -> Result<()> { + match v { + Value::Object(m) => { + let given = PASSWORD_KEYS.iter().any(|k| m.get(*k).and_then(Value::as_str).is_some_and(|p| !p.is_empty())); + if m.get(PASSWORD_REQUIRED) == Some(&Value::Bool(true)) && !given { + return Err(bad( + C, + "the PDF security settings were saved without their passwords: give openPassword or permissionsPassword again, or security without passwordRequired to export unprotected", + )); + } + m.values().try_for_each(check_passwords) + } + Value::Array(items) => items.iter().try_for_each(check_passwords), + _ => Ok(()), + } +} + +fn remove_passwords_in(v: &mut Value) { + match v { + Value::Object(m) => remove_passwords(m), + Value::Array(items) => items.iter_mut().for_each(remove_passwords_in), + _ => {} + } +} + /// Make `settings` the document's export settings. Not an undo step (like the settings of any /// export); the document has changed only if they differ. -pub(crate) fn store_settings(s: &mut Session, settings: Map) -> Result<()> { +pub(crate) fn store_settings(s: &mut Session, mut settings: Map) -> Result<()> { + remove_passwords(&mut settings); let st = s.doc_mut()?; if st.doc.export_settings != settings { Arc::make_mut(&mut st.doc).export_settings = settings; @@ -1280,7 +1348,26 @@ pub(super) fn export_settings(s: &mut Session, _: &Value) -> Result { #[cfg(test)] mod tests { - use super::{ScreenSize, safe_file_name}; + use super::{Output, ScreenSize, safe_file_name}; + + /// Files given one name are numbered in turn, each numbering going on from the last one (so + /// thousands of them don't each try every number used before), and a file asking again for + /// the name it got is told it has it. + #[test] + fn taken_names_are_numbered_from_the_last_number() { + let mut out = Output::default(); + assert_eq!(out.claim("a.png", "1").as_deref(), Some("a.png")); + assert_eq!(out.claim("A.png", "2").as_deref(), Some("A-2.png")); + assert_eq!(out.claim("a-3.png", "x").as_deref(), Some("a-3.png")); + assert_eq!(out.claim("a.png", "3").as_deref(), Some("a-4.png")); + assert_eq!(out.claim("a.png", "2"), None); + assert_eq!(out.claim("a.png", "1"), None); + assert_eq!(out.claim("sub/a.png", "1").as_deref(), Some("sub/a.png")); + for k in 0..20_000 { + assert!(out.claim("same.png", &k.to_string()).is_some()); + } + assert_eq!(out.claim("same.png", "last").as_deref(), Some("same-20001.png")); + } #[test] fn size_parse_refuses_signs_and_exponents() { @@ -1302,4 +1389,22 @@ mod tests { assert_eq!(safe_file_name("lpt9 .png"), "lpt9-.png"); assert_eq!(safe_file_name("My CON .png"), "My CON .png"); } + + /// The settings an export leaves in the document keep its PDF security choices but not its + /// passwords, in a row or in `settings.pdf`. + #[test] + fn stored_settings_leave_out_pdf_passwords() { + let mut s = crate::Session::new(); + s.execute("file.new", &serde_json::json!({"width": 100, "height": 100})).unwrap(); + let given = serde_json::json!({ + "formats": [{"format": "pdf", "security": {"openPassword": "open sesame", "permissionsPassword": "owner", "printing": "low"}}], + "settings": {"pdf": {"security": {"openPassword": "open sesame", "copy": false}}}, + }); + super::store_settings(&mut s, given.as_object().unwrap().clone()).unwrap(); + let kept = serde_json::Value::Object(s.doc().unwrap().doc.export_settings.clone()); + assert!(!kept.to_string().contains("Password"), "{kept}"); + assert_eq!(kept["formats"][0]["security"]["printing"], "low"); + assert_eq!(kept["settings"]["pdf"]["security"]["copy"], false); + assert_eq!(kept["formats"][0]["security"]["passwordRequired"], true); + } } diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index e8cd8e6538..69158c04b8 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -704,8 +704,8 @@ fn a_native_save_streams_the_bytes_the_encoder_makes() { } /// An option given beside the path (an SVG option flat or in `svg`) and in `options` with different -/// values is refused before anything is written; `compress`, `version` or `preview` beside the path of a format that doesn't -/// read it is named in the warnings. +/// values is refused before anything is written; `compress`, `version`, `preview` or `precision` beside the path of a format +/// that doesn't read it is named in the warnings. #[test] fn a_save_refuses_disagreeing_options_and_names_unread_native_ones() { let d = tmp_dir("save-options"); @@ -752,6 +752,16 @@ fn a_save_refuses_disagreeing_options_and_names_unread_native_ones() { let r = s.execute("file.saveCopy", &json!({"path": d.join("a.ai").to_string_lossy(), "compress": false, "version": 3})).unwrap(); let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); assert!(w.iter().any(|w| w.starts_with("`version` was not used")) && !w.iter().any(|w| w.starts_with("`compress`")), "{w:?}"); + // `precision` is read by native files and templates only. + for name in ["p.svg", "p.pdf", "p.ai", "p.eps"] { + let r = s.execute("file.saveCopy", &json!({"path": d.join(name).to_string_lossy(), "precision": 2})).unwrap(); + let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert!(w.iter().any(|w| w.starts_with("`precision` was not used:")), "{name}: {w:?}"); + } + for name in ["p.vectorcraft", "p.vctemplate"] { + let r = s.execute("file.saveCopy", &json!({"path": d.join(name).to_string_lossy(), "precision": 2})).unwrap(); + assert_eq!(r["warnings"], json!([]), "{name}: {r}"); + } let _ = std::fs::remove_dir_all(&d); } diff --git a/crates/engine/src/cmd/flatten/analysis.rs b/crates/engine/src/cmd/flatten/analysis.rs index 4bdbb8b723..eacd124052 100644 --- a/crates/engine/src/cmd/flatten/analysis.rs +++ b/crates/engine/src/cmd/flatten/analysis.rs @@ -112,8 +112,16 @@ pub(super) fn reach(n: &Node) -> Option { 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]) -> Vec> { +/// 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]) -> Result>, 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]) -> Vec> { i } let mut parent: Vec = (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 = (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 = 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 = (0..n).collect(); + by_left.sort_by(|&a, &b| boxes[a].1.x0.total_cmp(&boxes[b].1.x0)); + let mut by_right: Vec = (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![]; let mut slot: Vec> = vec![None; bounds.len()]; @@ -148,5 +212,84 @@ pub(super) fn overlapping(bounds: &[Option]) -> Vec> { } } } - groups + Ok(groups) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// What [`overlapping`] gives, comparing every pair. + fn every_pair(bounds: &[Option]) -> Vec> { + let n = bounds.len(); + let mut group: Vec = (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![]; + 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> = (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> = + (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]]); + } } diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index d229f1bbb8..e4113b47b1 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -26,6 +26,40 @@ pub(super) struct Flat { /// Where its image goes, and the image (once rendered). pub(super) area: Option, raster: Option, + /// When the group is one block of type over several lines: its lines, to group the regions by. + lines: Option, +} + +/// 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 { + 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 = 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>> = 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 { diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 8e68987f9f..585cd8a793 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -29,7 +29,7 @@ pub fn specs() -> Vec { "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 { 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 { (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, Vec) = 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 = 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] diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index 60712fb265..b958f51c16 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -59,8 +59,15 @@ //! opacity, blending, fills and effects). When the model group gains or loses objects, or one of //! them becomes another kind of object, each member takes the model's objects at that level //! whole, keeping its own ids in order. At most [`MAX_MEMBERS`] objects are taken, so that a huge -//! document can't stall the start or every edit. Rotated copies and excluding a member with a -//! Shift-click are not covered. +//! document can't stall the start or every edit. +//! +//! In the how-to above, a Shift-click on one of the found objects takes it out of the edit. Here a +//! Shift-click (not a Shift-drag) with the Selection tool on a highlighted member, or on an object +//! inside it, leaves that member out (`select.globalEditExclude`): it is no longer highlighted, +//! and later edits leave it as it is. +//! The object the edit started from can't be left out (a Shift-click on it selects it or +//! deselects it as before), Global Edit ends when fewer than two members are left, and leaving +//! one out is not an undo step. Rotated copies are not covered. use serde::Serialize; use serde_json::{Value, json}; @@ -68,10 +75,11 @@ use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, Nod use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, Shape}; use super::wand::{fill_of, stroke_of}; -use super::{CommandSpec, Result, Session, bad, bool_or, cmd, has_doc}; +use super::{CommandSpec, Result, Session, bad, bool_or, checked_id, cmd, has_doc}; const C: &str = "select.globalEdit"; const OPTIONS: &str = "select.globalEditOptions"; +const EXCLUDE: &str = "select.globalEditExclude"; /// The most objects a Global Edit takes, the selected one included. pub const MAX_MEMBERS: usize = 10_000; const UNSUPPORTED: &str = "Global Edit works on paths, compound paths, symbol instances and groups of them"; @@ -96,6 +104,15 @@ pub fn specs() -> Vec { has_doc, set_options ), + cmd!( + "select.globalEditExclude", + "Leave Out of Global Edit", + [], + None, + "{id} while Global Edit is on: leave the object `id` of the Global Edit (not the one it started from) out of it, as a Shift-click on it with the Selection tool does: it is no longer highlighted and later edits leave it as it is; with fewer than two objects left, Global Edit ends; not an undo step → {active, count, ids} (the objects left in it; none once it has ended)", + is_on, + exclude + ), ] } @@ -385,6 +402,35 @@ fn toggle(s: &mut Session, p: &Value) -> Result { Ok(json!({ "active": true, "count": ids.len(), "ids": ids })) } +fn is_on(s: &Session) -> std::result::Result<(), String> { + match s.active() { + None => Err("no document open".into()), + Some(st) if st.global_edit.is_none() => Err("Global Edit is off".into()), + Some(_) => Ok(()), + } +} + +/// Leave one object out of the Global Edit (a Shift-click on it): not the object it started from. +fn exclude(s: &mut Session, p: &Value) -> Result { + let id = checked_id(s, p.get("id").ok_or_else(|| bad(EXCLUDE, "missing id"))?, EXCLUDE)?; + let st = s.doc_mut()?; + let Some(ge) = &mut st.global_edit else { return Err(bad(EXCLUDE, "Global Edit is off")) }; + match ge.members.iter().position(|(m, _)| *m == id) { + Some(i) if i > 0 => { + ge.members.remove(i); + } + _ => return Err(bad(EXCLUDE, "only an object of the Global Edit other than the one it started from can be left out")), + } + let ids: Vec = if ge.members.len() < 2 { + st.global_edit = None; + vec![] + } else { + ge.members.iter().map(|(id, _)| id.0).collect() + }; + st.revision += 1; + Ok(json!({ "active": !ids.is_empty(), "count": ids.len(), "ids": ids })) +} + fn set_options(s: &mut Session, p: &Value) -> Result { let o = s.global_edit_options.with(p, &s.doc()?.doc, OPTIONS)?; s.global_edit_options = o.clone(); @@ -674,8 +720,9 @@ pub(crate) fn propagate(before: &Document, d: &mut Document, ge: &GlobalEdit, se edited } -/// The outlines of the members of the active document's Global Edit that are not selected, in -/// their layer's colour: the canvas highlights them while Global Edit is on. +/// The outlines of the members of the active document's Global Edit that are not selected, hold +/// no selected object and sit inside no selected object, in their layer's colour: the canvas +/// highlights them while Global Edit is on. pub fn highlights(s: &Session) -> Outlines { let Some(st) = s.active() else { return vec![] }; let Some(ge) = &st.global_edit else { return vec![] }; @@ -690,6 +737,9 @@ pub fn highlights(s: &Session) -> Outlines { .iter() .filter_map(|(id, _)| { let n = st.doc.node(*id).filter(|n| !holds(n, &st.selection.objects))?; + if st.doc.ancestry(*id).is_some_and(|a| a.iter().any(|p| st.selection.objects.contains(p))) { + return None; + } let path = match n.stroke_path() { Some(p) => p, None => n.geometric_bounds_with(&symbols)?.to_path(0.1), diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index b506c18f83..52daa9b747 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -312,10 +312,31 @@ pub(crate) fn apply_gradient_edit_in( bounds: Option, inside: &dyn Fn(Point) -> bool, ) -> std::result::Result { - let mut gp = match paint { + apply_gradient_edit_in_model(paint, p, bounds, inside, None) +} + +/// New implicit stops use the document's model; existing gradients retain their own colors. +fn gradient_for_edit(paint: &Paint, model: Option) -> GradientPaint { + match paint { Paint::Gradient(g) => (**g).clone(), - _ => GradientPaint::new(Gradient::default()), - }; + _ => { + let mut gradient = Gradient::default(); + for stop in &mut gradient.stops { + stop.color = super::paint::stored_color(model, stop.color); + } + GradientPaint::new(gradient) + } + } +} + +fn apply_gradient_edit_in_model( + paint: &Paint, + p: &Value, + bounds: Option, + inside: &dyn Fn(Point) -> bool, + model: Option, +) -> std::result::Result { + let mut gp = gradient_for_edit(paint, model); let mut switched = false; if let Some(k) = str_param(p, "kind") { let kind = parse_kind(k)?; @@ -414,13 +435,15 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "`dither` applies to gradient fills (stroke: false)")); } super::paint::check_keep_model(p, C)?; + let model = super::paint::new_color_model(s, p); // New RGB stop colors take the document's model; those of the swatches the stops name don't. let stored = stop_colors(s, p, p); // Stops naming swatches take their colours from them. let p = &link_stops(&s.doc()?.doc, p).map_err(|e| bad(C, e))?; // Validate against the defaults first so bad params fail without touching the document. let default_paint = if stroke { s.paint.stroke.clone() } else { s.paint.fill.clone() }; - let new_default = apply_gradient_edit(&default_paint, &with_stored_stops(p, &default_paint, &stored), None).map_err(|e| bad(C, e))?; + let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(p, &default_paint, &stored), None, &|_| true, model) + .map_err(|e| bad(C, e))?; let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform); edit_items(s, &ids, item, C, "Gradient", !stroke, |n, index| { if index.is_none() @@ -429,7 +452,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { let lb = t.local_bounds(); for r in &mut t.runs { let (cur, b) = run_paint_mut(r, stroke, lb); - *cur = apply_gradient_edit(cur, &with_stored_stops(p, cur, &stored), Some(b)).map_err(|e| bad(C, e))?; + *cur = apply_gradient_edit_in_model(cur, &with_stored_stops(p, cur, &stored), Some(b), &|_| true, model).map_err(|e| bad(C, e))?; } return Ok(()); } @@ -441,7 +464,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { None => &|_| true, }; let old = n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None); - let np = apply_gradient_edit_in(old, &with_stored_stops(p, old, &stored), b, inside).map_err(|e| bad(C, e))?; + let np = apply_gradient_edit_in_model(old, &with_stored_stops(p, old, &stored), b, inside, model).map_err(|e| bad(C, e))?; n.appearance.set_paint_at(index, !stroke, np); if let Some(m) = mode && let Some(st) = n.appearance.stroke_at_mut(index) @@ -547,12 +570,9 @@ impl GeomEdit { /// `cur` with the vector, aspect and focal point of `e` (given in the document). `to_doc` maps /// the paint's space (text space for type runs) to the document and `bounds` (in that space) fits /// an unplaced gradient, so what the document shows carries over where `e` keeps it. -fn vector_paint(cur: &Paint, e: &GeomEdit, to_doc: Affine, bounds: Option) -> Option { +fn vector_paint(cur: &Paint, e: &GeomEdit, to_doc: Affine, bounds: Option, model: Option) -> Option { let from_doc = invert(to_doc)?; - let mut gp = match cur { - Paint::Gradient(g) => (**g).clone(), - _ => GradientPaint::new(Gradient::default()), - }; + let mut gp = gradient_for_edit(cur, model); let kind = gp.gradient.kind; let map = |mut g: GradientGeom, a: Affine| { if a != Affine::IDENTITY { @@ -597,6 +617,7 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result { if targets.is_empty() { return Err(EngineError::Other("nothing selected".into())); } + let model = super::paint::new_color_model(s, &Value::Null); edit_items(s, &targets, item, C, "Gradient", !stroke, |n, index| { if index.is_none() && let NodeKind::Text(t) = &mut n.kind @@ -607,14 +628,14 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result { run_stroke_weight(&mut r.style); } let (paint, b) = run_paint_mut(r, stroke, lb); - if let Some(np) = vector_paint(paint, &edit, xf, Some(b)) { + if let Some(np) = vector_paint(paint, &edit, xf, Some(b), model) { *paint = np; } } return Ok(()); } let b = item_paint_bounds(n, index, !stroke); - if let Some(np) = vector_paint(n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None), &edit, Affine::IDENTITY, b) { + if let Some(np) = vector_paint(n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None), &edit, Affine::IDENTITY, b, model) { n.appearance.set_paint_at(index, !stroke, np); } Ok(()) diff --git a/crates/engine/src/cmd/graph/designs.rs b/crates/engine/src/cmd/graph/designs.rs index 1009bcceb7..6ab79bac77 100644 --- a/crates/engine/src/cmd/graph/designs.rs +++ b/crates/engine/src/cmd/graph/designs.rs @@ -145,6 +145,8 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result { return Ok(json!({ "id": id.0 })); } if let Some(names) = names_param(p, "delete", C)? { + // Each name once: a repeated one would regenerate the graphs using it again. + let names: std::collections::BTreeSet = names.into_iter().collect(); if let Some(n) = names.iter().find(|n| !taken(s, n)) { return Err(bad(C, format!("no design named `{n}`"))); } diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 36c9589cd1..5876de1d6e 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -1304,6 +1304,10 @@ fn graph_designs_are_saved_pasted_and_deleted() { s.execute("edit.undo", &json!({})).unwrap(); assert!(series_parts(&s, id, 0).iter().skip(1).all(|n| matches!(n.kind, NodeKind::Group { .. }))); assert!(s.execute("graph.design", &json!({"delete": "Nope"})).is_err()); + // A name listed many times deletes once (its graphs regenerate once). + s.execute("graph.design", &json!({"delete": vec!["Pill"; 1000]})).unwrap(); + assert!(s.doc().unwrap().doc.graph_designs.is_empty()); + assert!(series_parts(&s, id, 0).iter().all(|n| matches!(n.kind, NodeKind::Path { .. }))); } #[test] @@ -2588,6 +2592,18 @@ fn formatting_the_whole_graphs_text_survives_it_being_drawn_again() { assert_eq!(spec(&s, id).label_styles, vectorcraft_doc::LabelStyles::default()); } +/// A stroke given to all of a graph's text without a weight is kept at 1 pt, as `paint.setStroke` keeps it. +#[test] +fn a_stroke_given_to_the_whole_graphs_text_is_kept_at_1_pt() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("text.setStyle", &json!({"stroke": "#ff0000"})).unwrap(); + let legend = spec(&s, id).label_styles.legend.unwrap(); + assert_eq!((legend.stroke.color().map(|c| c.to_hex()), legend.stroke_width), (Some("#ff0000".into()), 1.0)); +} + #[test] fn formatting_one_label_keeps_that_kind_of_label() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 70aa9561fe..49865914e9 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -448,6 +448,8 @@ fn clip(name: &mut String) { fn uniquify<'a>(names: impl Iterator, fallback: &str, sep: &str, fold: bool) { let key = |n: &str| if fold { n.to_lowercase() } else { n.to_string() }; let mut seen = HashSet::new(); + // Per repeated name, the number to try next: a run of one name counts on instead of from 2. + let mut next: std::collections::HashMap = std::collections::HashMap::new(); for name in names { clip(name); if name.trim().is_empty() { @@ -455,7 +457,12 @@ fn uniquify<'a>(names: impl Iterator, fallback: &str, sep } if seen.contains(&key(name)) { let base = name.clone(); - *name = (2..).map(|n| format!("{base}{sep}{n}")).find(|n| !seen.contains(&key(n))).unwrap_or_default(); + let n = next.entry(key(&base)).or_insert(2); + while seen.contains(&key(&format!("{base}{sep}{n}"))) { + *n += 1; + } + *name = format!("{base}{sep}{n}"); + *n += 1; } seen.insert(key(name)); } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 2e8d974d65..441249b05b 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -1338,8 +1338,10 @@ fn placement_json(o: PlacementOptions) -> Value { /// Link Info's fields of the linked file `l` (of object `id` of `st`) into `out`. fn file_fields(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Value) { - // Within what the caller that opened the document may read, whoever asks. - crate::file_access::confine(st.opened_by.as_ref(), || file_fields_here(st, id, l, out)); + // A confined caller reads within its own roots; anyone else within what the caller that + // opened the document may read (never wider than the caller asking now). + let roots = crate::file_access::current().or_else(|| st.opened_by.clone()); + crate::file_access::confine(roots.as_ref(), || file_fields_here(st, id, l, out)); } fn file_fields_here(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Value) { diff --git a/crates/engine/src/cmd/objects_on_path.rs b/crates/engine/src/cmd/objects_on_path.rs index eebdd3e046..e2bd0957d9 100644 --- a/crates/engine/src/cmd/objects_on_path.rs +++ b/crates/engine/src/cmd/objects_on_path.rs @@ -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 { "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 { // ---------- 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, start: f64) -> Result<(Option, 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 { 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(()) })?; diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 33c69589b7..e53b9b8f3a 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -303,7 +303,7 @@ pub(crate) fn check_keep_model(p: &Value, cmd: &str) -> Result<()> { /// The model RGB colours given in `p` are stored in: the document's in a CMYK document (`None` in /// an RGB one, or with `keepModel`). -fn new_color_model(s: &Session, p: &Value) -> Option { +pub(super) fn new_color_model(s: &Session, p: &Value) -> Option { let mode = s.active()?.doc.color_mode; (mode != vectorcraft_doc::ColorMode::Rgb && !bool_or(p, "keepModel", false)).then(|| mode.model()) } @@ -697,8 +697,8 @@ fn black_or_white(c: &Color) -> bool { } } -/// The points the active tool has picked (its `meshPoints` option: the Mesh tool's or Direct -/// Selection's) on the gradient meshes among `ids`, in range, each mesh with its points. +/// The points the active tool has picked (its `meshPoints` option: the Mesh tool's, Direct +/// Selection's or the Lasso's) on the gradient meshes among `ids`, in range, each mesh with its points. fn picked_mesh_points(s: &Session, ids: &[NodeId]) -> Vec<(NodeId, Vec)> { let o = s.tool_options(); let (Some(picked), Ok(st)) = (o.get("meshPoints").and_then(Value::as_array), s.doc()) else { return vec![] }; diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 40df8f377d..0c8634edd1 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)", has_doc, set_format ), @@ -328,6 +328,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "tateChuYoko", "standardVerticalRoman", "noBreak", + "kashidas", "hyphenate", "hyphenateCapitalized", "romanHangingPunctuation", @@ -384,6 +385,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "leadingModel", "charAlign", "charDirection", + "kashidas", "proportionalMetrics", "tateChuYoko", "tcyUpDown", @@ -571,6 +573,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result { if let Some(v) = flag("noBreak") { st.no_break = v; } + if let Some(v) = flag("kashidas") { + st.kashidas = v; + } if let Some(v) = &font_axes { super::textedit::change_font_axes(st, v); } diff --git a/crates/engine/src/cmd/pdfcmds.rs b/crates/engine/src/cmd/pdfcmds.rs index c9c94d808b..b5a8778fe6 100644 --- a/crates/engine/src/cmd/pdfcmds.rs +++ b/crates/engine/src/cmd/pdfcmds.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; use vectorcraft_pdf::{PdfPreset, builtin_preset, builtin_presets}; use super::fileio::pdf::{find_preset, resolve}; -use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, str_param, unique_name}; +use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, str_param}; /// The `format` of a PDF presets file, also its extension. pub const PRESET_FORMAT: &str = "vcpdfpresets"; @@ -196,8 +196,12 @@ fn import(s: &mut Session, p: &Value) -> Result { for q in &file.presets { q.settings.check_values().map_err(|e| bad(C, format!("`{}`: {e}", q.name)))?; } + if file.presets.len() > super::MAX_IMPORTED_PRESETS { + return Err(bad(C, format!("a PDF presets file with over {} presets", super::MAX_IMPORTED_PRESETS))); + } let replace = bool_or(p, "replace", false); let mut imported = vec![]; + let mut next = std::collections::HashMap::new(); for mut preset in file.presets { preset.settings.clear_passwords(); let base = Some(preset.name.trim()).filter(|n| !n.is_empty()).unwrap_or("PDF Preset").to_string(); @@ -211,7 +215,7 @@ fn import(s: &mut Session, p: &Value) -> Result { } } None => { - preset.name = unique_name(&base, |n| s.pdf_preset_taken(n, None)); + preset.name = super::unique_name_from(&base, &mut next, |n| s.pdf_preset_taken(n, None)); imported.push(preset.name.clone()); s.store_pdf_preset(None, &preset); s.prefs.pdf_presets.push(preset); diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 6950eeaace..ad24afacbc 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -372,6 +372,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("newArtBasic", "General", "Appearance Panel", "New Art Has Basic Appearance", bool), // File Handling (continued) p!("templatesFolder", "File Handling", "Files", "Templates Folder", text), + // Off: raster images open in PhotoCraft where it is installed (#5236). + p!("editOriginalSystemDefaults", "File Handling", "Files", "Use System Defaults for Edit Original", bool), p!("appendConverted", "File Handling", "Files", "Mark Older Files as [Converted] When Opened", bool), // Native saves (`document.save {compress}`) p!("useCompression", "File Handling", "Files", "Use Compression", bool), diff --git a/crates/engine/src/cmd/printpresets.rs b/crates/engine/src/cmd/printpresets.rs index 8f0dd298d1..2cc44586eb 100644 --- a/crates/engine/src/cmd/printpresets.rs +++ b/crates/engine/src/cmd/printpresets.rs @@ -8,7 +8,7 @@ use vectorcraft_pdf::PrintSettings; use super::fileio::pdf::changed; use super::print::settings_over; -use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, str_param, unique_name}; +use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, str_param}; /// The built-in preset's name. pub const DEFAULT_PRESET: &str = "[Default]"; @@ -221,8 +221,12 @@ fn import(s: &mut Session, p: &Value) -> Result { for q in &file.presets { q.settings.check().map_err(|e| bad(C, format!("`{}`: {e}", q.name)))?; } + if file.presets.len() > super::MAX_IMPORTED_PRESETS { + return Err(bad(C, format!("a print presets file with over {} presets", super::MAX_IMPORTED_PRESETS))); + } let replace = bool_or(p, "replace", false); let mut imported = vec![]; + let mut next = std::collections::HashMap::new(); for mut preset in file.presets { // [Default] comes in as a saved copy ("Default 2"…): the built-in one stays. let name = preset.name.trim().trim_start_matches('[').trim_end_matches(']').trim(); @@ -236,7 +240,7 @@ fn import(s: &mut Session, p: &Value) -> Result { } } None => { - preset.name = unique_name(&base, |n| s.print_preset_taken(n, None)); + preset.name = super::unique_name_from(&base, &mut next, |n| s.print_preset_taken(n, None)); imported.push(preset.name.clone()); s.prefs.print_presets.push(preset); } diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 753fad69c2..1ad456b94e 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -308,6 +308,14 @@ impl RecoveryStore for FolderStore { } fn read(&self, name: &str) -> std::result::Result, String> { let f = self.file(name)?; + // Entry names come from the copy's metadata: refuse a link (or a folder another account + // owns) that would read a file from outside the store. + if let Some(dir) = f.parent() { + Self::own_area(dir)?; + } + if !std::fs::symlink_metadata(&f).map_err(|e| format!("{}: {e}", f.display()))?.file_type().is_file() { + return Err(format!("{}: not a plain file", f.display())); + } std::fs::read(&f).map_err(|e| format!("{}: {e}", f.display())) } fn write(&self, name: &str, bytes: &[u8]) -> std::result::Result<(), String> { @@ -693,11 +701,12 @@ impl RecoveryJob { let meta_bytes = serde_json::to_vec_pretty(&meta).map_err(|e| e.to_string())?; let area = self.file.split_once('/').map_or("", |(a, _)| a); let _turn = WRITES.lock().unwrap_or_else(|e| e.into_inner()); - let have: BTreeSet = if images.is_empty() { BTreeSet::new() } else { store.list()?.into_iter().collect() }; + let mut have: BTreeSet = if images.is_empty() { BTreeSet::new() } else { store.list()?.into_iter().collect() }; let mut image_bytes = 0; for (blob, data) in images { let name = format!("{area}/{blob}"); - if !have.contains(&name) { + // Images of several keys can share one entry: it is written once. + if have.insert(name.clone()) { store.write(&name, data)?; image_bytes += data.len(); } @@ -1001,16 +1010,21 @@ fn restore_one(s: &mut Session, store: &Arc, file: &str) -> R super::threads::mark_continued(&mut doc); // The images, from the entries of the copy's area. let from = file.split_once('/').map_or("", |(a, _)| a); - let mut blobs = vec![]; + let mut blobs: BTreeMap>> = BTreeMap::new(); for (key, r) in &meta.images { - match store.read(&format!("{from}/{}", r.blob)) { + // Keys sharing an entry share its bytes: each entry is read (and written again) once. + let read = match blobs.get(&r.blob) { + Some(data) => Ok(data.clone()), + None => store.read(&format!("{from}/{}", r.blob)).map(Arc::new), + }; + match read { Ok(data) => { - let mut blob = ImageBlob::new(r.mime.clone(), data); + let mut blob = ImageBlob { mime: r.mime.clone(), bytes: data, proxy: None }; // Until the linked file is read, the preview stands in for it. if r.proxy { blob.proxy = Some(blob.bytes.clone()); } - blobs.push((r.blob.clone(), blob.bytes.clone())); + blobs.insert(r.blob.clone(), blob.bytes.clone()); doc.images.insert(key.clone(), blob); } Err(e) => warnings.push(format!("the image “{key}” of the recovered document couldn't be read: {e}")), diff --git a/crates/engine/src/cmd/slices.rs b/crates/engine/src/cmd/slices.rs index cad1335c13..1adc147c56 100644 --- a/crates/engine/src/cmd/slices.rs +++ b/crates/engine/src/cmd/slices.rs @@ -348,8 +348,13 @@ fn from_guides(s: &mut Session, _: &Value) -> Result { v }; let (xs, ys) = (cuts(true, region.x0, region.x1), cuts(false, region.y0, region.y1)); - let rects: Vec = - ys.windows(2).flat_map(|y| xs.windows(2).map(move |x| Rect::new(x[0], y[0], x[1], y[1]))).filter(|r| valid_rect(*r)).collect(); + // One past the limit tells too many, without making every piece of a huge grid first. + let rects: Vec = ys + .windows(2) + .flat_map(|y| xs.windows(2).map(move |x| Rect::new(x[0], y[0], x[1], y[1]))) + .filter(|r| valid_rect(*r)) + .take(MAX_PIECES + 1) + .collect(); if rects.len() > MAX_PIECES { return Err(EngineError::Other(format!("Create from Guides: the guides make more than {MAX_PIECES} slices"))); } diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 80e8e2a122..4aa0c0b472 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -818,7 +818,7 @@ fn swatch_unused(s: &mut Session, _: &Value) -> Result { 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 { } 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::(v.clone()).ok()) { + paint(&p); + } + } + } let used = |w: &Swatch| { gradient_links.contains(&w.name) || links.iter().any(|(l, t)| match w.tint_of() { diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index 49e9f5a614..a2c4b0bdb8 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -7,7 +7,7 @@ //! document VectorCraft opens. `symbol.addFromLibrary` copies symbols into the document; //! `symbol.saveLibrary` writes the document's. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::sync::{Arc, LazyLock}; use serde_json::{Value, json}; @@ -104,10 +104,17 @@ impl SymbolLibrary { /// `name`: the symbols, the symbols they nest and every other resource they use, with their /// Symbol Options. pub fn from_document(src: &Document, names: &[String], name: String) -> std::result::Result { - if let Some(n) = names.iter().find(|n| !src.symbols.iter().any(|s| s.name == **n)) { + // Each name's first place in the panel, looked up rather than scanned for: scanning the + // symbols for each one made a library of N symbols cost N² comparisons. + let mut order: HashMap<&str, usize> = HashMap::new(); + for (i, s) in src.symbols.iter().enumerate() { + order.entry(s.name.as_str()).or_insert(i); + } + if let Some(n) = names.iter().find(|n| !order.contains_key(n.as_str())) { return Err(format!("no symbol `{n}`")); } - let picked = src.symbols.iter().filter(|s| names.is_empty() || names.contains(&s.name)); + let wanted: HashSet<&str> = names.iter().map(String::as_str).collect(); + let picked = src.symbols.iter().filter(|s| names.is_empty() || wanted.contains(s.name.as_str())); let clip = Clipboard::gather(src, picked.map(|s| instance(&s.name)).collect()); let mut doc = clip.to_document(); for l in &mut doc.layers { @@ -116,8 +123,7 @@ impl SymbolLibrary { } } // The panel order of the document they came from. - let order = |n: &str| src.symbols.iter().position(|s| s.name == n); - doc.symbols.sort_by_key(|s| order(&s.name)); + doc.symbols.sort_by_key(|s| order.get(s.name.as_str()).copied()); for s in &doc.symbols.clone() { copy_options(src, &s.name, &mut doc, &s.name); } @@ -344,3 +350,30 @@ fn load(s: &mut Session, p: &Value) -> Result { })?; Ok(json!({"library": info.id, "name": info.name, "count": lib.len()})) } + +#[cfg(test)] +mod tests { + use super::*; + + /// A library made from thousands of symbols holds them all, once each, in the panel order of + /// the document they came from, a name given twice kept at its first place. + #[test] + fn many_symbols_keep_their_panel_order() { + let mut src = Document::new(100.0, 100.0); + let n = 4000; + // Names out of alphabetical order, so the order kept is the panel's. + src.symbols = (0..n) + .map(|i| Symbol { name: format!("s{}", (i * 7919) % n), art: Arc::new(Node::group(NodeId(i as u64 + 1), vec![])), dynamic: false }) + .collect(); + let lib = SymbolLibrary::from_document(&src, &[], "Many".into()).unwrap(); + let names = |d: &Document| d.symbols.iter().map(|s| s.name.clone()).collect::>(); + assert_eq!(names(&lib.doc), names(&src)); + let picked = ["s3".to_string(), "s1".to_string()]; + let lib = SymbolLibrary::from_document(&src, &picked, "Two".into()).unwrap(); + let order = |name: &str| src.symbols.iter().position(|s| s.name == name); + let mut want = vec!["s3", "s1"]; + want.sort_by_key(|n| order(n)); + assert_eq!(names(&lib.doc), want); + assert!(SymbolLibrary::from_document(&src, &["nope".to_string()], "None".into()).is_err()); + } +} diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 133a3d788f..8ce750a5e1 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Touch Type", [], None, - "{id, start: byte (a character of it), dx?: pt, dy?: pt, hScale?: %, vScale?: %, rotation?: deg} change one character (a ligature, one glyph for several characters, as a whole) as a Touch Type tool drag does, as one undo step: dx moves it along its line in reading order by changing the kerning of the character before it on the line and its own kerning, and the characters after it stay where they are (an error for the first character of a line and for a right-to-left character; limited to what kerning from -1000 to 10000 can give); dy raises it (baseline shift, up from its line whatever its rotation, also for the first character of a line and a right-to-left character); dx and dy are document points; hScale (including the object transform), vScale and rotation set its scales and rotation as text.setRangeStyle does. The kerning of the two characters also keeps the character and the ones after it where they were along the line when the font kerned them with their neighbors; a wider or narrower character moves the ones after it by the change in its width → {id, start, end} (the character's bytes)", + "{id, start: byte (a character of it), dx?: pt, dy?: pt, hScale?: %, vScale?: %, rotation?: deg} change one character (a ligature, one glyph for several characters, as a whole) as a Touch Type tool drag does, as one undo step: dx moves it along its line in reading order by changing the kerning of the character before it on the line and its own kerning, and the characters after it stay where they are (an error for the first logical character of a line or at a reading-direction boundary; supported in either reading direction; limited to what kerning from -1000 to 10000 can give); dy raises it (baseline shift, up from its line whatever its rotation, also for the first character of a line and a right-to-left character); dx and dy are document points; hScale (including the object transform), vScale and rotation set its scales and rotation as text.setRangeStyle does. The kerning of the two characters also keeps the character and the ones after it where they were along the line when the font kerned them with their neighbors; a wider or narrower character moves the ones after it by the change in its width → {id, start, end} (the character's bytes)", has_doc, touch_type ), @@ -154,14 +154,14 @@ pub fn specs() -> Vec { ] } -fn text_mut(d: &mut vectorcraft_doc::Document, id: NodeId) -> Option<&mut TextObject> { +pub(crate) fn text_mut(d: &mut vectorcraft_doc::Document, id: NodeId) -> Option<&mut TextObject> { match d.node_mut(id).map(|n| &mut n.kind) { Some(NodeKind::Text(t)) => Some(t), _ => None, } } -fn text_ref(s: &Session, id: NodeId) -> Result { +pub(crate) fn text_ref(s: &Session, id: NodeId) -> Result { match s.doc()?.doc.node(id).map(|n| &n.kind) { Some(NodeKind::Text(t)) => Ok((**t).clone()), Some(_) => Err(EngineError::Other(format!("node {} is not text", id.0))), @@ -361,6 +361,7 @@ pub(crate) struct CharChange { small_caps: Option>, char_align: Option, char_direction: Option>, + kashidas: Option, proportional_metrics: Option, tate_chu_yoko: Option, /// Tate-chu-yoko Settings › Up/Down and Left/Right, in points. @@ -600,7 +601,11 @@ impl CharChange { /// `setup` gives the superscript, subscript and small caps proportions. pub(crate) fn parse(p: &Value, cmd: &str, setup: &vectorcraft_doc::DocSetup) -> Result { check_numbers(p, &["size", "tracking", "baselineShift", "hScale", "vScale", "rotation", "strokeWidth"], cmd)?; - check_switches(p, &["underline", "strikethrough", "allCaps", "proportionalMetrics", "tateChuYoko", "standardVerticalRoman", "noBreak"], cmd)?; + check_switches( + p, + &["underline", "strikethrough", "allCaps", "proportionalMetrics", "tateChuYoko", "standardVerticalRoman", "noBreak", "kashidas"], + cmd, + )?; let num = |k: &str| p.get(k).and_then(Value::as_f64); let (position, small_caps) = super::docsetup::script_params(p, setup, cmd)?; let flag = |k: &str| p.get(k).and_then(Value::as_bool); @@ -645,6 +650,7 @@ impl CharChange { small_caps, char_align: char_align_param(p, cmd)?, char_direction: char_direction_param(p, cmd)?, + kashidas: flag("kashidas"), proportional_metrics: flag("proportionalMetrics"), tate_chu_yoko: flag("tateChuYoko"), tcy_up_down: tcy_offset_param(p, "tcyUpDown", cmd)?, @@ -696,6 +702,7 @@ impl CharChange { && self.small_caps.is_none() && self.char_align.is_none() && self.char_direction.is_none() + && self.kashidas.is_none() && self.proportional_metrics.is_none() && self.tate_chu_yoko.is_none() && self.tcy_up_down.is_none() @@ -708,7 +715,7 @@ impl CharChange { && self.font_height_reference.is_none() } - fn localize(&mut self, t: &TextObject, cmd: &str) -> Result<()> { + pub(crate) fn localize(&mut self, t: &TextObject, cmd: &str) -> Result<()> { use super::typecmd::local_type_value; self.size = self.size.map(|v| local_type_value(t, v, (0.1, 1296.0), false, cmd)).transpose()?; self.leading = self.leading.map(|v| v.map(|v| local_type_value(t, v, (0.1, 5000.0), false, cmd)).transpose()).transpose()?; @@ -749,6 +756,9 @@ impl CharChange { if let Some(v) = self.char_direction { st.char_direction = v; } + if let Some(v) = self.kashidas { + st.kashidas = v; + } if let Some(v) = self.proportional_metrics { st.proportional_metrics = v; } @@ -1007,11 +1017,8 @@ fn touch_type(s: &mut Session, p: &Value) -> Result { // Document points per text-space point along `v`. let doc_len = |v: Vec2| linear(t.xf, v).hypot() / v.hypot(); let limit = 1296.0 / points; - if dx != 0.0 && g.rtl { - return Err(bad(C, "a right-to-left character moves only up and down (dy)")); - } // A list marker's glyphs (length 0) stand for no character. - let prev = lay.glyphs.iter().find(|h| h.line == g.line && h.len > 0 && h.byte + h.len == a); + let prev = lay.glyphs.iter().find(|h| h.line == g.line && h.len > 0 && h.byte + h.len == a && h.rtl == g.rtl); let pr = prev.map(|h| (h.byte, h.byte + h.len)); let db = vectorcraft_text::FontDb::global(); let em = glyph_em(db, &t, g).ok_or_else(|| bad(C, "the character's size can't be measured"))?; @@ -1055,8 +1062,10 @@ fn touch_type(s: &mut Session, p: &Value) -> Result { // to Fit and a path effect such as Skew scale: two layouts with the call's other changes and shifts one step apart, both within the range, // measure that length. Neither shift is one that a run already has, so the character's run // splits off alike in both. - let raise = if dy == 0.0 { - 0.0 + let drawn_move = g.rtl && moved != 0.0; + let up = Vec2::new(d.y, -d.x); + let (mut raise, baseline_step) = if dy == 0.0 && !drawn_move { + (0.0, 0.0) } else { let shift = edit::slice_runs(&t.runs, a, b).first().map_or(0.0, |r| r.style.baseline_shift); let from = shift.clamp(-limit, limit); @@ -1068,21 +1077,44 @@ fn touch_type(s: &mut Session, p: &Value) -> Result { // The character's pen with its baseline shift set to `to`. let pen_at = |to: f64| { let mut trial = t.clone(); - touch(&mut trial, None, None, to - shift); + // Hold kerning fixed: Optical spacing can change along the line as the baseline + // rises, which would make its horizontal drift count as baseline movement. + touch(&mut trial, pr.map(|_| 0.0), Some(0.0), to - shift); let l = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &trial); l.glyphs.iter().find(|h| h.byte == a && h.len > 0).map(|h| h.xf * Point::ZERO) }; - let per_step = match (pen_at(from + step), pen_at(from + 2.0 * step)) { - (Some(p), Some(q)) => linear(t.xf, q - p).hypot() / step.abs(), - _ => 0.0, + let (per_step, across) = match (pen_at(from + step), pen_at(from + 2.0 * step)) { + (Some(p), Some(q)) => (linear(t.xf, q - p).hypot() / step.abs(), (q - p).dot(up) / step), + _ => (0.0, 0.0), }; - dy / per_step + (dy / per_step, across) }; if !raise.is_finite() { return Err(bad(C, "the character's size can't be measured")); } - // Where a glyph starts along the line. - let pen = |h: &vectorcraft_text::PositionedGlyph| h.origin.to_vec2().dot(along); + // Along-line RTL movement must measure the drawn glyph: turning off automatic kerning can + // also remove font placement, and Character Rotation turns that placement across the line. + let pen = |h: &vectorcraft_text::PositionedGlyph| { + let at = if drawn_move { + h.xf * Point::ZERO + } else if h.rtl { + h.origin + Vec2::new(h.angle.cos(), h.angle.sin()) * h.width_start + } else { + h.origin + }; + at.to_vec2().dot(along) + }; + // Scaling or rotation in the same call may intentionally turn the glyph's font placement + // about its pen. Keep that change while compensating placement lost to manual kerning. + let intrinsic_delta = if drawn_move && ["hScale", "vScale", "rotation"].iter().any(|key| p.get(*key).is_some_and(|v| !v.is_null())) { + let mut trial = t.clone(); + touch(&mut trial, None, None, 0.0); + let l = vectorcraft_text::layout(db, &trial); + let intrinsic = |h: &vectorcraft_text::PositionedGlyph| h.xf * Point::ZERO - h.xf * h.pivot; + l.glyphs.iter().find(|h| h.byte == a && h.len > 0).map_or(Vec2::ZERO, |h| intrinsic(h) - intrinsic(g)) + } else { + Vec2::ZERO + }; // How much further the character's new scales advance it along the line: the character laid // out alone, in point type of the same orientation, before and after the change. let grown = { @@ -1096,10 +1128,27 @@ fn touch_type(s: &mut Session, p: &Value) -> Result { }; // The character lands `moved` further on, and the character after it on its line keeps its // distance from it, wider or narrower only by the character's new scales. - let goal = pen(g) + moved; + let goal = pen(g) + moved + intrinsic_delta.dot(along); let next_goal = lay.glyphs.iter().find(|h| h.byte == b && h.len > 0 && h.line == g.line).map(|h| pen(h) + grown); - // How far the character and the character after it on its line miss their places, along the - // line, with the kerning `k` (before, own) added. + let prev_goal = prev.map(pen); + let mut k = if moved != 0.0 { (em_prev.map(|ep| moved / ep * 1000.0), Some(-moved / em * 1000.0)) } else { (None, None) }; + if drawn_move { + if !baseline_step.is_finite() || baseline_step.abs() <= 1e-12 { + return Err(bad(C, "the character's size can't be measured")); + } + let mut trial = t.clone(); + touch(&mut trial, k.0, k.1, raise); + let l = vectorcraft_text::layout(db, &trial); + let h = l.glyphs.iter().find(|h| h.byte == a && h.len > 0).ok_or_else(|| bad(C, "the character's size can't be measured"))?; + let across_goal = (g.xf * Point::ZERO).to_vec2().dot(up) + dy / doc_len(up) + intrinsic_delta.dot(up); + raise += (across_goal - (h.xf * Point::ZERO).to_vec2().dot(up)) / baseline_step; + if !raise.is_finite() { + return Err(bad(C, "the character's size can't be measured")); + } + } + // Keep both neighbors: alignment can pin either end of an RTL line, making one neighbor + // insensitive to kerning even though the other one moves. The two spacing values must place + // the selected character and keep every available neighbor in place. let miss = |k: (Option, Option)| { let mut trial = t.clone(); touch(&mut trial, k.0, k.1, raise); @@ -1109,30 +1158,40 @@ fn touch_type(s: &mut Session, p: &Value) -> Result { (Some(n), Some(at)) => pen(n) - at, _ => 0.0, }; - Some((pen(h) - goal, next)) + let previous = match (pr.and_then(|(byte, _)| l.glyphs.iter().find(|n| n.byte == byte && n.len > 0 && n.line == h.line)), prev_goal) { + (Some(n), Some(at)) => pen(n) - at, + _ => 0.0, + }; + Some([pen(h) - goal, next, previous]) }; - let placed = |m: (f64, f64)| m.0.abs() <= 1e-9 && m.1.abs() <= 1e-9; - let mut k = if moved != 0.0 { (em_prev.map(|ep| moved / ep * 1000.0), Some(-moved / em * 1000.0)) } else { (None, None) }; + let placed = |m: [f64; 3]| m.iter().all(|v| v.abs() <= 1e-9); // A manual kerning value turns off the font's kerning for its character, each style run is // shaped apart, and centered, right-aligned and justified lines move as their width changes, so // the first values can miss. Layouts then measure what each kerning value does to the two - // characters, and the values are solved for from that (at most six layouts). - if !g.rtl && miss(k).is_some_and(|m| !placed(m)) { + // characters, and the values are solved for with a bounded set of layouts. + if miss(k).is_some_and(|m| !placed(m)) { k = (pr.map(|_| k.0.unwrap_or(0.0)), Some(k.1.unwrap_or(0.0))); if let Some(mut m) = miss(k) { const STEP: f64 = 10.0; - let column = |dk: (f64, f64)| miss((k.0.map(|v| v + dk.0), k.1.map(|v| v + dk.1))).map(|n| ((n.0 - m.0) / STEP, (n.1 - m.1) / STEP)); + let column = |dk: (f64, f64)| miss((k.0.map(|v| v + dk.0), k.1.map(|v| v + dk.1))).map(|n| std::array::from_fn(|i| (n[i] - m[i]) / STEP)); let by_before = if k.0.is_some() { column((STEP, 0.0)) } else { None }; let by_own = column((0.0, STEP)); // The kerning changes that cancel the misses `m`. - let solve = |m: (f64, f64)| match (by_before, by_own) { - (Some(p), Some(q)) if (p.0 * q.1 - q.0 * p.1).abs() > 1e-12 => { - let det = p.0 * q.1 - q.0 * p.1; - ((q.0 * m.1 - m.0 * q.1) / det, (m.0 * p.1 - p.0 * m.1) / det) + let solve = |m: [f64; 3]| { + let dot = |a: [f64; 3], b: [f64; 3]| a.into_iter().zip(b).map(|(a, b)| a * b).sum::(); + let (p, q) = (by_before.unwrap_or([0.0; 3]), by_own.unwrap_or([0.0; 3])); + let (pp, pq, qq) = (dot(p, p), dot(p, q), dot(q, q)); + let (pm, qm) = (dot(p, m), dot(q, m)); + let det = pp * qq - pq * pq; + if det > 1e-12 * pp * qq { + ((pq * qm - qq * pm) / det, (pq * pm - pp * qm) / det) + } else if pp >= qq && pp > 1e-24 { + (-pm / pp, 0.0) + } else if qq > 1e-24 { + (0.0, -qm / qq) + } else { + (0.0, 0.0) } - (Some(p), _) if p.0.abs() > 1e-12 => (-m.0 / p.0, 0.0), - (_, Some(q)) if q.1.abs() > 1e-12 => (0.0, -m.1 / q.1), - _ => (0.0, 0.0), }; for _ in 0..2 { if placed(m) { @@ -1255,7 +1314,7 @@ pub(crate) fn editing_range(s: &mut Session) -> Result Result> { // (text, its range; None: all of it). let targets: Vec<(NodeId, Option<(usize, usize)>)> = match id_param(p, "id") { + // An object that isn't type is refused as `ids` of it is. + Some(id) if s.doc()?.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Text(_))) => { + return Err(bad(c, "no text objects selected")); + } Some(id) => vec![(id, Some(range_of(p, edit::runs_len(&text_ref(s, id)?.runs), c)?))], None => { let editing = editing_range(s)?.filter(|_| p.get("ids").filter(|v| !v.is_null()).is_none()); diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index cb6b1d0b59..517af3a7b6 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -173,6 +173,7 @@ pub fn char_attrs(v: &CharStyle) -> Map { ("small_caps", json!(v.small_caps)), ("charAlign", json!(v.char_align)), ("charDirection", json!(v.char_direction)), + ("kashidas", json!(v.kashidas)), ("proportionalMetrics", json!(v.proportional_metrics)), ("tateChuYoko", json!(v.tate_chu_yoko)), ("tcyUpDown", json!(v.tcy_up_down)), @@ -477,10 +478,12 @@ fn name_param<'a>(p: &'a Value, kind: Kind, verb: &str) -> Result<&'a str> { str_param(p, "name").ok_or_else(|| bad(&kind.cmd(verb), "missing `name`")) } -/// The `attrs` of `p`, validated. `kept` holds the style's current attributes (`charStyle.edit`) or -/// the target text's attributes (`charStyle.new`): a language tag that is not in the list, which a -/// file can give a style or a run, stays when `attrs` keeps it. -fn attrs_param(p: &Value, kind: Kind, verb: &str, kept: Option<&Map>) -> Result>> { +/// 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>) -> Result>> { match p.get("attrs") { None | Some(Value::Null) => Ok(None), Some(Value::Object(m)) => { @@ -490,12 +493,25 @@ fn attrs_param(p: &Value, kind: Kind, verb: &str, kept: Option<&Map { let mut st = with_attrs(&CharStyle::default(), m, &c)?; + let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key); // A language of the list, stored as its tag (as text.setFormat takes it). if let Some(l) = &st.language && kept.and_then(|k| k.get("language")) != m.get("language") { st.language = vectorcraft_doc::setup::char_language(l).map_err(|e| bad(&c, e))?.map(str::to_string); } + for (key, paint) in [("fill", &mut st.fill), ("stroke", &mut st.stroke)] { + if changed(key) { + style_paint(d, paint, key, &c)?; + } + } + let (key, lo, hi) = ("stroke_width", 0.0, vectorcraft_doc::MAX_COORD); + if changed(key) && !(lo..=hi).contains(&st.stroke_width) { + return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); + } + if changed("features") { + style_features(&st.features, kept, &c)?; + } char_attrs(&st) } Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), m, &c)?), @@ -506,6 +522,51 @@ fn attrs_param(p: &Value, kind: Kind, verb: &str, kept: Option<&Map 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>, c: &str) -> Result<()> { + let kept: Vec<&str> = kept.and_then(|k| k.get("features")).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); + let max = vectorcraft_text::MAX_STYLE_FEATURES; + if features.len() > max.max(kept.len()) { + return Err(bad(c, format!("features lists at most {max} tags"))); + } + // One `-` or `+` at most, as the shaper reads a tag. + let known = |t: &str| vectorcraft_text::OtFeatures::known_tag(t) && !t.strip_prefix(['-', '+']).unwrap_or(t).starts_with(['-', '+']); + match features.iter().find(|t| !known(t) && !kept.contains(&t.as_str())) { + Some(t) => Err(bad(c, format!("unknown OpenType feature `{t}`"))), + None => Ok(()), + } +} + /// The attributes of a new style made from nothing (no `attrs`, no text selected): while the /// interface is in Japanese, new type's em box top-to-top leading (paragraph styles) and em box /// centre alignment (character styles); else none (the defaults). @@ -538,9 +599,15 @@ fn list(s: &mut Session, kind: Kind) -> Result { } fn new(s: &mut Session, p: &Value, kind: Kind) -> Result { + 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>) -> Result { let c = kind.cmd("new"); let target = selection_attrs(s, p, kind)?; - let attrs = match attrs_param(p, kind, "new", target.as_ref())? { + let attrs = match attrs_param(&s.doc()?.doc, p, kind, "new", copied.or(target.as_ref()))? { Some(a) => a, None => match target { Some(a) => a, @@ -668,7 +735,9 @@ fn redefine(s: &mut Session, p: &Value, kind: Kind) -> Result { fn set_attrs(s: &mut Session, p: &Value, kind: Kind) -> Result { let name = name_param(p, kind, "setAttrs")?.to_string(); - let attrs = attrs_param(p, kind, "setAttrs", None)?.ok_or_else(|| bad(&kind.cmd("setAttrs"), "missing `attrs`"))?; + let d = &s.doc()?.doc; + let old = kind.attrs(d, &name); + let attrs = attrs_param(d, p, kind, "setAttrs", old.as_ref())?.ok_or_else(|| bad(&kind.cmd("setAttrs"), "missing `attrs`"))?; redefine_to(s, kind, &name, attrs, "setAttrs") } @@ -678,7 +747,7 @@ fn edit_style(s: &mut Session, p: &Value, kind: Kind) -> Result { let to = str_param(p, "to").ok_or_else(|| bad(&c, "missing `to`"))?.trim().to_string(); let d = &s.doc()?.doc; let old = kind.attrs(d, &name).ok_or_else(|| bad(&c, format!("no style `{name}`")))?; - let attrs = attrs_param(p, kind, "edit", Some(&old))?.ok_or_else(|| bad(&c, "missing `attrs`"))?; + let attrs = attrs_param(d, p, kind, "edit", Some(&old))?.ok_or_else(|| bad(&c, "missing `attrs`"))?; if name == kind.normal() { return Err(bad(&c, format!("`{name}` can't be edited this way"))); } @@ -726,7 +795,7 @@ fn duplicate(s: &mut Session, p: &Value, kind: Kind) -> Result { .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 { diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index d7021efdab..90bb32bbbb 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -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 = (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 = (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"); diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index 3bb35b979a..537252dad0 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -93,14 +93,29 @@ thread_local! { /// makes "changed" a pointer comparison). Deleted frames' text flows into the remaining ones; a /// frame that is now point type leaves its thread with the text it holds. pub(crate) fn reflow(before: &Document, doc: &mut Document) { - let threads = std::mem::take(&mut doc.text_threads); + // A frame is in one thread, once: a file that lists it again (in its thread or another) would + // copy its text into the story each time, and write the grown story back for the next thread + // to copy again. Only its first place counts. + let mut seen = std::collections::HashSet::new(); + // A thread that lost a frame that way is flowed again: its frames' layout was made for the + // thread as listed (a frame left alone must lose its threaded continuation). + let threads: Vec<(Vec, bool)> = std::mem::take(&mut doc.text_threads) + .into_iter() + .map(|t| { + let listed = t.len(); + let t: Vec = t.into_iter().filter(|id| seen.insert(*id)).collect(); + let lost = t.len() != listed; + (t, lost) + }) + .collect(); let mut kept = vec![]; - for thread in threads { - let changed = thread.iter().any(|id| match (before.node(*id), doc.node(*id)) { - (Some(a), Some(b)) => !std::ptr::eq(a, b), - (None, None) => false, - _ => true, - }); + for (thread, lost) in threads { + let changed = lost + || thread.iter().any(|id| match (before.node(*id), doc.node(*id)) { + (Some(a), Some(b)) => !std::ptr::eq(a, b), + (None, None) => false, + _ => true, + }); // When no frame changed, the thread keeps its area-type frames and their text is not copied. if !changed { let live: Vec = thread.into_iter().filter(|id| text_of(doc, *id).is_some()).collect(); diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index 07531d4edd..9d56ca0c90 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -40,6 +40,47 @@ fn thread_flows_reflows_on_edit_and_survives_delete() { assert_eq!(s.doc().unwrap().doc.text_threads.len(), 1); } +/// A file that lists a frame more than once, in its own thread or in another, flows the story +/// through each frame once: repeated places would copy its text again and again. +#[test] +fn frames_listed_twice_flow_the_story_once() { + let (mut s, a, b) = setup(); + s.execute("text.thread.create", &json!({})).unwrap(); + let mut d = (*s.doc().unwrap().doc).clone(); + let (fa, fb) = (NodeId(a), NodeId(b)); + d.text_threads = vec![vec![fa, fb, fa, fb, fa], vec![fb, fa], vec![fa, fb]]; + reflow(&Document::new(1.0, 1.0), &mut d); + assert_eq!(d.text_threads, vec![vec![fa, fb]]); + let plain = |id: NodeId| match &d.node(id).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + }; + assert_eq!(format!("{}{}", plain(fa), plain(fb)), TEXT.repeat(4)); +} + +/// A frame left alone when a repeated listing is dropped (`[[a, b], [b, c]]` → `[[a, b], [c]]`) +/// is flowed again as a story of its own, even when no frame changed: it no longer continues a +/// paragraph from the frame before it. +#[test] +fn a_frame_left_alone_by_a_dropped_repeat_stops_continuing() { + let (mut s, a, b) = setup(); + s.execute("text.thread.create", &json!({})).unwrap(); + let c = + s.execute("text.create", &json!({"x": 400, "y": 10, "text": "Tail", "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(); + let mut d = (*s.doc().unwrap().doc).clone(); + let (fa, fb, fc) = (NodeId(a), NodeId(b), NodeId(c)); + d.text_threads = vec![vec![fa, fb], vec![fb, fc]]; + if let Some(NodeKind::Text(t)) = d.node_mut(fc).map(|n| &mut n.kind) { + t.first_para_continues = true; + } + let before = d.clone(); + reflow(&before, &mut d); + assert_eq!(d.text_threads, vec![vec![fa, fb]]); + let NodeKind::Text(t) = &d.node(fc).unwrap().kind else { panic!("not text") }; + assert!(!t.first_para_continues, "an unthreaded frame continues nothing"); + assert_eq!(t.plain_text(), "Tail"); +} + #[test] fn edits_copy_only_the_stories_of_threads_whose_frames_changed() { let (mut s, a, b) = setup(); diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 84221ced1c..d4a58c34d3 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -123,7 +123,7 @@ pub fn specs() -> Vec { "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 { 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> { + 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 { && 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 { 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 { 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 { 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(); } diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index 8c2d766486..20945f7702 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -1148,6 +1148,37 @@ fn character_direction_is_a_character_attribute_saved_only_when_set() { assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[0].style).get("charDirection"), Some(&serde_json::Value::Null)); } +/// The Character-menu switch is on for new and old text, and changing a selected range leaves +/// its neighbors alone. The paragraph's Insert Kashidas length is a separate setting. +#[test] +fn character_kashidas_default_on_and_round_trip_by_range() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "كتب محمد"})).unwrap()["id"].as_u64().unwrap(); + let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("text"), + }; + assert!(runs(&s)[0].style.kashidas); + let old = serde_json::to_value(&runs(&s)[0].style).unwrap(); + assert!(old.get("kashidas").is_none()); + assert!(serde_json::from_value::(old).unwrap().kashidas); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 6, "kashidas": false})).unwrap(); + assert_eq!(runs(&s).iter().map(|r| r.style.kashidas).collect::>(), [true, false, true]); + let err = s.execute("text.setRangeStyle", &json!({"id": id, "kashidas": "off"})).unwrap_err().to_string(); + assert!(err.contains("kashidas")); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(runs(&s).iter().all(|r| r.style.kashidas)); + s.execute("edit.redo", &json!({})).unwrap(); + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") }; + assert_eq!(t.runs.iter().map(|r| r.style.kashidas).collect::>(), [true, false, true]); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("text.setFormat", &json!({"kashidas": true})).unwrap(); + assert!(runs(&s).iter().all(|r| r.style.kashidas)); + assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[0].style)["kashidas"], true); +} + /// Proportional Metrics (#966): a character attribute, saved only when on. #[test] fn proportional_metrics_is_a_character_attribute_saved_only_when_on() { diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 76d39ea56e..4806531cde 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -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 { "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 { "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 ), diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index 5a4ba5100e..31e46787f2 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -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> { 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> { 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) -> 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 { 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 = + 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 { 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 { 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 = st.doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind)).collect(); - let existing: BTreeSet = st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect(); - (kinds, existing) - }; + let kinds: BTreeMap = 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 = 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 { return Err(bad(C, "CSV has a header but no data rows")); } let mut parsed: Vec = 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 { } let names: Vec = parsed.iter().map(|d| d.name.clone()).collect(); let new_variables: Vec = defined.iter().map(|v| v.name.clone()).collect(); + let deleted: Vec = 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 { 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}"))); } diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index dc1df88bed..5ed2abe1ce 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -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, @@ -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", diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index d110149dac..722b854d69 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -99,9 +99,14 @@ impl AutomationRoots { Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {path}")), }; } - let resolved = resolve(path)?; - if roots.iter().any(|r| inside(&resolved, &r.resolved)) { - return Ok(()); + // Resolving a path on another computer connects to it: unless a root is on a network + // share, such a path is refused by its name before anything is looked up. + let remote = cfg!(windows) && network_path(path) && !roots.iter().any(|r| network_path(&r.resolved.to_string_lossy())); + if !remote { + let resolved = resolve(path)?; + if roots.iter().any(|r| inside(&resolved, &r.resolved)) { + return Ok(()); + } } let shown: Vec = roots.iter().map(|r| r.shown.display().to_string()).collect(); match (shown.as_slice(), access) { @@ -282,6 +287,14 @@ pub(crate) fn is_device_name(component: &str) -> bool { matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT") } +/// Is `path` a Windows name of a file on another computer (`\\server\share\…`, `\\?\UNC\…`)? +/// (Judged by name alone, so it can be tested on any platform; `check` applies it on Windows only.) +fn network_path(path: &str) -> bool { + let p = path.replace('/', "\\"); + let upper = p.to_ascii_uppercase(); + upper.starts_with(r"\\?\UNC\") || upper.starts_with(r"\\.\UNC\") || (p.starts_with(r"\\") && !p.starts_with(r"\\?\") && !p.starts_with(r"\\.\")) +} + /// Why Windows would not take `path` as an ordinary file name, for the first of its components /// that is a device name, or holds a `:` (a drive letter's own colon belongs to the prefix, not to /// a name, so only a stream such as `x.svg:evil` has one). (Judged by name alone, so it can be @@ -315,6 +328,16 @@ mod tests { p.to_string_lossy().into_owned() } + #[test] + fn network_paths_are_told_by_name() { + for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] { + assert!(network_path(p), "{p}"); + } + for p in [r"C:\art\x.svg", r"\\?\C:\art\x.svg", r"\\.\C:\x", "/home/me/x.svg", "x.svg"] { + assert!(!network_path(p), "{p}"); + } + } + #[test] fn paths_inside_the_roots_pass_and_others_dont() { let (base, roots) = folders("inside"); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 0eed45b343..2a9fb16289 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -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, + /// 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>, /// 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, @@ -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)>, + /// 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>, /// A guide being dragged out of a ruler ([`Session::ruler_guide`]). pub(crate) ruler_guide: Option, /// Which selected type overflows its frame, for the ports every tool but the Type tools shows. diff --git a/crates/engine/src/link_watch.rs b/crates/engine/src/link_watch.rs index 94fc568f44..51ffbd0986 100644 --- a/crates/engine/src/link_watch.rs +++ b/crates/engine/src/link_watch.rs @@ -69,6 +69,9 @@ impl Session { } let Some(st) = self.active() else { return }; let (uid, files, doc_path) = (st.uid, crate::cmd::links::linked_groups(&st.doc), st.path.clone()); + // A confined caller's roots, else what the caller that opened the document may read (the + // desktop frame is unconfined). + let opened_by = st.opened_by.clone(); if files.is_empty() { return; } @@ -76,7 +79,11 @@ impl Session { let out = slot.clone(); let scope = crate::file_access::ScopeHandle::capture(); let spawned = std::thread::Builder::new().name("link-watch".into()).spawn(move || { - let stamps = scope.run(|| files.into_iter().map(|(p, ids)| (p.clone(), ids, stamp(&p, doc_path.as_deref()))).collect()); + let stamps = scope.run(|| { + crate::file_access::confine(crate::file_access::current().or(opened_by).as_ref(), || { + files.into_iter().map(|(p, ids)| (p.clone(), ids, stamp(&p, doc_path.as_deref()))).collect() + }) + }); *out.lock().unwrap_or_else(PoisonError::into_inner) = Some((uid, stamps)); }); if spawned.is_ok() { @@ -141,7 +148,8 @@ impl Session { let mode = if update { "automatically" } else { self.prefs.update_links.as_str() }; match mode { "automatically" => { - let r = self.execute("links.update", &json!({"ids": ids}))?; + let roots = crate::file_access::current().or_else(|| self.active().and_then(|d| d.opened_by.clone())); + let r = crate::file_access::confine(roots.as_ref(), || self.execute("links.update", &json!({"ids": ids})))?; // Not readable yet (still being written): the next look tries again. let unread: BTreeSet = r["missing"].as_array().map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default(); for (path, ids) in &changed { diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index db3ee7e752..5deb00ddde 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -253,6 +253,10 @@ pub struct Prefs { // File Handling (continued) /// Where Save as Template and New from Template start ("" = `Documents/VectorCraft Templates`). pub templates_folder: String, + /// File Handling → Use System Defaults for Edit Original (#5236): Links panel › Edit Original + /// opens a linked file in the system's default app for it; off, in the app that made it + /// (PhotoCraft for a raster image, where it is installed; the system's app otherwise). + pub edit_original_system_defaults: bool, /// Open older native files as " [Converted]" so Save asks for a new name. pub append_converted: bool, /// File Handling → Use Compression: native saves are gzip-compressed (`document.save @@ -464,6 +468,7 @@ impl Default for Prefs { pdf_presets: vec![], screen_export_presets: vec![], templates_folder: String::new(), + edit_original_system_defaults: true, append_converted: true, use_compression: false, web_export_presets: vec![], diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 71233cea6e..ba6ee2f1fe 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -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(); diff --git a/crates/engine/src/tests/assets.rs b/crates/engine/src/tests/assets.rs index 3eca3ca434..8719873a94 100644 --- a/crates/engine/src/tests/assets.rs +++ b/crates/engine/src/tests/assets.rs @@ -454,3 +454,21 @@ fn collecting_explicit_assets_rejects_invalid_ids_without_adding_anything() { assert_eq!(run(&mut s, "assets.add", json!({"ids": [b, a]}))["added"], 2); assert_eq!(assets(&mut s).len(), 2); } + +/// Settings saved without the PDF passwords they were given export only once a password is given +/// again, never as an unprotected PDF; security given without `passwordRequired` exports as given. +#[test] +fn settings_saved_without_their_pdf_passwords_refuse_to_export_until_given_again() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + run(&mut s, "assets.add", json!({"ids": [a]})); + let row = |security: Value| json!({"formats": [{"format": "pdf", "security": security}]}); + run(&mut s, "assets.settings.set", row(json!({"openPassword": "open sesame"}))); + let err = s.execute("assets.export", &json!({})).unwrap_err().to_string(); + assert!(err.contains("without their passwords"), "{err}"); + let encrypted = |r: &Value| files(r)[0].1.windows(8).any(|w| w == b"/Encrypt"); + let r = run(&mut s, "assets.export", row(json!({"openPassword": "open sesame", "passwordRequired": true}))); + assert!(encrypted(&r), "given again: protected"); + let r = run(&mut s, "assets.export", row(json!({}))); + assert!(!encrypted(&r), "left out on purpose: unprotected"); +} diff --git a/crates/engine/src/tests/clipflavours.rs b/crates/engine/src/tests/clipflavours.rs index fd72f2980d..313935c21f 100644 --- a/crates/engine/src/tests/clipflavours.rs +++ b/crates/engine/src/tests/clipflavours.rs @@ -350,6 +350,27 @@ fn type_only_copies_offer_their_text() { assert!(run(&mut s, "clipboard.exportText", json!({}))["text"].is_null()); } +/// Art too large to fit the clipboard's PNG side at the encoder's smallest scale gets no PNG, +/// instead of a picture hundreds of megabytes large. +#[test] +fn copy_leaves_out_the_png_of_art_too_large_to_scale_down() { + let mut s = session(); + let id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 1_000_000, "height": 1_000_000}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [id]})); + run(&mut s, "edit.copy", json!({})); + assert!(!s.clipboard.flavour_types(false, false).contains(&PNG), "not offered either"); + let (flavours, notes) = s.clipboard.flavours_with_warnings(false, false); + assert!(flavours.iter().all(|f| f.mime != PNG)); + assert!(notes.iter().any(|n| n.contains("too large to copy as a picture")), "{notes:?}"); + // Art that fits at that scale still gets its PNG, at most 4096 pixels a side. + let id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 200_000, "height": 100}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [id]})); + run(&mut s, "edit.copy", json!({})); + let png = s.clipboard.flavours(false, false).into_iter().find(|f| f.mime == PNG).expect("a PNG"); + let img = image::load_from_memory(&png.data).unwrap(); + assert!(img.width() <= 4096 && img.height() <= 4096, "{}x{}", img.width(), img.height()); +} + #[test] fn copy_offers_flavours_by_the_preferences() { let mut s = session(); diff --git a/crates/engine/src/tests/cmdsplit.rs b/crates/engine/src/tests/cmdsplit.rs index af94ea3f39..2511e6f3de 100644 --- a/crates/engine/src/tests/cmdsplit.rs +++ b/crates/engine/src/tests/cmdsplit.rs @@ -66,6 +66,28 @@ fn unique_name_appends_the_first_free_number() { assert_eq!(unique_name("A 2", |n| taken.contains(&n)), "A 2 2"); } +#[test] +fn unique_name_from_counts_on_for_a_run_of_one_name() { + let mut taken = vec!["A".to_string(), "a 3".to_string()]; + let mut next = std::collections::HashMap::new(); + for want in ["A 2", "A 4", "A 5"] { + let is_taken = |n: &str| taken.iter().any(|t| t.eq_ignore_ascii_case(n)); + let n = crate::cmd::unique_name_from("A", &mut next, is_taken); + assert_eq!(n, want); + taken.push(n); + } + assert_eq!(crate::cmd::unique_name_from("B", &mut next, |_| false), "B"); +} + +#[test] +fn a_presets_file_with_too_many_presets_is_refused() { + let mut s = Session::new(); + let presets: Vec<_> = (0..=crate::cmd::MAX_IMPORTED_PRESETS).map(|_| serde_json::json!({"name": "P"})).collect(); + let file = serde_json::json!({"format": crate::cmd::printpresets::PRESET_FORMAT, "presets": presets}).to_string(); + let e = s.execute("print.presets.import", &serde_json::json!({"data": file})).unwrap_err().to_string(); + assert!(e.contains("over"), "{e}"); +} + #[test] fn leaf_targets_expand_groups_and_stop_at_compound_paths() { let mut s = session(); diff --git a/crates/engine/src/tests/flatten.rs b/crates/engine/src/tests/flatten.rs index e2b9b4f6ad..d4671c11e3 100644 --- a/crates/engine/src/tests/flatten.rs +++ b/crates/engine/src/tests/flatten.rs @@ -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 = 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> = 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(); diff --git a/crates/engine/src/tests/freeform.rs b/crates/engine/src/tests/freeform.rs index df9ed3e4bc..4e65c86894 100644 --- a/crates/engine/src/tests/freeform.rs +++ b/crates/engine/src/tests/freeform.rs @@ -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}"); + } +} diff --git a/crates/engine/src/tests/globaledit.rs b/crates/engine/src/tests/globaledit.rs index aeb426ac45..60bf81a060 100644 --- a/crates/engine/src/tests/globaledit.rs +++ b/crates/engine/src/tests/globaledit.rs @@ -391,6 +391,138 @@ fn undo_and_redo_drop_the_members_the_document_lacks() { assert_eq!(members(&s), None); } +#[test] +fn an_object_left_out_keeps_its_own_shape_while_the_others_follow() { + let mut s = session(); + let [a, b, c, ..] = squares(&mut s); + assert_eq!(start(&mut s, a, json!({})), [a, b, c]); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("select.globalEditExclude", &json!({"id": b.0})).unwrap(); + assert_eq!(r, json!({"active": true, "count": 2, "ids": [a.0, c.0]})); + assert_eq!(members(&s), Some(vec![a, c])); + assert_eq!(crate::cmd::globaledit::highlights(&s).len(), 1, "the copy is no longer highlighted"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "not an undo step"); + assert_eq!(s.doc().unwrap().selection.objects, [a], "the selection stays"); + let b_was = node(&s, b); + s.execute("object.setBounds", &json!({"height": 50, "reference": 0})).unwrap(); + assert!(close(bounds(&s, c), Rect::new(500.0, 0.0, 520.0, 10.0)), "{:?}", bounds(&s, c)); + assert_eq!(node(&s, b), b_was, "the copy left out keeps its shape"); +} + +/// A Shift-drag with the Selection tool from `from` to `to`. +fn shift_drag(s: &mut Session, from: (f64, f64), to: (f64, f64)) { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + let v = ViewInfo::default(); + s.select_tool("selection", v).unwrap(); + let steps = if from == to { + vec![(PointerKind::Down, from), (PointerKind::Up, to)] + } else { + vec![(PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] + }; + for (kind, (x, y)) in steps { + s.pointer(&PointerEvent::new(kind, x, y).with_mods(Mods { shift: true, ..Mods::default() }), v).unwrap(); + } +} + +/// A Shift-click with the Selection tool at (`x`, `y`). +fn shift_click(s: &mut Session, x: f64, y: f64) { + shift_drag(s, (x, y), (x, y)); +} + +#[test] +fn a_shift_click_on_a_highlighted_object_leaves_it_out() { + let mut s = session(); + let [a, b, c, ..] = squares(&mut s); + start(&mut s, a, json!({})); + // A Shift-drag that starts on the copy selects it and moves it with the selection, and leaves + // the copy in. + shift_drag(&mut s, (350.0, 50.0), (390.0, 50.0)); + assert_eq!(members(&s), Some(vec![a, b, c]), "a drag leaves nothing out"); + assert_eq!(s.doc().unwrap().selection.objects, [a, b]); + assert!(bounds(&s, a).x0 > 0.0, "the selection moved: {:?}", bounds(&s, a)); + assert!(bounds(&s, b).x0 > 300.0, "the copy moved with it: {:?}", bounds(&s, b)); + s.execute("edit.undo", &json!({})).unwrap(); + sel(&mut s, &[a]); + shift_click(&mut s, 350.0, 50.0); + assert_eq!(members(&s), Some(vec![a, c]), "the copy is left out"); + assert_eq!(s.doc().unwrap().selection.objects, [a], "and not selected"); + // A Shift-click on the object the edit started from deselects it, as before. + shift_click(&mut s, 50.0, 50.0); + assert_eq!(members(&s), Some(vec![a, c])); + assert!(s.doc().unwrap().selection.objects.is_empty()); + shift_click(&mut s, 510.0, 10.0); + assert_eq!(members(&s), None, "one object left: Global Edit ends"); + assert!(s.doc().unwrap().selection.objects.is_empty()); + // With Global Edit off, a Shift-click selects, as before. + shift_click(&mut s, 350.0, 50.0); + assert_eq!(s.doc().unwrap().selection.objects, [b]); +} + +#[test] +fn a_shift_click_inside_a_matched_group_leaves_the_whole_group_out() { + let mut s = session(); + let (g, _) = card(&mut s, 0.0, 1.0); + let (copy, _) = card(&mut s, 300.0, 1.0); + let (small, _) = card(&mut s, 500.0, 0.5); + assert_eq!(start(&mut s, g, json!({})), [g, copy, small]); + // On the circle in the copy. + shift_click(&mut s, 370.0, 20.0); + assert_eq!(members(&s), Some(vec![g, small])); + assert_eq!(s.doc().unwrap().selection.objects, [g]); + // An object inside a member that is selected: a Shift-click deselects it, as before. + let inner = kids(&s, small)[0]; + sel(&mut s, &[inner]); + shift_click(&mut s, 505.0, 5.0); + assert_eq!(members(&s), Some(vec![g, small])); +} + +#[test] +fn a_shift_click_on_a_member_inside_a_selected_group_deselects_the_group() { + let mut s = session(); + let [a, b, c, wide, _] = squares(&mut s); + let pair = group_of(&mut s, &[b, wide]); + let all = start(&mut s, a, json!({})); + assert_eq!(all, [a, c, b], "the copy in the group comes after the small square"); + sel(&mut s, &[pair]); + assert_eq!(crate::cmd::globaledit::highlights(&s).len(), 2, "the copy inside the selected group is not highlighted"); + shift_click(&mut s, 350.0, 50.0); + assert_eq!(members(&s), Some(all), "nothing is left out"); + assert!(s.doc().unwrap().selection.objects.is_empty(), "the group is deselected"); +} + +#[test] +fn leaving_out_all_but_one_ends_global_edit_and_the_first_object_stays() { + let mut s = session(); + let [a, b, c, wide, _] = squares(&mut s); + let e = s.execute("select.globalEditExclude", &json!({"id": b.0})).unwrap_err().to_string(); + assert!(e.contains("Global Edit is off"), "{e}"); + start(&mut s, a, json!({})); + for id in [a, wide] { + let e = s.execute("select.globalEditExclude", &json!({"id": id.0})).unwrap_err().to_string(); + assert!(e.contains("other than the one it started from"), "{id}: {e}"); + } + assert_eq!(members(&s), Some(vec![a, b, c]), "nothing left out"); + s.execute("select.globalEditExclude", &json!({"id": c.0})).unwrap(); + let r = s.execute("select.globalEditExclude", &json!({"id": b.0})).unwrap(); + assert_eq!(r, json!({"active": false, "count": 0, "ids": []})); + assert_eq!(members(&s), None, "one object left: Global Edit ends"); + assert!(crate::cmd::globaledit::highlights(&s).is_empty()); +} + +#[test] +fn a_group_left_out_keeps_its_objects_while_the_others_follow() { + let mut s = session(); + let (g, [_, dot, _]) = card(&mut s, 0.0, 1.0); + let (copy, [_, cdot, _]) = card(&mut s, 300.0, 1.0); + let (small, [_, sdot, _]) = card(&mut s, 500.0, 0.5); + assert_eq!(start(&mut s, g, json!({})), [g, copy, small]); + s.execute("select.globalEditExclude", &json!({"id": copy.0})).unwrap(); + let was = fill(&s, cdot); + sel(&mut s, &[dot]); + s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap(); + assert_eq!((fill(&s, sdot), fill(&s, cdot)), ("#12ab34".to_string(), was)); +} + /// Two 100 pt squares and a 20 pt one made after `begin`, all three in a Global Edit; `put_back` /// takes the document back to before the small one. The small square leaves the Global Edit, and /// a square made under its freed id is not edited with the others. diff --git a/crates/engine/src/tests/gradient.rs b/crates/engine/src/tests/gradient.rs index c36addcbc5..e6f9383fe3 100644 --- a/crates/engine/src/tests/gradient.rs +++ b/crates/engine/src/tests/gradient.rs @@ -30,6 +30,47 @@ fn fill_gradient(s: &Session, id: NodeId) -> GradientPaint { } } +#[test] +fn new_gradient_defaults_follow_the_cmyk_document_mode() { + for kind in ["linear", "radial", "freeform"] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width":200,"height":200,"colorMode":"cmyk"})).unwrap(); + let id = rect(&mut s, 10.0, 10.0, 100.0, 100.0); + s.execute("paint.editGradient", &json!({"kind":kind})).unwrap(); + let g = fill_gradient(&s, id); + assert!(g.gradient.stops.iter().all(|stop| matches!(stop.color, Color::Cmyk { .. })), "{kind}: {:?}", g.gradient.stops); + if let Some(freeform) = g.freeform { + assert!(freeform.points.iter().all(|point| matches!(point.color, Color::Cmyk { .. })), "freeform points must use the same color model"); + } + } +} + +#[test] +fn editing_an_explicit_rgb_gradient_in_cmyk_keeps_its_color_model() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width":200,"height":200,"colorMode":"cmyk"})).unwrap(); + let id = rect(&mut s, 10.0, 10.0, 100.0, 100.0); + s.execute("paint.editGradient", &json!({"kind":"linear","keepModel":true})).unwrap(); + let before = fill_gradient(&s, id).gradient.stops; + assert!(before.iter().all(|stop| matches!(stop.color, Color::Rgb { .. }))); + s.execute("paint.editGradient", &json!({"angle":45})).unwrap(); + assert_eq!(fill_gradient(&s, id).gradient.stops, before); +} + +#[test] +fn drawing_a_new_gradient_vector_uses_cmyk_default_stops() { + for stroke in [false, true] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width":200,"height":200,"colorMode":"cmyk"})).unwrap(); + let id = rect(&mut s, 10.0, 10.0, 100.0, 100.0); + s.execute("paint.setGradientGeom", &json!({"start":[10,10],"end":[110,10],"stroke":stroke})).unwrap(); + let appearance = &node(&s, id).appearance; + let paint = if stroke { appearance.stroke_paint() } else { appearance.fill_paint() }; + let Paint::Gradient(g) = paint else { panic!("not a gradient") }; + assert!(g.gradient.stops.iter().all(|stop| matches!(stop.color, Color::Cmyk { .. })), "stroke={stroke}: {:?}", g.gradient.stops); + } +} + /// A three-stop freeform gradient with a 0.3 midpoint, partial opacity and a placed vector. fn three_stops() -> GradientPaint { let stop = |offset, color, opacity, midpoint| GradientStop { opacity, midpoint, ..GradientStop::new(offset, color) }; diff --git a/crates/engine/src/tests/library.rs b/crates/engine/src/tests/library.rs index 92c780e29d..a9bafc540b 100644 --- a/crates/engine/src/tests/library.rs +++ b/crates/engine/src/tests/library.rs @@ -821,6 +821,18 @@ fn imported_libraries_are_made_consistent() { ); } +/// A library of one name repeated as often as it may hold numbers the copies in one pass. +#[test] +fn a_library_of_one_repeated_name_imports_numbered() { + let mut s = session(); + let red = json!({"name": "Red", "color": {"model": "rgb", "r": 1, "g": 0, "b": 0}}); + let lib = json!({"name": "Many", "colors": vec![red; 10_000]}); + run(&mut s, "library.import", json!({"data": lib.to_string()})); + let got = run(&mut s, "library.get", json!({})); + let colors = got["colors"].as_array().unwrap(); + assert_eq!((colors.len(), colors[1]["name"].as_str(), colors[9_999]["name"].as_str()), (10_000, Some("Red 2"), Some("Red 10000"))); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_library_is_exported_to_a_file_and_imported_from_it() { diff --git a/crates/engine/src/tests/linkspanel.rs b/crates/engine/src/tests/linkspanel.rs index b08d9acab6..56784b69d9 100644 --- a/crates/engine/src/tests/linkspanel.rs +++ b/crates/engine/src/tests/linkspanel.rs @@ -278,6 +278,24 @@ fn link_info_has_the_file_and_placement_details() { assert_eq!((i["status"].as_str(), i["linked"].as_bool(), i["fileName"].as_str()), (Some("embedded"), Some(false), None)); } +/// Link Info reads within the opener's roots for an unconfined caller, and never past a confined +/// caller's own roots. +#[test] +fn link_info_stays_within_the_asking_callers_roots() { + let dir = Folder::new("info-roots"); + let other = Folder::new("info-other"); + let pic = dir.file("photo.png"); + write(&pic, &png(60, 30, RED)); + let mut s = session(); + let id = place(&mut s, &pic); + let roots = |p: &std::path::Path| crate::file_access::AutomationRoots::new(&[p], &[]).unwrap().unwrap(); + s.active_mut().unwrap().opened_by = Some(roots(&dir.0)); + assert_eq!(run(&mut s, "links.info", json!({"id": id.0}))["status"], "ok"); + let narrow = roots(&other.0); + let i = crate::file_access::confine(Some(&narrow), || run(&mut s, "links.info", json!({"id": id.0}))); + assert_ne!(i["status"], "ok", "{i}"); +} + /// A 600×300 pt image at the centre of the artboard, its placement options set to `options`, /// relinked to a 300×100 px file → the image's id and session. fn relinked(name: &str, options: Value) -> (Session, NodeId, Folder) { diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 7bac52cc9c..0c351dba7d 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1948,6 +1948,62 @@ fn select_same_font_size_and_fill() { assert!(s.execute("select.same.fontSize", &json!({})).is_err()); } +/// Select › Same › Text Fill & Stroke Color selects the type with characters whose fill and stroke +/// both match the first character of the selected type: the same fill with another stroke, or the +/// same stroke with another fill, is left out, and in type with several runs one run has to match +/// both. +#[test] +fn select_same_text_fill_and_stroke_color_needs_both_to_match() { + let mut s = session(); + let typed = |s: &mut Session, y: f64, fill: &str, stroke: &str| { + let id = id_of(&s.execute("text.create", &json!({"x": 0, "y": y, "text": "type"})).unwrap()); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 4, "fill": fill, "stroke": stroke})).unwrap(); + id + }; + let (red, blue, green) = ("#ff0000", "#0000ff", "#00ff00"); + let a = typed(&mut s, 20.0, red, blue); + let both = typed(&mut s, 60.0, red, blue); + let same_fill = typed(&mut s, 100.0, red, green); + let same_stroke = typed(&mut s, 140.0, green, blue); + // Mixed runs: "ty" matches both; the other runs do not. + let mixed = typed(&mut s, 180.0, green, green); + s.execute("text.setRangeStyle", &json!({"id": mixed.0, "start": 0, "end": 2, "fill": red, "stroke": blue})).unwrap(); + // Mixed runs where one run has the fill and another the stroke: no run matches both. + let split = typed(&mut s, 220.0, green, green); + s.execute("text.setRangeStyle", &json!({"id": split.0, "start": 0, "end": 2, "fill": red})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": split.0, "start": 2, "end": 4, "stroke": blue})).unwrap(); + let r = rect(&mut s, 300.0, 0.0, 5.0, 5.0); + s.execute("paint.setFill", &json!({"ids": [r.0], "color": red})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + sel(&mut s, &[a]); + assert_eq!(s.execute("select.same.textFillAndStrokeColor", &json!({})).unwrap()["count"], 3); + assert_eq!(selected(&s), vec![a, both, mixed]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "selecting adds no undo step"); + // The single-attribute commands take the type that matches one of the two. + sel(&mut s, &[a]); + assert_eq!(s.execute("select.same.textFillColor", &json!({})).unwrap()["count"], 5); + assert_eq!(selected(&s), vec![a, both, same_fill, mixed, split]); + sel(&mut s, &[a]); + assert_eq!(s.execute("select.same.textStrokeColor", &json!({})).unwrap()["count"], 5); + assert_eq!(selected(&s), vec![a, both, same_stroke, mixed, split]); + // With no type selected the command reports it. + sel(&mut s, &[r]); + 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(); diff --git a/crates/engine/src/tests/objects_on_path.rs b/crates/engine/src/tests/objects_on_path.rs index a309eb69ba..8c0f359df4 100644 --- a/crates/engine/src/tests/objects_on_path.rs +++ b/crates/engine/src/tests/objects_on_path.rs @@ -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) { + 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)); +} diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index 7c3ff56ab1..3c86e513e6 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -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. diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index f94143cb64..08071df059 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -349,6 +349,30 @@ fn native_included_links_keep_missing_placed_documents_editable() { } } +/// Output prepared by a caller that may not read the placed file shows its preview, not the full +/// art an earlier caller that could read it left cached. +#[test] +fn a_confined_export_does_not_reuse_full_art_read_for_another_caller() { + let dir = Folder::new("placed-confined"); + let other = Folder::new("placed-confined-other"); + let src = dir.file("src.vectorcraft"); + source(&src, 100.0, 50.0, BLUE, 0); + let mut s = session(); + place(&mut s, &src); + // As a document saved with previews opens: each placed file's blob holds only its preview. + for b in std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).images.values_mut() { + if let Some(p) = b.proxy.clone() { + b.bytes = p; + } + } + let d = s.doc().unwrap().doc.clone(); + let preview = |d: &Document| d.images.keys().any(|k| k.starts_with(vectorcraft_doc::placed_document::RESOURCE_PREFIX) && k.ends_with("/preview")); + assert!(!preview(&d.with_placed_art()), "the file is read in full"); + let roots = crate::file_access::AutomationRoots::new(&[&other.0], &[]).unwrap().unwrap(); + let confined = crate::file_access::confine(Some(&roots), || d.with_placed_art().into_owned()); + assert!(preview(&confined), "only the preview shows"); +} + #[test] fn a_document_saved_with_previews_outputs_its_files_art() { let dir = Folder::new("placed-preview-output"); @@ -693,6 +717,53 @@ fn a_placed_documents_resources_stay_its_own() { assert!(near(centre_colour(&old), BLUE)); } +#[test] +fn saved_for_older_apps_with_a_precision_the_placed_art_is_rounded_too() { + let dir = Folder::new("placed-precision"); + let src = dir.file("triangle.vectorcraft"); + let mut d = Document::new(100.0, 100.0); + let layer = d.layers[0].id; + let id = d.alloc_id(); + let points = [(3.4876474632797176, 1.0), (90.0, 2.123456789), (40.0, 80.0)].map(|(x, y)| vectorcraft_geom::Point::new(x, y)); + let path = vectorcraft_geom::PathData::single(vectorcraft_geom::path::SubPath::polyline(&points, true)); + d.insert(Some(layer), 0, Node::path(id, path, look(BLUE))).unwrap(); + write(&src, &vectorcraft_format::save_file(&d)); + let mut s = session(); + place(&mut s, &src); + // The coordinates of every anchor and handle in a file's layers. + fn coords(v: &Value, out: &mut Vec) { + match v { + Value::Object(o) => { + for a in o.get("anchors").and_then(Value::as_array).into_iter().flatten() { + out.extend(["p", "in", "out"].iter().filter_map(|k| a[*k].as_array()).flatten().filter_map(Value::as_f64)); + } + o.values().for_each(|c| coords(c, out)); + } + Value::Array(a) => a.iter().for_each(|c| coords(c, out)), + _ => {} + } + } + let mut saved = |p: Value| { + let file: Value = serde_json::from_slice(&decode(&s.execute("document.serialize", &p).unwrap())).unwrap(); + assert!(!file.to_string().contains("placeddocument"), "{file}"); + let mut out = vec![]; + coords(&file["document"]["layers"], &mut out); + out + }; + let at4 = |x: f64| (x * 1e4).round() / 1e4 == x; + let exact = saved(json!({"format": "vectorcraft", "version": 3})); + assert!(exact.len() >= 6 && !exact.iter().all(|x| at4(*x)), "{exact:?}"); + let rounded = saved(json!({"format": "vectorcraft", "version": 3, "precision": 4})); + assert_eq!(rounded.len(), exact.len()); + assert!(rounded.iter().all(|x| at4(*x)), "{rounded:?}"); + // The preview shows the rounded art the older app opens, not the placed file's exact art. + let file = decode(&s.execute("file.saveCopy", &json!({"version": 3, "precision": 0, "preview": true})).unwrap()); + let preview = vectorcraft_format::preview(&file); + assert!(preview.is_some()); + assert_eq!(preview, crate::cmd::fileio::preview_png(&vectorcraft_format::load(&file).unwrap()).unwrap()); + assert_ne!(preview, crate::cmd::fileio::preview_png(&s.doc().unwrap().doc).unwrap()); +} + #[test] fn break_link_gives_the_editable_copy_placing_without_link_gives() { let dir = Folder::new("placed-break"); diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 5727e9db13..b590e3c289 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -1658,6 +1658,30 @@ fn real_time_drawing_off_still_shows_a_dragged_guide() { assert_eq!((s.doc().unwrap().doc.guides[0].pos, s.doc().unwrap().history.undo.last().map(|e| e.label.as_str())), (150.0, Some("Move Guide"))); } +/// With Real-time Drawing off, a 9-slice guide of the edited symbol moved with the Selection tool +/// still moves while it is dragged, and the release leaves one Symbol Options undo step. +#[test] +fn real_time_drawing_off_still_shows_a_dragged_nine_slice_guide() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + s.execute("symbol.new", &json!({"name": "Box", "nineSlice": true})).unwrap(); + s.execute("symbol.edit", &json!({})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("selection", v).unwrap(); + set_pref(&mut s, "realTimeDrawing", json!(false)); + let left = |s: &Session| s.doc().unwrap().doc.symbol_nine_slice("Box").unwrap().left; + assert_eq!(left(&s), 0.25); + let steps = s.doc().unwrap().history.undo.len(); + s.pointer(&PointerEvent::new(PointerKind::Down, 125.0, 150.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 110.0, 150.0), v).unwrap(); + assert!((left(&s) - 0.1).abs() < 1e-9, "the guide moves while dragged: {}", left(&s)); + s.pointer(&PointerEvent::new(PointerKind::Up, 110.0, 150.0), v).unwrap(); + let d = s.doc().unwrap(); + assert!((left(&s) - 0.1).abs() < 1e-9); + assert_eq!((d.history.undo.len(), d.history.undo.last().map(|e| e.label.as_str())), (steps + 1, Some("Symbol Options"))); +} + /// Real-time Drawing turned on mid-drag still applies the deferred preview on commit. #[test] fn real_time_drawing_turned_on_mid_drag_still_commits_deferred_preview() { diff --git a/crates/engine/src/tests/recovery.rs b/crates/engine/src/tests/recovery.rs index cfd72aedf4..56c8d899da 100644 --- a/crates/engine/src/tests/recovery.rs +++ b/crates/engine/src/tests/recovery.rs @@ -417,6 +417,21 @@ fn the_folder_store_makes_owner_only_folders() { let _ = std::fs::remove_dir_all(&base); } +/// An entry that is a link (the copy's metadata names it) is not followed out of the store. +#[cfg(unix)] +#[test] +fn the_folder_store_reads_no_linked_entries() { + let base = std::env::temp_dir().join(format!("vc-recovery-links-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let store = FolderStore::new(&base); + store.write("1-1/Untitled-1-1.vectorcraft", b"copy").unwrap(); + std::fs::write(base.join("outside"), b"private").unwrap(); + std::os::unix::fs::symlink(base.join("outside"), base.join("1-1").join("img")).unwrap(); + assert_eq!(store.read("1-1/Untitled-1-1.vectorcraft").unwrap(), b"copy"); + assert!(store.read("1-1/img").is_err()); + let _ = std::fs::remove_dir_all(&base); +} + #[test] fn saving_reverting_or_closing_removes_the_copy() { let dir = std::env::temp_dir().join(format!("vc-recovery-save-{}", std::process::id())); @@ -628,6 +643,31 @@ fn images_are_kept_apart_and_written_again_only_when_they_change() { assert!(store.images().is_empty(), "{:?}", store.list()); } +/// Image keys sharing their bytes share one entry: it is written once when saved, and read and +/// written once when restored. +#[test] +fn images_sharing_an_entry_are_written_once() { + let store = Arc::new(Counting::default()); + let mut s = Session::new(); + s.recovery.set_store(store.clone()); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + place_png(&mut s, "red.png", crate::tests_links::RED); + let doc = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let blob = doc.images.values().next().unwrap().clone(); + for i in 0..50 { + doc.images.insert(format!("copy-{i}"), blob.clone()); + } + s.execute("file.recovery.save", &json!({})).unwrap(); + assert_eq!(store.images_written().len(), 1); + let images = images_of(&s); + drop(s); + let mut s = Session::new(); + s.recovery.set_store(store.clone()); + assert_eq!(restored(s.execute("file.recovery.restore", &json!({})).unwrap()), 1); + assert_eq!(images_of(&s), images); + assert_eq!(store.images_written().len(), 1, "restored into this session's area once"); +} + #[test] fn copies_from_before_images_were_kept_apart_still_restore() { let store = Arc::new(MemoryStore::default()); diff --git a/crates/engine/src/tests/saveoptions.rs b/crates/engine/src/tests/saveoptions.rs index ff17ef34eb..d52cbba610 100644 --- a/crates/engine/src/tests/saveoptions.rs +++ b/crates/engine/src/tests/saveoptions.rs @@ -353,3 +353,122 @@ fn format_options_list_the_save_options() { let v = s.execute("file.formatOptions", &json!({})).unwrap(); assert_eq!(v["options"]["includeLinked"]["value"], true); } + +/// The anchors of the first object in the native file at `path`. +fn saved_anchors(path: &str) -> Vec { + let d = vectorcraft_format::load(&std::fs::read(path).unwrap()).unwrap(); + let NodeKind::Path { path, .. } = &d.layers[0].children().unwrap()[0].kind else { panic!("not a path") }; + path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect() +} + +#[test] +fn precision_rounds_the_paths_of_that_save_only() { + let dir = Folder::new("precision"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 1000, "height": 1000})).unwrap(); + // 1,000 anchors at coordinates with many decimal places (a fixed pseudo-random sequence). + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = || { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (seed >> 11) as f64 / (1u64 << 53) as f64 * 1000.0 + }; + let anchors: Vec = (0..1000).map(|_| json!({"x": next(), "y": next()})).collect(); + s.execute("path.create", &json!({"anchors": anchors})).unwrap(); + let (exact, rounded) = (dir.file("exact.vectorcraft"), dir.file("rounded.vectorcraft")); + s.execute("document.save", &json!({"path": exact, "compress": false})).unwrap(); + s.execute("document.save", &json!({"path": rounded, "compress": false, "precision": 3})).unwrap(); + let (e, r) = (std::fs::metadata(&exact).unwrap().len(), std::fs::metadata(&rounded).unwrap().len()); + assert!(r < e, "{r} bytes rounded, {e} exact"); + let (want, got) = (saved_anchors(&exact), saved_anchors(&rounded)); + assert_eq!(got.len(), 1000); + for (w, g) in want.iter().zip(&got) { + assert!((w.x - g.x).abs() <= 0.0005 && (w.y - g.y).abs() <= 0.0005, "{w:?} saved as {g:?}"); + assert_eq!(((g.x * 1000.0).round() / 1000.0, (g.y * 1000.0).round() / 1000.0), (g.x, g.y)); + } + // The document keeps its exact anchors, and Save doesn't remember the precision. + let v = s.execute("file.formatOptions", &json!({})).unwrap(); + assert!(v["options"]["precision"]["value"].is_null(), "{}", v["options"]["precision"]); + s.execute("document.save", &json!({})).unwrap(); + assert_eq!(saved_anchors(&rounded), want); + // A precision that isn't a whole number from 0 to 9 is refused, by the command that was given it. + for (wrong, got) in [(json!(10), "10"), (json!(2.5), "2.5"), (json!(-1), "-1"), (json!("4"), "\"4\""), (json!(true), "true")] { + for cmd in ["file.saveCopy", "document.save"] { + let e = s.execute(cmd, &json!({"precision": wrong})).unwrap_err().to_string(); + assert!(e.contains(&format!("`{cmd}`")) && !e.contains("document.export"), "{cmd} {wrong}: {e}"); + assert!(e.contains(&format!("`precision` must be a whole number between 0 and 9 (got {got})")), "{cmd} {wrong}: {e}"); + } + } + // A type error in another native option names that command too. + let e = s.execute("document.save", &json!({"version": "4"})).unwrap_err().to_string(); + assert!(e.contains("`document.save`") && !e.contains("document.export"), "{e}"); +} + +#[test] +fn precision_is_not_remembered_for_new_documents() { + let dir = Folder::new("precision-preferences"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("document.save", &json!({"path": dir.file("rounded.vectorcraft"), "precision": 3})).unwrap(); + assert!(!s.prefs.native_save_options.contains_key("precision")); + + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let options = s.execute("file.formatOptions", &json!({"format": "vectorcraft"})).unwrap(); + assert!(options["options"]["precision"]["value"].is_null(), "{}", options["options"]["precision"]); +} + +#[test] +fn a_ai_file_ignores_precision_as_save_does() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("path.create", &json!({"anchors": [{"x": 10.123456789, "y": 20.987654321}, {"x": 60.5, "y": 70.25}]})).unwrap(); + let want: Vec<_> = { + let NodeKind::Path { path, .. } = &s.doc().unwrap().doc.layers[0].children().unwrap()[0].kind else { panic!("not a path") }; + path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect() + }; + for cmd in ["document.export", "file.saveCopy"] { + for precision in [json!(3), json!(10)] { + let r = s.execute(cmd, &json!({"format": "ai", "precision": precision})).unwrap(); + let mut t = Session::new(); + t.execute("document.open", &json!({"name": "x.ai", "dataBase64": r["dataBase64"]})).unwrap(); + let NodeKind::Path { path, .. } = &t.doc().unwrap().doc.layers[0].children().unwrap()[0].kind else { panic!("not a path") }; + let got: Vec<_> = path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect(); + assert_eq!(got, want, "{cmd} {precision}"); + } + } +} + +/// The anchors of every path in `n` and the art it holds. +fn all_anchors(n: &vectorcraft_doc::Node, out: &mut Vec) { + if let NodeKind::Path { path, .. } = &n.kind { + out.extend(path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))); + } + for c in n.children().into_iter().flatten() { + all_anchors(c, out); + } +} + +#[test] +fn the_preview_and_pdf_of_a_save_at_a_precision_show_the_rounded_art() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let anchors = json!([{"x": 10.4, "y": 20.3}, {"x": 80.6, "y": 30.7}, {"x": 45.35, "y": 85.65}]); + s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap(); + let file = bytes_of(&s.execute("file.saveCopy", &json!({"precision": 0, "pdfCompatible": true, "preview": true})).unwrap()["dataBase64"]); + // The embedded PDF, opened, has the path on whole points. + let pdf = vectorcraft_format::pdf_content(&file).unwrap(); + let mut t = Session::new(); + t.execute("document.open", &json!({"name": "x.pdf", "dataBase64": vectorcraft_format::base64_encode(&pdf)})).unwrap(); + let mut got = vec![]; + for l in &t.doc().unwrap().doc.layers { + all_anchors(l, &mut got); + } + for (x, y) in [(10.0, 20.0), (81.0, 31.0), (45.0, 86.0)] { + assert!(got.iter().any(|p| (p.x - x).abs() < 1e-3 && (p.y - y).abs() < 1e-3), "({x}, {y}) not in {got:?}"); + } + assert!(got.iter().all(|p| (p.x - p.x.round()).abs() < 1e-3 && (p.y - p.y.round()).abs() < 1e-3), "{got:?}"); + // The preview is the one the saved document draws, not the exact art's. + let preview = vectorcraft_format::preview(&file); + assert!(preview.is_some()); + assert_eq!(preview, crate::cmd::fileio::preview_png(&vectorcraft_format::load(&file).unwrap()).unwrap()); + assert_ne!(preview, crate::cmd::fileio::preview_png(&s.doc().unwrap().doc).unwrap()); +} diff --git a/crates/engine/src/tests/slices.rs b/crates/engine/src/tests/slices.rs index f14e878d31..eee1a47694 100644 --- a/crates/engine/src/tests/slices.rs +++ b/crates/engine/src/tests/slices.rs @@ -86,6 +86,19 @@ fn releasing_a_user_slice_leaves_an_unpainted_rectangle() { assert_eq!(s.doc().unwrap().selection.objects, vec![NodeId(rid)]); } +/// Guides cutting more pieces than a document takes are refused before the grid is made. +#[test] +fn too_many_guide_pieces_are_refused() { + let mut s = session(); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + for i in 1..3000 { + for vertical in [true, false] { + doc.guides.push(vectorcraft_doc::Guide::new(vertical, f64::from(i) * 0.1)); + } + } + assert!(s.execute("object.slice.fromGuides", &json!({})).unwrap_err().to_string().contains("more than")); +} + #[test] fn guides_give_nine_slices() { let mut s = session(); diff --git a/crates/engine/src/tests/symbol_nine_slice.rs b/crates/engine/src/tests/symbol_nine_slice.rs index 127af65c74..fba17f11ee 100644 --- a/crates/engine/src/tests/symbol_nine_slice.rs +++ b/crates/engine/src/tests/symbol_nine_slice.rs @@ -2,8 +2,9 @@ //! their size; Break Link to Symbol gives the art as it draws, in one step. use serde_json::json; -use vectorcraft_doc::{Node, NodeKind}; -use vectorcraft_geom::Rect; +use vectorcraft_doc::{EditedNineSlice, NineSliceGuide, Node, NodeKind}; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_tools::{PointerEvent, PointerKind}; use crate::*; @@ -209,3 +210,43 @@ fn a_dynamic_instance_keeps_its_changes_through_the_guides() { assert_eq!(fills.last().cloned().flatten().as_deref(), Some("#ff0000"), "{fills:?}"); assert_ne!(fills[0].as_deref(), Some("#ff0000"), "only the changed object"); } + +/// The boxes of the paths a symbol instance `id` draws, placed through its symbol's guides. +fn placed_boxes(s: &Session, id: NodeId) -> Vec { + let d = &s.doc().unwrap().doc; + let NodeKind::SymbolInstance { symbol, xf } = &d.node(id).unwrap().kind else { panic!("still an instance") }; + let art = d.symbols.iter().find(|s| &s.name == symbol).unwrap().art.clone(); + path_boxes(&d.place_symbol_art(symbol, &art, *xf).unwrap()) +} + +/// Dragging the left guide on the canvas while editing the symbol changes how a scaled instance +/// draws: with the guide moved from 25% to 5%, the corner square of the 200 × 150 instance reaches +/// past the left cell into the stretched center band, so it draws about 17.14 pt wide instead of 10. +#[test] +fn a_guide_dragged_on_the_canvas_changes_how_a_scaled_instance_draws() { + let (mut s, id) = panel(); + assert_sliced(&placed_boxes(&s, id)); + s.execute("symbol.edit", &json!({"name": "Panel"})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("selection", v).unwrap(); + let mid = |e: &EditedNineSlice, g| { + let (a, b) = e.line(g); + Point::new((a.x + b.x) / 2.0, (a.y + b.y) / 2.0) + }; + let e = s.doc().unwrap().doc.edited_nine_slice().unwrap(); + // The left guide sits at 25% of the art's width and the right one at 75%: 5% lies 0.4 of + // that span to the left of the left guide. + let (from, right) = (mid(&e, NineSliceGuide::Left), mid(&e, NineSliceGuide::Right)); + let to = from + (from - right) * 0.4; + s.pointer(&PointerEvent::new(PointerKind::Down, from.x + 1.0, from.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, to.x, to.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, to.x, to.y), v).unwrap(); + s.execute("symbol.exitEditing", &json!({})).unwrap(); + let boxes = placed_boxes(&s, id); + assert_eq!(boxes.len(), 3, "{boxes:?}"); + // 5 pt of the square in the left cell, then 5 pt of the 70 pt center band stretched to 170 pt. + let want = 5.0 + 5.0 * 170.0 / 70.0; + assert!(close(boxes[1], Rect::new(50.0, 50.0, 50.0 + want, 60.0)), "{boxes:?}"); + let left = s.doc().unwrap().doc.symbol_nine_slice("Panel").unwrap().left; + assert!((left - 0.05).abs() < 1e-9, "{left}"); +} diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index a3e8f7c66e..60243f343e 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -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::>(); + 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(); @@ -574,6 +627,33 @@ fn touch_type_moves_one_character_in_centered_and_right_aligned_lines() { } } +#[test] +fn touch_type_centered_ltr_scale_keeps_the_expected_width_change() { + let mut s = session(); + let id = NodeId( + s.execute("text.create", &json!({"x": 200, "y": 100, "text": "Type", "size": 40, "justify": "center"})).unwrap()["id"].as_u64().unwrap(), + ); + let before = glyph_pens(&s, id); + s.execute("text.touchType", &json!({"id": id.0, "start": 1, "hScale": 150})).unwrap(); + let after = glyph_pens(&s, id); + let previous = moved_by(&before, &after, 0).0; + let following = moved_by(&before, &after, 2).0; + assert!(previous < -1.0, "centered line shifts left: {previous}"); + assert!(following > 1.0, "the wider character shifts following text right: {following}"); + assert!((following + previous).abs() < 0.1, "width growth is shared around the center: {previous}, {following}"); +} + +#[test] +fn touch_type_refuses_horizontal_move_across_a_direction_boundary() { + let mut s = session(); + let id = text(&mut s, "abc אבג"); + let before = obj(&s, id); + let result = s.execute("text.touchType", &json!({"id": id.0, "start": 4, "dx": 5})); + assert!(result.is_err(), "a mixed-direction boundary has no safe preceding glyph for kerning"); + assert_eq!(obj(&s, id), before, "a refused move leaves the text unchanged"); + s.execute("text.touchType", &json!({"id": id.0, "start": 4, "dy": 3})).unwrap(); +} + /// `dy` moves a rotated character that many document points up from its line, also in type /// scaled unevenly. #[test] @@ -693,15 +773,15 @@ fn touch_type_raises_a_rotated_character_on_a_skewed_path() { assert!(((x * x + y * y).sqrt() - 10.0).abs() < 1e-6, "({x}, {y})"); } -/// A right-to-left character moves only up and down. +/// A right-to-left character can move along its line and up from it. #[test] -fn touch_type_moves_a_right_to_left_character_only_up_and_down() { +fn touch_type_moves_a_right_to_left_character_along_its_line_and_up() { let mut s = session(); let id = NodeId(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "אבג", "size": 40})).unwrap()["id"].as_u64().unwrap()); - assert!(s.execute("text.touchType", &json!({"id": id.0, "start": 2, "dx": 5})).is_err()); let before = glyph_pens(&s, id); - s.execute("text.touchType", &json!({"id": id.0, "start": 2, "dy": 3})).unwrap(); - let (_, up) = moved_by(&before, &glyph_pens(&s, id), 2); + s.execute("text.touchType", &json!({"id": id.0, "start": 2, "dx": 5, "dy": 3})).unwrap(); + let (along, up) = moved_by(&before, &glyph_pens(&s, id), 2); + assert!((along + 5.0).abs() < 1e-9, "{along}"); assert!((up + 3.0).abs() < 1e-9, "{up}"); } @@ -1204,6 +1284,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(); @@ -1493,6 +1595,141 @@ fn rtl_edit_commands_and_undo_preserve_logical_source_and_style_ranges() { assert_eq!(obj(&s, id).plain_text(), "שלום Rust 123"); } +#[test] +fn touch_type_rtl_move_keeps_neighbors_and_undo_restores_the_original() { + use vectorcraft_text::test_fonts::{RIGHT_TO_LEFT_OPTICAL_FAMILY, right_to_left_optical_font}; + + // Repeated registration of this synthetic face is harmless in the shared database. + vectorcraft_text::FontDb::global().add_font(right_to_left_optical_font().unwrap()); + let mut s = session(); + let id = NodeId( + s.execute("text.create", &json!({"x": 300, "y": 250, "text": "אבא", "size": 100, "font": RIGHT_TO_LEFT_OPTICAL_FAMILY})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let original = obj(&s, id); + let before = glyph_pens(&s, id); + assert_eq!(before.len(), 3); + s.execute("text.touchType", &json!({"id": id.0, "start": 2, "dx": 5, "dy": 3})).unwrap(); + let after = glyph_pens(&s, id); + assert!(near(moved_by(&before, &after, 2), (-5.0, -3.0)), "{:?}", moved_by(&before, &after, 2)); + for byte in [0, 4] { + assert!(near(moved_by(&before, &after, byte), (0.0, 0.0)), "neighbor {byte}: {:?}", moved_by(&before, &after, byte)); + } + assert_eq!(obj(&s, id).plain_text(), original.plain_text()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(obj(&s, id), original); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(near(moved_by(&before, &glyph_pens(&s, id), 2), (-5.0, -3.0))); + assert!(s.execute("text.touchType", &json!({"id": id.0, "start": 0, "dx": 5})).is_err()); +} + +#[test] +fn touch_type_rtl_move_keeps_rotated_font_placement() { + use vectorcraft_text::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font}; + vectorcraft_text::FontDb::global().add_font(pair_kerning_font().unwrap()); + let mut s = session(); + // An explicit RTL override gives the existing synthetic S/S positioning pair RTL order. + let id = + NodeId( + s.execute("text.create", &json!({"x": 300, "y": 250, "text": "\u{202e}SSS\u{202c}", "size": 100, "font": PAIR_KERNING_FAMILY})).unwrap() + ["id"] + .as_u64() + .unwrap(), + ); + s.execute("text.touchType", &json!({"id": id.0, "start": 4, "rotation": 90})).unwrap(); + let original = obj(&s, id); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &original); + let glyph = lay.glyphs.iter().find(|g| g.byte == 4).unwrap(); + assert!(glyph.rtl && glyph.width_start.abs() > 0.1, "fixture needs RTL font x-placement"); + let before = glyph_pens(&s, id); + s.execute("text.touchType", &json!({"id": id.0, "start": 4, "dx": 5, "dy": 3})).unwrap(); + let after = glyph_pens(&s, id); + assert!(near(moved_by(&before, &after, 4), (-5.0, -3.0)), "{:?}", moved_by(&before, &after, 4)); + for byte in [3, 5] { + assert!(near(moved_by(&before, &after, byte), (0.0, 0.0)), "neighbor {byte}: {:?}", moved_by(&before, &after, byte)); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(obj(&s, id), original); +} + +#[test] +fn touch_type_rtl_moves_rotated_characters_in_aligned_and_transformed_text() { + use vectorcraft_geom::{Affine, Vec2}; + use vectorcraft_text::test_fonts::{RIGHT_TO_LEFT_OPTICAL_FAMILY, right_to_left_optical_font}; + + vectorcraft_text::FontDb::global().add_font(right_to_left_optical_font().unwrap()); + let matrices = + [Affine::IDENTITY, Affine::scale_non_uniform(2.0, 0.5), Affine::new([1.0, 0.25, 0.4, 1.2, 0.0, 0.0]), Affine::scale_non_uniform(-1.0, 1.0)]; + for justify in ["auto", "left", "center", "right"] { + for rotation in [0.0, 90.0, -90.0] { + for matrix in matrices { + for (kerning, start) in [("auto", 2), ("optical", 2), ("auto", 4), ("optical", 4)] { + let case = format!("{justify}, {rotation} degrees, {matrix:?}, {kerning}, byte {start}"); + let mut s = session(); + let r = s + .execute( + "text.create", + &json!({"x": 300, "y": 250, "text": "אבא", "size": 100, "font": RIGHT_TO_LEFT_OPTICAL_FAMILY, "justify": justify}), + ) + .unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": kerning})).unwrap(); + s.execute("object.transform", &json!({"ids": [id.0], "matrix": matrix.as_coeffs()})).unwrap(); + s.execute("text.touchType", &json!({"id": id.0, "start": start, "rotation": rotation})).unwrap(); + let original = obj(&s, id); + let before = glyph_pens(&s, id); + let linear = |v: Vec2| original.xf * (Point::ZERO + v) - original.xf * Point::ZERO; + let expected = linear(Vec2::new(-1.0, 0.0)).normalize() * 5.0 + linear(Vec2::new(0.0, -1.0)).normalize() * 3.0; + s.execute("text.touchType", &json!({"id": id.0, "start": start, "dx": 5, "dy": 3})).unwrap(); + let after = glyph_pens(&s, id); + assert!( + near(moved_by(&before, &after, start), (expected.x, expected.y)), + "{case}: {:?}, expected {expected:?}", + moved_by(&before, &after, start) + ); + for byte in [0, 2, 4].into_iter().filter(|byte| *byte != start) { + assert!(near(moved_by(&before, &after, byte), (0.0, 0.0)), "{case}, neighbor {byte}: {:?}", moved_by(&before, &after, byte)); + } + let changed = obj(&s, id); + let reopened: TextObject = serde_json::from_value(serde_json::to_value(&changed).unwrap()).unwrap(); + assert_eq!( + serde_json::to_value(&changed).unwrap(), + serde_json::to_value(&reopened).unwrap(), + "{case}: stored attributes round trip" + ); + let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &reopened); + for g in &layout.glyphs { + let expected = after.iter().find(|(byte, _)| *byte == g.byte).unwrap().1; + assert!( + (reopened.xf * (g.xf * Point::ZERO) - expected).hypot() < 1e-6, + "{case}: reopened character {} keeps its place", + g.byte + ); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(obj(&s, id), original, "{case}: Undo restores every attribute"); + } + } + } + } +} + +#[test] +fn touch_type_optical_spacing_does_not_shorten_a_baseline_nudge() { + let mut s = session(); + let r = s.execute("text.create", &json!({"x": 300, "y": 250, "text": "AVA", "size": 100, "font": "Source Sans 3"})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": "optical"})).unwrap(); + let before = glyph_pens(&s, id); + s.execute("text.touchType", &json!({"id": id.0, "start": 1, "dy": 3})).unwrap(); + let after = glyph_pens(&s, id); + assert!(near(moved_by(&before, &after, 1), (0.0, -3.0)), "{:?}", moved_by(&before, &after, 1)); + for byte in [0, 2] { + assert!(near(moved_by(&before, &after, byte), (0.0, 0.0)), "neighbor {byte}: {:?}", moved_by(&before, &after, byte)); + } +} + #[test] fn automatic_alignment_updates_during_edits_and_can_be_overridden() { let mut s = session(); diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index d1224e05da..3e522a5529 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -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(); diff --git a/crates/engine/src/tests/typescale.rs b/crates/engine/src/tests/typescale.rs index bdfb27f2f9..5bc09827b9 100644 --- a/crates/engine/src/tests/typescale.rs +++ b/crates/engine/src/tests/typescale.rs @@ -271,6 +271,30 @@ fn a_file_with_type_sizes_out_of_range_opens_with_them_in_range() { assert!(b.width().is_finite() && b.height().is_finite(), "{b:?}"); } +/// A file whose character styles hold a Tate-chu-yoko Up/Down or Left/Right offset past +/// `MAX_COORD` either way opens with the nearer end, and text that takes the style gets it. An +/// offset within range stays as saved. +#[test] +fn a_file_with_tate_chu_yoko_offsets_out_of_range_in_a_character_style_opens_with_them_in_range() { + let mut s = session(); + let id = NodeId(s.execute("text.create", &json!({"x": 40, "y": 60, "size": 20, "text": "12"})).unwrap()["id"].as_u64().unwrap()); + let mut d = (*s.doc().unwrap().doc).clone(); + let attrs = json!({"tateChuYoko": true, "tcyUpDown": 1e12, "tcyLeftRight": -1e12}); + d.char_styles.push(vectorcraft_doc::TextStyleDef { name: "Far".into(), attrs: attrs.as_object().unwrap().clone() }); + let attrs = json!({"tcyUpDown": 5000, "tcyLeftRight": -3.5}); + d.char_styles.push(vectorcraft_doc::TextStyleDef { name: "Near".into(), attrs: attrs.as_object().unwrap().clone() }); + let data = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d)); + s.execute("document.open", &json!({"name": "tcy.vectorcraft", "dataBase64": data})).unwrap(); + let max = vectorcraft_doc::MAX_COORD; + let doc = &s.doc().unwrap().doc; + let fixed = json!({"tateChuYoko": true, "tcyUpDown": max, "tcyLeftRight": -max}); + assert_eq!(doc.char_styles[0].attrs, *fixed.as_object().unwrap()); + assert_eq!(doc.char_styles[1].attrs, *json!({"tcyUpDown": 5000, "tcyLeftRight": -3.5}).as_object().unwrap()); + s.execute("charStyle.apply", &json!({"name": "Far", "id": id.0})).unwrap(); + let t = text(&s, id); + assert_eq!(t.runs.iter().map(|r| (r.style.tcy_up_down, r.style.tcy_left_right)).collect::>(), [(max, -max)]); +} + /// SVG import keeps type sizes outside the Character panel's 0.1 to 1296 pt, and it gives a line /// aligned differently from the one before it an indent, here past the Paragraph panel's 1296 pt. /// A native file of the result opens with the same type. diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 493871de2a..e6ef5e69dd 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -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 = (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::>(); + 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(); diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index eb503cce98..5dfd7ca09b 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -976,6 +976,27 @@ fn lasso_selects_anchor_subset() { assert_eq!(st.selection.partial(a).map(|p| p.len()), Some(2)); } +/// #5351: a Lasso loop round a gradient mesh's points keeps the mesh selected and picks the +/// points inside it, so a solid fill colour recolours just those points. +#[test] +fn lasso_picks_gradient_mesh_points() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.mesh.create", &json!({"rows": 2, "cols": 2})).unwrap(); + // Round the top row of points (100,100), (150,100) and (200,100). + gesture(&mut s, "lasso", &[(90.0, 90.0), (210.0, 90.0), (210.0, 110.0), (90.0, 110.0), (90.0, 110.0)], Mods::default()); + let st = s.doc().unwrap(); + let Some(NodeKind::Mesh(m)) = st.doc.node(a).map(|n| &n.kind) else { panic!("still a gradient mesh") }; + assert_eq!(m.points.len(), 9); + assert_eq!(st.selection.objects, vec![a], "the mesh stays selected"); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let Some(NodeKind::Mesh(m)) = s.doc().unwrap().doc.node(a).map(|n| &n.kind) else { panic!("still a gradient mesh") }; + let red: Vec = (0..m.points.len()).filter(|i| m.points[*i].color.to_hex() == "#ff0000").collect(); + let top: Vec = (0..3).map(|c| m.idx(0, c)).collect(); + assert_eq!(red, top, "only the points inside the loop are recoloured"); +} + /// Shift-drag a marquee with the Selection tool (#483): the selected objects it reaches are /// deselected and the others selected, the rest of the selection staying as it was. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index efaef7d642..4eb1912294 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -65,6 +65,13 @@ fn rgb(hex: &str, fallback: [u8; 3]) -> [u8; 3] { }) } +/// Whether a tool preview of `cmd` with params `p` sets only a symbol's 9-slice guides: a +/// `symbol.options` whose params hold `nineSliceGuides` and nothing besides `name`. +fn nine_slice_guide_preview(cmd: &str, p: &Value) -> bool { + cmd == "symbol.options" + && p.as_object().is_some_and(|m| m.contains_key("nineSliceGuides") && m.keys().all(|k| k == "name" || k == "nineSliceGuides")) +} + /// Requests from tools that only the frontend can fulfil. #[derive(Clone, Debug, PartialEq)] pub enum UiRequest { @@ -328,6 +335,7 @@ impl Session { screen: view.screen, plane_widget: self.prefs.perspective_widget.show.then_some(self.prefs.perspective_widget.position), precise_cursors: self.precise_cursors(), + global_edit: st.global_edit.as_ref().map_or(&[], |g| g.members.as_slice()), }; let tool = &mut self.tool; match crate::guard::catch_panic(|| f(tool.as_mut(), &cx)) { @@ -350,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> { + 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 { + 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> { 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)?; } @@ -650,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> { + 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() } @@ -665,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) -> 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())); @@ -784,8 +872,9 @@ impl Session { Action::Preview(cmd, p) => { // Performance › Real-time Drawing and Editing (#394): off, remember the latest // params and apply them once on Commit instead of every move. A ruler guide - // being dragged still shows: the guide is all there is to see (#4646). - if !self.prefs.real_time_drawing && !matches!(cmd.as_str(), "guide.add" | "guide.move") { + // being dragged still shows: the guide is all there is to see (#4646). So does a + // symbol's 9-slice guide being dragged. + if !self.prefs.real_time_drawing && !matches!(cmd.as_str(), "guide.add" | "guide.move") && !nine_slice_guide_preview(&cmd, &p) { self.clear_deferred_overlay_cache(); let st = self.doc_mut()?; if let Some(it) = &mut st.interaction { @@ -833,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. diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 884d9f21b6..45f6b47680 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -653,6 +653,12 @@ fn structured_junk() { ("addon.pen.reshape", json!({"id": 2, "segment": 0, "t": "x", "dx": 1, "dy": 1, "mode": "symmetric"})), ("addon.pen.nextSegment", json!({"curved": "yes"})), ("addon.pen.closeJoin", json!({"ids": [u64::MAX]})), + // Type Tools add-on. + ("addon.type.textTweaker", json!({"attribute": "size", "from": 1296, "to": 0.1, "shape": "random", "seed": u64::MAX})), + ("addon.type.textTweaker", json!({"attribute": "tracking", "from": f64::MAX, "to": -1e308, "shape": "spike"})), + ("addon.type.textTweaker", json!({"attribute": "rotation", "from": -360, "to": 360, "shape": "bow", "skipSpaces": false, "ids": [u64::MAX]})), + ("addon.type.textTweaker", json!({"attribute": "hScale", "id": 2, "start": u64::MAX, "end": 0, "shape": "ease"})), + ("addon.type.textTweaker", json!({"attribute": ["size"], "from": "x", "seed": 1e308, "skipSpaces": "no", "ids": "all"})), ("addon.cleanup.breakText", json!({"by": "glyphs", "ids": [0, 1, 2, 3, 4, 5, 6, 7, 8, u64::MAX]})), ("addon.cleanup.breakText", json!({"by": ["lines"]})), ("addon.cleanup.breakText", json!({"by": "paragraphs"})), diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index bd9069bd20..095d0ec146 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -648,6 +648,8 @@ proptest! { survive(&svg, || vectorcraft_svg::import(&svg).ok())?; } + /// The linked `` gets an id from the importer, so attribute selectors in `sheet` reach the + /// pass that copies style sheet matches into the elements' styles. #[test] fn svg_hostile_css_never_panics( sheet in r#"[a-z#.>*\[\]=:;{}@ !"'/,-]{0,160}"#, @@ -655,7 +657,7 @@ proptest! { body in prop::collection::vec(arb_svg_element(1), 0..3), ) { let svg = format!( - "abc{}", + "abc{}", body.concat() ); survive(&svg, || vectorcraft_svg::import(&svg).ok())?; @@ -3601,6 +3603,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 { @@ -3906,6 +3942,10 @@ fn arb_ai_token() -> impl Strategy { "(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 +4156,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::(), + 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::().is_ok_and(|c| c == 0.0); + let check = |d: Option| { + 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 diff --git a/crates/eps/src/import/ai/legacy_text.rs b/crates/eps/src/import/ai/legacy_text.rs index 3c0d4cf43f..17590b3203 100644 --- a/crates/eps/src/import/ai/legacy_text.rs +++ b/crates/eps/src/import/ai/legacy_text.rs @@ -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() }); } diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 2dfee6f2c4..93cc0af6b3 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -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, /// The tile (y down) of each pattern read, by name. pattern_tiles: HashMap, + /// 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, /// The legacy text object being read (`To` … `TO`), and the modal type attributes. text: Option, 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, diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index be4f6214c8..ed838b51b6 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -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, +} + +/// `(colors) @ (tile) &`, or `(colors) @ _ &` (no tile: the tile's box is filled with the colors' fill). +struct LegacyLayer { + color: Vec, + tile: Option>, +} + +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>, ()> { + 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; diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index ee82175a6f..f38ec76239 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -661,11 +661,15 @@ impl<'a> Reader<'a> { // of a default swatch of that name when the file has no palette of its own (a reserved name // in brackets, such as `[None]`, keeps its swatch). let mut defined = std::collections::HashSet::new(); + // The swatch names there are, looked up rather than scanned for each name a file defines + // (`Document::swatch` also knows the registration colour). + let mut have: std::collections::HashSet = doc.swatches_iter().map(|s| s.name.clone()).collect(); + have.insert(vectorcraft_color::swatch::REGISTRATION.to_string()); let colors = self.spots.iter().chain(&self.stop_spots).map(|n| (n, n.spot)).chain(self.custom_colors.iter().map(|n| (n, true))); for (n, spot) in colors { let first = defined.insert(n.name.clone()); let swatch = Swatch { name: n.name.clone(), paint: Paint::solid(n.color), global: true, spot }; - if doc.swatch(&n.name).is_none() { + if have.insert(n.name.clone()) { doc.swatches.push(swatch); } else if first && !own_palette @@ -679,7 +683,7 @@ impl<'a> Reader<'a> { doc.metadata.author = author; } for name in doc.patterns.iter().map(|p| p.name.clone()).collect::>() { - if doc.swatch(&name).is_none() { + if have.insert(name.clone()) { doc.swatches.push(Swatch { paint: Paint::Pattern { pattern: name.clone(), xf: Affine::IDENTITY }, name, global: false, spot: false }); } } diff --git a/crates/eps/src/import/ai/read/on_path.rs b/crates/eps/src/import/ai/read/on_path.rs index 4fe14e8545..1e33e09a1b 100644 --- a/crates/eps/src/import/ai/read/on_path.rs +++ b/crates/eps/src/import/ai/read/on_path.rs @@ -182,7 +182,7 @@ fn apply_one(doc: &mut Document, found: &OnPath, at: &HashMap 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(()) } diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 88f1325686..e8ff52f6c7 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -82,6 +82,14 @@ impl<'a> Reader<'a> { // highlight `-- -- angle length Bh`): a NaN keeps the other operands where they are. "--" => return self.push(V::Num(f64::NAN)), "[" => { + // Drop marks that operators have taken off, so `marks` is the open nesting. + while self.marks.last().is_some_and(|&m| !matches!(self.stack.get(m), Some(V::Mark))) { + self.marks.pop(); + } + // Arrays nest as deep as their `[`s; dropping a deeper one would overflow the stack. + if self.marks.len() >= MAX_DEPTH { + return Err("its objects are nested too deeply".into()); + } self.marks.push(self.stack.len()); return self.push(V::Mark); } @@ -402,7 +410,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 +422,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 = + 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 +614,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 +715,33 @@ fn pattern_xf(space: Affine, matrix: Option, tile: Rect) -> Option= 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 { + 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, patterns: &'a HashMap, + v7_patterns: &'a HashSet, space: Affine, } @@ -740,7 +784,8 @@ fn placed_paints(look: &Node, out: &mut HashMap, 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 { 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 +793,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 +825,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 })) } }, diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index 0437145185..e1947bfdaf 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -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, 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, }, Stroke { paint: Paint, @@ -185,6 +213,8 @@ struct Filter { params: HashMap, /// How each key of its dictionary is written. kinds: HashMap, + /// A key of its dictionary is written more than once. + repeated: bool, /// Its dictionary's arrays (`/Array : v /Real , … ; (key) ,`), by key. arrays: HashMap>, fill: Option, @@ -199,8 +229,8 @@ struct Filter { gradient: bool, /// The gradient's swatch and angle (`Bg`). gradient_of: Option<(Option, 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)>, /// `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 { } 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 { 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 { 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 = + 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 { // 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 { + 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, ()> { 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 } diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index 444f5c4fd9..2815f589c5 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -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::()), + ("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. diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 13316561d3..52248aa1b7 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -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}; @@ -54,6 +54,14 @@ fn ruler_units_from_the_header_set_the_documents_units() { assert_eq!(read(with_px.as_bytes()).unwrap().doc.units, Unit::Pixels); } +#[test] +fn arrays_nested_past_the_depth_limit_are_refused() { + let deep = |n: usize| layer(&format!("{}{} pop", "[".repeat(n), "]".repeat(n))); + let nested = |n: usize| read(stream(&deep(n)).as_bytes()).err().is_some_and(|e| e.contains("nested too deeply")); + assert!(!nested(200)); + assert!(nested(100_000)); +} + /// The children of the first layer. fn art(doc: &Document) -> Vec> { doc.layers.first().and_then(|l| l.children()).cloned().unwrap_or_default() @@ -525,7 +533,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 +573,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::>()); + // 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::>()); +} + +/// 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 +3256,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. diff --git a/crates/eps/src/import/data/filters.rs b/crates/eps/src/import/data/filters.rs index d049e39a9d..e3268b240a 100644 --- a/crates/eps/src/import/data/filters.rs +++ b/crates/eps/src/import/data/filters.rs @@ -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), + /// 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, + from: Option>>, + }, Buf { data: Vec, pos: usize, diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index 3b4046de91..c5c588557c 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -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>) -> Res<(Option, 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>, n: usize) -> Res> { 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>) -> Res>> { - 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>) -> Res> { 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>) -> 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>) -> Res { + let (chain, from) = match &*f.borrow() { + Stream::Pending { chain, from } => (chain.clone(), from.clone()), _ => return Ok(()), }; let mut buf: Option<(Vec, Option)> = 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) } diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index 12232624f8..f4c210b9cd 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -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>>, pub stack: Vec, pub dicts: Vec, 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`, ). + 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`, ), + /// 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>) -> 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()))?; @@ -1135,9 +1172,12 @@ impl<'a> Interp<'a> { PdfMark => { self.pop_to_mark()?; } + // True for a simple object, and for a composite one in global VM (PLRM 3rd ed., `gcheck`); + // every composite here is in local VM. Procsets that copy values into global VM leave + // alone those whose `gcheck` is true, such as a halftone's numbers. Gcheck | Scheck => { - self.pop()?; - self.push(Obj::Bool(false))?; + let simple = !self.pop()?.is_composite(); + self.push(Obj::Bool(simple))?; } CurrentShared => self.push(Obj::Bool(false))?, SetShared | SetVmThreshold | VmReclaim | Echo => { @@ -1409,6 +1449,17 @@ fn index(k: &Obj) -> Res { } } +/// `known`: a key may be any object but null (PLRM 3rd ed., §3.3.9, ), +/// 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 { + 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) { diff --git a/crates/eps/src/import/obj.rs b/crates/eps/src/import/obj.rs index b4dc34364a..4f07678a71 100644 --- a/crates/eps/src/import/obj.rs +++ b/crates/eps/src/import/obj.rs @@ -286,6 +286,11 @@ impl Obj { Self::GState(_) => "gstatetype", } } + + /// A composite object, whose value lives in VM; the others are simple (PLRM 3rd ed., §3.3.1). + pub fn is_composite(&self) -> bool { + matches!(self, Self::Str(_) | Self::ExecStr(_) | Self::Array { .. } | Self::Dict(_) | Self::File { .. } | Self::Save(_) | Self::GState(_)) + } } /// The values of a string or an array: a run of storage that other strings or arrays may share diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index aa97f32cb5..52c098bb05 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -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`, ). +/// 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, ), +/// 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"); diff --git a/crates/eps/src/import/tests_generators.rs b/crates/eps/src/import/tests_generators.rs index 2fe6ba324c..4337b9474c 100644 --- a/crates/eps/src/import/tests_generators.rs +++ b/crates/eps/src/import/tests_generators.rs @@ -592,6 +592,21 @@ showpage"##; assert!(near(bounds(&meshes[1]), Rect::new(150.0, 90.0, 190.0, 140.0)), "{:?}", bounds(&meshes[1])); } +/// Ghostscript 9's `eps2write` copies the initial graphics state (`currenthalftone`, +/// `currentcolortransfer`) into global VM before it draws, with a copier for each composite type. +/// It copies only what `gcheck` says is in local VM: `gcheck` is true for every simple object +/// (PLRM 3rd ed., `gcheck`), so the halftone's numbers stay as they are. Written from the PLRM. +#[test] +fn gcheck_is_true_for_simple_objects() { + super::tests::check("1 gcheck 2.5 gcheck and /n gcheck and true gcheck and null gcheck and /add load gcheck and mark gcheck and"); + super::tests::check("(s) gcheck not 1 dict gcheck not and {} gcheck not and 1 scheck and (s) scheck not and"); + super::tests::check( + "/copiers << /dicttype { << exch { cp2g } forall >> } /arraytype { [ exch { cp2g } forall ] } >> def \ + /cp2g { dup gcheck not { copiers 1 index type get exec } if } bind def \ + currenthalftone cp2g /Frequency get 60 eq [ currentcolortransfer ] cp2g length 4 eq and", + ); +} + /// A procset written as the PostScript Language Reference (3rd ed.) describes the Level 2 and 3 /// facilities programs probe before drawing: a resource category made from `Generic` and /// resources defined and found in it (§3.9), local and global VM (`currentglobal`, `setglobal`, diff --git a/crates/eps/src/import/tests_illustrator.rs b/crates/eps/src/import/tests_illustrator.rs index 9d748f459f..d4ae4db83e 100644 --- a/crates/eps/src/import/tests_illustrator.rs +++ b/crates/eps/src/import/tests_illustrator.rs @@ -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 { diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 199a6ed7ab..1600742300 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -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`, ): 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. diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 29a45ae195..daeea4826a 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -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::>(), ["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 { diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index f79b0bd370..c208f1b524 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -288,7 +288,13 @@ fn keep_acl(target: &Path, tmp: &Path) -> bool { let mut buf = vec![0u8; 64 << 10]; match rustix::fs::getxattr(target, ACL, &mut buf[..]) { Ok(n) => buf.get(..n).is_some_and(|acl| rustix::fs::setxattr(tmp, ACL, acl, rustix::fs::XattrFlags::empty()).is_ok()), - Err(e) => e == Errno::NODATA || e == Errno::NOTSUP, + // None to keep: drop the one `tmp` may have inherited from the folder's default ACL, which + // the old file's group bits (its mask) would otherwise open to the people it names. + Err(e) if e == Errno::NODATA => match rustix::fs::removexattr(tmp, ACL) { + Ok(()) => true, + Err(e) => e == Errno::NODATA || e == Errno::NOTSUP, + }, + Err(e) => e == Errno::NOTSUP, } } @@ -313,6 +319,24 @@ mod tests { d } + /// A replaced file that had no access ACL gets none from the folder's default ACL, whose named + /// users the old file's group bits would let in. (Skipped where `setfacl` or ACLs are missing.) + #[cfg(target_os = "linux")] + #[test] + fn a_replacement_takes_no_inherited_acl_the_old_file_lacked() { + let d = dir("acl"); + let f = d.join("doc.vectorcraft"); + std::fs::write(&f, b"old").unwrap(); + let set = std::process::Command::new("setfacl").args(["-d", "-m", "u:nobody:rw"]).arg(&d).status(); + if !set.is_ok_and(|s| s.success()) { + return; + } + write_atomic(&f, b"new").unwrap(); + let mut buf = vec![0u8; 4096]; + assert_eq!(rustix::fs::getxattr(&f, "system.posix_acl_access", &mut buf[..]), Err(rustix::io::Errno::NODATA)); + let _ = std::fs::remove_dir_all(&d); + } + /// The other files in `d` besides `keep`. fn leftovers(d: &Path, keep: &str) -> Vec { std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect() diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 6eb2e2bd35..57a5cfc952 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -139,11 +139,26 @@ pub struct SaveOptions { pub profiles: BTreeMap>, /// Create PDF-Compatible File: a PDF of the document to carry. pub pdf: Option>, + /// Decimal places to round path anchors and handles to ([`Document::round_geometry`]), at + /// most [`MAX_PRECISION`] (a larger value rounds to that many); `None` writes them exactly. + pub precision: Option, } +/// The most decimal places [`SaveOptions::precision`] rounds path geometry to. +pub const MAX_PRECISION: u8 = 9; + impl Default for SaveOptions { fn default() -> Self { - Self { pretty: false, compress: false, version: VERSION, preview: None, include_linked: false, profiles: BTreeMap::new(), pdf: None } + Self { + pretty: false, + compress: false, + version: VERSION, + preview: None, + include_linked: false, + profiles: BTreeMap::new(), + pdf: None, + precision: None, + } } } @@ -206,7 +221,8 @@ struct Body { } /// `doc` as [`save_to`] writes it with `o`: without editing-mode working copies, with placed -/// documents as their art for older versions, and its images taken out. +/// documents as their art for older versions, path geometry rounded to `o.precision`, and its +/// images taken out. fn body(doc: &Document, o: &SaveOptions) -> Result { let version = o.version; let mut d = doc.without_edit_modes().into_owned(); @@ -218,6 +234,10 @@ fn body(doc: &Document, o: &SaveOptions) -> Result { } else { d.drop_placed_resources(); } + // The art placed documents became for older versions is rounded too. + if let Some(decimals) = o.precision { + d.round_geometry(decimals.min(MAX_PRECISION)); + } let linked = d.linked_only_images(); // The blobs go in the file's `images` (only those the document uses). let blobs = std::mem::take(&mut d.images); diff --git a/crates/format/tests/it/save_options.rs b/crates/format/tests/it/save_options.rs index c9a82839c2..3cd163ed15 100644 --- a/crates/format/tests/it/save_options.rs +++ b/crates/format/tests/it/save_options.rs @@ -5,10 +5,15 @@ use std::sync::Arc; use serde_json::Value; +use vectorcraft_doc::color::{Color, Paint}; use vectorcraft_doc::links::LinkInfo; -use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind, Symbol}; -use vectorcraft_format::{ICC_MIME, PRETTY_MAX_BYTES, PRETTY_MAX_OBJECTS, SaveOptions, load, load_file, pdf_content, save_file, save_with}; -use vectorcraft_geom::path::{PathData, SubPath}; +use vectorcraft_doc::{ + Appearance, BlendSpec, Document, EnvelopeKind, ImageBlob, ImageObject, LiveShape, MAX_COORD, Node, NodeKind, OpacityMask, Symbol, +}; +use vectorcraft_format::{ + ICC_MIME, MAX_PRECISION, PRETTY_MAX_BYTES, PRETTY_MAX_OBJECTS, SaveOptions, load, load_file, pdf_content, save_file, save_with, +}; +use vectorcraft_geom::path::{Anchor, PathData, SubPath}; use vectorcraft_geom::{Affine, Point}; use vectorcraft_testkit::fixtures::DocBuilder; @@ -206,3 +211,204 @@ fn art_outside_the_layers_counts_too() { assert!(!is_pretty(&bytes)); assert_eq!(load(&bytes).unwrap().symbols.len(), 1); } + +/// One path at `x, y`, its out handle at `x + 6.1234567, y - 0.00001` (`-0.0` at 4 decimals when +/// `y` is 0), filled with a color whose components have many digits. +fn precise_path(d: &mut Document, x: f64, y: f64) -> Node { + let p = Point::new(x, y); + let a = Anchor { p, h_in: p, h_out: Point::new(x + 6.1234567, y - 0.00001), kind: Default::default() }; + let sp = SubPath::new(vec![a, Anchor::corner(Point::new(x + 20.0, y))], false); + let fill = Paint::solid(Color::rgb(0.02745098, 0.33333334, 0.9019608)); + Node::path(d.alloc_id(), PathData::single(sp), Appearance::basic(fill, Paint::None, 0.0)) +} + +/// A document with a precise path in the layer, in an opacity mask, in a symbol (placed with a +/// precise transform) and in a brush kept as foreign data. +fn precise_doc() -> Document { + let mut d = Document::new(100.0, 100.0); + let layer = d.layers[0].id; + let mut n = precise_path(&mut d, 3.4876474632797176, 3.499999999999999); + n.extras_mut().mask = Some(Box::new(OpacityMask::new(precise_path(&mut d, 7.77777777, 1.0), false))); + d.insert(Some(layer), 0, n).unwrap(); + let art = precise_path(&mut d, 1.23456789, 0.0); + d.symbols.push(Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); + let xf = Affine::new([1.0, 0.0, 0.0, 1.0, 0.123456789, 0.0]); + let id = d.alloc_id(); + d.insert(Some(layer), 1, Node::new(id, NodeKind::SymbolInstance { symbol: "S".into(), xf })).unwrap(); + let brush = serde_json::to_value(precise_path(&mut d, 5.55555555, 4.0)).unwrap(); + d.unknown.insert("brushes".into(), serde_json::json!([{"name": "B", "type": "art", "art": brush}])); + d +} + +fn first_anchor(n: &Node) -> Anchor { + let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path: {n:?}") }; + path.subpaths[0].anchors[0] +} + +#[test] +fn precision_rounds_path_anchors_and_handles_only() { + let d = precise_doc(); + let bytes = save_with(&d, &SaveOptions { precision: Some(4), ..SaveOptions::default() }).unwrap(); + let text = String::from_utf8(bytes.clone()).unwrap(); + assert!(!text.contains("-0.0"), "a handle rounded to zero is written as 0.0"); + let back = load(&bytes).unwrap(); + let path = &back.layers[0].children().unwrap()[0]; + let a = first_anchor(path); + assert_eq!((a.p, a.h_in, a.h_out), (Point::new(3.4876, 3.5), Point::new(3.4876, 3.5), Point::new(9.6111, 3.5))); + let mask = path.extras().mask.as_ref().unwrap(); + assert_eq!(first_anchor(&mask.art).p, Point::new(7.7778, 1.0)); + let a = first_anchor(&back.symbols[0].art); + assert_eq!((a.p, a.h_out), (Point::new(1.2346, 0.0), Point::new(7.358, 0.0))); + let brush = &back.unknown["brushes"][0]["art"]["kind"]["path"]["subpaths"][0]["anchors"][0]; + assert_eq!((brush["p"][0].as_f64(), brush["out"][0].as_f64()), (Some(5.5556), Some(11.679))); + // Colors and transforms keep every digit. + let original = &d.layers[0].children().unwrap()[0]; + assert_eq!(path.appearance, original.appearance); + assert_eq!(mask.art.appearance, original.extras().mask.as_ref().unwrap().art.appearance); + let NodeKind::SymbolInstance { xf, .. } = &back.layers[0].children().unwrap()[1].kind else { panic!("not an instance") }; + assert_eq!(xf.as_coeffs()[4], 0.123456789); + // The document saved is left as it was. + assert_eq!(first_anchor(&d.layers[0].children().unwrap()[0]).p.x, 3.4876474632797176); +} + +#[test] +fn precision_rounds_the_paths_objects_keep_besides_their_own() { + let mut d = Document::new(100.0, 100.0); + let layer = d.layers[0].id; + let path = || PathData::single(SubPath::polyline(&[Point::new(1.23456789, 0.0), Point::new(9.87654321, 5.0)], false)); + // Live Corners' uncut outline, and Intertwine areas of tiers 1 and 2. + let mut n = precise_path(&mut d, 1.0, 1.0); + if let NodeKind::Path { live, .. } = &mut n.kind { + *live = Some(Box::new(LiveShape::Path { base: path(), radii: vec![2.0], kinds: vec![], radii_relative: false })); + } + n.extras_mut().intertwine = Some(Box::new(path())); + n.extras_mut().intertwine_tiers = vec![path()]; + d.insert(Some(layer), 0, n).unwrap(); + // A blend's replaced spine and an envelope's top-object outline. + let keys = vec![Arc::new(precise_path(&mut d, 1.0, 1.0)), Arc::new(precise_path(&mut d, 50.0, 1.0))]; + let blend = BlendSpec { spine: Some(path()), ..BlendSpec::default() }; + let id = d.alloc_id(); + d.insert(Some(layer), 1, Node::new(id, NodeKind::Blend { children: keys, spec: Box::new(blend) })).unwrap(); + let envelope = NodeKind::Envelope { + content: vec![Arc::new(precise_path(&mut d, 1.0, 1.0))], + kind: Box::new(EnvelopeKind::TopObject { path: path() }), + fidelity: 50.0, + editing: false, + options: Default::default(), + frame: Default::default(), + }; + let id = d.alloc_id(); + d.insert(Some(layer), 2, Node::new(id, envelope)).unwrap(); + // The same three objects as brushes' art, and type, whose frame stays exact. + let mut brushes: Vec = d.layers[0].children().unwrap().iter().map(|n| serde_json::json!({"art": n})).collect(); + let frame = serde_json::json!({"subpaths": [{"anchors": [{"p": [1.23456789, 0.0]}], "closed": true}]}); + brushes.push(serde_json::json!({"art": {"id": 99, "kind": {"type": "text", "kind": "area", "frame": frame}}})); + d.unknown.insert("brushes".into(), Value::Array(brushes)); + let text = |precision| String::from_utf8(save_with(&d, &SaveOptions { precision, ..SaveOptions::default() }).unwrap()).unwrap(); + let exact = text(None); + assert_eq!((exact.matches("1.23456789").count(), exact.matches("9.87654321").count()), (11, 10), "{exact}"); + let rounded = text(Some(4)); + assert_eq!((rounded.matches("1.23456789").count(), rounded.matches("9.87654321").count()), (1, 0), "{rounded}"); + assert_eq!((rounded.matches("1.2346").count(), rounded.matches("9.8765").count()), (10, 10), "{rounded}"); +} + +#[test] +fn without_precision_coordinates_are_written_exactly() { + let d = precise_doc(); + let exact = save_with(&d, &SaveOptions::default()).unwrap(); + let text = String::from_utf8(exact.clone()).unwrap(); + for x in ["3.4876474632797176", "3.499999999999999", "7.77777777", "1.23456789", "5.55555555"] { + assert!(text.contains(x), "{x}"); + } + assert_eq!(first_anchor(&load(&exact).unwrap().layers[0].children().unwrap()[0]).p.x, 3.4876474632797176); + // A precision over MAX_PRECISION rounds to MAX_PRECISION decimals. + let at = |p| save_with(&d, &SaveOptions { precision: Some(p), ..SaveOptions::default() }).unwrap(); + assert_eq!(at(200), at(MAX_PRECISION)); + assert!(at(0).len() < at(MAX_PRECISION).len()); +} + +/// A document holding one path through `points`. +fn doc_with_path(points: &[Point], closed: bool) -> Document { + let mut d = Document::new(100.0, 100.0); + let layer = d.layers[0].id; + let id = d.alloc_id(); + let path = PathData::single(SubPath::polyline(points, closed)); + d.insert(Some(layer), 0, Node::path(id, path, Appearance::basic(Paint::None, Paint::None, 0.0))).unwrap(); + d +} + +/// The first subpath of the first object of `d` saved at `precision` and opened again. +fn saved_subpath(d: &Document, precision: Option) -> SubPath { + let back = load(&save_with(d, &SaveOptions { precision, ..SaveOptions::default() }).unwrap()).unwrap(); + let NodeKind::Path { path, .. } = &back.layers[0].children().unwrap()[0].kind else { panic!("not a path") }; + path.subpaths[0].clone() +} + +#[test] +fn without_precision_every_coordinate_reopens_bit_for_bit() { + // 500 anchors at coordinates of every size and sign (a fixed pseudo-random sequence). + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = || { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + let unit = (seed >> 11) as f64 / (1u64 << 53) as f64 - 0.5; + unit * 10f64.powi((seed % 13) as i32 - 6) + }; + let mut points: Vec = (0..500).map(|_| Point::new(next(), next())).collect(); + points.extend([Point::new(MAX_COORD, -1e-300), Point::new(f64::MIN_POSITIVE, -3_999_999.123_456_789)]); + let d = doc_with_path(&points, false); + let bytes = save_with(&d, &SaveOptions::default()).unwrap(); + let got: Vec = saved_subpath(&d, None).anchors.iter().map(|a| a.p).collect(); + let bits = |ps: &[Point]| ps.iter().map(|p| (p.x.to_bits(), p.y.to_bits())).collect::>(); + assert_eq!(bits(&got), bits(&points)); + // Saving the reopened file writes the same bytes. + assert_eq!(save_with(&load(&bytes).unwrap(), &SaveOptions::default()).unwrap(), bytes); +} + +#[test] +fn precision_rounds_halves_away_from_zero() { + // These halves are exact in binary, so the scaled value is exactly .5. + let d = doc_with_path(&[Point::new(0.125, -0.125), Point::new(0.375, -0.375), Point::new(1.5, -2.5)], false); + let at = |p| saved_subpath(&d, Some(p)).anchors.iter().map(|a| a.p).collect::>(); + assert_eq!(at(2), [Point::new(0.13, -0.13), Point::new(0.38, -0.38), Point::new(1.5, -2.5)]); + assert_eq!(at(0), [Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(2.0, -3.0)]); + // `1.005` is stored as slightly less than the decimal, so it goes down. + let d = doc_with_path(&[Point::new(1.005, -1.005)], false); + assert_eq!(saved_subpath(&d, Some(2)).anchors[0].p, Point::new(1.0, -1.0)); +} + +#[test] +fn a_rounded_closed_path_stays_closed_on_its_first_anchor() { + let first = Point::new(10.123456, 20.987654); + let d = doc_with_path(&[first, Point::new(50.55555, 20.4444), Point::new(30.01, 60.996), first], true); + let sp = saved_subpath(&d, Some(2)); + assert!(sp.closed); + assert_eq!(sp.anchors.len(), 4); + assert_eq!(sp.anchors[0].p, Point::new(10.12, 20.99)); + assert_eq!(sp.anchors[3].p, sp.anchors[0].p); +} + +#[test] +fn a_shape_smaller_than_the_precision_keeps_its_anchors_on_one_point() { + let d = doc_with_path(&[Point::new(5.0001, 5.0001), Point::new(5.0004, 5.0001), Point::new(5.0002, 5.0004)], true); + let sp = saved_subpath(&d, Some(3)); + assert!(sp.closed); + assert_eq!(sp.anchors.iter().map(|a| a.p).collect::>(), [Point::new(5.0, 5.0); 3]); +} + +#[test] +fn precision_rounds_coordinates_at_the_edge_of_the_canvas() { + let points = [Point::new(3_999_999.123_456_789, -3_999_999.987_654_321), Point::new(MAX_COORD, -MAX_COORD)]; + let d = doc_with_path(&points, false); + let at = |p| saved_subpath(&d, Some(p)).anchors.iter().map(|a| a.p).collect::>(); + assert_eq!(at(3), [Point::new(3_999_999.123, -3_999_999.988), points[1]]); + for (got, want) in at(MAX_PRECISION).iter().zip(&points) { + assert!((got.x - want.x).abs() <= 1e-9 && (got.y - want.y).abs() <= 1e-9, "{got:?} vs {want:?}"); + } +} + +#[test] +fn saving_a_rounded_file_at_the_same_precision_again_writes_the_same_bytes() { + let o = SaveOptions { precision: Some(2), ..SaveOptions::default() }; + let once = save_with(&precise_doc(), &o).unwrap(); + assert_eq!(save_with(&load(&once).unwrap(), &o).unwrap(), once); +} diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 4455c4ed9a..d836d2e021 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -278,7 +278,7 @@ impl SubPath { } let mut pos = vec![0.0]; for i in 0..self.segment_count() { - let len = kurbo::ParamCurveArclen::arclen(&self.segment(i), 1e-3); + let len = measured_arclen(&PathSeg::Cubic(self.segment(i)), 1e-3); pos.push(pos.last().copied().unwrap_or(0.0) + len); } pos @@ -621,7 +621,7 @@ const MEASURE_LIMIT: f64 = 1e9; /// The length of `seg` to `accuracy`; 0 for a segment whose control points are not finite or past /// [`MEASURE_LIMIT`]. -pub(crate) fn measured_arclen(seg: &PathSeg, accuracy: f64) -> f64 { +pub fn measured_arclen(seg: &PathSeg, accuracy: f64) -> f64 { let ok = |p: Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= MEASURE_LIMIT && p.y.abs() <= MEASURE_LIMIT; let fits = match seg { PathSeg::Line(l) => ok(l.p0) && ok(l.p1), @@ -838,6 +838,13 @@ mod tests { assert_eq!(c.kind, AnchorKind::Corner); } + /// Handles too large to measure give the curve no length instead of subdividing it without end. + #[test] + fn anchor_positions_of_an_unmeasurable_curve_are_finite() { + let p = curve(Point::new(100.0, 1e300), Point::new(300.0, -1e300)); + assert_eq!(p.subpaths[0].anchor_arc_positions(), [0.0, 0.0]); + } + #[test] fn length_of_square() { assert!((square().length() - 40.0).abs() < 1e-6); diff --git a/crates/geom/src/projective.rs b/crates/geom/src/projective.rs index 80758d3bab..070048f38c 100644 --- a/crates/geom/src/projective.rs +++ b/crates/geom/src/projective.rs @@ -50,36 +50,80 @@ impl Homography { [m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], m[2][2]] } - /// Map a point; `None` when it lands on or beyond the horizon (w ≤ 0), or when it does not map - /// to a finite page point. + /// Map a point; `None` when it lands on or beyond the horizon (w at most 1e-9 times the largest + /// magnitude in the map's `w` row, so the answer is the same at any scale of the map), or when + /// it does not map to a finite page point. The point is mapped through [`Self::upscaled`]. pub fn apply(&self, p: Point) -> Option { - let m = &self.0; + let m = self.upscaled(p); let x = m[0][0] * p.x + m[0][1] * p.y + m[0][2]; let y = m[1][0] * p.x + m[1][1] * p.y + m[1][2]; let w = m[2][0] * p.x + m[2][1] * p.y + m[2][2]; - if w <= 1e-9 || !x.is_finite() || !y.is_finite() { + let k = m[2].iter().fold(0.0_f64, |k, v| k.max(v.abs())); + if w <= 1e-9 * k || !x.is_finite() || !y.is_finite() { return None; } let q = Point::new(x / w, y / w); q.is_finite().then_some(q) } + /// The entries for mapping `p`, multiplied by a power of two of at least 1 (an exact step that + /// keeps a map at a tiny scale from losing precision to subnormal products). When every entry + /// is below 1/2 in magnitude, the power brings the largest to at least 1/2 and below 1, divided + /// by the power of two of `p`'s larger coordinate magnitude when that is 1 or more, so that no + /// product of an entry and a coordinate reaches 1. Otherwise the entries are unchanged. + fn upscaled(&self, p: Point) -> [[f64; 3]; 3] { + let largest = self.0.iter().flatten().fold(0.0_f64, |k, v| k.max(v.abs())); + let e_p = frexp(p.x.abs().max(p.y.abs())).1.max(0); + let e = (frexp(largest).1.min(0) + e_p).min(0); + self.0.map(|row| row.map(|v| ldexp(v, -e))) + } + pub fn det(&self) -> f64 { let m = &self.0; m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]) } - /// Whether the map is invertible: the magnitude of its determinant is above 1e-15, or, when the - /// determinant is not finite, [`Self::inverse`] gives one. + /// Whether the map is invertible: [`Self::has_significant_det`], or, when the determinant is + /// not finite, [`Self::inverse`] gives one. fn is_invertible(&self) -> bool { - let d = self.det(); - if d.is_finite() { - return d.abs() > 1e-15; + if self.det().is_finite() { + return self.has_significant_det(); } self.inverse().is_some() } + /// Whether every entry is finite and the determinant's magnitude is more than 1e-15 times that + /// of the largest of the six products it sums (a test that gives the same answer at any scale + /// of the map). Each product is formed as a mantissa product and an exponent sum, and all six + /// are divided by the power of two of the largest before they are summed, so the largest is at + /// least 1/8 and below 1 and none of them overflows. + fn has_significant_det(&self) -> bool { + if !self.is_finite() { + return false; + } + let terms = self.det_terms(); + let Some(e) = terms.iter().filter(|(m, _)| *m != 0.0).map(|(_, e)| *e).max() else { + return false; + }; + let terms = terms.map(|(m, x)| ldexp(m, x - e)); + let largest = terms.iter().fold(0.0_f64, |k, v| k.max(v.abs())); + let d: f64 = terms.iter().sum(); + d.abs() > 1e-15 * largest + } + + /// The six signed products the determinant sums, each as a mantissa product and an exponent + /// sum. + fn det_terms(&self) -> [(f64, i32); 6] { + let f = self.0.map(|row| row.map(frexp)); + // The columns each of the six products takes from rows 0, 1 and 2, and its sign. + let cols = [(0, 1, 2, 1.0), (0, 2, 1, -1.0), (1, 0, 2, -1.0), (1, 2, 0, 1.0), (2, 0, 1, 1.0), (2, 1, 0, -1.0)]; + cols.map(|(a, b, c, sign)| { + let (a, b, c) = (f[0][a], f[1][b], f[2][c]); + (sign * a.0 * b.0 * c.0, a.1 + b.1 + c.1) + }) + } + /// The same map with every entry divided by one power of two, chosen so that the largest of the /// six products its determinant sums is at least 1/8 and below 4. `None` when every one of /// those products is 0 or an entry is not finite. @@ -100,54 +144,58 @@ impl Homography { Some(Self(self.0.map(|row| row.map(|v| ldexp(v, -e))))) } - /// Inverse; `None` when the map is not invertible or its inverse has an entry that is not - /// finite. When the determinant is not finite, this is the inverse of [`Self::scaled`] (the - /// exact inverse multiplied by one power of two, which is the same map), and that copy counts - /// as not invertible when the magnitude of its determinant is at most 1e-15 times that of the largest - /// of the six products the determinant sums. + /// Inverse; `None` when [`Self::has_significant_det`] counts the map as not invertible. The + /// inverse is formed from the map itself when its determinant is finite, and is kept when every + /// entry is finite and its own determinant is not 0. Otherwise it is the inverse of + /// [`Self::scaled`] (the exact inverse multiplied by one power of two, which is the same map), + /// and `None` when that one fails the same checks. pub fn inverse(&self) -> Option { - let d = self.det(); - let (h, d) = if d.is_finite() { - if d.abs() < 1e-15 { - return None; - } - (*self, d) - } else { - let s = self.scaled()?; - let m = &s.0; - let terms = [ - m[0][0] * m[1][1] * m[2][2], - m[0][0] * m[1][2] * m[2][1], - m[0][1] * m[1][0] * m[2][2], - m[0][1] * m[1][2] * m[2][0], - m[0][2] * m[1][0] * m[2][1], - m[0][2] * m[1][1] * m[2][0], - ]; - let largest = terms.iter().fold(0.0_f64, |k, v| k.max(v.abs())); - let d = s.det(); - if d.abs() <= 1e-15 * largest { - return None; - } - (s, d) - }; - let m = &h.0; - let c = |r0: usize, c0: usize, r1: usize, c1: usize| m[r0][c0] * m[r1][c1] - m[r0][c1] * m[r1][c0]; - let adj = [ - [c(1, 1, 2, 2), -c(0, 1, 2, 2), c(0, 1, 1, 2)], - [-c(1, 0, 2, 2), c(0, 0, 2, 2), -c(0, 0, 1, 2)], - [c(1, 0, 2, 1), -c(0, 0, 2, 1), c(0, 0, 1, 1)], - ]; - let mut out = [[0.0; 3]; 3]; - for (r, row) in adj.iter().enumerate() { - for (k, v) in row.iter().enumerate() { - out[r][k] = v / d; - } - } - if out.iter().flatten().any(|v| !v.is_finite()) { + if !self.has_significant_det() { return None; } + if self.det().is_finite() + && let Some(inv) = self.adjugate_inverse() + { + return Some(inv); + } + self.scaled()?.adjugate_inverse() + } + + /// The adjugate divided by the determinant; `None` when an entry is not finite, the + /// determinant is 0, or the result has an entry that is not finite or a determinant of 0 (its + /// six products, each held as a mantissa and a power of two, sum to 0, as when a row underflows + /// to 0). Every cofactor and the determinant are held as a mantissa and a power of two, so an + /// entry of the result is lost only when that entry itself is beyond the range of `f64`. + fn adjugate_inverse(&self) -> Option { + if !self.is_finite() { + return None; + } + let f = self.0.map(|row| row.map(frexp)); + let mul = |a: (f64, i32), b: (f64, i32)| (a.0 * b.0, a.1 + b.1); + let c = |r0: usize, c0: usize, r1: usize, c1: usize| { + let (a, b) = (mul(f[r0][c0], f[r1][c1]), mul(f[r0][c1], f[r1][c0])); + split_sum(&[a, (-b.0, b.1)]) + }; + let neg = |(m, e): (f64, i32)| (-m, e); + let adj = [ + [c(1, 1, 2, 2), neg(c(0, 1, 2, 2)), c(0, 1, 1, 2)], + [neg(c(1, 0, 2, 2)), c(0, 0, 2, 2), neg(c(0, 0, 1, 2))], + [c(1, 0, 2, 1), neg(c(0, 0, 2, 1)), c(0, 0, 1, 1)], + ]; + // The determinant expanded along the first row, as `det` sums it. + let (dm, de) = split_sum(&[mul(f[0][0], adj[0][0]), mul(f[0][1], adj[1][0]), mul(f[0][2], adj[2][0])]); + if dm == 0.0 { + return None; + } + let mut out = [[0.0; 3]; 3]; + for (r, row) in adj.iter().enumerate() { + for (k, (m, e)) in row.iter().enumerate() { + out[r][k] = ldexp(m / dm, e - de); + } + } + let out = Self(out); // H⁻¹·(x, y, 1) = (u, v, 1)/w_H, so points in front of the camera keep w > 0. - Some(Self(out)) + (out.is_finite() && split_sum(&out.det_terms()).0 != 0.0).then_some(out) } /// `self ∘ other`: `other` first. @@ -216,7 +264,7 @@ impl Homography { /// The affine map that matches `self` to first order at `p` (its derivative there), `None` /// beyond the horizon or when the derivative is not finite. pub fn affine_at(&self, p: Point) -> Option { - let m = &self.0; + let m = self.upscaled(p); let w = m[2][0] * p.x + m[2][1] * p.y + m[2][2]; let q = self.apply(p)?; // d(x/w) = (dx − (x/w)·dw) / w, and the same for y. @@ -251,6 +299,17 @@ fn frexp(v: f64) -> (f64, i32) { (f64::from_bits((bits & !(0x7ff << 52)) | (1022 << 52)), e + bias) } +/// The sum of `m·2^e` over `terms`, in order, as a mantissa `0.5 ≤ |m| < 1` (or 0) and a power of +/// two. Every term is first divided by the power of two of the largest nonzero one, so none of +/// them overflows. +fn split_sum(terms: &[(f64, i32)]) -> (f64, i32) { + let Some(e) = terms.iter().filter(|(m, _)| *m != 0.0).map(|(_, e)| *e).max() else { + return (0.0, 0); + }; + let (m, x) = frexp(terms.iter().map(|&(m, x)| ldexp(m, x - e)).sum()); + (m, e + x) +} + /// `m·2^e`, multiplied in steps of powers of two that are each within the normal range. fn ldexp(mut m: f64, mut e: i32) -> f64 { while e > 1023 && m.is_finite() { @@ -397,12 +456,148 @@ mod tests { let want = t * far.apply(p).unwrap(); assert!(c.apply(t * p).unwrap().distance(want) <= 1e-9 * want.to_vec2().hypot(), "{c:?}"); } - // A determinant that does not overflow is judged as it is. - assert!(Homography::from_array([1e-6, 0.0, 0.0, 0.0, 1e-6, 0.0, 0.0, 0.0, 1e-6]).is_none()); + // A determinant that does not overflow is judged against the size of the map's entries: + // the identity with every entry 1e-6 is the identity, and two equal rows are not invertible. + let small = [1e-6, 0.0, 0.0, 0.0, 1e-6, 0.0, 0.0, 0.0, 1e-6]; + let q = Homography::from_array(small).unwrap().apply(Point::new(2.0, 3.0)).unwrap(); + assert!(q.distance(Point::new(2.0, 3.0)) < 1e-12); + assert!(Homography::from_array([1e-6, 2e-6, 0.0, 1e-6, 2e-6, 0.0, 0.0, 0.0, 1e-6]).is_none()); assert!(Homography::from_array([f64::NAN; 9]).is_none()); assert!(Homography::from_array([0.0; 9]).is_none()); } + #[test] + fn the_checks_do_not_depend_on_the_scale_of_the_map() { + let times = |h: Homography, f: f64| Homography(h.0.map(|row| row.map(|v| v * f))); + // The same map with its w row's largest entry 1. + let unit = |h: Homography| { + let k = h.0[2].iter().fold(0.0_f64, |k, v| k.max(v.abs())); + Homography(h.0.map(|row| row.map(|v| v / k))) + }; + // The horizon of h() is 0.001x + 0.002y + 1 = 0: two points in front of it, one with w of + // about 5e-10 (too close to it to draw), and two beyond it. + let pts = + [Point::new(30.0, -12.0), Point::new(-999.99, 0.0), Point::new(-999.9999995, 0.0), Point::new(-2000.0, 0.0), Point::new(0.0, -600.0)]; + let at_unit: Vec<_> = pts.iter().map(|&p| h().apply(p)).collect(); + assert!(at_unit[0].is_some() && at_unit[1].is_some()); + assert!(at_unit[2..].iter().all(Option::is_none)); + let inv = h().inverse().unwrap(); + // Two equal rows (up to a factor of 2), with entries that are exact in binary. + let flat = Homography([[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [0.25, 0.5, 1.0]]); + assert!(!flat.is_invertible()); + assert_eq!(flat.inverse(), None); + for f in [1e-200, 1e-12, 1e12, 1e200] { + let s = times(h(), f); + for (&p, want) in pts.iter().zip(&at_unit) { + match (s.apply(p), want) { + (Some(q), Some(w)) => assert!(q.distance(*w) <= 1e-6 * w.to_vec2().hypot(), "{f} {p:?}"), + (None, None) => {} + (got, _) => panic!("{f} {p:?}: {got:?}"), + } + } + assert!(s.is_invertible(), "{f}"); + let si = unit(s.inverse().unwrap_or_else(|| panic!("{f}"))); + for (a, b) in si.to_array().iter().zip(unit(inv).to_array()) { + assert!((a - b).abs() <= 1e-9 * b.abs().max(1.0), "{f}: {si:?}"); + } + let sf = times(flat, f); + assert!(!sf.is_invertible(), "{f}"); + assert_eq!(sf.inverse(), None, "{f}"); + } + // Entries of very different sizes: the determinant is about 1e-7 and every entry of the + // inverse is finite, though one power of two that brings the products near 1 takes the + // first entry past the largest finite number. + let uneven = Homography([[1e307, 0.0, 0.0], [0.0, 1e-157, 0.0], [0.0, 0.0, 1e-157]]); + assert!(uneven.det().is_finite()); + assert_eq!(Homography::from_array(uneven.to_array()), Some(uneven)); + let inv = uneven.inverse().unwrap(); + for p in [Point::new(1e-300, 2.0), Point::new(-3e-299, -0.5)] { + let q = uneven.apply(p).unwrap(); + let back = inv.apply(q).unwrap(); + assert!((back.x - p.x).abs() <= 1e-9 * p.x.abs() && (back.y - p.y).abs() <= 1e-9 * p.y.abs(), "{p:?} {back:?}"); + } + // A normal determinant (1e-200) whose cofactor 1e-200 · 1e-200 is below the smallest + // positive f64: the inverse still has a w row that is not 0. + let tiny = Homography([[1e-200, 0.0, 0.0], [0.0, 1e-200, 0.0], [0.0, 0.0, 1e200]]); + assert_eq!(Homography::from_array(tiny.to_array()), Some(tiny)); + let inv = tiny.inverse().unwrap(); + for p in [Point::new(1e300, -2e299), Point::new(-4e299, 5e300)] { + let q = tiny.apply(p).unwrap(); + let back = inv.apply(q).unwrap(); + assert!((back.x - p.x).abs() <= 1e-9 * p.x.abs() && (back.y - p.y).abs() <= 1e-9 * p.y.abs(), "{p:?} {back:?}"); + } + // A normal determinant (1e-300) whose cofactor 1e-300 · 1e-300 is below the smallest + // positive f64, and where one power of two that brings the products near 1 takes 1e300 past + // the largest finite number: the inverse is still diag(1e300, 1e-300, 1e300). + let spread = Homography([[1e-300, 0.0, 0.0], [0.0, 1e300, 0.0], [0.0, 0.0, 1e-300]]); + assert_eq!(Homography::from_array(spread.to_array()), Some(spread)); + let inv = spread.inverse().unwrap(); + let want = [1e300, 0.0, 0.0, 0.0, 1e-300, 0.0, 0.0, 0.0, 1e300]; + for (v, w) in inv.to_array().iter().zip(want) { + assert!((v - w).abs() <= 1e-12 * w.abs(), "{inv:?}"); + } + } + + #[test] + fn an_invertible_map_has_an_inverse_at_any_scale() { + let times = |h: Homography, f: f64| Homography(h.0.map(|row| row.map(|v| v * f))); + // Determinant 1e-17 against a largest product of 1e-9 (and 1e-8 at 1e3 times the map): its + // inverse is finite, though that inverse's own determinant is near 1e-16 of its largest + // product. + let skew = Homography([[-1000.0, -1e-8, -1e-5], [0.0, 1e-4, -1e7], [1e-8, 0.0, 1e-8]]); + let exact = [1e5, 10.0, 1e16 + 1e8, -1e16, -1e12 + 1e4, -1e27, -1e5, -10.0, -1e16]; + for f in [1.0, 1e3] { + let s = times(skew, f); + assert_eq!(Homography::from_array(s.to_array()), Some(s), "{f}"); + let inv = s.inverse().unwrap_or_else(|| panic!("{f}")); + for (v, w) in inv.to_array().iter().zip(exact) { + assert!((v * f - w).abs() <= 1e-9 * w.abs(), "{f}: {inv:?}"); + } + // The map times its inverse is the identity, to within the rounding of the products + // each entry sums (they cancel by up to 1e23 in the second row). + let id = s.then_after(&inv); + for (r, row) in id.0.iter().enumerate() { + for (k, v) in row.iter().enumerate() { + let size: f64 = (0..3).map(|i| (s.0[r][i] * inv.0[i][k]).abs()).sum(); + let want = if r == k { 1.0 } else { 0.0 }; + assert!((v - want).abs() <= 1e-12 * size, "{f}: {id:?}"); + } + } + } + } + + #[test] + fn a_map_at_a_tiny_scale_maps_points_as_at_unit_scale() { + for f in [5e-324, 1e-300] { + let h = Homography(Homography::IDENTITY.0.map(|row| row.map(|v| v * f))); + assert_eq!(Homography::from_array(h.to_array()), Some(h), "{f}"); + for p in [Point::new(0.5, 0.5), Point::new(1e-20, 1e-20)] { + let q = h.apply(p).unwrap_or_else(|| panic!("{f}: {p:?}")); + assert!((q.x - p.x).abs() <= 1e-12 * p.x && (q.y - p.y).abs() <= 1e-12 * p.y, "{f}: {p:?} -> {q:?}"); + } + } + // A perspective map whose entries are exact at 2^-1060 times their size, so the scaled + // copy holds the same map. + let unit = Homography([[1.0, 0.0, 2.0], [0.0, 1.0, 3.0], [0.5, 0.25, 1.0]]); + let tiny = Homography(unit.0.map(|row| row.map(|v| v * pow2(-1022) * pow2(-38)))); + let p = Point::new(0.3, 0.7); + let (a, b) = (tiny.affine_at(p).unwrap(), unit.affine_at(p).unwrap()); + for (u, v) in a.as_coeffs().iter().zip(b.as_coeffs()) { + assert!((u - v).abs() <= 1e-12 * v.abs().max(1.0), "{a:?} {b:?}"); + } + } + + #[test] + fn a_map_at_a_small_scale_maps_a_far_point() { + // Every product of an entry and a coordinate is finite, but the entries brought to 1/2 or + // more would overflow against this point. + let h = Homography([[1e-6, 1e-6, 0.0], [0.0, 1e-6, 0.0], [1e-6, 0.0, 1e-6]]); + let p = Point::new(1.75e308, 1.75e308); + let q = h.apply(p).unwrap_or_else(|| panic!("{p:?}")); + assert!((q.x - 2.0).abs() <= 1e-12 && (q.y - 1.0).abs() <= 1e-12, "{q:?}"); + assert!(h.affine_at(p).is_some()); + } + #[test] fn a_product_that_overflows_is_none() { // Each factor is finite and invertible, but the product's first entry is 1e400. diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 5ed71fcc67..64a7f0ea1f 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -352,7 +352,10 @@ impl Headless { "document.node" => self.exec("document.node", p), "document.json" => self.exec("document.json", &json!({})), "ui.tool.select" => self.select_tool(p), - "ui.tool.list" => Ok(serde_json::to_value(TOOL_GROUPS).unwrap_or_default()), + "ui.tool.list" => { + let groups: Vec<_> = TOOL_GROUPS.iter().chain(vectorcraft_tools::addons::GROUPS).copied().collect(); + Ok(serde_json::to_value(groups).unwrap_or_default()) + } "ui.pointer" => self.pointer(p), "ui.key" => self.key(p), "ui.render" | "ui.screenshot" => self.render(p), diff --git a/crates/mcp/src/intake.rs b/crates/mcp/src/intake.rs index 272c2a6ecc..35a7bb17ad 100644 --- a/crates/mcp/src/intake.rs +++ b/crates/mcp/src/intake.rs @@ -146,10 +146,15 @@ impl Shared { fn long_running(&self, st: &State) -> Option { let r = st.running.as_ref()?; let secs = r.since.elapsed(); - (secs >= self.busy_after).then(|| json!({"running": r.label, "requestId": r.key, "seconds": secs.as_secs()})) + // A long id isn't repeated: every busy reply would carry it twice. + let key = r.key.as_deref().filter(|k| k.len() <= MAX_ECHOED_ID); + (secs >= self.busy_after).then(|| json!({"running": r.label, "requestId": key, "seconds": secs.as_secs()})) } } +/// The longest running request id a busy reply repeats (as JSON, quotes included). +const MAX_ECHOED_ID: usize = 256; + /// The id of a request message: `Some` when `msg` is a JSON-RPC 2.0 request with a usable id. fn request_id(msg: &Value) -> Option<&Value> { let o = msg.as_object()?; diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index f61b8839cf..2e153b62b7 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1297,7 +1297,16 @@ fn headless_backend_methods() { assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(600), Some(400))); let cmds = h.call("engine.commands", json!({})).unwrap(); assert!(cmds.as_array().unwrap().iter().any(|c| c["id"] == "file.export")); - assert!(h.call("ui.tool.list", json!({})).unwrap().is_array()); + let listed = h.call("ui.tool.list", json!({})).unwrap(); + let groups = listed.as_array().unwrap(); + for tool in vectorcraft_tools::addons::GROUPS.iter().flat_map(|group| group.iter()) { + let matching: Vec<_> = groups.iter().flat_map(|group| group.as_array().unwrap()).filter(|entry| entry["id"] == tool.id).collect(); + assert_eq!(matching.len(), 1, "{}", tool.id); + assert_eq!(matching[0]["label"], tool.label); + assert!(matching[0]["shortcut"].is_null()); + let selected = h.call("ui.tool.select", json!({"tool": tool.id})).unwrap(); + assert_eq!(selected["tool"], tool.id); + } assert!(h.call("ui.resize", json!({})).is_err()); } diff --git a/crates/mcp/src/tests/fileio.rs b/crates/mcp/src/tests/fileio.rs index cc506b1828..d6f522b3b5 100644 --- a/crates/mcp/src/tests/fileio.rs +++ b/crates/mcp/src/tests/fileio.rs @@ -195,6 +195,15 @@ fn save_file_takes_the_native_save_options() { let shown = saved_with(&mut h, "preview.vectorcraft", json!({"preview": true})); assert!(vectorcraft_format::preview(&shown).is_some(), "a preview"); assert!(vectorcraft_format::preview(&plain).is_none(), "off by default"); + // `precision` rounds the path coordinates of that save only. + let mut p = Headless::new(); + p.call("engine.execute", json!({"command": "file.new", "params": {"width": 100, "height": 100}})).unwrap(); + p.call("engine.execute", json!({"command": "path.create", "params": {"anchors": [{"x": 10.123456, "y": 20.654321}, {"x": 30.5, "y": 40.25}]}})) + .unwrap(); + let exact = String::from_utf8(saved_with(&mut p, "exact.vectorcraft", json!({"compress": false}))).unwrap(); + assert!(exact.contains("10.123456") && exact.contains("20.654321"), "{exact}"); + let rounded = String::from_utf8(saved_with(&mut p, "rounded.vectorcraft", json!({"compress": false, "precision": 1}))).unwrap(); + assert!(!rounded.contains("10.123456") && !rounded.contains("20.654321") && rounded.contains("20.7"), "{rounded}"); // Version 2 files can't be compressed: the engine's error comes back. let r = call_tool(&mut h, "save_file", &json!({"path": tmp("v2.vectorcraft"), "version": 2, "compress": true})); assert!(r.is_error && r.content[0]["text"].as_str().unwrap().contains("can't be compressed"), "{r:?}"); @@ -232,6 +241,9 @@ fn save_file_warns_about_options_it_does_not_use() { let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp("ignored.ai"), "compress": false, "version": 3}))); let w = warnings(&r); assert!(ignored(&w, "version") && !ignored(&w, "compress"), "{w:?}"); + // `precision` is read by native files only. + let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp("ignored-precision.svg"), "precision": 2}))); + assert!(ignored(&warnings(&r), "precision"), "{r}"); // A top-level value that disagrees with `options` is refused, and nothing is written. let path = tmp("both.vectorcraft"); @@ -241,7 +253,9 @@ fn save_file_warns_about_options_it_does_not_use() { assert!(r.is_error && e.contains("`compress: true` and `options.compress: false` disagree"), "{r:?}"); assert!(!std::path::Path::new(&path).exists(), "nothing is written"); // Nothing to say when they agree or when every option applies. - for mut args in [json!({"compress": true, "options": {"compress": true}}), json!({"compress": false, "version": 3, "preview": true})] { + for mut args in + [json!({"compress": true, "options": {"compress": true}}), json!({"compress": false, "version": 3, "preview": true, "precision": 4})] + { args["path"] = json!(tmp("quiet.vectorcraft")); let r = text(&call_tool(&mut h, "save_file", &args)); assert_eq!(r["warnings"], json!([]), "{args}: {r}"); @@ -272,12 +286,12 @@ fn save_file_is_the_same_call_in_the_app_and_headless() { let path = tmp("app.vectorcraft"); let (addr, app) = recording_app(); let mut remote = Remote::connect(&addr).unwrap(); - let args = json!({"path": path, "compress": true, "version": 3, "preview": null, "options": {"preview": true}}); + let args = json!({"path": path, "compress": true, "version": 3, "preview": null, "precision": 2, "options": {"preview": true}}); assert!(!call_tool(&mut remote, "save_file", &args).is_error); drop(remote); let seen = app.join().unwrap(); assert_eq!(seen[0]["method"], "app.save"); - assert_eq!(seen[0]["params"], json!({"path": path, "compress": true, "version": 3, "options": {"preview": true}, "wait": true})); + assert_eq!(seen[0]["params"], json!({"path": path, "compress": true, "version": 3, "precision": 2, "options": {"preview": true}, "wait": true})); } /// The app is asked to write the file before it replies (`wait`), even with Background Save on, so a diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index bfe8921e8c..c889c2237a 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -13,7 +13,7 @@ fn string(desc: &str) -> Value { } /// The arguments `save_file` passes on to `document.save` beside `path`. -pub(super) const SAVE_FILE_OPTIONS: [&str; 4] = ["compress", "version", "preview", "options"]; +pub(super) const SAVE_FILE_OPTIONS: [&str; 5] = ["compress", "version", "preview", "precision", "options"]; /// The arguments `doc_inspect` / `inspect_document` pass on to `document.inspect`. pub(super) const INSPECT_KEYS: [&str; 6] = ["depth", "childLimit", "ids", "kind", "limit", "offset"]; @@ -367,7 +367,7 @@ pub fn tool_definitions() -> Vec { "save_file", "Save file", &format!( - "Save the active document with the engine's document.save: by default to its own file in its own format (native .vectorcraft unless it was opened from or saved as SVG, PDF or a restorable .ai). With `path`, the extension picks the format: .{}. Other formats are exports (see export). A native file is gzipped when `compress` is true (default: the useCompression preference, Preferences > File Handling > Use Compression); `version` writes it for an older VectorCraft and `preview` embeds a PNG of the first artboard. `options` carries the format's save options (see run_command document.formats); giving `compress`, `version` or `preview` both at the top level and in `options` with different values is an error. The reply's `format` says what was written and `warnings` what that format loses and each option given that the format doesn't read (such as `compress` for .svg). In the running app the call returns once the file is written, or with the error, even with Background Save on. When the save asks first (before replacing a file that opened with losses, or with a file dialog for an untitled document without `path`), the reply is `pending` or \"cancelled\" as before.", + "Save the active document with the engine's document.save: by default to its own file in its own format (native .vectorcraft unless it was opened from or saved as SVG, PDF or a restorable .ai). With `path`, the extension picks the format: .{}. Other formats are exports (see export). A native file is gzipped when `compress` is true (default: the useCompression preference, Preferences > File Handling > Use Compression); `version` writes it for an older VectorCraft, `preview` embeds a PNG of the first artboard, and `precision` rounds path anchors and handles to that many decimal places for that save only. `options` carries the format's save options (see run_command document.formats); giving `compress`, `version`, `preview` or `precision` both at the top level and in `options` with different values is an error. The reply's `format` says what was written and `warnings` what that format loses and each option given that the format doesn't read (such as `compress` for .svg). In the running app the call returns once the file is written, or with the error, even with Background Save on. When the save asks first (before replacing a file that opened with losses, or with a file dialog for an untitled document without `path`), the reply is `pending` or \"cancelled\" as before.", save_extensions().join(", .") ), obj( @@ -376,6 +376,7 @@ pub fn tool_definitions() -> Vec { "compress": {"type": "boolean", "description": "Native files: gzip the file (default: the useCompression preference)"}, "version": {"type": "integer", "minimum": 1, "maximum": vectorcraft_format::VERSION, "description": "Native files: the format version to write (default: the current one; 1 and 2 are never compressed)"}, "preview": {"type": "boolean", "description": "Native files: embed a PNG of the first artboard, at most 256 px (default false)"}, + "precision": {"type": "integer", "minimum": 0, "maximum": vectorcraft_format::MAX_PRECISION, "description": "Native files: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact (default: exact)"}, "options": {"type": "object", "description": "The format's save options, passed through (see run_command document.formats); default: as last saved"}, }), &[], diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index 9310b12be8..9e3af3dbaa 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -286,7 +286,8 @@ fn named_export_params(a: &Args) -> &'static [&'static str] { /// What `save_file` with arguments `a` adds to the save's `warnings`, for a file written in format /// `written` (none when nothing was written yet): each key in `options` that the format doesn't -/// read. The save itself warns about `compress`, `version` and `preview` given at the top level. +/// read. The save itself warns about `compress`, `version`, `preview` and `precision` given at the +/// top level. fn save_file_warnings(a: &Args, written: Option<&str>) -> Vec { let Some(f) = written.and_then(format) else { return vec![] }; let nested = a.get("options").and_then(Value::as_object); @@ -451,7 +452,8 @@ fn render_preview(b: &mut dyn Backend, a: &Args) -> Result { let r = b.call("ui.render", p)?; let encoded = r.get("pngBase64").and_then(Value::as_str).ok_or("renderer returned no image")?; let png = vectorcraft_format::base64_decode(encoded).ok_or("renderer returned bad base64")?; - let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| format!("read preview: {e}"))?; + // The render was asked for at most 4096 a side. + let img = super::handlers::decode_png(&png, 8192).map_err(|e| format!("read preview: {e}"))?; let img = if img.width() > max || img.height() > max { img.thumbnail(max, max) } else { img }; let mut out = std::io::Cursor::new(Vec::new()); img.write_to(&mut out, image::ImageFormat::Png).map_err(|e| format!("encode preview: {e}"))?; diff --git a/crates/mcp/src/tools/handlers.rs b/crates/mcp/src/tools/handlers.rs index c9d203c6b3..ea2c6ec706 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -442,12 +442,27 @@ pub(super) fn max_side(a: &Args) -> Result, String> { } } +/// The longest side of a window capture that is decoded (a screen is never wider). +const MAX_CAPTURE_SIDE: u32 = 16_384; + +/// `png` decoded, refused when a side is longer than `side` or the decode needs more than 256 MiB: +/// the picture is the app's reply, and its header names the size it is decoded at. +pub(super) fn decode_png(png: &[u8], side: u32) -> Result { + let mut reader = image::ImageReader::with_format(std::io::Cursor::new(png), image::ImageFormat::Png); + let mut limits = image::Limits::default(); + limits.max_image_width = Some(side); + limits.max_image_height = Some(side); + limits.max_alloc = Some(256 << 20); + reader.limits(limits); + reader.decode() +} + /// A window capture with `max_side`: scaled down when its longer side is larger, with its own size /// in `capturedWidth` / `capturedHeight` and the returned image's in `width` / `height`. Without /// `max_side` the capture and `info` stay as they are. fn fit_capture(png: Vec, max: Option, info: &mut Value) -> Result, String> { let Some(max) = max else { return Ok(png) }; - let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| format!("read capture: {e}"))?; + let img = decode_png(&png, MAX_CAPTURE_SIDE).map_err(|e| format!("read capture: {e}"))?; info["capturedWidth"] = json!(img.width()); info["capturedHeight"] = json!(img.height()); if img.width().max(img.height()) <= max { @@ -472,3 +487,17 @@ pub(super) fn image_result(png: &[u8], info: Value) -> ToolResult { is_error: false, } } + +#[cfg(test)] +mod decode_tests { + use super::decode_png; + + #[test] + fn a_picture_with_a_side_past_the_limit_is_not_decoded() { + let mut png = std::io::Cursor::new(Vec::new()); + image::RgbaImage::new(200, 10).write_to(&mut png, image::ImageFormat::Png).unwrap(); + let png = png.into_inner(); + assert!(decode_png(&png, 100).is_err()); + assert_eq!(decode_png(&png, 200).unwrap().width(), 200); + } +} diff --git a/crates/metafile/src/import.rs b/crates/metafile/src/import.rs index ed31d496e7..0a3d791ee2 100644 --- a/crates/metafile/src/import.rs +++ b/crates/metafile/src/import.rs @@ -429,6 +429,9 @@ impl Player { let start = self.free_hint.min(self.objects.len()); let i = self.objects.iter().skip(start).position(Option::is_none).map_or(self.objects.len(), |p| p + start); if i > u16::MAX as usize { + // The table is full past the hint: the next creation looks from the end, not again + // through every slot. + self.free_hint = i; return; } if i == self.objects.len() { @@ -897,3 +900,25 @@ pub(crate) fn import(bytes: &[u8]) -> Result { None => Err("not an EMF or WMF file".into()), } } + +#[cfg(test)] +mod table_tests { + use super::*; + + /// Once the WMF table is full, a rejected creation leaves the hint at its end, so the next + /// ones don't scan every slot again; a freed slot is still found. + #[test] + fn a_full_object_table_is_not_rescanned() { + let mut p = Player::new(Kind::Wmf, Affine::IDENTITY, 1.0, Rect::new(0.0, 0.0, 10.0, 10.0)); + for _ in 0..=u16::MAX as usize + 1 { + p.create(Obj::Other); + } + p.delete(5); + p.create(Obj::Other); + p.create(Obj::Other); + assert!(p.free_hint > u16::MAX as usize); + p.delete(7); + p.create(Obj::Other); + assert!(p.objects[7].is_some()); + } +} diff --git a/crates/metafile/src/scene.rs b/crates/metafile/src/scene.rs index 7dea2afba4..36aa663d87 100644 --- a/crates/metafile/src/scene.rs +++ b/crates/metafile/src/scene.rs @@ -412,6 +412,7 @@ impl<'a> Scene<'a> { field.grid(area, cols, rows).flat_map(|(c, a)| [q(c[0]), q(c[1]), q(c[2]), q(a)]).collect() } else { let geom = g.resolve(bounds); + let sample = g.gradient.sampler(); let (cw, ch) = (area.width() / f64::from(cols), area.height() / f64::from(rows)); (0..usize::from(rows) * usize::from(cols)) .flat_map(|i| { @@ -419,7 +420,7 @@ impl<'a> Scene<'a> { let p = Point::new(area.x0 + (x as f64 + 0.5) * cw, area.y0 + (y as f64 + 0.5) * ch); let t = geom.param_at(g.gradient.kind, p); let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; - let (c, a) = g.gradient.sample(t as f32); + let (c, a) = sample(t as f32); c.to_rgba8(a) }) .collect() diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index 32b47b7b97..2a39cccfa6 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -3,7 +3,8 @@ use std::collections::{BTreeMap, BTreeSet}; -use kurbo::{CubicBez, ParamCurveArclen, Point, Rect, Vec2}; +use kurbo::{CubicBez, PathSeg, Point, Rect, Vec2}; +use vectorcraft_geom::path::measured_arclen; use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; use crate::boolean::{Seg, segs_to_subpath}; @@ -115,7 +116,8 @@ fn simplify_run(run: &[Seg], opts: &SimplifyOptions) -> Vec { } let mut pts = Vec::new(); for (k, s) in piece.iter().enumerate() { - let len = s.c.arclen(1e-6); + // Guarded: kurbo subdivides without end on huge finite coordinates. + let len = measured_arclen(&PathSeg::Cubic(s.c), 1e-6); let m = ((len / (tol * 0.5)).ceil() as usize).clamp(4, 256); sample(&s.c, m, &mut pts, k == 0); } @@ -454,7 +456,7 @@ fn seam_error(original: &SubPath, before: &SubPath, fit: &SubPath, tol: f64) -> let mut pts = Vec::new(); for j in (0..sp.segment_count()).filter(|&j| !seam_only || is_seam(j)) { let c = sp.segment(j); - let m = ((c.arclen(1e-6) / (tol.max(1e-6) * 0.5)).ceil() as usize).clamp(4, 256); + let m = ((measured_arclen(&PathSeg::Cubic(c), 1e-6) / (tol.max(1e-6) * 0.5)).ceil() as usize).clamp(4, 256); sample(&c, m, &mut pts, true); } pts diff --git a/crates/pdf/src/editing.rs b/crates/pdf/src/editing.rs index 9b56008293..a8dd48628c 100644 --- a/crates/pdf/src/editing.rs +++ b/crates/pdf/src/editing.rs @@ -6,7 +6,8 @@ use std::collections::HashSet; use std::sync::Arc; use craft_pdf::syntax::Pdf; -use craft_pdf::syntax::object::{Array, Dict, Object, ObjectIdentifier, Stream, String as PdfString}; +use craft_pdf::syntax::object::{Array, Dict, MaybeRef, Object, ObjectIdentifier, Stream, String as PdfString}; +use craft_pdf::syntax::xref::XRef; use craft_pdf::write::backend as krilla; use krilla::embed::{AssociationKind, EmbeddedFile, MimeType}; use krilla::metadata::DateTime; @@ -81,7 +82,7 @@ pub(crate) fn editing_in(pdf: &Pdf) -> Option { let xref = pdf.xref(); let catalog = xref.get::>(xref.root_id())?; let tree = catalog.get::>(b"Names")?.get::>(b"EmbeddedFiles")?; - let spec = editing_spec(&tree, 0, &mut HashSet::new())?; + let spec = editing_spec(&tree, 0, &mut HashSet::new(), xref)?; let files = spec.get::>(b"EF")?; let stream = files.get::>(b"F").or_else(|| files.get::>(b"UF"))?; let data = stream.decoded().map(|d| d.into_owned()).unwrap_or_default(); @@ -97,7 +98,7 @@ pub(crate) fn editing_in(pdf: &Pdf) -> Option { /// The file specification of the editing file in the name tree node `node`. `seen` holds the indirect /// nodes already searched, so a node shared by many `Kids` arrays is searched once, not once per path. -fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet) -> Option> { +fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet, xref: &'a XRef) -> Option> { if let Some(names) = node.get::>(b"Names") { let mut items = names.iter::>(); while let (Some(_), Some(spec)) = (items.next(), items.next()) { @@ -112,12 +113,15 @@ fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet>(b"Kids")?; - // Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). - items(&kids).zip(kids.iter::>()).find_map(|(raw, kid)| { - if raw.as_obj_ref().is_some_and(|r| !seen.insert(r.into())) { - return None; - } - editing_spec(&kid, depth + 1, seen) + // Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The + // reference is checked before the kid is read, so a shared kid is read once. + items(&kids).find_map(|raw| { + let kid = match raw { + MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::>(r.into())?, + MaybeRef::NotRef(Object::Dict(kid)) => kid, + _ => return None, + }; + editing_spec(&kid, depth + 1, seen, xref) }) } @@ -130,9 +134,26 @@ fn is_editing_file(spec: &Dict<'_>) -> bool { }) } -/// FNV-1a of the pages' media boxes and decoded content, as 16 hex digits. +/// The most decoded page content [`page_hash`] reads in all (bytes). +const MAX_HASHED: usize = 256 << 20; + +/// FNV-1a of the pages' media boxes and decoded content, as 16 hex digits. Past [`MAX_HASHED`] +/// bytes of content in all (pages sharing a stream count it each time) a marker stands for the +/// rest, so writing and reading a file hash it the same way within bounded work. fn page_hash(pdf: &Pdf) -> String { let fnv = |h: u64, bytes: &[u8]| bytes.iter().fold(h, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100000001b3)); + let mut left = MAX_HASHED; + let mut content = |h: u64, stream: &Stream<'_>| { + if left > 0 + && let Ok(data) = stream.decoded_within(left) + && data.len() < left + { + left -= data.len(); + return fnv(h, &data); + } + left = 0; + fnv(h, b"\0past the hashed content") + }; let mut h = 0xcbf29ce484222325; for page in pdf.pages().iter() { let b = page.media_box(); @@ -141,12 +162,10 @@ fn page_hash(pdf: &Pdf) -> String { // page's copy for as long as the PDF lives, even when pages share one stream. let contents = page.raw(); if let Some(stream) = contents.get::>(b"Contents") { - h = fnv(h, stream.decoded().as_deref().unwrap_or_default()); + h = content(h, &stream); } else if let Some(array) = contents.get::>(b"Contents") { for stream in array.iter::>() { - if let Ok(data) = stream.decoded() { - h = fnv(fnv(h, &data), b" "); - } + h = fnv(content(h, &stream), b" "); } } } diff --git a/crates/pdf/src/export/paint.rs b/crates/pdf/src/export/paint.rs index 06c08bc2dc..e8dfd4a07d 100644 --- a/crates/pdf/src/export/paint.rs +++ b/crates/pdf/src/export/paint.rs @@ -36,18 +36,37 @@ impl Exporter<'_> { Some(SeparationSpace::new(SeparationColorant::Custom(ink), alt)) } - /// The ink name of spot swatch `name` and its CMYK equivalent at 100% (a Lab spot color is - /// noted for [`crate::lab_spot`]); `None` when `name` isn't a spot color. + /// The ink name of spot swatch `name` ([`Self::colorant_name`]) and its CMYK equivalent at + /// 100% (a Lab spot color is noted for [`crate::lab_spot`]); `None` when `name` isn't a spot + /// color. pub(super) fn spot_ink(&mut self, name: &str) -> Option<(String, [f32; 4])> { let doc = self.doc; let sw = doc.swatch(name).filter(|s| s.spot)?; let color = doc.linked_color(sw.paint.color()?, true); + let ink = self.colorant_name(&sw.name); if let Color::Lab { l, a, b } = color - && !self.lab_spots.iter().any(|(n, _)| n == name) + && !self.lab_spots.iter().any(|(n, _)| *n == ink) { - self.lab_spots.push((name.to_string(), vectorcraft_color::cms::Lab::new(l, a, b))); + self.lab_spots.push((ink.clone(), vectorcraft_color::cms::Lab::new(l, a, b))); } - Some((sw.name.clone(), self.out.cmyk(&color, self.intent))) + Some((ink, self.out.cmyk(&color, self.intent))) + } + + /// The colorant name spot swatch `name` is written under: its own name, except that `All` + /// (every plate in PDF) and `None` (no plate) become `All Spot` and `None Spot`, numbered + /// `All Spot 2`, `All Spot 3`, … past the names of the document's spot swatches. + fn colorant_name(&self, name: &str) -> String { + if name != "All" && name != "None" { + return name.to_string(); + } + let taken = |c: &str| self.doc.swatches_iter().any(|s| s.spot && s.name == c); + let mut colorant = format!("{name} Spot"); + let mut n = 2; + while taken(&colorant) { + colorant = format!("{name} Spot {n}"); + n += 1; + } + colorant } /// A solid paint, in the Separation colour space at its tint when it's linked to a spot swatch @@ -109,12 +128,13 @@ impl Exporter<'_> { fn spot_of<'s>(doc: &vectorcraft_doc::Document, s: &'s vectorcraft_color::GradientStop) -> Option<&'s str> { s.swatch.as_deref().filter(|n| doc.swatch(n).is_some_and(|w| w.spot)) } - let mut spots: Vec<(String, [f32; 4])> = Vec::new(); + // Each spot ink: its swatch's name, then its colorant name and CMYK equivalent. + let mut spots: Vec<(&str, (String, [f32; 4]))> = Vec::new(); for s in &g.stops { if let Some(n) = spot_of(doc, s) - && !spots.iter().any(|(m, _)| m == n) + && !spots.iter().any(|(m, _)| *m == n) { - spots.push(self.spot_ink(n)?); + spots.push((n, self.spot_ink(n)?)); } } // Each stop's ink coverage: the four process inks, then one tint per spot ink. @@ -123,7 +143,7 @@ impl Exporter<'_> { let mut v = vec![0.0; 4 + spots.len()]; match spot_of(doc, s) { Some(n) => { - let i = spots.iter().position(|(m, _)| m == n)?; + let i = spots.iter().position(|(m, _)| *m == n)?; v[4 + i] = s.tint; } None if self.paper_stop(s) => {} @@ -142,7 +162,7 @@ impl Exporter<'_> { let colorants = process .iter() .map(|&i| Colorant::Process(Process::ALL[i])) - .chain(spots.iter().map(|(name, f)| Colorant::Spot { name: name.clone(), alternate: cmyk::Color::new_f32(f[0], f[1], f[2], f[3]) })); + .chain(spots.iter().map(|(_, (name, f))| Colorant::Spot { name: name.clone(), alternate: cmyk::Color::new_f32(f[0], f[1], f[2], f[3]) })); let Some(space) = DeviceNSpace::new(colorants) else { self.warn("gradients whose spot inks can't share a DeviceN color space are exported without the spot inks"); return None; diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index c75a28a60f..9319443846 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -229,7 +229,11 @@ pub(crate) fn recode(bytes: &[u8], size: (f64, f64), c: &CompressionSettings, in let keep = Recoded { image: None, warning: None }; let Ok(reader) = ImageReader::new(Cursor::new(bytes)).with_guessed_format() else { return keep }; let jpeg = reader.format() == Some(ImageFormat::Jpeg); - let Ok(decoder) = reader.into_decoder() else { return keep }; + let Ok(mut decoder) = reader.into_decoder() else { return keep }; + // What the header declares is decoded within the image allowance, not whatever it asks for. + if decoder.set_limits(limits()).is_err() { + return keep; + } let dims = decoder.dimensions(); use ExtendedColorType as T; let grey = matches!(decoder.original_color_type(), T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16); @@ -249,7 +253,7 @@ pub(crate) fn recode(bytes: &[u8], size: (f64, f64), c: &CompressionSettings, in if kept(&rule, dims, size, jpeg) && convert.is_none() { return Recoded { image: None, warning: rule.instead }; } - let Some(img) = pixels.or_else(|| image::load_from_memory(bytes).ok()) else { return keep }; + let Some(img) = pixels.or_else(|| decoded(bytes)) else { return keep }; let mut rgba = resample(img, &rule, sized(&rule, dims, size)).into_rgba8(); if kind == Kind::Mono { // Resampling greys the edges: back to black and white. @@ -345,6 +349,23 @@ pub(crate) fn recode_cmyk( Recoded { image, warning: rule.instead } } +/// The most one image read here may allocate (bytes), as the image reader allows by default. +const MAX_DECODE: u64 = 512 << 20; + +/// The decoder limits of an image read here: [`MAX_DECODE`] bytes. +fn limits() -> image::Limits { + let mut l = image::Limits::default(); + l.max_alloc = Some(MAX_DECODE); + l +} + +/// `bytes` decoded within [`limits`]: an image whose header asks for more is not decoded. +fn decoded(bytes: &[u8]) -> Option { + let mut r = ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?; + r.limits(limits()); + r.decode().ok() +} + /// The alpha an opacity mask whose art is greyscale image `blob` alone gives the image of /// `width` × `height` pixels it covers pixel for pixel: the mask's luminance, over black where the /// mask image is transparent when it clips (`clip`), else over white. `None` when `blob` isn't @@ -353,7 +374,13 @@ pub(crate) fn mask_alpha(blob: &ImageBlob, width: u32, height: u32, clip: bool) if blob.is_cmyk() { return None; } - let img = image::load_from_memory(&blob.bytes).ok()?.into_rgba8(); + // The size from the header first: a mask of another size, or too large to hold as RGBA, is + // not decoded at all. + let reader = ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok()?; + if reader.into_dimensions().ok()? != (width, height) || u64::from(width) * u64::from(height) * 4 > MAX_DECODE { + return None; + } + let img = decoded(&blob.bytes)?.into_rgba8(); if img.dimensions() != (width, height) || !neutral(img.as_raw()) { return None; } diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index f0049787f8..86a4a89a37 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -173,8 +173,8 @@ impl<'p> Builder<'p> { } /// The group art drawn now belongs to (the innermost marked as one). - fn current_group(&self) -> Option { - self.marked.iter().rev().find_map(|g| *g) + pub(super) fn current_group(&self) -> Option { + self.marked.last().and_then(|(_, current)| *current) } /// Add `n` to the open frame; `group`: the optional content group it was drawn in, if it diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index f89deaaf95..84d8885a0b 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -363,7 +363,8 @@ impl<'a> Device<'a> for Builder<'_> { { f.group.get_or_insert(g); } - self.marked.push(group); + let current = group.or_else(|| self.current_group()); + self.marked.push((group, current)); } fn end_marked_content(&mut self) { @@ -371,7 +372,7 @@ impl<'a> Device<'a> for Builder<'_> { return; } // The runs gathered within a layer's sequence are its art: finish them before it ends. - if self.marked.last().copied().flatten().is_some() { + if self.marked.last().is_some_and(|(group, _)| group.is_some()) { self.flush(); } self.marked.pop(); diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index f2d974f159..abf7499d05 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -136,8 +136,9 @@ pub(super) struct Builder<'p> { /// Some groups are hidden or don't print: art in marked content whose group can't be told /// (once the scan and the interpreter part) is [`UNSORTED`] rather than the page's. pub(super) unsure: bool, - /// The marked-content sequences open: the group each marks. - pub(super) marked: Vec>, + /// The marked-content sequences open: the group each marks, and the innermost group marked + /// at or around it (kept per level, so art drawn deep in sequences finds its group at once). + pub(super) marked: Vec<(Option, Option)>, pub(super) nested: u32, /// Reading an alpha soft mask's art: images are read white with their own alpha, so the /// mask's luminance is their alpha, as whitened vector art's is (cairo, and so Inkscape, diff --git a/crates/pdf/src/print/plates.rs b/crates/pdf/src/print/plates.rs index 9025f342f4..7c84996427 100644 --- a/crates/pdf/src/print/plates.rs +++ b/crates/pdf/src/print/plates.rs @@ -14,15 +14,20 @@ use vectorcraft_doc::{ColorMode, Document, Node, NodeKind}; use super::{DEFAULT_FREQUENCY, PrintInk, PrintSettings}; /// The inks of a separation of `doc`: the process inks, then one per spot swatch (none when -/// spots print as process), with the options of [`super::PrintOutput::inks`]; and a warning for -/// each option naming no ink. +/// spots print as process), with the options of [`super::PrintOutput::inks`]; and a warning +/// naming the options that name no ink. pub fn print_inks(doc: &Document, set: &PrintSettings) -> (Vec, Vec) { let out = &set.output; + // Options by ink name, the first for a name winning: looked up, not searched for each ink. + let mut options = std::collections::HashMap::new(); + for o in &out.inks { + options.entry(o.name.as_str()).or_insert(o); + } let list: Vec = plates(doc) .into_iter() .filter(|p| !(p.spot && out.spots_to_process)) .map(|p| { - let o = out.inks.iter().find(|i| i.name == p.name); + let o = options.get(p.name.as_str()).copied(); PrintInk { print: o.is_none_or(|o| o.print), frequency: o.and_then(|o| o.frequency).unwrap_or(DEFAULT_FREQUENCY), @@ -32,17 +37,27 @@ pub fn print_inks(doc: &Document, set: &PrintSettings) -> (Vec, Vec>().join(", ")) - }) - .collect(); + // One warning for all the options naming no ink, each list cut short: the options and the + // inks both come from the file. + let names: BTreeSet<&str> = list.iter().map(|p| p.name.as_str()).collect(); + let unknown: Vec<&str> = out.inks.iter().map(|i| i.name.as_str()).filter(|n| !names.contains(n)).collect(); + let warnings = if unknown.is_empty() { + vec![] + } else { + let few = |all: Vec<&str>| { + let more = all.len().saturating_sub(MAX_NAMED); + let shown = all.into_iter().take(MAX_NAMED).map(|n| format!("`{n}`")).collect::>().join(", "); + if more > 0 { format!("{shown} and {more} more") } else { shown } + }; + let inks = few(list.iter().map(|p| p.name.as_str()).collect()); + vec![format!("there is no ink named {} to print (inks: {inks})", few(unknown))] + }; (list, warnings) } +/// The most names a warning of [`print_inks`] lists. +const MAX_NAMED: usize = 10; + /// The colour settings separations of `doc` convert with: the document's colour spaces /// ([`crate::output::document_cms`]), with the printer profile as their CMYK profile when it is a /// CMYK one. diff --git a/crates/pdf/src/streams.rs b/crates/pdf/src/streams.rs index b2142ace36..8fb57198fe 100644 --- a/crates/pdf/src/streams.rs +++ b/crates/pdf/src/streams.rs @@ -116,7 +116,7 @@ fn hex(data: &[u8]) -> Vec { } /// `data` decoded from base-85 (white space skipped, `z` for four zeros, up to `~>`). -fn base85(data: &[u8]) -> Vec { +fn base85(data: &[u8], max: usize) -> Vec { let (mut out, mut group) = (vec![], vec![]); let flush = |group: &mut Vec, out: &mut Vec| { let n = group.len(); @@ -128,6 +128,10 @@ fn base85(data: &[u8]) -> Vec { group.clear(); }; for &c in data.iter().take_while(|c| **c != b'~') { + // Past `max` the caller refuses it: stop growing (a `z` is four bytes from one). + if out.len() > max { + break; + } match c { b'z' if group.is_empty() => out.extend([0; 4]), b'!'..=b'u' => { @@ -144,13 +148,15 @@ fn base85(data: &[u8]) -> Vec { } /// The most data of `len` bytes can grow to through `filters`: 1,032 times through Flate (its -/// largest ratio), 3,641 through LZW (4,096 bytes from a 9-bit code), 64 through run-length. +/// largest ratio), 3,641 through LZW (4,096 bytes from a 9-bit code), 64 through run-length, 4 +/// through ASCII85 (`z`). fn most_after(len: usize, filters: &[Name<'_>]) -> u128 { filters.iter().fold(len as u128, |n, f| { n.saturating_mul(match f.as_ref() { b"FlateDecode" | b"Fl" => 1032, b"LZWDecode" | b"LZW" => 3641, b"RunLengthDecode" | b"RL" => 64, + b"ASCII85Decode" | b"A85" => 4, _ => 1, }) }) @@ -213,7 +219,7 @@ fn decode(data: &[u8], dict: &Dict<'_>, keep: bool) -> Result>, T b"LZWDecode" | b"LZW" => lzw(&data, early, max), b"RunLengthDecode" | b"RL" => Some(run_length(&data, max)), b"ASCIIHexDecode" | b"AHx" => Some(hex(&data)), - b"ASCII85Decode" | b"A85" => Some(base85(&data)), + b"ASCII85Decode" | b"A85" => Some(base85(&data, max)), _ => None, }; match out { @@ -740,8 +746,10 @@ mod tests { #[test] fn the_decoders_read_what_the_specification_writes() { assert_eq!(hex(b"48 65 6c6C6\n>junk"), b"Hell`"); - assert_eq!(base85(b"87cURD]i,\"Ebo80~>"), b"Hello World!"); - assert_eq!(base85(b"z!!~>"), [0, 0, 0, 0, 0]); + assert_eq!(base85(b"87cURD]i,\"Ebo80~>", usize::MAX), b"Hello World!"); + assert_eq!(base85(b"z!!~>", usize::MAX), [0, 0, 0, 0, 0]); + // Zeros past the allowance are not written: a little over it, and the caller refuses it. + assert!(base85(&[b'z'; 1 << 20], 1000).len() <= 1004); assert_eq!(run_length(&[2, b'a', b'b', b'c', 254, b'x', 128, b'q'], MAX_DECODED), b"abcxxx"); let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); std::io::Write::write_all(&mut e, &[7; 1000]).unwrap(); diff --git a/crates/pdf/src/tests/colorize.rs b/crates/pdf/src/tests/colorize.rs index 91ee3d5f22..406ae08b81 100644 --- a/crates/pdf/src/tests/colorize.rs +++ b/crates/pdf/src/tests/colorize.rs @@ -179,3 +179,15 @@ fn a_pixelated_colorized_image_asks_viewers_not_to_smooth_it() { assert_eq!(String::from_utf8_lossy(&out).contains("/Interpolate"), !pixelated, "pixelated: {pixelated}"); } } + +/// Ink options naming no ink give one warning, its lists cut short, however many there are. +#[test] +fn ink_options_naming_no_ink_give_one_short_warning() { + let d = doc(ColorMode::Cmyk, None); + let inks: Vec = (0..10_000).map(|i| serde_json::json!({"name": format!("Missing {i}")})).collect(); + let settings: PrintSettings = serde_json::from_value(serde_json::json!({"output": {"mode": "separations", "inks": inks}})).unwrap(); + let (list, warnings) = print_inks(&d, &settings); + assert!(list.iter().any(|i| i.name == "Cyan")); + assert_eq!(warnings.len(), 1); + assert!(warnings[0].contains("`Missing 0`") && warnings[0].contains("and 9990 more") && warnings[0].len() < 500, "{}", warnings[0]); +} diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index ab70e4521c..9e012e330a 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -158,3 +158,32 @@ fn codecs_the_writer_lacks_are_zip_with_a_warning() { // The codecs of other kinds of images say nothing. assert!(pdf(&png, json!({"mono": {"compression": "ccittG4"}})).1.is_empty()); } + +/// A PNG whose header declares `w` × `h` grey pixels and whose data holds a few: what a file can +/// declare, not what it holds. +fn declared_png(w: u32, h: u32) -> Vec { + let chunk = |kind: &[u8], data: &[u8]| { + let mut crc = flate2::Crc::new(); + crc.update(kind); + crc.update(data); + [&(data.len() as u32).to_be_bytes()[..], kind, data, &crc.sum().to_be_bytes()].concat() + }; + let ihdr = [&w.to_be_bytes()[..], &h.to_be_bytes(), &[8, 0, 0, 0, 0]].concat(); + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut z, &[0; 64]).unwrap(); + let idat = z.finish().unwrap(); + [&b"\x89PNG\r\n\x1a\n"[..], &chunk(b"IHDR", &ihdr), &chunk(b"IDAT", &idat), &chunk(b"IEND", &[])].concat() +} + +/// Images a document holds are decoded within the decode allowance: a header declaring billions of +/// pixels is refused before they are allocated, as an opacity mask and when recoded. +#[test] +fn images_declaring_more_than_the_allowance_are_not_decoded() { + let png = declared_png(60_000, 60_000); + let blob = ImageBlob::new("image/png", png.clone()); + assert_eq!(crate::images::mask_alpha(&blob, 60_000, 60_000, false), None); + assert_eq!(crate::images::mask_alpha(&blob, 2, 2, false), None, "another size is not decoded at all"); + let c: CompressionSettings = serde_json::from_value(json!({"gray": {"downsample": "bicubic", "ppi": 72, "abovePpi": 100}})).unwrap(); + let r = crate::images::recode(&png, (10.0, 10.0), &c, false, None); + assert!(r.image.is_none(), "kept as it is"); +} diff --git a/crates/pdf/src/tests/editing.rs b/crates/pdf/src/tests/editing.rs index 69dbbc538b..9cc77ff689 100644 --- a/crates/pdf/src/tests/editing.rs +++ b/crates/pdf/src/tests/editing.rs @@ -131,18 +131,25 @@ fn pdf_a_carries_no_editing_data() { /// A tiny PDF made of the given objects (numbered from 1), with the cross-reference table written. fn raw_pdf(objects: &[String]) -> Vec { + raw_pdf_bytes(objects.iter().map(|o| o.clone().into_bytes())) +} + +/// [`raw_pdf`] of objects that may hold binary data. +fn raw_pdf_bytes(objects: impl IntoIterator>) -> Vec { let mut out = b"%PDF-1.7\n".to_vec(); let mut offsets = Vec::new(); - for (i, body) in objects.iter().enumerate() { + for (i, body) in objects.into_iter().enumerate() { offsets.push(out.len()); - out.extend_from_slice(format!("{} 0 obj\n{body}\nendobj\n", i + 1).as_bytes()); + out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + out.extend_from_slice(&body); + out.extend_from_slice(b"\nendobj\n"); } let xref = out.len(); - out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes()); - for at in offsets { + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes()); + for at in &offsets { out.extend_from_slice(format!("{at:010} 00000 n \n").as_bytes()); } - out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes()); + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes()); out } @@ -168,6 +175,36 @@ fn a_name_tree_node_shared_by_many_kids_is_searched_once() { assert_eq!((e.data.as_slice(), e.intact), (&b"hello"[..], true)); } +#[test] +fn pages_sharing_a_large_content_stream_are_hashed_within_a_budget() { + use std::io::Write; + // 300 pages showing one stream of 1 MiB of spaces: 300 MiB decoded, past the 256 MiB hashed. + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); + z.write_all(&vec![b' '; 1 << 20]).unwrap(); + let packed = z.finish().unwrap(); + let pages = 300; + let kids: String = (0..pages).map(|i| format!("{} 0 R ", 7 + i)).collect(); + let mut objects = vec![ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + format!("<< /Type /Pages /Kids [{kids}] /Count {pages} >>"), + "<< /Names [(a) 4 0 R] >>".to_string(), + format!("<< /Type /Filespec /UF ({EDITING_FILE}) /Desc (hash 0000000000000000) /EF << /F 5 0 R >> >>"), + "<< /Length 5 >>\nstream\nhello\nendstream".to_string(), + String::new(), + ]; + for _ in 0..pages { + objects.push("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] /Contents 6 0 R >>".to_string()); + } + let mut stream = format!("<< /Length {} /Filter /FlateDecode >>\nstream\n", packed.len()).into_bytes(); + stream.extend_from_slice(&packed); + stream.extend_from_slice(b"\nendstream"); + let bytes = raw_pdf_bytes(objects.into_iter().enumerate().map(|(i, o)| if i == 5 { stream.clone() } else { o.into_bytes() })); + let start = std::time::Instant::now(); + let e = editing(&bytes).unwrap(); + assert_eq!((e.data.as_slice(), e.intact), (&b"hello"[..], false)); + assert!(start.elapsed() < std::time::Duration::from_secs(60), "{:?}", start.elapsed()); +} + #[test] fn direct_name_tree_kids_are_all_searched() { // Direct kids report the object holding them as their id; none of them may be taken as seen. diff --git a/crates/pdf/src/tests/import_layers.rs b/crates/pdf/src/tests/import_layers.rs index 8ddeb2f834..86e1a88fb1 100644 --- a/crates/pdf/src/tests/import_layers.rs +++ b/crates/pdf/src/tests/import_layers.rs @@ -448,3 +448,15 @@ fn private_data_reads_without_a_pdf_part_that_cant_be_read() { assert!(illustrator_data_without_pdf_part(&pdf, None).is_none(), "{odd}"); } } + +/// Art in ordinary tags nested inside a layer's sequence goes to that layer; the group is kept +/// with each level, not searched for through the tags for each object. +#[test] +fn art_deep_in_tags_inside_a_layer_reaches_it() { + let (objs, catalog, ids) = groups(1, "/OFF [{B}]"); + let content = format!("/OC /MC0 BDC {} 1 0 0 rg 10 10 30 30 re f {} EMC 0 1 0 rg 0 0 5 5 re f", "/Span BMC ".repeat(200), "EMC ".repeat(200)); + let page = PdfPage { resources: format!("/Properties << /MC0 {} 0 R /MC1 {} 0 R >>", ids[0], ids[1]), ..PdfPage::new(100.0, 100.0, &content) }; + let d = import(&pdf_with_catalog(&[page], &[&objs[0], &objs[1]], &catalog, None)).unwrap(); + let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); + assert_eq!(colors(shapes), [Color::rgb(1.0, 0.0, 0.0)]); +} diff --git a/crates/pdf/src/tests/output.rs b/crates/pdf/src/tests/output.rs index 36eb939ffd..f7732821c1 100644 --- a/crates/pdf/src/tests/output.rs +++ b/crates/pdf/src/tests/output.rs @@ -161,6 +161,70 @@ fn spot_alternates_and_device_n_gradient_inks_are_written_as_the_document_holds_ assert!(text.contains("/C0[0 0 0.75]/C1[0.75 0.04 0]"), "the stops' C75, K4 and 75% Gold are written as they are"); } +/// A spot swatch's Separation space with alternate C0 M20 Y80 K10 under `colorant` (a PDF name). +fn gold_separation(colorant: &str) -> String { + format!("[/Separation{colorant}/DeviceCMYK<>]") +} + +#[test] +fn spot_inks_named_all_or_none_are_written_under_names_of_their_own() { + let solid = |name: &str, color: Color| Paint::Solid { color, swatch: Some(name.into()), tint: 0.5 }; + let gold = Color::cmyk(0.0, 0.2, 0.8, 0.1); + let rect = |d: &mut Document, i: usize, y: f64, paint: Paint, stroke: Paint| { + let l = d.layers[0].id; + let n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, y, 140.0, y + 20.0)), Appearance::basic(paint, stroke, 1.0)); + d.insert(Some(l), i, n).unwrap(); + }; + let stop = |offset: f32, ink: &str, tint: f32| { + let mut s = GradientStop::new(offset, gold.tinted(tint)); + s.swatch = Some(ink.into()); + s.tint = tint; + s + }; + let gradient = |stops| Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + for (name, colorant) in [("All", "/All#20Spot"), ("None", "/None#20Spot")] { + let mut d = doc(ColorMode::Cmyk, &[]); + for ink in [name, "Gold"] { + d.swatches.push(Swatch { name: ink.into(), paint: Paint::solid(gold), global: true, spot: true }); + } + // A fill of the spot ink with a Registration stroke, a gradient of the spot ink's tints, + // and a gradient from Gold to the spot ink. + let registration = solid(vectorcraft_color::swatch::REGISTRATION, Color::cmyk(1.0, 1.0, 1.0, 1.0)); + rect(&mut d, 0, 10.0, solid(name, gold), registration); + rect(&mut d, 1, 40.0, gradient(vec![stop(0.0, name, 1.0), stop(1.0, name, 0.25)]), Paint::None); + rect(&mut d, 2, 70.0, gradient(vec![stop(0.0, "Gold", 1.0), stop(1.0, name, 1.0)]), Paint::None); + let text = String::from_utf8_lossy(&export(&d, &PdfOptions::uncompressed()).unwrap()).into_owned(); + let spaces = text.matches(&format!("[/Separation{colorant}/")).count(); + assert!(spaces > 0 && text.matches(&gold_separation(colorant)).count() == spaces, "{name}: {text}"); + assert!(!text.contains(&gold_separation(&format!("/{name}"))), "{name} is not the colorant: {text}"); + assert!(text.contains("[/Separation/All/DeviceCMYK<<"), "Registration prints on every plate: {text}"); + assert!(text.contains(&format!("[/DeviceN[/Gold{colorant}]")), "{name}: {text}"); + } + + // A spot swatch already named All Spot keeps its name, and All is numbered past it. + let mut d = doc(ColorMode::Cmyk, &[]); + for name in ["All", "All Spot"] { + d.swatches.push(Swatch { name: name.into(), paint: Paint::solid(gold), global: true, spot: true }); + } + rect(&mut d, 0, 10.0, solid("All", gold), solid("All Spot", gold)); + let text = String::from_utf8_lossy(&export(&d, &PdfOptions::uncompressed()).unwrap()).into_owned(); + assert!(text.contains(&gold_separation("/All#20Spot#202")) && text.contains(&gold_separation("/All#20Spot")), "{text}"); +} + +#[test] +fn a_lab_spot_ink_named_all_keeps_its_lab_alternate() { + let mut d = doc(ColorMode::Cmyk, &[]); + let lab = Color::Lab { l: 60.0, a: 40.0, b: 50.0 }; + d.swatches.push(Swatch { name: "All".into(), paint: Paint::solid(lab), global: true, spot: true }); + let fill = Paint::Solid { color: lab, swatch: Some("All".into()), tint: 1.0 }; + let l = d.layers[0].id; + let n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Appearance::basic(fill, Paint::None, 0.0)); + d.insert(Some(l), 0, n).unwrap(); + let text = String::from_utf8_lossy(&export(&d, &PdfOptions::uncompressed()).unwrap()).into_owned(); + assert!(text.contains("[/Separation/All#20Spot[/Lab<<"), "{text}"); + assert!(!text.contains("[/Separation/All/") && !text.contains("[/Separation/All["), "{text}"); +} + /// The uncompressed PDF of a CMYK document whose rectangle is filled with gradient `stops` /// (Perceptual when `perceptual`), with spot swatch "Gold" (C0 M20 Y80 K10). fn gold_gradient_pdf(stops: Vec, perceptual: bool) -> String { diff --git a/crates/render/src/blobs.rs b/crates/render/src/blobs.rs index 4ff88e36be..88d7216380 100644 --- a/crates/render/src/blobs.rs +++ b/crates/render/src/blobs.rs @@ -38,8 +38,17 @@ pub(crate) fn blob_pixmap(blob: &vectorcraft_doc::ImageBlob, touch: bool) -> Opt paint::add_decode_failures(1); return None; } - // Decoded outside the lock: other renderers carry on meanwhile. - let pm = match lut.and_then(|lut| ink::cmyk_pixmap(blob, &lut)) { + // Decoded outside the lock: other renderers carry on meanwhile. The inks and the pixels + // shown from them are admitted together, as other images are, before either is made: + // without room the image is read as other images are (which reduces it). + let room = || { + image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())) + .with_guessed_format() + .ok() + .and_then(|r| r.into_dimensions().ok()) + .is_some_and(|(w, h)| paint::within_allowance(w, h.saturating_mul(2))) + }; + let pm = match lut.filter(|_| room()).and_then(|lut| ink::cmyk_pixmap(blob, &lut)) { Some(pm) => pm, None => match paint::decode_pixmap_or_why(&blob.bytes) { Ok(pm) => pm, diff --git a/crates/render/src/encode/tga.rs b/crates/render/src/encode/tga.rs index abac01dba4..031b5f1b61 100644 --- a/crates/render/src/encode/tga.rs +++ b/crates/render/src/encode/tga.rs @@ -34,7 +34,8 @@ pub fn encode(rgba: &[u8], width: u32, height: u32, o: &TgaOptions) -> Result().0; diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 9512d89d62..987499710f 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -378,6 +378,9 @@ impl Renderer { /// What [`Self::draw_object_fx`] draws inside the object's transparency group. fn draw_object_fx_art(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc, cache: bool) { + if !self.charge_fx_instance(f.doc, a) { + return; + } let art = self.fx_art(f.doc, a, cache); // Art the cache did not keep is made again in the next frame. let kept = cache && self.fx_arts.get(&(Arc::as_ptr(a) as usize), self.stamp).is_some_and(|e| Arc::ptr_eq(&e.1, &art)); @@ -410,6 +413,19 @@ impl Renderer { self.made_again = outer; } + /// Whether the frame has room for the art of `a` when it is a symbol instance, charged to the + /// frame's symbol budget as an instance without effects is (`draw_node`): an instance whose + /// effects reshape its art draws through here, and nested instances would otherwise expand + /// without a limit. True for any other object. + pub(crate) fn charge_fx_instance(&mut self, doc: &vectorcraft_doc::Document, a: &Node) -> bool { + let NodeKind::SymbolInstance { symbol, .. } = &a.kind else { return true }; + let count = doc.symbols.iter().find(|s| &s.name == symbol).map_or(0, |s| s.art.count() as u64); + let mut used = self.symbol_nodes; + let room = vectorcraft_doc::charge_symbol_art(&mut used, count, || ((), count)).is_some(); + self.symbol_nodes = used; + room + } + /// The art [`Self::draw_object_fx`] draws for `a` (cached by `Arc` identity when `cache`): /// reshaped by its geometry effects, else type, images and paths as themselves and the others /// as their evaluated art (groups and layers: [`effects::evaluate_container`], keeping their diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 218ef06205..4d619e0454 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -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); } diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index 25f6260914..79455cd75b 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -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> { - 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> { + 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), diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 81a91d8ea8..e1ded30c8e 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1322,6 +1322,20 @@ fn a_kept_decoded_image_is_drawn_without_decoding_it() { assert!(!image_cached(&cmyk)); } +/// A CMYK image's inks and the pixels shown from them are admitted against the decode allowance +/// before either is made: past it, the image is read as other images are (reduced), not whole. +#[test] +fn cmyk_images_past_the_allowance_are_not_decoded_whole() { + use vectorcraft_doc::ImageBlob; + use vectorcraft_doc::cmyk::Inks; + let cmyk = ImageBlob::cmyk_tiff(&Inks::new(64, 48, [11, 22, 33, 44].repeat(64 * 48)).unwrap()).unwrap(); + let whole = with_allowance(1 << 20, || crate::blobs::blob_pixmap(&cmyk, false)).map(|(_, pm)| (pm.width(), pm.height())); + assert_eq!(whole, Some((64, 48)), "within the allowance, whole"); + let other = ImageBlob::cmyk_tiff(&Inks::new(64, 48, [12, 22, 33, 44].repeat(64 * 48)).unwrap()).unwrap(); + let small = with_allowance(64 * 48 * 4 - 1, || crate::blobs::blob_pixmap(&other, false)).map(|(_, pm)| (pm.width(), pm.height())); + assert_ne!(small, Some((64, 48)), "past it, not decoded whole"); +} + /// An image drawn larger than its pixels samples smoothly, or with `smooth_images` off each screen /// pixel takes its nearest image pixel (Pixel Preview with File Handling › Display Bitmaps as /// Anti-aliased Images off, #394). diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index 8b3648604c..f0c4b40e1f 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -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> = (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"); +} diff --git a/crates/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index 85f7505dde..edc044f0ad 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -884,3 +884,17 @@ fn darkness_adjusts_gradient_stop_colors_before_interpolation() { } } } + +/// A symbol instance with object effects is charged to the frame's symbol budget like one +/// without: past the budget it isn't expanded. +#[test] +fn symbol_instances_with_effects_are_charged_to_the_symbol_budget() { + let d = symbol_doc(vec![fx("distort.roughen", json!({}))]); + let inst = d.layers[0].children().unwrap()[0].clone(); + let mut r = Renderer::new(); + r.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES - 1; + assert!(r.charge_fx_instance(&d, &inst), "one object fits"); + assert_eq!(r.symbol_nodes, vectorcraft_doc::MAX_SYMBOL_NODES); + assert!(!r.charge_fx_instance(&d, &inst), "the next does not"); + assert_eq!(r.symbol_nodes, vectorcraft_doc::MAX_SYMBOL_NODES); +} diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 6ef3b64ddf..44b8c696e4 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -28,6 +28,7 @@ flate2 = { workspace = true } image = { workspace = true } # Colour / transform / length parsing for the fallback (MIT OR Apache-2.0; already used by usvg). svgtypes = "0.16" +simplecss = "0.2.2" [dev-dependencies] # Reading embedded font subsets back. diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index 747dae25bb..1b19da8019 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -4,7 +4,7 @@ //! here, colours are `#rrggbb` (or `rgba()` where CSS has no separate opacity), gradients take the //! stops SVG export writes, and numbers go through [`fmt_num`]. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use serde::{Deserialize, Serialize}; use vectorcraft_color::{BlendMode, Color, GradientKind, GradientPaint, Paint}; @@ -26,7 +26,28 @@ pub(crate) fn declarations<'a>(props: impl IntoIterator String { - format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) + quoted(s, '"') +} + +/// `s` as a CSS string in `quote`s. A backslash and the quote are escaped, and so are line breaks +/// and other control characters (a newline would end the string and let the rest be rules) and +/// `<` and `>` (which could end a `"), r#""w\d \"\3c /style\3e ""#); + assert_eq!(css_string("wght"), "\"wght\""); + } } diff --git a/crates/svg/src/entities.rs b/crates/svg/src/entities.rs index a055e55fd5..d1eb4cfef7 100644 --- a/crates/svg/src/entities.rs +++ b/crates/svg/src/entities.rs @@ -10,9 +10,14 @@ const MAX_EXPANDED: usize = 16 << 20; /// How deep entities that refer to entities are followed (the reader's own limit is lower). const MAX_NESTING: u32 = 16; -/// The internal general entities declared in `svg`: name → value. -fn declared(svg: &str) -> HashMap<&str, &str> { - let mut map = HashMap::new(); +/// The longest entity name a reference is looked for with ([`references`]). +const MAX_NAME: usize = 256; + +/// The internal general entities declared in `svg`: name → every value declared for it. Text that +/// only looks like a declaration (in a comment, or in another entity's value) is kept too: the +/// largest value counts, so it can only make the estimate larger. +fn declared(svg: &str) -> HashMap<&str, Vec<&str>> { + let mut map: HashMap<&str, Vec<&str>> = HashMap::new(); for (at, _) in svg.match_indices(" HashMap<&str, &str> { let rest = rest.trim_start(); let Some(quote) = rest.chars().next().filter(|q| matches!(q, '"' | '\'')) else { continue }; let Some(value) = rest.get(1..).and_then(|r| r.split_once(quote)).map(|(v, _)| v) else { continue }; - map.entry(name).or_insert(value); + map.entry(name).or_default().push(value); } map } @@ -34,27 +39,31 @@ fn references(text: &str) -> impl Iterator { text.match_indices('&').filter_map(|(at, _)| { let rest = text.get(at + 1..)?; // Look no further than the longest name: a file of `&`s without `;` would be read quadratically. - let end = rest.bytes().take(257).position(|b| b == b';')?; + let end = rest.bytes().take(MAX_NAME + 1).position(|b| b == b';')?; let name = rest.get(..end)?; - (!name.is_empty() && name.len() <= 256 && !name.starts_with('#') && !name.contains(char::is_whitespace)).then_some(name) + (!name.is_empty() && name.len() <= MAX_NAME && !name.starts_with('#') && !name.contains(char::is_whitespace)).then_some(name) }) } /// What entity `name` expands to (bytes), references in its value followed. -fn expanded<'a>(name: &'a str, entities: &HashMap<&'a str, &'a str>, memo: &mut HashMap<&'a str, usize>, depth: u32) -> usize { +fn expanded<'a>(name: &'a str, entities: &HashMap<&'a str, Vec<&'a str>>, memo: &mut HashMap<&'a str, usize>, depth: u32) -> usize { if let Some(n) = memo.get(name) { return *n; } - let Some(value) = entities.get(name) else { return 0 }; + let Some(values) = entities.get(name) else { return 0 }; if depth >= MAX_NESTING { return usize::MAX; } - let mut total = value.len(); - for inner in references(value) { - total = total.saturating_add(expanded(inner, entities, memo, depth + 1)); + let mut most = 0usize; + for value in values { + let mut total = value.len(); + for inner in references(value) { + total = total.saturating_add(expanded(inner, entities, memo, depth + 1)); + } + most = most.max(total); } - memo.insert(name, total); - total + memo.insert(name, most); + most } /// Whether the references to the entities `svg` declares expand to more than [`MAX_EXPANDED`] @@ -64,6 +73,10 @@ pub(crate) fn expansion_too_large(svg: &str) -> bool { if entities.is_empty() { return false; } + // A reference to a longer name isn't looked for: refuse such a declaration instead. + if entities.keys().any(|name| name.len() > MAX_NAME) { + return true; + } let mut memo = HashMap::new(); let mut total = 0usize; for name in references(svg) { @@ -96,4 +109,17 @@ mod tests { assert!(!expansion_too_large(&ersands)); assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed()); } + + #[test] + fn declarations_in_comments_and_long_names_cannot_hide_a_large_entity() { + let big = "x".repeat(1 << 20); + let refs = "&a;".repeat(20); + let commented = format!(" -->]>"); + assert!(expansion_too_large(&commented)); + let in_value = format!("\">]>"); + assert!(expansion_too_large(&in_value)); + let long = "n".repeat(MAX_NAME + 1); + let long_name = format!("]>"); + assert!(expansion_too_large(&long_name)); + } } diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index d2b18c39b2..7be7483919 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -1,4 +1,4 @@ -use super::output::{sanitize_id, valid_xml_value, xml_attr_escape}; +use super::output::{sanitize_id, valid_xml_value, xml_attr_escape, xml_attr_valid}; use super::paint::{StrokePlan, has_raster, pixel_gradient}; use super::text::OUTLINE_TOLERANCE; use super::{ @@ -489,7 +489,10 @@ impl Writer<'_> { self.layer_nest += layer; match n.url().filter(|_| n.visible && !self.anonymous) { Some(url) => { - self.line(&format!("", xml_escape(url))); + if !valid_xml_value(url) { + self.warn("Link URLs containing invalid XML characters had those characters removed"); + } + self.line(&format!("", xml_attr_valid(url))); self.depth += 1; self.node_body(n); self.depth -= 1; diff --git a/crates/svg/src/export/output.rs b/crates/svg/src/export/output.rs index cc7680e902..01d33c833b 100644 --- a/crates/svg/src/export/output.rs +++ b/crates/svg/src/export/output.rs @@ -19,6 +19,12 @@ pub(super) fn xml_text(s: &str) -> String { xml_escape(&s) } +/// `s` without the characters XML 1.0 does not allow, ready for a double-quoted attribute. +pub(super) fn xml_attr_valid(s: &str) -> String { + let s: String = s.chars().filter(|c| valid_xml_value(c.encode_utf8(&mut [0; 4]))).collect(); + xml_attr_escape(&s) +} + pub(super) fn valid_xml_value(s: &str) -> bool { s.chars().all(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{d7ff}' | '\u{e000}'..='\u{fffd}' | '\u{10000}'..='\u{10ffff}')) } diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index bab0cf3270..5fc015039f 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -1,4 +1,4 @@ -use super::output::xml_text; +use super::output::{xml_attr_valid, xml_text}; use super::{ Affine, AppearanceItem, Arc, BTreeSet, BezPath, BlendMode, CharStyle, FillRule, FontDb, FontFace, GradientKind, HashMap, Justify, Node, NodeId, NodeKind, Paint, PathData, Props, Rect, StrokeAlign, Styling, TextKind, TextObject, Writer, base64_encode, css, css_string, fmt_num, @@ -163,7 +163,7 @@ impl Writer<'_> { // Glyphs bent along a path (joined scripts on a curve) can only be outlines: the group // names its text for screen readers and search. let label = if lay.glyphs.iter().any(|g| g.bend.is_some()) { - format!(" role=\"img\" aria-label=\"{}\"", xml_escape(&t.plain_text())) + format!(" role=\"img\" aria-label=\"{}\"", xml_attr_valid(&t.plain_text())) } else { String::new() }; diff --git a/crates/svg/src/glyph.rs b/crates/svg/src/glyph.rs index 9c0ac5d5a5..c019f9b0a8 100644 --- a/crates/svg/src/glyph.rs +++ b/crates/svg/src/glyph.rs @@ -99,10 +99,18 @@ fn glyph(svg: &str, id: &str, color: &str) -> Option { // Edits: byte ranges to cut and what to put in their place, in order. let mut edits: Vec<(Range, String)> = vec![]; // Cut with the left-out elements: images of SVG documents, as the table asks (a glyph draws no - // documents inside it). Their link is `href`, else `xlink:href`, as the importer reads it. + // documents inside it). Their link is `href`, else `xlink:href`, as the importer reads it. Any + // data URL not typed as a raster goes too: the importer reads an untyped one (`text/plain`) as + // SVG, SVGZ as well, when its bytes aren't a raster. let svg_image = |n: &roxmltree::Node| { let href = n.attribute("href").or_else(|| n.attribute(("http://www.w3.org/1999/xlink", "href"))); - n.tag_name().name() == "image" && href.and_then(|h| h.trim_start().get(..14)).is_some_and(|v| v.eq_ignore_ascii_case("data:image/svg")) + let data = href.map(|h| h.trim_start()).filter(|h| h.get(..5).is_some_and(|v| v.eq_ignore_ascii_case("data:"))); + let raster = |h: &str| { + ["data:image/png", "data:image/jpeg", "data:image/jpg", "data:image/gif", "data:image/webp"] + .iter() + .any(|t| h.get(..t.len()).is_some_and(|v| v.eq_ignore_ascii_case(t)) && h[t.len()..].starts_with([';', ','])) + }; + n.tag_name().name() == "image" && data.is_some_and(|h| !raster(h)) }; for n in root.descendants().filter(|n| n.is_element() && (LEFT_OUT.contains(&n.tag_name().name()) || svg_image(n))) { edits.push((n.range(), String::new())); @@ -172,13 +180,18 @@ fn edited(svg: &str, range: Range, edits: &[(Range, String)]) -> O Some(out) } -/// `n` as art of its own, made from `doc` (the glyph's document): no ids (they aren't a document's), -/// its members' neither, and its images holding the pixels `doc` keeps for them, named by their -/// content. A linked image, or one whose pixels `doc` doesn't hold, is left out (`None` when `n` -/// is one). +/// `n` as art of its own, made from `doc` (the glyph's document): no ids (they aren't a document's) +/// or links, its members' neither, and its images holding the pixels `doc` keeps for them, named +/// by their content. A linked image, or one whose pixels `doc` doesn't hold, is left out (`None` +/// when `n` is one). fn own_art(n: &Node, doc: &Document) -> Option { let mut n = n.clone(); n.id = NodeId(u64::MAX); + // A glyph is drawn, not followed: an ``'s link (a `javascript:` one too) would be written + // as a link again when its text is exported as outlines. + if n.url().is_some() { + n.edit_attrs(|a| a.url.clear()); + } if let NodeKind::Image(im) = &mut n.kind { // A glyph's images are embedded: a link (to no file of the font's) shows nothing. let blob = doc.images.get(&im.key).filter(|b| im.link.is_none() && !b.bytes.is_empty())?; diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 18f4f088d6..11795b83fa 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -113,7 +113,7 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions, max_nodes: usize) -> Resul let Some(height) = depth::height(&xml, depth::MAX_ELEMENT_DEPTH) else { return Err(too_deep()); }; - let (svg, found) = prepass(svg, &scan.markers, &xml, opts); + let (svg, found) = prepass(svg, &scan.markers, &xml, opts)?; // The prepass's edits are in the text: the XML is read again only when it made any. let xml = match &svg { Cow::Borrowed(_) => xml, @@ -126,7 +126,8 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions, max_nodes: usize) -> Resul let units = RootUnits::of(xml.root_element()); let root_name = root_layer_name(xml.root_element()); let mut warnings = found.warnings; - let (src, slots) = text::prepare(svg, &xml, units.dpi, &mut warnings); + let text_xml = found.text_source.as_deref().map(parse).transpose()?; + let (src, slots) = text::prepare(svg, &xml, text_xml.as_ref(), units.dpi, &mut warnings); let files = found.files; let tree = { let opt = usvg::Options { @@ -153,6 +154,9 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions, max_nodes: usize) -> Resul hidden: found.hidden, uses: found.uses, symbols: HashMap::new(), + symbol_names: HashSet::new(), + symbol_suffixes: HashMap::new(), + pattern_suffixes: HashMap::new(), blends: fx::blends(&xml, &scan.markers), files, non_scaling: found.non_scaling, @@ -161,6 +165,7 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions, max_nodes: usize) -> Resul foreign: found.foreign, sublayers: found.sublayers, sublayer_groups: HashSet::new(), + ellipses: found.ellipses, screen: k, converted_nodes: 1, max_nodes, @@ -302,6 +307,11 @@ struct Importer { uses: HashMap, /// The symbols made so far, by `` id. symbols: HashMap, + /// The names of the symbols made so far. + symbol_names: HashSet, + /// Where the suffixes of each symbol and pattern name base go on from (`unique_name`). + symbol_suffixes: HashMap, + pattern_suffixes: HashMap, /// Blend modes of the shadows and glows our export wrote, by filter id ([`fx::blends`]). blends: HashMap, /// The files `` elements link to. @@ -318,6 +328,8 @@ struct Importer { sublayers: HashSet, /// The groups made of them, made sublayers where they sit in a layer ([`promote_sublayers`]). sublayer_groups: HashSet, + /// Ids of the `` and `` elements ([`prepass`]). + ellipses: HashSet, /// Points per screen pixel (the root's user unit before its `viewBox`): what a non-scaling /// stroke's width is measured in. screen: f64, diff --git a/crates/svg/src/import/convert.rs b/crates/svg/src/import/convert.rs index 40c2cf5779..92f5234ee6 100644 --- a/crates/svg/src/import/convert.rs +++ b/crates/svg/src/import/convert.rs @@ -1,4 +1,6 @@ -use super::{Affine, Arc, BezPath, BlendMode, Color, FillRule, GradientStop, HashMap, Node, Point, XNode, roxmltree}; +use super::{Affine, Arc, BezPath, BlendMode, Color, FillRule, GradientStop, HashMap, Node, PathData, Point, XNode, roxmltree}; +use vectorcraft_geom::path::{Anchor, AnchorKind, SubPath}; +use vectorcraft_geom::shapes::KAPPA; /// `n` with every object id (its descendants' and its mask art's too) zeroed, to compare art. pub(super) fn without_ids(n: &Node) -> Node { @@ -13,15 +15,20 @@ pub(super) fn without_ids(n: &Node) -> Node { n } -/// `base`, or `base 2`, `base 3`… : the first that isn't `taken`. -pub(super) fn unique_name(base: &str, taken: impl Fn(&str) -> bool) -> String { - let mut name = base.to_string(); - let mut k = 2; - while taken(&name) { - name = format!("{base} {k}"); - k += 1; +/// `base`, or `base 2`, `base 3`… : the first that isn't `taken`. `next` keeps where each base's +/// suffixes go on from, so names sharing a base take linear work in all. +pub(super) fn unique_name(base: &str, next: &mut HashMap, taken: impl Fn(&str) -> bool) -> String { + if !taken(base) { + return base.to_string(); + } + let k = next.entry(base.to_string()).or_insert(2); + loop { + let name = format!("{base} {k}"); + *k += 1; + if !taken(&name) { + return name; + } } - name } /// The stops our export added for midpoints (`data-vc-midpoint`), by gradient id: for each stop, @@ -135,6 +142,50 @@ pub(super) fn bezpath(p: &usvg::tiny_skia_path::Path, m: Affine) -> BezPath { bp } +/// The path usvg makes of a `` or `` (`p`: one closed outline of arcs from the +/// right end of the horizontal axis round through the bottom) as the ellipse VectorCraft draws: four +/// smooth anchors on the axes in the same order, each quarter a cubic with handles [`KAPPA`] of the +/// radii long, the ellipse export writes as ``. `None` when `p` is not such an outline. +pub(super) fn drawn_ellipse(p: &usvg::tiny_skia_path::Path) -> Option { + use usvg::tiny_skia_path::PathSegment as S; + let mut ends = vec![]; + let mut closed = false; + for s in p.segments() { + match s { + S::MoveTo(q) if ends.is_empty() => ends.push(Point::new(q.x as f64, q.y as f64)), + S::LineTo(q) | S::QuadTo(_, q) | S::CubicTo(_, _, q) if !ends.is_empty() && !closed => ends.push(Point::new(q.x as f64, q.y as f64)), + S::Close if !closed => closed = true, + _ => return None, + } + } + let (x0, x1) = ends.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), q| (lo.min(q.x), hi.max(q.x))); + let (y0, y1) = ends.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), q| (lo.min(q.y), hi.max(q.y))); + let (c, rx, ry) = (Point::new((x0 + x1) / 2.0, (y0 + y1) / 2.0), (x1 - x0) / 2.0, (y1 - y0) / 2.0); + // usvg works in f32: points match within a few of its steps at the size of the coordinates, and + // a radius of fewer than two steps does not survive the conversion. + let step = f64::from(f32::EPSILON) * [x0, x1, y0, y1].iter().fold(1.0f64, |m, v| m.max(v.abs())); + let tol = 16.0 * step; + let axes = [Point::new(x1, c.y), Point::new(c.x, y1), Point::new(x0, c.y), Point::new(c.x, y0)]; + let off = 1e-3 + 4.0 * tol / rx.min(ry); + let on_ellipse = |q: &Point| (((q.x - c.x) / rx).powi(2) + ((q.y - c.y) / ry).powi(2) - 1.0).abs() <= off; + if !closed + || rx < 2.0 * step + || ry < 2.0 * step + || ends.first().is_none_or(|s| s.distance(axes[0]) > tol) + || !axes.iter().all(|a| ends.iter().any(|q| q.distance(*a) <= tol)) + || !ends.iter().all(on_ellipse) + { + return None; + } + let anchors = (0..4) + .map(|i| { + let (p, next, prev) = (axes[i], axes[(i + 1) % 4], axes[(i + 3) % 4]); + Anchor { p, h_in: p + (prev - c) * KAPPA, h_out: p + (next - c) * KAPPA, kind: AnchorKind::Smooth } + }) + .collect(); + Some(PathData::single(SubPath::new(anchors, true))) +} + /// The shapes of clip path `cp` on an element whose user space `ts` maps to the document. pub(super) fn clip_shapes(cp: &usvg::ClipPath, ts: Affine) -> Vec<(BezPath, FillRule)> { fn collect(g: &usvg::Group, m: Affine, out: &mut Vec<(BezPath, FillRule)>) { diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 0e0b8127ef..0a0372e3f4 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -1,4 +1,4 @@ -use super::convert::{aff, bezpath, blend, clip_shapes, gradient_stops, is_plain, made_up, rule, uncut, unique_name, without_ids}; +use super::convert::{aff, bezpath, blend, clip_shapes, drawn_ellipse, gradient_stops, is_plain, made_up, rule, uncut, unique_name, without_ids}; use super::layers::filter_names; use super::prepass::link; use super::{ @@ -183,7 +183,10 @@ impl Importer { Some(made) if whole && made.art == without_ids(&art) && made.reuse.allows(xf) => made.name.clone(), Some(_) => return None, None => { - let name = unique_name(self.name_of(&sym), |n| self.doc.symbols.iter().any(|s| s.name == n)); + let base = self.name_of(&sym).to_string(); + let names = &self.symbol_names; + let name = unique_name(&base, &mut self.symbol_suffixes, |n| names.contains(n)); + self.symbol_names.insert(name.clone()); let reuse = Reuse::of(&self.doc, &art); let made = SymbolMade { name: name.clone(), art: without_ids(&art), reuse }; self.doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.clone(), art: Arc::new(art) }); @@ -541,7 +544,8 @@ impl Importer { let art = self.named("", NodeKind::Group { children, clip: true }); let Some(art) = art else { return Paint::None }; let base = if pt.id().is_empty() { "Pattern" } else { pt.id() }; - let name = unique_name(base, |n| self.doc.pattern(n).is_some()); + let doc = &self.doc; + let name = unique_name(base, &mut self.pattern_suffixes, |n| doc.pattern(n).is_some()); let mut def = PatternDef::new(&name, vec![Arc::new(art)]); def.tile = tile; self.doc.patterns.push(def); @@ -601,7 +605,8 @@ impl Importer { if !p.is_visible() { return None; } - let path = PathData::from_bezpath(&bezpath(p.data(), acc)); + let ellipse = if self.ellipses.contains(p.id()) { drawn_ellipse(p.data()) } else { None }; + let path = ellipse.map_or_else(|| PathData::from_bezpath(&bezpath(p.data(), acc)), |e| e.transformed(acc)); if path.is_empty() { return None; } @@ -683,9 +688,10 @@ impl Importer { std::mem::take(&mut self.non_scaling), std::mem::take(&mut self.data), std::mem::take(&mut self.events), + std::mem::take(&mut self.ellipses), ); let art = self.group_node(tree.root(), acc); - (self.links, self.hidden, self.uses, self.labels, self.non_scaling, self.data, self.events) = outer; + (self.links, self.hidden, self.uses, self.labels, self.non_scaling, self.data, self.events, self.ellipses) = outer; art } } @@ -712,6 +718,9 @@ mod tests { hidden: HashSet::new(), uses: HashMap::new(), symbols: HashMap::new(), + symbol_names: HashSet::new(), + symbol_suffixes: HashMap::new(), + pattern_suffixes: HashMap::new(), blends: HashMap::new(), files: Files::default(), non_scaling: HashSet::new(), @@ -720,6 +729,7 @@ mod tests { foreign: HashMap::new(), sublayers: HashSet::new(), sublayer_groups: HashSet::new(), + ellipses: HashSet::new(), screen: 1.0, converted_nodes: 0, max_nodes: 1000, diff --git a/crates/svg/src/import/prepass.rs b/crates/svg/src/import/prepass.rs index 8018138dc6..3f52c4e35f 100644 --- a/crates/svg/src/import/prepass.rs +++ b/crates/svg/src/import/prepass.rs @@ -5,6 +5,8 @@ use super::{ symbol_units, vector_effect, }; +mod id_styles; + /// What usvg would lose, found in the XML before it runs ([`prepass`]). #[derive(Default)] pub(super) struct Found { @@ -28,6 +30,11 @@ pub(super) struct Found { pub(super) scripts: Vec, /// Ids of the `` elements marked as layers ([`marked_layer`]). pub(super) sublayers: HashSet, + /// Ids of the `` and `` elements, which come back as the ellipse VectorCraft + /// draws ([`drawn_ellipse`](super::convert::drawn_ellipse)). + pub(super) ellipses: HashSet, + /// The text importer reads styles from this SVG before tracking IDs are added. + pub(super) text_source: Option, pub(super) warnings: Vec, } @@ -35,8 +42,15 @@ pub(super) struct Found { #[derive(Default)] pub(crate) struct Edits { list: Vec<(std::ops::Range, String)>, + /// These edits assign tracking IDs. + id_edits: Vec<(std::ops::Range, String)>, /// The ids made up so far, by element. ids: HashMap, + /// The numbers `n` of the `{MADE_UP_ID}n` the file names (as an element's id, in a style + /// sheet's `#id` selector or in a `#id` link to no element), read when the first id is made up. + taken: Option>, + /// The number the next made-up id is tried with: the numbers below it are made up or taken. + next: usize, /// Declarations added to elements' `style`s, by element: (where they go, whether the element /// has a `style` attribute, the declarations, XML-escaped). styles: HashMap, @@ -47,7 +61,8 @@ impl Edits { self.list.push((at..at, text)); } - /// The id of element `n` (in `svg`), made up and written in when it has none. + /// The id of element `n` (in `svg`), made up and written in when it has none. A made-up id is + /// one the file does not name ([`named_made_up_ids`]). pub(super) fn id(&mut self, svg: &str, n: XNode) -> String { if let Some(id) = n.attribute("id").filter(|id| !id.is_empty()) { return id.to_string(); @@ -55,8 +70,19 @@ impl Edits { if let Some(id) = self.ids.get(&n.id()) { return id.clone(); } - let id = format!("{MADE_UP_ID}{}", self.ids.len()); - self.set(svg, n, "id", &id); + let taken = self.taken.get_or_insert_with(|| named_made_up_ids(n.document())); + while taken.contains(&self.next) { + self.next += 1; + } + let id = format!("{MADE_UP_ID}{}", self.next); + self.next += 1; + match n.attributes().find(|a| a.name() == "id" && a.namespace().is_none()) { + Some(a) => self.id_edits.push((a.range_value(), id.clone())), + None => { + let at = tag_name_end(svg, n); + self.id_edits.push((at..at, format!(" id=\"{id}\""))); + } + } self.ids.insert(n.id(), id.clone()); id } @@ -84,6 +110,7 @@ impl Edits { /// `svg` with the edits made; overlapping ones and ranges off character boundaries are /// skipped. fn apply(mut self, svg: &str) -> Cow<'_, str> { + self.list.append(&mut self.id_edits); for (at, has_style, decls) in std::mem::take(&mut self.styles).into_values() { self.insert(at, if has_style { decls } else { format!(" style=\"{}\"", decls.strip_prefix(';').unwrap_or(&decls)) }); } @@ -105,6 +132,24 @@ impl Edits { } } +/// The number after each [`MADE_UP_ID`] followed by digits in the attribute values and text of +/// `xml`, read with their character references decoded (numbers too large for a `usize` left out). +fn named_made_up_ids(xml: &roxmltree::Document) -> HashSet { + fn numbers(s: &str) -> impl Iterator + '_ { + s.match_indices(MADE_UP_ID).filter_map(|(at, _)| { + let rest = s.get(at + MADE_UP_ID.len()..)?; + let digits = rest.bytes().take_while(u8::is_ascii_digit).count(); + rest.get(..digits)?.parse().ok() + }) + } + let mut taken = HashSet::new(); + for n in xml.descendants() { + taken.extend(n.attributes().flat_map(|a| numbers(a.value()))); + taken.extend(n.text().filter(|_| n.is_text()).into_iter().flat_map(numbers)); + } + taken +} + /// usvg reads `` and `` as plain groups, drops what isn't displayed and reads linked /// files on its own. Before it runs, the SVG is changed so that what we keep can be found: /// * every `` and every `` of a `` gets an id when it has none @@ -115,6 +160,9 @@ impl Edits { /// * objects with event attributes get an id when they have none, recorded with them /// ([`user_events`]), and the `"##; @@ -220,9 +220,13 @@ fn svg_images_are_left_out() { + + "##, vectorcraft_svg::base64_encode(inner.as_bytes()), - vectorcraft_svg::xml_escape(&inner.replace('#', "%23")) + vectorcraft_svg::xml_escape(&inner.replace('#', "%23")), + vectorcraft_svg::base64_encode(inner.as_bytes()), + vectorcraft_svg::base64_encode(inner.as_bytes()) ); let fills = fills(&art(&doc, 1).unwrap()); assert!(fills.contains(&Paint::solid(Color::rgb8(0, 0, 255))), "the glyph's own art"); @@ -255,3 +259,15 @@ fn an_images_plain_href_decides_whether_it_is_an_svg_image() { assert_eq!(images(image("png", "svg+xml")), 1, "the PNG stays"); assert_eq!(images(image("svg+xml", "png")), 0, "the document goes"); } + +/// A glyph's `` draws its art but keeps no link: outlined text must not export a +/// `javascript:` link from a font. +#[test] +fn links_in_a_glyph_are_left_out() { + let doc = r##""##; + let art = art(doc, 1).unwrap(); + assert!(fills(&art).contains(&Paint::solid(Color::rgb8(0, 0, 255)))); + let mut urls = vec![]; + art.walk(&mut |n| urls.extend(n.url().map(str::to_string))); + assert!(urls.is_empty(), "{urls:?}"); +} diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index d6319a9c69..cecaba6b13 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -40,8 +40,9 @@ pub use vectorcraft_engine::{Session, doc::NodeId}; pub use {vectorcraft_doc as doc, vectorcraft_format as format, vectorcraft_render as render, vectorcraft_svg as svg}; /// A per-process temporary directory for test output (created on first use). It is made with -/// `create_dir` (owner-only on Unix), and a directory that already exists is reused only when it is a -/// real directory, not a link, with no access for others and writable by this user: one pre-made in a shared temp folder is refused. +/// `create_dir` (owner-only on Unix), and a directory that already exists is reused only when it is +/// a real directory, not a link, with no access for others and owned by this user: one pre-made in +/// a shared temp folder is refused. /// The first call for a `tag` in a process empties a directory left by an earlier process of the /// same id (Windows reuses ids soon); later calls share it. pub fn temp_dir(tag: &str) -> std::path::PathBuf { @@ -60,12 +61,19 @@ pub fn temp_dir(tag: &str) -> std::path::PathBuf { assert!(e.kind() == std::io::ErrorKind::AlreadyExists && m.is_dir(), "create temp dir: {e}"); #[cfg(unix)] assert!(std::os::unix::fs::PermissionsExt::mode(&m.permissions()) & 0o077 == 0, "{}: not private", dir.display()); - // A private directory made by another user passes the mode check but is closed to this one: - // writing a probe file tells it apart from ours without needing the user ids. + // A directory made by another user may pass the mode check now and be opened up later: a + // probe file made new (never through a link left in its place) is this user's, and the + // directory must belong to the same user. // Named for this call: tests running alongside probe the same directory. static PROBES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); let probe = dir.join(format!(".probe-{}", PROBES.fetch_add(1, std::sync::atomic::Ordering::Relaxed))); - assert!(std::fs::write(&probe, b"").and_then(|()| std::fs::remove_file(&probe)).is_ok(), "{}: not owned by this user", dir.display()); + let made = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe).and_then(|f| f.metadata()); + let _ = std::fs::remove_file(&probe); + let made = made.unwrap_or_else(|e| panic!("{}: not owned by this user ({e})", dir.display())); + #[cfg(unix)] + assert_eq!(std::os::unix::fs::MetadataExt::uid(&made), std::os::unix::fs::MetadataExt::uid(&m), "{}: not owned by this user", dir.display()); + #[cfg(not(unix))] + let _ = made; if first { for entry in std::fs::read_dir(&dir).expect("temp dir").flatten() { let path = entry.path(); diff --git a/crates/text/build.rs b/crates/text/build.rs index 25544a3a60..412c471c11 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -81,6 +81,7 @@ fn craft_fonts(dir: &Path) -> Result { println!("cargo::rerun-if-changed={}", manifest.display()); let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e}", manifest.display()))?; let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32"); + let root = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?; let mut out = String::new(); for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) { let f: Vec<&str> = line.split(" | ").map(str::trim).collect(); @@ -91,6 +92,10 @@ fn craft_fonts(dir: &Path) -> Result { continue; } let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; + // The manifest is supplier data: embed only regular files inside the checkout. + if !path.starts_with(&root) || !path.is_file() { + return Err(format!("{file}: not a file inside the font checkout")); + } println!("cargo::rerun-if-changed={}", path.display()); let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); let _ = writeln!( diff --git a/crates/text/build/web_fonts.rs b/crates/text/build/web_fonts.rs index a2e2a8054e..ccd387afab 100644 --- a/crates/text/build/web_fonts.rs +++ b/crates/text/build/web_fonts.rs @@ -69,7 +69,8 @@ pub fn sri(hex: &str) -> Option { /// name>`. Relative, so the site works under any path; content-addressed, so it can be cached /// forever. pub fn url(sha256: &str, file: &str) -> String { - let name = file.rsplit('/').next().unwrap_or(file); + // Either separator: on Windows a backslash in supplier data would otherwise pick a folder. + let name = file.rsplit(['/', '\\']).next().unwrap_or(file); format!("fonts/{}/{name}", sha256.get(..16).unwrap_or(sha256)) } @@ -98,6 +99,7 @@ mod tests { fn url_is_relative_and_content_addressed() { let sha = "63111b5b2e074dd48cc67692e0a2726d86ee94c1c37fe8598257b7b4e87e869e"; assert_eq!(url(sha, "fonts/noto-sans-arabic/NotoSansArabic.ttf"), "fonts/63111b5b2e074dd4/NotoSansArabic.ttf"); + assert_eq!(url(sha, "fonts\\..\\..\\NotoSansArabic.ttf"), "fonts/63111b5b2e074dd4/NotoSansArabic.ttf"); assert!(!url(sha, "x.ttf").starts_with('/')); } diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index 0df8c2e333..506c3b1bf1 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -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`, + /// ), 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> { + 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::>>()?; + (!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> { + 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> { + 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. diff --git a/crates/text/src/kashida.rs b/crates/text/src/kashida.rs index 7d4cde0c98..90f4efe277 100644 --- a/crates/text/src/kashida.rs +++ b/crates/text/src/kashida.rs @@ -110,7 +110,7 @@ pub(crate) const MAX_TATWEELS: f64 = 64.0; /// Stylistic kashida is a whole number of tatweels, at most [`MAX_TATWEELS`], and a word whose /// share is shorter than one tatweel gets none. A line of words without joined letters, or whose /// font has no tatweel, gets none. -pub(crate) fn plan(text: &str, sg: &[SGlyph], line: Range, kind: Kashida, room: f64) -> Vec<(usize, f64)> { +pub(crate) fn plan(text: &str, sg: &[SGlyph], line: Range, kind: Kashida, room: f64, allows: impl Fn(usize) -> bool) -> Vec<(usize, f64)> { if kind == Kashida::None || !room.is_finite() || room <= 0.0 { return vec![]; } @@ -128,7 +128,7 @@ pub(crate) fn plan(text: &str, sg: &[SGlyph], line: Range, kind: Kashida, picks.extend(word.take()); prev = None; } else { - if prev.and_then(|p| sg.get(p)).is_some_and(|a| joined(text, a, g)) && tatweel(g).is_some() { + if prev.and_then(|p| sg.get(p)).is_some_and(|a| joined(text, a, g) && allows(a.byte) && allows(g.byte)) && tatweel(g).is_some() { word = Some(j); } prev = Some(j); diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index a7665612ce..9d7ed666ea 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -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 = 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::>()) + } 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::>()) + }; + 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, @@ -86,7 +140,9 @@ impl Ctx<'_> { /// stretch. fn char_directions(&self, r: &Range) -> Vec<(Range, ParaDirection)> { let mut out: Vec<(Range, ParaDirection)> = Vec::new(); - for (rr, st) in &self.runs { + // Only the paragraph's own runs (they are in order), not every run of the text. + let first = self.runs.partition_point(|(rr, _)| rr.end <= r.start); + for (rr, st) in self.runs.iter().skip(first).take_while(|(rr, _)| rr.start < r.end) { let (a, b) = (rr.start.max(r.start), rr.end.min(r.end)); let Some(d) = st.char_direction.filter(|_| a < b) else { continue }; let (a, b) = (a - r.start, b - r.start); @@ -158,7 +214,10 @@ impl Ctx<'_> { fn prepend_marker(&self, pr: &Range, para: &ParaStyle, text: Option<&str>, rtl: bool, sg: &mut Vec) -> usize { let Some(text) = text.filter(|_| para.list.is_some() && !pr.is_empty()) else { return 0 }; let st = vectorcraft_doc::text::ParaList::marker_style(self.style_at(pr.start)); - let Some(run) = self.runs.iter().position(|(r, _)| r.start <= pr.start && pr.start < r.end) else { return 0 }; + let run = self.runs.partition_point(|(r, _)| r.end <= pr.start); + if !self.runs.get(run).is_some_and(|(r, _)| r.start <= pr.start && pr.start < r.end) { + return 0; + } // The paragraph's direction: the marker starts a right-to-left paragraph at its right. let level = if rtl { Level::rtl() } else { Level::ltr() }; let mut marker = Vec::with_capacity(text.len() + 1); @@ -226,25 +285,26 @@ impl Ctx<'_> { let upright = self.vertical && !self.on_path && g.tcy.is_none() && stands_upright(g); let lead = if upright { 0.0 } else { g.lead }; let local = match &g.inline { - // Inline graphics: art space to glyph space (no font outline). - Some(ib) => Affine::translate((-lead, -g.bshift)) * ib.xf, + // Inline graphics: art space to glyph space (no font outline), moved along the line by + // right-to-left manual kerning as a glyph is. + Some(ib) => Affine::translate((g.kern_shift - lead, -g.bshift)) * ib.xf, // Baseline shift moves the glyph across its line, and Character Rotation then turns it // about its shifted pen position, so the shift is across the line at any rotation. - // Right-to-left manual kerning moves that pen position along the line. + // Manual kerning and composition trim move that pen position along the line. None => { - Affine::translate((g.kern_shift, -g.bshift)) + Affine::translate((g.kern_shift - lead, -g.bshift)) * Affine::rotate(-g.rotation.to_radians()) - * Affine::translate((g.dx - lead, g.dy)) + * Affine::translate((g.dx, g.dy)) * Affine::scale_non_uniform(g.sx, g.sy) } }; // The turning point in font units, which later moves of the glyph's transform keep. let pivot = match local.determinant() { - det if det != 0.0 && det.is_finite() => local.inverse() * Point::new(g.kern_shift, -g.bshift), + det if det != 0.0 && det.is_finite() => local.inverse() * Point::new(g.kern_shift - lead, -g.bshift), _ => Point::ZERO, }; let unturned = if g.inline.is_none() && g.rotation != 0.0 && g.sx != 0.0 && g.sy != 0.0 { - let placed = Affine::translate((g.dx - lead, g.dy)) * Affine::scale_non_uniform(g.sx, g.sy); + let placed = Affine::translate((g.dx, g.dy)) * Affine::scale_non_uniform(g.sx, g.sy); placed.inverse() * Affine::rotate(g.rotation.to_radians()) * placed } else { Affine::IDENTITY @@ -277,7 +337,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)) @@ -299,6 +359,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) }); } @@ -322,6 +405,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, }); } diff --git a/crates/text/src/layout/driver.rs b/crates/text/src/layout/driver.rs index 0b76f2c5ac..01fef17656 100644 --- a/crates/text/src/layout/driver.rs +++ b/crates/text/src/layout/driver.rs @@ -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 } diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index 03c2eb3c40..112dabb233 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -418,7 +418,7 @@ fn run_paragraph_lines(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, t: &TextObject, mut hyphen_run = if position.hyph && position.end > index { hyphen_run + 1 } else { 0 }; pen.pending = 0.0; let geometry = prepare_line_geometry(cx, t, ¶graph, position, index); - let justification = justify_flow_line(cx.vertical, cx.text, ¶graph, &geometry); + let justification = justify_flow_line(cx, ¶graph, &geometry); emit_flow_line(cx, pen, ¶graph, &geometry, &justification); line_in_paragraph += 1; index = geometry.position.end; @@ -591,7 +591,7 @@ fn flow_line_flex(glyph: usize, flex: &[Flex], held: &[usize], hung: &[usize]) - value } -fn justify_flow_line(vertical: bool, text: &str, paragraph: &ParagraphData<'_, '_>, line: &LineGeometry) -> LineJustification { +fn justify_flow_line(cx: &Ctx<'_>, paragraph: &ParagraphData<'_, '_>, line: &LineGeometry) -> LineJustification { let para = paragraph.para; let sg = ¶graph.sg; let (held, hung) = (&line.held, &line.hung); @@ -629,8 +629,8 @@ fn justify_flow_line(vertical: bool, text: &str, paragraph: &ParagraphData<'_, ' }; // Insert Kashidas: the Arabic words of a horizontal line take its room on kashidas, // and the word spaces and gaps take what is left. - let kashidas = if justify && !vertical && room > line.render_width + EPS { - kashida::plan(text, sg, line.index..line.body, para.kashida, room - line.render_width) + let kashidas = if justify && !cx.vertical && room > line.render_width + EPS { + kashida::plan(cx.text, sg, line.index..line.body, para.kashida, room - line.render_width, |byte| cx.style_at(byte).kashidas) } else { Vec::new() }; diff --git a/crates/text/src/layout/ruby.rs b/crates/text/src/layout/ruby.rs index 59ce52c4ca..1cf34e24ce 100644 --- a/crates/text/src/layout/ruby.rs +++ b/crates/text/src/layout/ruby.rs @@ -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, } } diff --git a/crates/text/src/layout/vertical.rs b/crates/text/src/layout/vertical.rs index e571953d8b..8f01a5d32b 100644 --- a/crates/text/src/layout/vertical.rs +++ b/crates/text/src/layout/vertical.rs @@ -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`). diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index 2e036c3cf9..9f1a048b38 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -49,6 +49,56 @@ fn source_range(glyphs: &[SGlyph], start: usize, end: usize) -> Range { first.byte..last.byte + last.len } +#[test] +fn composition_trim_stays_along_the_line_when_a_character_rotates() { + let db = FontDb::with_font_dirs(vec![]); + let style = CharStyle::default(); + let opts = LayoutOptions::default(); + for angle in [0.0_f64, std::f64::consts::FRAC_PI_4, std::f64::consts::FRAC_PI_2] { + let origin = Point::new(100.0, 80.0); + let pre = Affine::translate(origin.to_vec2()) * Affine::rotate(angle); + let draw = |rotation: f64, lead: f64| { + let mut glyph = synthetic_glyphs(&[(0, 1, 30.0, 'A')]).remove(0); + glyph.sx = 0.02; + glyph.sy = 0.02; + glyph.dx = 2.0; + glyph.dy = -1.0; + glyph.bshift = 4.0; + glyph.kern_shift = 3.0; + glyph.rotation = rotation; + glyph.lead = lead; + let mut cx = Ctx { + on_path: angle != 0.0, + db: &db, + text: "A", + runs: vec![(0..1, &style)], + inlines: vec![None], + default: style.clone(), + opts: &opts, + vertical: false, + system_layout: false, + fractional_widths: true, + upright_cluster: None, + out: TextLayout::default(), + }; + cx.emit(&glyph, pre, origin, angle, 30.0 - lead, 0); + cx.out.glyphs.remove(0) + }; + let expected = Vec2::new(-angle.cos(), -angle.sin()) * 5.0; + for rotation in [0.0, 45.0, 90.0, -90.0] { + let (plain, trimmed) = (draw(rotation, 0.0), draw(rotation, 5.0)); + assert!(!trimmed.outline.elements().is_empty(), "fixture has drawn geometry"); + let shift = trimmed.xf * Point::ZERO - plain.xf * Point::ZERO; + assert!((shift - expected).hypot() < 1e-9, "line {angle}, character {rotation}: {shift:?} versus {expected:?}"); + let pivot_shift = trimmed.xf * trimmed.pivot - plain.xf * plain.pivot; + assert!((pivot_shift - expected).hypot() < 1e-9, "composition moves the turning point along the line: {pivot_shift:?}"); + let unrotated = draw(0.0, 5.0); + let actual = (trimmed.xf * trimmed.unturned).as_coeffs(); + assert!(actual.iter().zip(unrotated.xf.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "removing rotation keeps composition placement"); + } + } +} + #[test] fn greedy_wrap_keeps_an_oversized_first_cluster_and_its_source_range() { let text = "بَت"; diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index a1b77e02aa..1d32036076 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -147,8 +147,27 @@ pub struct PositionedGlyph { /// its Character Rotation. The identity for a glyph without one. pub unturned: Affine, /// Font units: `xf * pivot` is the point its Character Rotation turns it about, its pen - /// position on the baseline moved by its baseline shift. + /// position after composition spacing adjustments, 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 + '_ { + 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 + '_ { + 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, 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 diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index e2ba0a8a9a..3311a8aa44 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -375,7 +375,13 @@ pub(crate) fn shape_range( art: Option<&'a InlineArt>, } let mut spans: Vec> = Vec::new(); - for (ri, (rr, st)) in runs.iter().enumerate() { + // The runs are in order: start at the first that ends inside the range and stop past it, so + // that each paragraph looks only at its own runs. + let first = runs.partition_point(|(rr, _)| rr.end <= range.start); + for (ri, (rr, st)) in runs.iter().enumerate().skip(first) { + if rr.start >= range.end { + break; + } let a = rr.start.max(range.start); let b = rr.end.min(range.end); if a >= b || text.get(a..b).is_none() { @@ -401,7 +407,7 @@ pub(crate) fn shape_range( let b = bytes.end; if let Some(art) = art { if let Some(face) = db.style_face(st).or_else(|| db.face_covering('a')) { - out.push(inline_glyph(&face, st, art, source_runs.start, a..b, text, level_at(a))); + out.push(inline_glyph(&face, st, art, source_runs.start, a..b, text, level_at(a), feats.vertical)); } continue; } @@ -688,7 +694,7 @@ fn source_run_at(runs: &[(Range, &CharStyle)], span: &Range, byte: /// Do text runs in styles `a` and `b` shape alike, so that they are shaped as one piece of text? /// They do when they differ only in paint and stroke, underline and strikethrough, overprint, the /// character style's name, leading, baseline shift, rotation, Character Alignment, Character -/// Direction (text is shaped apart where its bidi level changes), the kerning (each glyph takes its +/// Direction (text is shaped apart where its bidi level changes), Kashidas, the kerning (each glyph takes its /// run's, see [`shape_segment`]) and the tracking, as long as the tracking keeps or drops standard /// ligatures alike ([`crate::features::ligatures_suppressed_by`]). fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { @@ -726,6 +732,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { small_caps, char_align: _, char_direction: _, + kashidas: _, proportional_metrics, tate_chu_yoko, tcy_up_down: _, @@ -795,10 +802,21 @@ fn shaping_script(c: char) -> Script { /// /// The art is scaled uniformly to `scale` x the font size tall, its left edge on the pen and its /// vertical centre on the middle of the cap height raised by the inline's shift (see -/// [`InlineArt`]). Its advance is the scaled art width plus tracking; the glyph's ascent and -/// descent grow to the art's extent so a tall graphic opens up its line. A missing symbol takes a -/// square of the same height and draws nothing. -fn inline_glyph(face: &Arc, st: &CharStyle, art: &InlineArt, run: usize, range: Range, text: &str, level: Level) -> SGlyph { +/// [`InlineArt`]). Its advance is the scaled art width plus tracking and its character's manual +/// kerning, which right to left in horizontal type also moves the art right by the value, as it +/// moves a letter's glyph. The glyph's ascent and descent grow to the art's extent so a tall +/// graphic opens up its line. A missing symbol takes a square of the same height and draws nothing. +#[allow(clippy::too_many_arguments)] +fn inline_glyph( + face: &Arc, + st: &CharStyle, + art: &InlineArt, + run: usize, + range: Range, + text: &str, + level: Level, + vertical: bool, +) -> SGlyph { let size = if st.size.is_finite() { st.size.max(0.0) } else { 0.0 }; let vs = if st.v_scale.is_finite() { st.v_scale / 100.0 } else { 1.0 }; let km = size / face.upem; @@ -815,7 +833,8 @@ fn inline_glyph(face: &Arc, st: &CharStyle, art: &InlineArt, run: usiz _ => (kurbo::Affine::IDENTITY, h, None), }; let tracking = st.tracking / 1000.0 * size; - let adv = width + if tracking.is_finite() { tracking } else { 0.0 }; + let manual_kern = st.kerning.map(|v| v / 1000.0 * size).filter(|k| k.is_finite()).unwrap_or(0.0); + let adv = width + if tracking.is_finite() { tracking } else { 0.0 } + manual_kern; SGlyph { face: face.clone(), gid: 0, @@ -825,7 +844,7 @@ fn inline_glyph(face: &Arc, st: &CharStyle, art: &InlineArt, run: usiz adv: if adv.is_finite() { adv } else { 0.0 }, dx: 0.0, dy: 0.0, - kern_shift: 0.0, + kern_shift: if level.is_rtl() && !vertical { manual_kern } else { 0.0 }, // Not used to draw (the art has its own transform), but they make the glyph's em box // its run's em: Character Alignment and Top-to-Top leading treat an inline graphic as a // character of its run's size, whatever its scale (see `layout::glyph_em`). diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index a4e0fcde6a..2a6072762c 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -489,6 +489,195 @@ pub fn lam_alef_font(feature: &[u8; 4]) -> Option> { 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) -> Option> { + 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::>>()?).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> { + 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, 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> { + 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> { + 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"; diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index db28b20138..002e4b921d 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -15,6 +15,7 @@ mod hang; mod inline; mod joiners; mod justify; +mod ligature_carets; mod path_joins; mod ruby; mod scripts; @@ -554,6 +555,19 @@ fn multiple_runs_and_styles() { assert_ne!(l.glyphs[0].font_id, l.glyphs[3].font_id); } +#[test] +fn many_paragraphs_of_their_own_runs_lay_out_in_linear_time() { + // 20,000 one-letter paragraphs, each a run of its own: every paragraph looking through every + // run would be 400 million steps. + let n = 20_000; + let mut t = point("", style(10.0)); + t.runs = (0..n).map(|i| TextRun { text: "a\n".into(), style: style(if i % 2 == 0 { 10.0 } else { 11.0 }), inline: None }).collect(); + let start = std::time::Instant::now(); + let l = layout(db(), &t); + assert!(start.elapsed() < std::time::Duration::from_secs(60), "{:?}", start.elapsed()); + assert!(l.glyphs.iter().any(|g| g.run == n - 1)); +} + #[test] fn layout_is_fast() { let text: String = LOREM.chars().cycle().take(1000).collect(); diff --git a/crates/text/src/tests/bidi.rs b/crates/text/src/tests/bidi.rs index 7e49312979..d7cd584013 100644 --- a/crates/text/src/tests/bidi.rs +++ b/crates/text/src/tests/bidi.rs @@ -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; } diff --git a/crates/text/src/tests/inline.rs b/crates/text/src/tests/inline.rs index ebc90351dd..d492608cc5 100644 --- a/crates/text/src/tests/inline.rs +++ b/crates/text/src/tests/inline.rs @@ -248,6 +248,56 @@ fn inline_art_in_a_right_to_left_paragraph_is_placed_by_the_bidi_reordering() { assert!(inline_rtl && inline < first); } +/// A manual kerning value on an inline graphic's character spaces it from the next character in +/// reading order by the distance the same value spaces a letter of its size: left to right, right +/// to left and down a vertical column. The character before it keeps its place, and a graphic's 0 +/// sets the text as no value does. +#[test] +fn manual_kerning_on_an_inline_graphic_spaces_it_like_a_letter() { + let db = FontDb::global(); + // `before`, then the graphic (or `letter` in its place) with `kerning`, then `after`. + let set = |before: &str, letter: Option<&str>, after: &str, kerning: Option, vertical: bool| { + let mut t = TextObject::point(Point::ZERO, before, style(20.0)); + let st = CharStyle { kerning, ..style(20.0) }; + t.runs.push(match letter { + Some(c) => TextRun::new(c, st), + None => TextRun::inline(art(1.0), st), + }); + t.runs.push(TextRun::new(after, style(20.0))); + t.vertical = vertical; + let l = layout(db, &t); + let ink = |run: usize, last: bool| { + let mut g: Vec<&PositionedGlyph> = l.glyphs.iter().filter(|g| g.run == run).collect(); + g.sort_by_key(|g| g.byte); + let g = if last { g.last() } else { g.first() }; + g.expect("glyph").xf * Point::ZERO + }; + assert_eq!(l.inlines.len(), usize::from(letter.is_none())); + // Distance along the line: across the page, or down the column. + let along = |a: Point, b: Point| if vertical { (b.y - a.y).abs() } else { (b.x - a.x).abs() }; + let (previous, middle, next) = (ink(0, true), ink(1, false), ink(2, false)); + (along(previous, middle), along(middle, next), l.glyphs.iter().map(|g| (g.origin, g.advance)).collect::>()) + }; + for (before, letter, after, vertical) in [("A", "X", "B", false), ("אב", "ג", "דה", false), ("ab", "x", "cd", true)] { + for letter in [None, Some(letter)] { + let (before_plain, after_plain, plain) = set(before, letter, after, Some(0.0), vertical); + let (before_kerned, after_kerned, _) = set(before, letter, after, Some(200.0), vertical); + // 200/1000 em of 20 pt. + assert!((after_kerned - after_plain - 4.0).abs() < 1e-6, "{before:?} {letter:?}: {after_plain} -> {after_kerned}"); + assert!((before_kerned - before_plain).abs() < 1e-6, "{before:?} {letter:?}: {before_plain} -> {before_kerned}"); + if letter.is_some() { + // A letter's 0 also turns off its font's kerning pairs; a graphic has none. + continue; + } + let (_, _, none) = set(before, letter, after, None, vertical); + assert!( + plain.iter().zip(&none).all(|(a, b)| (a.0 - b.0).hypot() < 1e-9 && (a.1 - b.1).abs() < 1e-9), + "{before:?} {letter:?}: 0 sets the text as no value does" + ); + } + } +} + /// Character Alignment: an inline graphic's em box is its run's, whatever its scale. It moves with /// its run's text when that is smaller than the line's largest characters, and a big graphic in /// small text doesn't make its line's small characters move. diff --git a/crates/text/src/tests/justify.rs b/crates/text/src/tests/justify.rs index 6cb9e77184..95646bc57b 100644 --- a/crates/text/src/tests/justify.rs +++ b/crates/text/src/tests/justify.rs @@ -4,7 +4,7 @@ use crate::*; use kurbo::{Affine, Shape}; use vectorcraft_doc::text::Kashida; -use vectorcraft_doc::{CharStyle, JustificationOptions, Justify, SingleWordJustify, TextKind}; +use vectorcraft_doc::{CharStyle, JustificationOptions, Justify, SingleWordJustify, TextKind, TextRun}; use vectorcraft_geom::PathData; fn db() -> &'static FontDb { @@ -282,6 +282,30 @@ fn justified_arabic_lines_take_their_room_on_kashidas() { } } +/// A character with Kashidas off prevents insertion at either of its joined edges. Other +/// eligible pairs in the word remain available; old text defaults to allowing them. +#[test] +fn character_kashidas_filter_joined_pairs() { + let Some(face) = arabic_face("character_kashidas_filter_joined_pairs") else { return }; + let text = "كتب ورد محمد"; + let mut t = arabic_area(&face, text, Justify::JustifyAll, Kashida::Medium); + let default_bytes = kashidas(&layout(db(), &t), &face).into_iter().map(|g| g.byte).collect::>(); + assert!(default_bytes.contains(&("كت".len()))); + let mut off = t.runs[0].style.clone(); + off.kashidas = false; + let on = t.runs[0].style.clone(); + t.runs = vec![TextRun::new("كت", on.clone()), TextRun::new("ب", off.clone()), TextRun::new(" ورد محمد", on.clone())]; + let one_off = layout(db(), &t); + let bytes = kashidas(&one_off, &face).into_iter().map(|g| g.byte).collect::>(); + assert!(!bytes.contains(&("كت".len())), "the disabled beh has no kashida before it"); + assert!(bytes.contains(&("ك".len())), "the earlier eligible pair remains"); + t.runs = vec![TextRun::new("ك", on.clone()), TextRun::new("تب", off), TextRun::new(" ورد محمد", on)]; + let both_off = layout(db(), &t); + let bytes = kashidas(&both_off, &face).into_iter().map(|g| g.byte).collect::>(); + assert!(!bytes.contains(&("ك".len())) && !bytes.contains(&("كت".len()))); + assert!(bytes.contains(&(text.len() - 'د'.len_utf8())), "another word still takes its kashida"); +} + /// Where the kashida before the cluster at byte `b` starts, where the letter before it in the text /// starts (the kashida's end), and how many tatweels draw it. fn kashida_span(l: &TextLayout, face: &FontFace, b: usize) -> (f64, f64, usize) { diff --git a/crates/text/src/tests/ligature_carets.rs b/crates/text/src/tests/ligature_carets.rs new file mode 100644 index 0000000000..ee42864c58 --- /dev/null +++ b/crates/text/src/tests/ligature_carets.rs @@ -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>) -> 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>| { + 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::>(), 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>, 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}"); +} diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 2627b81eef..092ed4c09f 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -1729,6 +1729,28 @@ fn proportional_metrics_set_full_width_glyphs_on_their_proportional_widths() { assert!((moved - 10.0).abs() < 0.01, "〙's empty half goes past the line's end: あ moved {moved}"); } +#[test] +fn mojikumi_trim_keeps_a_rotated_opening_bracket_on_its_line() { + use vectorcraft_doc::Mojikumi; + if db().face("Shippori Mincho", "Regular").is_none_or(|f| f.family != "Shippori Mincho") { + eprintln!("skipped: Shippori Mincho is not in CRAFT_FONTS_DIR"); + return; + } + let lay = |rotation, mojikumi| { + let st = CharStyle { font_family: "Shippori Mincho".into(), size: 20.0, rotation, ..Default::default() }; + let mut t = area("「あ", st, Rect::new(0.0, 0.0, 200.0, 200.0), Justify::Left); + t.para.mojikumi = mojikumi; + layout(db(), &t) + }; + for rotation in [0.0, 45.0, 90.0, -90.0] { + let (plain, trimmed) = (lay(rotation, Mojikumi::None), lay(rotation, Mojikumi::LineEndHalf)); + let (a, b) = (&plain.glyphs[0], &trimmed.glyphs[0]); + assert!((a.advance - 20.0).abs() < 0.01 && (b.advance - 10.0).abs() < 0.01, "full-width bracket fixture"); + let shift = b.xf * Point::ZERO - a.xf * Point::ZERO; + assert!((shift.x + 10.0).abs() < 0.01 && shift.y.abs() < 0.01, "{rotation} degrees: {shift:?}"); + } +} + /// The arrows pass a Thai consonant with its vowel and tone marks whole (น้ำ: no, mai tho, sara am), /// as an accented letter written with a combining mark; plain text moves a character at a time. #[test] diff --git a/crates/tools/src/addons.rs b/crates/tools/src/addons.rs index aff7069a56..42643538ed 100644 --- a/crates/tools/src/addons.rs +++ b/crates/tools/src/addons.rs @@ -1,9 +1,10 @@ //! The tools of VectorCraft's built-in add-ons. They aren't in the toolbars as they ship: the All //! Tools drawer lists them (under their add-on's heading) so they can be added, and each add-on's -//! submenu selects them. Like every tool they only emit commands (`addon..*`). +//! submenu selects them. Tool gestures emit engine commands. pub mod anchor_eraser; pub mod corner_tool; +pub mod enclosing_lasso; pub mod extend_path; pub mod measure_inspect; pub mod parametric_shape; @@ -27,12 +28,14 @@ pub const PATH_TOOLS: &[ToolInfo] = &[ /// Smart Pen's tool, a flyout group of its own. pub const SMART_PEN: &[ToolInfo] = &[ToolInfo { id: smart_pen::ID, label: "Smart Pen Tool", shortcut: None, icon: "spline-pointer" }]; +pub const ENCLOSING_LASSO: &[ToolInfo] = &[ToolInfo { id: enclosing_lasso::ID, label: "Enclosing Lasso Tool", shortcut: None, icon: "tool-lasso" }]; + /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]), each with the /// heading the All Tools drawer lists it under (its add-on's name). -const HEADED: &[(&[ToolInfo], &str)] = &[(PATH_TOOLS, "Path Precision Tools"), (SMART_PEN, "Smart Pen")]; +const HEADED: &[(&[ToolInfo], &str)] = &[(PATH_TOOLS, "Path Precision Tools"), (SMART_PEN, "Smart Pen"), (ENCLOSING_LASSO, "Enclosing Lasso")]; /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]). -pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN]; +pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, ENCLOSING_LASSO]; /// The heading the All Tools drawer lists tool `id` under: its add-on's name. pub fn heading(id: &str) -> Option<&'static str> { @@ -50,6 +53,7 @@ pub fn create(id: &str) -> Option> { shared_edge::ID => Box::new(shared_edge::SharedEdgeTool::default()), slide_anchor::ID => Box::new(slide_anchor::SlideAnchorTool::default()), smart_pen::ID => Box::new(smart_pen::SmartPenTool::default()), + enclosing_lasso::ID => Box::new(enclosing_lasso::EnclosingLassoTool::default()), _ => return None, }) } @@ -69,6 +73,7 @@ mod tests { } assert!(PATH_TOOLS.iter().all(|t| heading(t.id) == Some("Path Precision Tools"))); assert_eq!(heading(smart_pen::ID), Some("Smart Pen")); + assert_eq!(heading(enclosing_lasso::ID), Some("Enclosing Lasso")); assert_eq!(GROUPS.len(), HEADED.len()); assert!(crate::catalog::all_tools().any(|t| t.id == extend_path::ID)); assert!(create("pen").is_none() && heading("pen").is_none()); diff --git a/crates/tools/src/addons/enclosing_lasso.rs b/crates/tools/src/addons/enclosing_lasso.rs new file mode 100644 index 0000000000..9b92f0833d --- /dev/null +++ b/crates/tools/src/addons/enclosing_lasso.rs @@ -0,0 +1,183 @@ +//! Enclosing Lasso selects whole objects by a freehand loop. Path geometry is measured without +//! stroke width or effects, as with the Selection tool's enclosed marquee. Other objects use +//! their geometric box. Ordinary groups are traversed; compound paths stay one object. + +mod region; + +use serde_json::json; +use vectorcraft_doc::hit::enclosure_candidates; +use vectorcraft_doc::{AppearanceItem, Node, NodeKind, SymbolBoxes}; +use vectorcraft_geom::kurbo::{ParamCurve, PathEl}; +use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Shape}; +use vectorcraft_pathops::{BoolOp, DEFAULT_PRECISION, try_boolean}; + +use self::region::Region; +use crate::xform::{BLUE, polygon}; + +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, json_ids}; + +pub const ID: &str = "enclosingLasso"; +/// The most points a loop keeps (one per screen pixel dragged): room for a loop around a 4K screen +/// many times over. +pub(crate) const MAX_POINTS: usize = 65_536; + +#[derive(Default)] +pub struct EnclosingLassoTool { + points: Vec, + active: bool, +} + +/// Splitting at every crossing catches curves that leave a concave loop between their anchors. +fn enclosed(path: &BezPath, region: &Region) -> bool { + let mut any = false; + // A subpath can be a single anchor with no segments. Check every start, including stray + // points beside other subpaths, so a whole object's disconnected points cannot be missed. + for el in path.elements() { + if let PathEl::MoveTo(p) = el { + any = true; + if !region.contains(*p) { + return false; + } + } + } + for seg in path.segments() { + any = true; + let mut ts = vec![0.0, 1.0]; + for line in region.near(seg.bounding_box()) { + ts.extend(seg.intersect_line(*line).iter().map(|x| x.segment_t).filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0)); + } + ts.sort_by(f64::total_cmp); + ts.dedup(); + if !ts.iter().all(|t| region.contains(seg.eval(*t))) || !ts.windows(2).all(|w| region.contains(seg.eval((w[0] + w[1]) / 2.0))) { + return false; + } + } + any +} + +fn path_inside(path: &PathData, rule: FillRule, filled: bool, region: &Region) -> bool { + if !enclosed(&path.to_bezpath(), region) { + return false; + } + // A self-crossing loop can have a hole wholly inside a filled object without crossing its + // outline. The filled difference also checks that interior (and implicit fill closures). + !filled || try_boolean(path, rule, ®ion.data, FillRule::EvenOdd, BoolOp::Difference, DEFAULT_PRECISION).is_ok_and(|outside| outside.is_empty()) +} + +fn node_inside(n: &Node, symbols: &SymbolBoxes, region: &Region) -> bool { + let mut bounds = n.geometric_bounds_with(symbols); + // Curve bounds omit isolated MoveTo points when other subpaths have segments. + let mut include_points = |path: &PathData| { + for p in path.subpaths.iter().filter(|sp| sp.segment_count() == 0).filter_map(|sp| sp.anchors.first().map(|a| a.p)) { + bounds = Some(bounds.map_or_else(|| Rect::from_points(p, p), |b| b.union_pt(p))); + } + }; + match &n.kind { + NodeKind::Path { path, .. } => include_points(path), + NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).for_each(include_points), + _ => {} + } + // Most candidates lie well inside the loop. A box untouched by its boundary is entirely + // inside or outside, so it needs no curve intersections or filled boolean operation. + if let Some(covered) = bounds.and_then(|b| region.box_coverage(b)) { + return covered; + } + let filled = n.appearance.items.iter().any(|item| matches!(item, AppearanceItem::Fill(fill) if fill.visible && !fill.paint.is_none())); + match &n.kind { + NodeKind::Path { path, rule, .. } => path_inside(path, *rule, filled, region), + NodeKind::Compound { rule, .. } => n.stroke_path().is_some_and(|path| path_inside(&PathData::from_bezpath(&path), *rule, filled, region)), + _ => { + n.geometric_bounds_with(symbols).is_some_and(|b| path_inside(&PathData::from_bezpath(&b.to_path(0.01)), FillRule::NonZero, true, region)) + } + } +} + +impl Tool for EnclosingLassoTool { + fn id(&self) -> &'static str { + ID + } + + fn busy(&self) -> bool { + self.active + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + if !ev.pos.is_finite() { + if ev.kind == PointerKind::Up { + self.active = false; + self.points.clear(); + } + return vec![]; + } + match ev.kind { + PointerKind::Down => { + self.points = vec![ev.pos]; + self.active = true; + } + PointerKind::Drag if self.active => { + if self.points.last().is_none_or(|p| p.distance(ev.pos) >= cx.tol(1.0)) { + // Cancel rather than testing a truncated loop that could select other art. + if self.points.len() >= MAX_POINTS { + self.active = false; + self.points.clear(); + return vec![]; + } + self.points.push(ev.pos); + } + } + PointerKind::Up if self.active => { + self.active = false; + let mut points = std::mem::take(&mut self.points); + if points.last().is_some_and(|p| p.distance(ev.pos) >= cx.tol(1.0)) { + points.push(ev.pos); + } + let symbols = cx.doc.symbol_boxes(); + let region = (points.len() >= 3).then(|| Region::new(polygon(&points, true))).flatten(); + let mut ids = if let Some(region) = region { + enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation) + .into_iter() + .filter(|id| cx.doc.node(*id).is_some_and(|n| node_inside(n, &symbols, ®ion))) + .collect() + } else { + vec![] + }; + let command = if ev.mods.alt { + ids.retain(|id| cx.selection.contains(*id)); + "select.toggle" + } else if ev.mods.shift { + "select.add" + } else { + "select.set" + }; + if ids.is_empty() && (ev.mods.alt || ev.mods.shift) { + return vec![]; + } + return vec![Action::Exec(command.into(), json!({"ids": json_ids(&ids)}))]; + } + _ => {} + } + vec![] + } + + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + if key == ToolKey::Escape { + self.active = false; + self.points.clear(); + } + vec![] + } + + fn overlays(&self, _cx: &ToolContext) -> Vec { + if !self.active || self.points.len() < 2 { + return vec![]; + } + vec![Overlay::Path { path: polygon(&self.points, true), color: BLUE, width: 1.0, dashed: false }] + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { + Cursor::Lasso + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/tools/src/addons/enclosing_lasso/region.rs b/crates/tools/src/addons/enclosing_lasso/region.rs new file mode 100644 index 0000000000..fdf4ac8b55 --- /dev/null +++ b/crates/tools/src/addons/enclosing_lasso/region.rs @@ -0,0 +1,93 @@ +//! A freehand loop prepared once for an Enclosing Lasso selection gesture. + +use vectorcraft_geom::kurbo::{Line, ParamCurveNearest, PathSeg}; +use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Shape}; +use vectorcraft_pathops::try_normalize; + +pub(super) struct Region { + pub(super) path: BezPath, + pub(super) data: PathData, + bounds: Rect, + edges: Vec, + rows: Vec>, +} + +impl Region { + pub(super) fn new(path: BezPath) -> Option { + let data = PathData::from_bezpath(&path); + // A figure eight can have zero signed area and still enclose two regions. + if try_normalize(&data, FillRule::EvenOdd).ok()?.is_empty() { + return None; + } + let bounds = path.bounding_box(); + if !bounds.width().is_finite() || !bounds.height().is_finite() || bounds.width() <= 0.0 || bounds.height() <= 0.0 { + return None; + } + let edges: Vec<_> = path.segments().map(|s| if let PathSeg::Line(l) = s { Some(l) } else { None }).collect::>()?; + let rows = vec![vec![]; edges.len().clamp(1, 256)]; + let mut region = Self { path, data, bounds, edges, rows }; + for (i, edge) in region.edges.iter().enumerate() { + let first = region.row(edge.p0.y.min(edge.p1.y) - 1e-7); + let last = region.row(edge.p0.y.max(edge.p1.y) + 1e-7); + for row in region.rows.get_mut(first..=last)? { + row.push(i); + } + } + Some(region) + } + + fn row(&self, y: f64) -> usize { + (((y - self.bounds.y0) / self.bounds.height()) * self.rows.len() as f64).floor().clamp(0.0, self.rows.len() as f64 - 1.0) as usize + } + + /// Only one row participates in a horizontal containment ray. + pub(super) fn contains(&self, p: Point) -> bool { + if !p.is_finite() || p.x < self.bounds.x0 - 1e-7 || p.x > self.bounds.x1 + 1e-7 || p.y < self.bounds.y0 - 1e-7 || p.y > self.bounds.y1 + 1e-7 + { + return false; + } + let mut inside = false; + for edge in self.rows.get(self.row(p.y)).into_iter().flatten().filter_map(|i| self.edges.get(*i)) { + if edge.nearest(p, 1e-9).distance_sq <= 1e-14 { + return true; + } + let (a, b) = (edge.p0, edge.p1); + if (a.y > p.y) != (b.y > p.y) && p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x { + inside = !inside; + } + } + inside + } + + /// Edges near a box, conservatively, each returned only in its first queried row. + pub(super) fn near(&self, b: Rect) -> impl Iterator { + let first = self.row(b.y0 - 1e-7); + let last = self.row(b.y1 + 1e-7); + self.rows + .get(first..=last) + .into_iter() + .flatten() + .enumerate() + .flat_map(move |(offset, row)| { + row.iter().filter_map(move |i| { + let edge = self.edges.get(*i)?; + let start = self.row(edge.p0.y.min(edge.p1.y) - 1e-7); + (first + offset == first.max(start)).then_some(edge) + }) + }) + .filter(move |e| { + e.p0.x.min(e.p1.x) <= b.x1 + 1e-7 + && e.p0.x.max(e.p1.x) >= b.x0 - 1e-7 + && e.p0.y.min(e.p1.y) <= b.y1 + 1e-7 + && e.p0.y.max(e.p1.y) >= b.y0 - 1e-7 + }) + } + + /// Without a boundary through the box, all of it lies on the same side of the loop. + pub(super) fn box_coverage(&self, b: Rect) -> Option { + if !b.is_finite() { + return Some(false); + } + self.near(b).next().is_none().then(|| self.contains(b.origin())) + } +} diff --git a/crates/tools/src/addons/enclosing_lasso/tests.rs b/crates/tools/src/addons/enclosing_lasso/tests.rs new file mode 100644 index 0000000000..836e640306 --- /dev/null +++ b/crates/tools/src/addons/enclosing_lasso/tests.rs @@ -0,0 +1,369 @@ +use super::*; +use crate::testutil::*; +use vectorcraft_doc::{Appearance, Document, NodeId, Selection}; +use vectorcraft_geom::{Rect, shapes}; + +fn gesture(d: &Document, s: &Selection, points: &[(f64, f64)], mods: Mods, isolation: Option) -> Vec { + let p = paint(); + let cx = ToolContext { isolation, ..cx(d, s, &p) }; + let mut tool = crate::create(ID); + assert_eq!(tool.id(), ID); + let &(x, y) = points.first().unwrap(); + tool.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y)); + for &(x, y) in points.iter().skip(1) { + tool.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y)); + } + let &(x, y) = points.last().unwrap(); + tool.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(mods)) +} + +const AROUND: &[(f64, f64)] = &[(90.0, 90.0), (210.0, 90.0), (210.0, 210.0), (90.0, 210.0)]; + +#[test] +fn enclosing_lasso_selects_only_whole_objects_and_preserves_modifier_rules() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + assert_eq!(gesture(&d, &s, AROUND, Mods::default(), None), vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]); + let corner = &[(90.0, 90.0), (150.0, 90.0), (90.0, 150.0)]; + assert_eq!(gesture(&d, &s, corner, Mods::default(), None), vec![Action::Exec("select.set".into(), json!({"ids": []}))]); + let shift = Mods { shift: true, ..Mods::default() }; + let alt = Mods { alt: true, ..Mods::default() }; + assert_eq!(gesture(&d, &s, AROUND, shift, None), vec![Action::Exec("select.add".into(), json!({"ids": [id.0]}))]); + assert!(gesture(&d, &s, AROUND, alt, None).is_empty()); + s.objects.push(id); + assert_eq!(gesture(&d, &s, AROUND, alt, None), vec![Action::Exec("select.toggle".into(), json!({"ids": [id.0]}))]); + assert!(gesture(&d, &s, corner, shift, None).is_empty()); +} + +#[test] +fn enclosing_lasso_checks_curves_and_concave_edges_between_inside_anchors() { + let region = crate::xform::polygon(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)], true); + let region = Region::new(region).unwrap(); + let mut curve = BezPath::new(); + curve.move_to((2.0, 5.0)); + curve.curve_to((3.0, -15.0), (7.0, -15.0), (8.0, 5.0)); + assert!(!enclosed(&curve, ®ion), "inside endpoints do not contain a curve that bulges outside"); + let notch = crate::xform::polygon( + &[ + Point::new(0.0, 0.0), + Point::new(10.0, 0.0), + Point::new(10.0, 10.0), + Point::new(6.0, 10.0), + Point::new(6.0, 4.0), + Point::new(4.0, 4.0), + Point::new(4.0, 10.0), + Point::new(0.0, 10.0), + ], + true, + ); + let line = |a, b| { + let mut p = BezPath::new(); + p.move_to(a); + p.line_to(b); + p + }; + let notch = Region::new(notch).unwrap(); + assert!(!enclosed(&line((2.0, 8.0), (8.0, 8.0)), ¬ch)); + assert!(enclosed(&line((2.0, 2.0), (8.0, 2.0)), ¬ch)); + assert!(enclosed(&Rect::new(0.0, 0.0, 10.0, 10.0).to_path(0.01), ®ion), "boundary contact is enclosed"); +} + +#[test] +fn enclosing_lasso_uses_path_geometry_instead_of_its_bounding_box() { + let (mut d, id) = doc_with_rect(); + let mut triangle = BezPath::new(); + triangle.move_to((100.0, 100.0)); + triangle.line_to((190.0, 100.0)); + triangle.line_to((100.0, 190.0)); + triangle.close_path(); + let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!() }; + *path = PathData::from_bezpath(&triangle); + let loop_points = &[(90.0, 90.0), (210.0, 90.0), (90.0, 210.0)]; + assert_eq!( + gesture(&d, &Selection::default(), loop_points, Mods::default(), None), + vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))] + ); +} + +#[test] +fn enclosing_lasso_skips_locked_hidden_and_out_of_isolation_objects() { + let (mut d, id) = doc_with_rect(); + let s = Selection::default(); + d.node_mut(id).unwrap().locked = true; + assert_eq!(gesture(&d, &s, AROUND, Mods::default(), None), vec![Action::Exec("select.set".into(), json!({"ids": []}))]); + d.node_mut(id).unwrap().locked = false; + d.node_mut(id).unwrap().visible = false; + assert_eq!(gesture(&d, &s, AROUND, Mods::default(), None), vec![Action::Exec("select.set".into(), json!({"ids": []}))]); + d.node_mut(id).unwrap().visible = true; + let other = d.alloc_id(); + d.insert(Some(d.layers[0].id), 1, Node::path(other, shapes::rectangle(Rect::new(300.0, 300.0, 350.0, 350.0)), Appearance::default_art())) + .unwrap(); + assert_eq!(gesture(&d, &s, AROUND, Mods::default(), Some(other)), vec![Action::Exec("select.set".into(), json!({"ids": []}))]); +} + +#[test] +fn enclosing_lasso_escape_cancels_without_changing_selection() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut tool = EnclosingLassoTool::default(); + tool.pointer(&cx, &PointerEvent::new(PointerKind::Down, 90.0, 90.0)); + tool.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 210.0, 90.0)); + assert!(tool.busy()); + assert_eq!(tool.overlays(&cx).len(), 1); + assert!(tool.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); + assert!(!tool.busy()); + assert!(tool.overlays(&cx).is_empty()); + assert!(tool.pointer(&cx, &PointerEvent::new(PointerKind::Up, 90.0, 210.0)).is_empty()); +} + +#[test] +fn enclosing_lasso_degenerate_loop_does_not_select_a_boundary_line() { + let (mut d, id) = doc_with_rect(); + let mut line = BezPath::new(); + line.move_to((100.0, 100.0)); + line.line_to((200.0, 200.0)); + let n = d.node_mut(id).unwrap(); + *n.path_data_mut().unwrap() = PathData::from_bezpath(&line); + n.appearance.set_fill(vectorcraft_color::Paint::None); + let points = &[(90.0, 90.0), (150.0, 150.0), (210.0, 210.0)]; + assert_eq!(gesture(&d, &Selection::default(), points, Mods::default(), None), vec![Action::Exec("select.set".into(), json!({"ids": []}))]); +} + +#[test] +fn enclosing_lasso_invalid_release_cancels_the_gesture() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut tool = EnclosingLassoTool::default(); + tool.pointer(&cx, &PointerEvent::new(PointerKind::Down, 90.0, 90.0)); + tool.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 210.0, 90.0)); + assert!(tool.pointer(&cx, &PointerEvent::new(PointerKind::Up, f64::NAN, 210.0)).is_empty()); + assert!(!tool.busy()); + assert!(tool.overlays(&cx).is_empty()); +} + +fn loop_with_hole() -> BezPath { + crate::xform::polygon( + &[ + Point::new(0.0, 0.0), + Point::new(10.0, 0.0), + Point::new(10.0, 10.0), + Point::new(0.0, 10.0), + Point::new(0.0, 0.0), + Point::new(3.0, 3.0), + Point::new(3.0, 7.0), + Point::new(7.0, 7.0), + Point::new(7.0, 3.0), + Point::new(3.0, 3.0), + Point::new(0.0, 0.0), + ], + true, + ) +} + +#[test] +fn enclosing_lasso_rejects_filled_objects_covering_a_hole_in_the_loop() { + let region = Region::new(loop_with_hole()).unwrap(); + let path = shapes::rectangle(Rect::new(2.0, 2.0, 8.0, 8.0)); + assert!(enclosed(&path.to_bezpath(), ®ion), "the hole does not cross the object's outline"); + assert!(!path_inside(&path, FillRule::NonZero, true, ®ion)); + assert!(path_inside(&path, FillRule::NonZero, false, ®ion), "an unfilled outline may surround the hole"); + let mut node = Node::path(NodeId(10), path, Appearance::default_art()); + let doc = Document::new(20.0, 20.0); + let symbols = doc.symbol_boxes(); + assert!(!node_inside(&node, &symbols, ®ion)); + for item in &mut node.appearance.items { + if let AppearanceItem::Fill(fill) = item { + fill.visible = false; + } + } + assert!(node_inside(&node, &symbols, ®ion), "a hidden fill does not cover the loop's hole"); +} + +#[test] +fn enclosing_lasso_selects_group_members_but_keeps_compounds_whole() { + let (mut d, id) = doc_with_rect(); + let group = d.alloc_id(); + let a = d.alloc_id(); + let b = d.alloc_id(); + let children = vec![ + std::sync::Arc::new(Node::path(a, shapes::rectangle(Rect::new(120.0, 120.0, 140.0, 140.0)), Appearance::default_art())), + std::sync::Arc::new(Node::path(b, shapes::rectangle(Rect::new(300.0, 300.0, 320.0, 320.0)), Appearance::default_art())), + ]; + d.insert(Some(d.layers[0].id), 1, Node::new(group, NodeKind::Group { children: children.clone(), clip: false })).unwrap(); + let s = Selection::default(); + assert_eq!(gesture(&d, &s, AROUND, Mods::default(), None), vec![Action::Exec("select.set".into(), json!({"ids": [id.0, a.0]}))]); + d.node_mut(group).unwrap().kind = NodeKind::Compound { children, rule: FillRule::NonZero }; + assert_eq!(gesture(&d, &s, AROUND, Mods::default(), None), vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]); +} + +#[test] +fn enclosing_lasso_accepts_a_figure_eight_with_zero_signed_area() { + let (mut d, id) = doc_with_rect(); + *d.node_mut(id).unwrap().path_data_mut().unwrap() = shapes::rectangle(Rect::new(130.0, 105.0, 170.0, 115.0)); + let points = &[(90.0, 90.0), (210.0, 210.0), (90.0, 210.0), (210.0, 90.0)]; + assert_eq!(gesture(&d, &Selection::default(), points, Mods::default(), None), vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]); +} + +#[test] +fn enclosing_lasso_checks_nonpath_box_interiors_as_well_as_edges() { + let (d, _) = doc_with_rect(); + let mut n = Node::new(NodeId(900), NodeKind::SymbolInstance { symbol: "missing".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + // Place the missing-symbol fallback box exactly inside the outer loop. + let b = n.geometric_bounds().unwrap(); + let xf = vectorcraft_geom::Affine::translate((2.0, 2.0)) + * vectorcraft_geom::Affine::scale_non_uniform(6.0 / b.width(), 6.0 / b.height()) + * vectorcraft_geom::Affine::translate((-b.x0, -b.y0)); + n.kind = NodeKind::SymbolInstance { symbol: "missing".into(), xf }; + let region = Region::new(loop_with_hole()).unwrap(); + assert!(!node_inside(&n, &d.symbol_boxes(), ®ion)); +} + +#[test] +fn enclosing_lasso_uses_the_release_position_and_click_clears_only_without_modifiers() { + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut tool = EnclosingLassoTool::default(); + tool.pointer(&cx, &PointerEvent::new(PointerKind::Down, 90.0, 90.0)); + tool.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 210.0, 90.0)); + tool.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 210.0, 210.0)); + assert_eq!(tool.pointer(&cx, &PointerEvent::new(PointerKind::Up, 90.0, 210.0)), vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]); + assert!(!tool.busy()); + assert!(tool.overlays(&cx).is_empty()); + assert_eq!(gesture(&d, &s, &[(90.0, 90.0)], Mods::default(), None), vec![Action::Exec("select.set".into(), json!({"ids": []}))]); + assert!(gesture(&d, &s, &[(90.0, 90.0)], Mods { shift: true, ..Mods::default() }, None).is_empty()); +} + +#[test] +fn enclosing_lasso_selects_single_anchor_objects_but_checks_every_disconnected_point() { + let (mut d, id) = doc_with_rect(); + let mut point = BezPath::new(); + point.move_to((150.0, 150.0)); + *d.node_mut(id).unwrap().path_data_mut().unwrap() = PathData::from_bezpath(&point); + assert_eq!(gesture(&d, &Selection::default(), AROUND, Mods::default(), None), vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]); + let mut path = shapes::rectangle(Rect::new(120.0, 120.0, 140.0, 140.0)).to_bezpath(); + path.move_to((300.0, 300.0)); + *d.node_mut(id).unwrap().path_data_mut().unwrap() = PathData::from_bezpath(&path); + assert_eq!(gesture(&d, &Selection::default(), AROUND, Mods::default(), None), vec![Action::Exec("select.set".into(), json!({"ids": []}))]); +} + +#[test] +fn enclosing_lasso_cancels_an_overlong_gesture_instead_of_silently_truncating_it() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut tool = EnclosingLassoTool::default(); + tool.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + for i in 1..=MAX_POINTS { + assert!(tool.pointer(&cx, &PointerEvent::new(PointerKind::Drag, i as f64, 100.0)).is_empty()); + } + assert!(!tool.busy()); + assert!(tool.overlays(&cx).is_empty()); + assert!(tool.pointer(&cx, &PointerEvent::new(PointerKind::Up, 0.0, 200.0)).is_empty()); +} + +#[test] +#[ignore = "manual large-document selection timing"] +fn enclosing_lasso_dense_document_timing() { + let count = std::env::var("ENCLOSING_LASSO_BENCH_OBJECTS").ok().and_then(|v| v.parse::().ok()).unwrap_or(1000).clamp(1, 50_000); + let d = Document::new(1000.0, 1000.0); + let symbols = d.symbol_boxes(); + let nodes: Vec<_> = (0..count) + .map(|i| { + let (x, y) = if count <= 1000 { + (350.0 + (i % 25) as f64 * 5.0, 350.0 + (i / 25) as f64 * 5.0) + } else { + (250.0 + (i % 250) as f64 * 2.0, 300.0 + (i / 250) as f64 * 2.0) + }; + Node::path(NodeId(i as u64 + 10), shapes::rectangle(Rect::new(x, y, x + 2.0, y + 2.0)), Appearance::default_art()) + }) + .collect(); + let points: Vec<_> = (0..1000) + .map(|i| { + let angle = f64::from(i) * std::f64::consts::TAU / 1000.0; + Point::new(500.0 + angle.cos() * 450.0, 500.0 + angle.sin() * 450.0) + }) + .collect(); + let start = std::time::Instant::now(); + let region = Region::new(crate::xform::polygon(&points, true)).unwrap(); + let selected = nodes.iter().filter(|n| node_inside(n, &symbols, ®ion)).count(); + let elapsed = start.elapsed(); + assert_eq!(selected, count); + eprintln!("Enclosing Lasso: {selected} objects, 1000-point loop, {} microseconds", elapsed.as_micros()); +} + +#[test] +fn enclosing_lasso_selection_does_not_change_when_a_concave_loop_has_more_samples() { + let (d, _) = doc_with_rect(); + let sparse = [(90.0, 90.0), (210.0, 90.0), (210.0, 210.0), (160.0, 210.0), (160.0, 150.0), (140.0, 150.0), (140.0, 210.0), (90.0, 210.0)]; + let mut dense = vec![]; + for (a, b) in sparse.iter().zip(sparse.iter().cycle().skip(1)) { + let (a, b) = (Point::new(a.0, a.1), Point::new(b.0, b.1)); + for i in 0..40 { + let p = a.lerp(b, f64::from(i) / 40.0); + dense.push((p.x, p.y)); + } + } + let s = Selection::default(); + assert_eq!(gesture(&d, &s, &sparse, Mods::default(), None), vec![Action::Exec("select.set".into(), json!({"ids": []}))]); + assert_eq!(gesture(&d, &s, &dense, Mods::default(), None), gesture(&d, &s, &sparse, Mods::default(), None)); +} + +#[test] +fn enclosing_lasso_boundary_query_does_not_repeat_an_edge_across_its_height() { + let region = Region::new(Rect::new(0.0, 0.0, 10.0, 10.0).to_path(0.01)).unwrap(); + assert_eq!( + region.near(Rect::new(0.0, 0.0, 10.0, 10.0)).count(), + 4, + "one intersection check per boundary edge, even for a query spanning its full height" + ); +} + +#[test] +fn enclosing_lasso_considers_the_geometry_a_visible_compound_paints() { + let (mut d, rect) = doc_with_rect(); + let compound = d.alloc_id(); + let mut children = vec![]; + for x in [120.0, 160.0] { + let mut member = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 120.0, x + 20.0, 140.0)), Appearance::default_art()); + member.visible = false; + children.push(std::sync::Arc::new(member)); + } + // Compound painting assembles all member paths, independently of their own visibility flags. + let mut object = Node::new(compound, NodeKind::Compound { children, rule: FillRule::NonZero }); + object.appearance = Appearance::default_art().into(); + d.insert(Some(d.layers[0].id), 1, object).unwrap(); + let s = Selection::default(); + assert_eq!( + vectorcraft_doc::hit::marquee(&d, Rect::new(90.0, 90.0, 210.0, 210.0), None, true), + vec![rect], + "the existing rectangular marquee rule is unchanged" + ); + assert_eq!(gesture(&d, &s, AROUND, Mods::default(), None), vec![Action::Exec("select.set".into(), json!({"ids": [rect.0, compound.0]}))]); + d.node_mut(compound).unwrap().locked = true; + assert_eq!(gesture(&d, &s, AROUND, Mods::default(), None), vec![Action::Exec("select.set".into(), json!({"ids": [rect.0]}))]); + d.node_mut(compound).unwrap().locked = false; + d.node_mut(compound).unwrap().visible = false; + assert_eq!(gesture(&d, &s, AROUND, Mods::default(), None), vec![Action::Exec("select.set".into(), json!({"ids": [rect.0]}))]); + d.node_mut(compound).unwrap().visible = true; + let NodeKind::Compound { children, .. } = &mut d.node_mut(compound).unwrap().kind else { panic!() }; + *std::sync::Arc::make_mut(&mut children[1]).path_data_mut().unwrap() = shapes::rectangle(Rect::new(300.0, 120.0, 320.0, 140.0)); + assert_eq!( + gesture(&d, &s, AROUND, Mods::default(), None), + vec![Action::Exec("select.set".into(), json!({"ids": [rect.0]}))], + "every member contributes to the compound's geometry" + ); + for visible in [[true, false], [false, true], [true, true], [false, false]] { + let NodeKind::Compound { children, .. } = &mut d.node_mut(compound).unwrap().kind else { panic!() }; + for (child, visible) in children.iter_mut().zip(visible) { + std::sync::Arc::make_mut(child).visible = visible; + } + assert_eq!( + gesture(&d, &s, AROUND, Mods::default(), None), + vec![Action::Exec("select.set".into(), json!({"ids": [rect.0]}))], + "a compound with an outside member is not enclosed: {visible:?}" + ); + } +} diff --git a/crates/tools/src/addons/measure_inspect.rs b/crates/tools/src/addons/measure_inspect.rs index d46edb6c64..1ea8a9324d 100644 --- a/crates/tools/src/addons/measure_inspect.rs +++ b/crates/tools/src/addons/measure_inspect.rs @@ -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}"); + } } diff --git a/crates/tools/src/addons/smart_pen.rs b/crates/tools/src/addons/smart_pen.rs index f2b52219e6..90c73620a1 100644 --- a/crates/tools/src/addons/smart_pen.rs +++ b/crates/tools/src/addons/smart_pen.rs @@ -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 { + 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()) } diff --git a/crates/tools/src/builder/map.rs b/crates/tools/src/builder/map.rs index e217d6980d..ddcbcb310e 100644 --- a/crates/tools/src/builder/map.rs +++ b/crates/tools/src/builder/map.rs @@ -448,9 +448,15 @@ pub fn hatch(path: &BezPath, gap: f64) -> BezPath { y1 = y1.max(a.y.max(c.y)); } let gap = gap.max((y1 - y0) / 400.0).max(1e-6); - let mut y = (y0 / gap).floor() * gap + gap * 0.5; + let start = (y0 / gap).floor() * gap + gap * 0.5; let mut xs: Vec = vec![]; - while y < y1 { + // Counted, not summed: far from the origin `y + gap` can round back to `y`. The gap is at least + // a 400th of the height, so 402 lines cover it. + for i in 0..402u32 { + let y = start + f64::from(i) * gap; + if y.partial_cmp(&y1) != Some(std::cmp::Ordering::Less) { + break; + } xs.clear(); for (a, c) in &edges { if (a.y <= y) != (c.y <= y) { @@ -462,7 +468,6 @@ pub fn hatch(path: &BezPath, gap: f64) -> BezPath { out.move_to(unrot(Point::new(pair[0], y))); out.line_to(unrot(Point::new(pair[1], y))); } - y += gap; } out } diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index acaac0ec83..2104609cf7 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -713,6 +713,13 @@ fn hatch_stays_inside_region() { assert!(h.elements().len() > 10); } +#[test] +fn hatch_far_from_the_origin_ends() { + // At 1e17 a 4-point gap is below the coordinates' precision: adding it doesn't move the line. + let bp = shapes::rectangle(Rect::new(0.0, 1e17, 64.0, 1e17 + 64.0)).to_bezpath(); + assert!(hatch(&bp, 4.0).elements().len() <= 2 * 402); +} + /// An empty hidden sources group for a Live Paint group made in a test. fn empty_sources(d: &mut Document) -> Arc { let mut g = Node::group(d.alloc_id(), vec![]); diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index d6860bb7bc..85b7272223 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -256,6 +256,9 @@ pub struct ToolContext<'a> { /// General › Use Precise Cursors, or Caps Lock while it is on: the drawing tools' pointers are /// crosshairs ([`crate::Cursor::precise`]), and the Blob Brush and the Eraser show no tip outline. pub precise_cursors: bool, + /// The objects of the Global Edit in progress (Select › Start Global Edit), the one it started + /// from first, each with its transform; empty while Global Edit is off. + pub global_edit: &'a [(NodeId, vectorcraft_geom::Affine)], } impl ToolContext<'_> { diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs index 52f347e91c..ff716bf171 100644 --- a/crates/tools/src/cropimage.rs +++ b/crates/tools/src/cropimage.rs @@ -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 { + 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(); diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index 5447261e63..0ac3e610ab 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -672,7 +672,7 @@ hotspot = "The tip." [[cursor]] id = "Lasso" group = "Drawing and editing tools" -shown_when = ["The Lasso tool: drag a loop round anchor points and segments to select them; Shift adds to the selection, Alt takes from it."] +shown_when = ["The Lasso tool: drag a loop round anchor points and segments to select them; Shift adds to the selection, Alt takes from it.", "The Enclosing Lasso tool: draw a loop to select fully enclosed objects; Shift adds, Alt subtracts."] hotspot = "Where the loop is drawn from." [[cursor]] diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index d3c7bdf83e..2290f5d2fd 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -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 { + if self.dragging { + return self.key(cx, ToolKey::Escape, Mods::default()); + } + self.press = None; + vec![] + } fn deactivate(&mut self, cx: &ToolContext) -> Vec { 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"); + } +} diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 4a38efc82a..c321975182 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -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, } 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 { } 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 { + 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 }; diff --git a/crates/tools/src/distort/liquify.rs b/crates/tools/src/distort/liquify.rs index 3e23b769d1..efc68132a1 100644 --- a/crates/tools/src/distort/liquify.rs +++ b/crates/tools/src/distort/liquify.rs @@ -508,31 +508,46 @@ fn simplify(sp: &mut SubPath, tol: f64, region: Rect) { if tol <= 0.0 { return; } + let min = if sp.closed { 4 } else { 3 }; + let src = std::mem::take(&mut sp.anchors); + let n = src.len(); + // Compacted into `out`, each anchor moved once: removing them from the middle one by one + // shifts the rest every time. + let mut out: Vec = Vec::with_capacity(n); + let mut src = src.into_iter().peekable(); + out.extend(src.next()); + let last = if sp.closed { n } else { n.saturating_sub(1) }; let mut i = 1; - loop { - let n = sp.anchors.len(); - let min = if sp.closed { 4 } else { 3 }; - if n < min { - return; - } - let last = if sp.closed { n } else { n - 1 }; - if i >= last { - return; - } - let (pa, k, pb) = (sp.anchors[i - 1], sp.anchors[i], sp.anchors[(i + 1) % n]); - let flat = region.contains(k.p) + while let Some(k) = src.next() { + // Anchors left if `k` stays: those kept, `k`, and those not yet looked at. + let left = out.len() + 1 + src.len(); + let Some(&pa) = out.last() else { break }; + let pb = match src.peek() { + Some(pb) => *pb, + None => out[0], + }; + let flat = i < last + && left >= min + && region.contains(k.p) && [k.p, k.h_in, k.h_out, pa.h_out, pb.h_in].iter().all(|q| dist_seg(*q, pa.p, pb.p) <= tol) && (k.p - pa.p).dot(pb.p - k.p) > 0.0; - if flat { - let lab = pa.p.distance(pb.p); - let (lak, lkb) = (pa.p.distance(k.p).max(1e-9), k.p.distance(pb.p).max(1e-9)); - sp.anchors[i - 1].h_out = pa.p + (pa.h_out - pa.p) * (lab / lak); - sp.anchors[(i + 1) % n].h_in = pb.p + (pb.h_in - pb.p) * (lab / lkb); - sp.anchors.remove(i); - } else { - i += 1; + i += 1; + if !flat { + out.push(k); + continue; + } + let lab = pa.p.distance(pb.p); + let (lak, lkb) = (pa.p.distance(k.p).max(1e-9), k.p.distance(pb.p).max(1e-9)); + if let Some(a) = out.last_mut() { + a.h_out = pa.p + (pa.h_out - pa.p) * (lab / lak); + } + let h_in = pb.p + (pb.h_in - pb.p) * (lab / lkb); + match src.peek_mut() { + Some(b) => b.h_in = h_in, + None => out[0].h_in = h_in, } } + sp.anchors = out; } /// Apply a liquify stroke (its dabs, at the brush's intensity) to `path`. `salt` decorrelates @@ -888,6 +903,21 @@ mod tests { LiquifyParams { intensity: 1.0, ..LiquifyParams::new(kind) } } + #[test] + fn simplify_drops_flat_anchors_and_keeps_the_ends() { + let pts: Vec = (0..200_000).map(|i| Point::new(i as f64, 0.0)).collect(); + let mut open = SubPath::polyline(&pts, false); + let start = std::time::Instant::now(); + simplify(&mut open, 0.5, Rect::new(-1.0, -1.0, 1e6, 1.0)); + assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed()); + assert_eq!(open.anchors.iter().map(|a| a.p).collect::>(), [pts[0], pts[199_999]]); + // A closed square with a flat midpoint on each side keeps its four corners. + let ring = [(0.0, 0.0), (5.0, 0.0), (10.0, 0.0), (10.0, 5.0), (10.0, 10.0), (5.0, 10.0), (0.0, 10.0), (0.0, 5.0)]; + let mut closed = SubPath::polyline(&ring.map(|(x, y)| Point::new(x, y)), true); + simplify(&mut closed, 0.5, Rect::new(-1.0, -1.0, 11.0, 11.0)); + assert_eq!(closed.anchors.iter().map(|a| (a.p.x, a.p.y)).collect::>(), [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]); + } + #[test] fn dabs_are_evenly_spaced() { let d = dabs(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0)], 10.0); diff --git a/crates/tools/src/distort/width.rs b/crates/tools/src/distort/width.rs index 27592035b2..e7050d3a79 100644 --- a/crates/tools/src/distort/width.rs +++ b/crates/tools/src/distort/width.rs @@ -105,6 +105,8 @@ pub struct WidthTool { drag: Option, /// Selected width points: the stroke's owner and their positions t. selected: Option<(NodeId, Vec)>, + /// The selected width points when the button went down: a dropped press puts them back. + before_press: Option<(NodeId, Vec)>, } /// 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 { + self.drag = None; + self.selected = self.before_press.take(); + vec![] + } fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { 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(); diff --git a/crates/tools/src/draw2/curvature.rs b/crates/tools/src/draw2/curvature.rs index 8301c108ce..70ad9a7e4a 100644 --- a/crates/tools/src/draw2/curvature.rs +++ b/crates/tools/src/draw2/curvature.rs @@ -35,6 +35,9 @@ pub struct CurvatureTool { id: Option, /// 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)>, /// Last touched point of the path being drawn (Backspace removes it). current: Option, hover: Option, @@ -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 { + 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 { match key { ToolKey::Escape | ToolKey::Enter => { diff --git a/crates/tools/src/draw2/curvature/tests.rs b/crates/tools/src/draw2/curvature/tests.rs index 412292ef91..05593a3dc3 100644 --- a/crates/tools/src/draw2/curvature/tests.rs +++ b/crates/tools/src/draw2/curvature/tests.rs @@ -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() { diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 1ca8df7c01..bf2edac343 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -24,6 +24,7 @@ pub mod intertwine; pub mod meshblend; pub mod meshedit; pub mod mirror; +pub mod nineslice; pub mod objects_on_path; pub mod params; pub mod pathtype; @@ -123,6 +124,12 @@ pub trait Tool: Send { fn key(&mut self, _cx: &ToolContext, _key: ToolKey, _mods: Mods) -> Vec { 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 { + self.key(cx, ToolKey::Escape, Mods::default()) + } fn overlays(&self, _cx: &ToolContext) -> Vec { vec![] } @@ -508,6 +515,7 @@ pub(crate) mod testutil { screen: None, plane_widget: Some(Default::default()), precise_cursors: false, + global_edit: &[], } } } @@ -530,6 +538,7 @@ mod cursor_tests { let away = Point::new(400.0, 400.0); for (id, c) in [ ("lasso", Cursor::Lasso), + (addons::enclosing_lasso::ID, Cursor::Lasso), ("magicWand", Cursor::MagicWand), ("paintbrush", Cursor::Paintbrush), ("blobBrush", Cursor::BlobBrush), diff --git a/crates/tools/src/meshblend.rs b/crates/tools/src/meshblend.rs index 0790407d2a..a9f3928ec0 100644 --- a/crates/tools/src/meshblend.rs +++ b/crates/tools/src/meshblend.rs @@ -48,6 +48,9 @@ pub struct BlendTool { first: Option, /// 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, 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 { + if let Some((first, chained)) = self.before_press.take() { + (self.first, self.chained) = (first, chained); + } + vec![] + } fn deactivate(&mut self, _cx: &ToolContext) -> Vec { (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(); diff --git a/crates/tools/src/meshedit.rs b/crates/tools/src/meshedit.rs index e0ef779fb5..c0c1d96231 100644 --- a/crates/tools/src/meshedit.rs +++ b/crates/tools/src/meshedit.rs @@ -257,6 +257,27 @@ impl MeshEdit { meshes.into_iter().map(|id| (id, self.picked.range((id, 0)..=(id, usize::MAX)).next().is_some())).collect() } + /// A Lasso's picks: the points `inside` it are picked alone, or added to the picked points + /// (`add`), or taken away from them (`sub`). Returns each mesh with points inside and whether + /// any of its points are picked now. + pub fn lasso(&mut self, inside: &[(NodeId, usize)], add: bool, sub: bool) -> Vec<(NodeId, bool)> { + if !add && !sub { + return self.marquee(inside, false); + } + for k in inside { + if sub { + self.picked.remove(k); + } else { + self.picked.insert(*k); + } + } + self.click = None; + self.focus = self.focus.filter(|f| self.picked.contains(f)); + let mut meshes: Vec = inside.iter().map(|(id, _)| *id).collect(); + meshes.dedup(); + meshes.into_iter().map(|id| (id, self.picked.range((id, 0)..=(id, usize::MAX)).next().is_some())).collect() + } + /// An arrow key's nudge of the picked points of the meshes `shown` accepts /// (`object.mesh.movePoints`); `None` during a drag, for other keys or without picked points. pub fn nudge(&self, cx: &ToolContext, key: ToolKey, mods: Mods, shown: &dyn Fn(NodeId) -> bool) -> Option> { diff --git a/crates/tools/src/nineslice.rs b/crates/tools/src/nineslice.rs new file mode 100644 index 0000000000..61de9e9580 --- /dev/null +++ b/crates/tools/src/nineslice.rs @@ -0,0 +1,229 @@ +//! The 9-slice guides of a symbol edited in symbol editing mode: two horizontal and two vertical +//! guides over its art +//! ([helpx: maintain proportions while scaling symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html)). +//! The canvas draws them, dotted, with any tool. With the Selection tool, the pointer near a guide +//! takes the Move cursor, and dragging the guide moves it (`symbol.options`'s +//! `nineSliceGuides`), in one undo step. +//! +//! VectorCraft's own rules: a guide stays within the art's box and stops short of the opposite +//! guide; the drag does not snap and its modifiers change nothing; a guide within reach takes the +//! press before the art and the bounding box, and of two guides within reach the nearer one, else +//! the first of left, top, right and bottom; Escape during the drag puts the guide back. + +use serde_json::json; +use vectorcraft_doc::{EditedNineSlice, NineSliceGuide}; +use vectorcraft_geom::Point; + +use crate::{Action, PointerEvent, ToolContext}; + +/// How near (screen px) the pointer must come to a guide to take it. +const HIT_PX: f64 = 4.0; + +/// The distance from `p` to the segment from `a` to `b`. +fn to_segment(p: Point, a: Point, b: Point) -> f64 { + let d = b - a; + let len2 = d.hypot2(); + let t = if len2 > 0.0 { ((p - a).dot(d) / len2).clamp(0.0, 1.0) } else { 0.0 }; + p.distance(a + d * t) +} + +/// The edited symbol's guides and the one within reach of `p`, the nearest first. +pub fn guide_at(cx: &ToolContext, p: Point) -> Option<(EditedNineSlice, NineSliceGuide)> { + if !(p.x.is_finite() && p.y.is_finite()) { + return None; + } + let e = cx.doc.edited_nine_slice()?; + let reach = cx.tol(HIT_PX); + let near = e + .lines() + .into_iter() + .map(|(g, a, b)| (g, to_segment(p, a, b))) + .filter(|(_, d)| *d <= reach) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(g, _)| g)?; + Some((e, near)) +} + +/// Is `p` over a guide of the edited symbol? +pub fn over_guide(cx: &ToolContext, p: Point) -> bool { + guide_at(cx, p).is_some() +} + +/// Dragging a 9-slice guide. +#[derive(Clone, Debug)] +pub struct GuideDrag { + frame: EditedNineSlice, + guide: NineSliceGuide, + start: Point, + began: bool, +} + +impl GuideDrag { + /// Start a drag when the press `ev` is on a guide of the edited symbol. + pub fn hit(cx: &ToolContext, ev: &PointerEvent) -> Option { + let (frame, guide) = guide_at(cx, ev.pos)?; + Some(Self { frame, guide, start: ev.pos, began: false }) + } + + /// The drag has left the click: the guide is moving. + pub fn adjusting(&self) -> bool { + self.began + } + + pub fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec { + if !(p.x.is_finite() && p.y.is_finite()) || (!self.began && p.distance(self.start) < cx.tol(3.0)) { + return vec![]; + } + let mut out = vec![]; + if !self.began { + self.began = true; + out.push(Action::Begin("Symbol Options".into())); + } + let guides = self.frame.moved(self.guide, p); + out.push(Action::Preview("symbol.options".into(), json!({ "name": self.frame.symbol, "nineSliceGuides": guides.to_value() }))); + out + } + + pub fn finish(self) -> Vec { + if self.began { vec![Action::Commit] } else { vec![] } + } + + pub fn cancel(self) -> Vec { + if self.began { vec![Action::Cancel] } else { vec![] } + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::*; + use crate::select::SelectionTool; + use crate::testutil::*; + use crate::{Cursor, Mods, PointerKind, Tool, ToolKey}; + use vectorcraft_doc::{Appearance, Document, Node, Selection, Symbol, SymbolEdit, SymbolNineSlice}; + use vectorcraft_geom::{Affine, Rect, shapes}; + + /// A 100 × 100 symbol "S" with 9-slice guides `guides`, edited in symbol editing mode with its + /// art, a filled square, at (100, 100) on the editing layer: its guides lie at x and y = 125 + /// and 175. + fn editing(guides: Option) -> Document { + let mut d = Document::new(500.0, 500.0); + let square = |d: &mut Document, r: Rect| Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art()); + let art = square(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0)); + d.symbols.push(Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); + d.set_symbol_nine_slice("S", guides); + let layer = d.add_layer(Some("S")); + let copy = square(&mut d, Rect::new(100.0, 100.0, 200.0, 200.0)); + d.insert(Some(layer), 0, copy).unwrap(); + d.symbol_edit = Some(SymbolEdit { + symbol: "S".into(), + layer, + instance: None, + xf: Affine::translate((100.0, 100.0)), + group: false, + changed: false, + back_isolation: None, + back_layer: None, + }); + d + } + + fn ev(kind: PointerKind, x: f64, y: f64) -> PointerEvent { + PointerEvent::new(kind, x, y) + } + + fn preview(a: &Action) -> (String, serde_json::Value) { + match a { + Action::Preview(cmd, v) => (cmd.clone(), v.clone()), + other => panic!("{other:?}"), + } + } + + /// The pointer within 4 screen px of a guide takes it at any zoom, the nearer of two where + /// they cross, and nothing is taken outside symbol editing mode or without guides. + #[test] + fn a_guide_is_taken_within_a_few_screen_pixels_at_any_zoom() { + let d = editing(Some(SymbolNineSlice::default())); + let (s, p) = (Selection::default(), paint()); + for zoom in [0.25, 1.0, 8.0] { + let c = ToolContext { zoom, ..cx(&d, &s, &p) }; + let at = |x: f64, y: f64| guide_at(&c, Point::new(x, y)).map(|(_, g)| g); + assert_eq!(at(125.0 + 3.5 / zoom, 150.0), Some(NineSliceGuide::Left), "{zoom}"); + assert_eq!(at(125.0 + 5.0 / zoom, 150.0), None, "{zoom}"); + assert_eq!(at(150.0, 175.0 - 2.0 / zoom), Some(NineSliceGuide::Bottom), "{zoom}"); + // Past the art's box the guides end. + assert_eq!(at(125.0, 100.0 - 6.0 / zoom), None, "{zoom}"); + } + let c = cx(&d, &s, &p); + assert_eq!(guide_at(&c, Point::new(176.0, 173.0)).map(|(_, g)| g), Some(NineSliceGuide::Right)); + assert_eq!(guide_at(&c, Point::new(173.0, 176.0)).map(|(_, g)| g), Some(NineSliceGuide::Bottom)); + assert_eq!(guide_at(&c, Point::new(125.0, 125.0)).map(|(_, g)| g), Some(NineSliceGuide::Left), "left before top"); + assert!(guide_at(&c, Point::new(f64::NAN, 150.0)).is_none()); + let off = editing(None); + assert!(!over_guide(&cx(&off, &s, &p), Point::new(125.0, 150.0))); + let mut out = editing(Some(SymbolNineSlice::default())); + out.symbol_edit = None; + assert!(!over_guide(&cx(&out, &s, &p), Point::new(125.0, 150.0))); + } + + /// With the Selection tool, a press on a guide over the art takes the guide, not the art: the + /// pointer shows the Move cursor, the drag previews that guide alone, and the release commits + /// it as one step. A click without a drag sends nothing. + #[test] + fn dragging_a_guide_moves_that_guide_in_one_step() { + let d = editing(Some(SymbolNineSlice::default())); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let mut t = SelectionTool::default(); + assert_eq!(t.cursor(&c, Point::new(126.0, 150.0), Mods::default()), Cursor::Move); + assert_ne!(t.cursor(&c, Point::new(150.0, 150.0), Mods::default()), Cursor::Move, "the art between the guides"); + assert!(t.pointer(&c, &ev(PointerKind::Down, 126.0, 150.0)).is_empty(), "the art is not selected"); + assert!(t.busy()); + assert_eq!(t.cursor(&c, Point::new(300.0, 300.0), Mods::default()), Cursor::Move, "kept during the drag"); + let a = t.pointer(&c, &ev(PointerKind::Drag, 110.0, 400.0)); + assert_eq!(a[0], Action::Begin("Symbol Options".into())); + let (cmd, v) = preview(&a[1]); + assert_eq!(cmd, "symbol.options"); + assert_eq!(v, json!({ "name": "S", "nineSliceGuides": [0.1, 0.25, 0.25, 0.25] })); + // Past the opposite guide it stops short of it; modifiers change nothing. + let shifted = PointerEvent { mods: Mods { shift: true, alt: true, ..Mods::default() }, ..ev(PointerKind::Drag, 190.0, 150.0) }; + let (_, v) = preview(&t.pointer(&c, &shifted)[0]); + let left = v["nineSliceGuides"][0].as_f64().unwrap(); + assert!((left - (0.75 - vectorcraft_doc::MIN_CENTER_BAND)).abs() < 1e-12, "{v}"); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, 190.0, 150.0)), vec![Action::Commit]); + assert!(!t.busy()); + // A click on a guide without moving. + assert!(t.pointer(&c, &ev(PointerKind::Down, 175.0, 150.0)).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Drag, 176.0, 150.0)).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, 176.0, 150.0)).is_empty()); + // The top guide moves up and down only. + t.pointer(&c, &ev(PointerKind::Down, 150.0, 125.0)); + let a = t.pointer(&c, &ev(PointerKind::Drag, 10.0, 140.0)); + assert_eq!(preview(&a[1]).1["nineSliceGuides"], json!([0.25, 0.4, 0.25, 0.25])); + } + + /// Escape during a guide drag cancels it and is the tool's; the release after it commits + /// nothing. A double-click on a guide neither edits the art nor leaves the mode. + #[test] + fn escape_cancels_a_guide_drag_and_a_double_click_stays_on_the_guide() { + let d = editing(Some(SymbolNineSlice::default())); + let (s, p) = (Selection::default(), paint()); + let c = ToolContext { isolation: d.symbol_edit.as_ref().map(|e| e.layer), ..cx(&d, &s, &p) }; + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, 175.0, 150.0)); + assert_eq!(t.pointer(&c, &ev(PointerKind::Drag, 160.0, 150.0))[0], Action::Begin("Symbol Options".into())); + assert!(t.claims_key(&c, ToolKey::Escape)); + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert!(!t.busy() && !t.claims_key(&c, ToolKey::Escape)); + assert!(t.pointer(&c, &ev(PointerKind::Up, 160.0, 150.0)).is_empty()); + // Escape after a click that did not move cancels nothing. + t.pointer(&c, &ev(PointerKind::Down, 175.0, 150.0)); + assert!(t.key(&c, ToolKey::Escape, Mods::default()).is_empty()); + for k in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + assert!(t.pointer(&c, &ev(k, 175.0, 150.0)).is_empty(), "{k:?}"); + } + // Away from the guides a double-click outside the art still leaves isolation. + assert_eq!(t.pointer(&c, &ev(PointerKind::DoubleClick, 400.0, 400.0)), vec![Action::Exec("object.exitIsolation".into(), json!({}))]); + } +} diff --git a/crates/tools/src/objects_on_path.rs b/crates/tools/src/objects_on_path.rs index 47aff8910f..fe5a8b9215 100644 --- a/crates/tools/src/objects_on_path.rs +++ b/crates/tools/src/objects_on_path.rs @@ -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: . +//! 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: , +//! . 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], &'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 { - 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), +} + +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 { + 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::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) -> 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 { + 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 { + 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 { + 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 { + 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, /// The Rotate All widget drag, while the button is down after a press on the widget. rotating: Option, + /// The Space widget drag, while the button is down after a press on the widget. + spacing: Option, /// 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 { 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, 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 = 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; 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) -> (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) -> (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; 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()); + } + } } diff --git a/crates/tools/src/pathtype.rs b/crates/tools/src/pathtype.rs index 21fdaefc93..9f888de6cb 100644 --- a/crates/tools/src/pathtype.rs +++ b/crates/tools/src/pathtype.rs @@ -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::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 { + 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 { +/// 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, drag: Option<&BracketDrag>) -> Vec { 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 { + 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 { 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:?}"); + } } diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index a2e9d38814..e5906db59f 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -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 { + 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 { let path = self.path; diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index e6fa43602f..572c667e4b 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -11,7 +11,8 @@ //! a guide path to release it ([`release_guide_at`]), drag the brackets of type on a path //! ([`crate::pathtype`]), double-click the type widget to convert point type to area type and back //! ([`crate::typewidget`]), click a Shaper Group's mode widget to switch between Face Selection and -//! Construction mode ([`crate::shaperwidget`]). +//! Construction mode ([`crate::shaperwidget`]), drag the 9-slice guides of the symbol being edited +//! in symbol editing mode ([`crate::nineslice`]). //! The bounding box stands at the selection's own angle after a rotation, so its handles scale //! along the objects' axes. A handle drag resizes area type's frame (the type area) instead of //! scaling its type: the text reflows at its size. @@ -32,6 +33,8 @@ //! With Smart Guides and Invoke Distance Guides on, Alt/Option held over another object shows how //! far the selection is from it, and over an empty part of an artboard how far it is from the //! artboard's edges ([`crate::guides::distance_guides`]). +//! While Global Edit is on, a Shift-click on a highlighted object of it, or on an object inside +//! one, leaves that object out of the edit (`select.globalEditExclude`). use std::cell::RefCell; use std::collections::HashMap; @@ -44,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; @@ -73,6 +76,11 @@ enum State { /// guides: released without a drag, it becomes the key object that Align aligns to if /// `can_be_key` allows it (the key again: no key). key: Option, + /// Shift-pressed on this highlighted object of the Global Edit, and the object the press + /// hit: released without a drag, the first leaves the Global Edit + /// (`select.globalEditExclude`); a drag selects the second and moves it with the + /// selection. + exclude: Option<(NodeId, NodeId)>, }, Scaling { handle: Handle, @@ -99,12 +107,16 @@ 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. GridRepeat(crate::repeat_grid::GridDrag), /// Dragging a bracket of type on a path. Bracket(BracketDrag), + /// Dragging a 9-slice guide of the symbol being edited. + NineSlice(crate::nineslice::GuideDrag), /// Loaded with the text of area type or type on a path `from` by a click on its out port, or /// on its in port (`before`: the frame it goes into comes before `from` in its thread); /// `press`: where the next press went down and where the pointer is now. @@ -140,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, } /// What Distance Guides measure the selection to. @@ -546,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 @@ -612,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. @@ -639,6 +671,12 @@ impl Tool for SelectionTool { { return d.cancel(); } + if key == ToolKey::Escape + && matches!(self.state, State::NineSlice(_)) + && let State::NineSlice(d) = std::mem::take(&mut self.state) + { + return d.cancel(); + } if key == ToolKey::Escape && matches!(self.state, State::Loaded { .. }) { self.state = State::Idle; return vec![]; @@ -653,11 +691,23 @@ 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 { + 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'), State::Corner(_) => matches!(key, ToolKey::Up | ToolKey::Down), - State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) => key == ToolKey::Escape, + State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) | State::NineSlice(_) => key == ToolKey::Escape, _ => false, } } @@ -667,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 { @@ -679,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(), @@ -687,7 +739,9 @@ impl Tool for SelectionTool { } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + 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 @@ -695,6 +749,10 @@ impl Tool for SelectionTool { { return out; } + // The edited symbol's 9-slice guides take precedence over every other control and the art. + if let Some(out) = self.nine_slice_guides(cx, ev) { + return out; + } // Mirror and grid repeat controls take precedence over art and ruler guides; the mirror // axis line and the grid's controls yield to the bounding-box handles they overlap. if let Some(out) = self.repeat_controls(cx, ev) { @@ -728,7 +786,7 @@ impl Tool for SelectionTool { && cx.select_behind && let Some(behind) = object_behind(cx, p) { - self.state = State::Moving { start: p, press: p, hold: p, began: false, deselect: None, key: None }; + self.state = State::Moving { start: p, press: p, hold: p, began: false, deselect: None, key: None, exclude: None }; return vec![Action::Exec("select.set".into(), json!({ "ids": [behind.0] }))]; } let (hit, scope) = match selected_source_hit(cx, p) { @@ -739,15 +797,9 @@ impl Tool for SelectionTool { Some(h) => { let top = h.top_object(scope); let mut out = vec![]; - let (mut deselect, mut key) = (None, None); + let (mut deselect, mut key, mut exclude) = (None, None, None); if m.shift { - // A Shift-click takes a selected object out of the selection when it - // is released; a Shift-drag moves the selection, constrained. - if cx.selection.contains(top) { - deselect = Some(top); - } else { - out.push(Action::Exec("select.toggle".into(), json!({ "id": top.0 }))); - } + (deselect, exclude) = shift_press(cx, &h, top, &mut out); } else if !cx.selection.contains(top) { out.push(Action::Exec("select.set".into(), json!({ "ids": [top.0] }))); } else if (cx.selection.objects.len() > 1 || !cx.selection.guides.is_empty()) && !m.cmd && !m.alt { @@ -756,7 +808,7 @@ impl Tool for SelectionTool { // Grabbed by no anchor or centre, a press on a path's stroke or beside its // edge holds the path there, and that point of it snaps (#3701). let hold = if grabbed.is_some() { grab } else { hold_point(cx, &h, p) }; - self.state = State::Moving { start: grab, press: p, hold, began: false, deselect, key }; + self.state = State::Moving { start: grab, press: p, hold, began: false, deselect, key, exclude }; out } None => { @@ -765,8 +817,8 @@ impl Tool for SelectionTool { } } } - (PointerKind::Drag, State::Moving { start, press, hold, began, .. }) => { - self.drag_moving(cx, p, m, ev.backquote, (start, press, hold, began)) + (PointerKind::Drag, State::Moving { start, press, hold, began, exclude, .. }) => { + self.drag_moving(cx, p, m, ev.backquote, (start, press, hold, began), exclude) } (PointerKind::Drag, State::Scaling { handle, bx, areas }) => { self.last_backquote = ev.backquote; @@ -842,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); @@ -851,7 +912,9 @@ impl Tool for SelectionTool { self.state = State::Idle; b.finish() } - (PointerKind::Up, State::Moving { began, deselect, key, .. }) => self.release_move(cx, ev.backquote, began, deselect, key), + (PointerKind::Up, State::Moving { began, deselect, key, exclude, .. }) => { + self.release_move(cx, ev.backquote, began, deselect, key, exclude) + } (PointerKind::Up, State::Scaling { .. } | State::Rotating { .. }) => { let mut out = if ev.backquote || self.last_backquote { self.last_box_pos.map_or_else(Vec::new, |pos| self.pointer(cx, &PointerEvent { kind: PointerKind::Drag, pos, ..*ev })) @@ -883,7 +946,9 @@ impl Tool for SelectionTool { } fn overlays(&self, cx: &ToolContext) -> Vec { - 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() { @@ -896,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))), _ => {} } @@ -923,6 +989,9 @@ impl Tool for SelectionTool { if let State::GridRepeat(d) = &self.state { return d.cursor(cx); } + if matches!(self.state, State::NineSlice(_)) || (matches!(self.state, State::Idle) && crate::nineslice::over_guide(cx, p)) { + return Cursor::Move; + } if matches!(self.state, State::Idle) && !m.cmd && !m.ctrl @@ -941,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, _ => {} @@ -957,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; } @@ -999,6 +1072,34 @@ fn object_behind(cx: &ToolContext, p: Point) -> Option { stack.get(next).or(stack.first()).copied() } +/// A Shift-press on `top` (hit by `h`): a Shift-click takes a selected object out of the selection +/// when it is released, and a Shift-drag moves the selection, constrained. On an object of the +/// Global Edit that is highlighted, the release leaves that object out of the edit instead, and a +/// drag selects `top` when it starts. Returns the object to deselect and the object to leave out +/// on release (with `top`); adds to `out` the action that selects `top` at once. +fn shift_press(cx: &ToolContext, h: &Hit, top: NodeId, out: &mut Vec) -> (Option, Option<(NodeId, NodeId)>) { + if let Some(member) = global_edit_member(cx, h) { + (None, Some((member, top))) + } else if cx.selection.contains(top) { + (Some(top), None) + } else { + out.push(Action::Exec("select.toggle".into(), json!({ "id": top.0 }))); + (None, None) + } +} + +/// The object of the Global Edit in progress that the click `h` lands on or inside, when it is +/// highlighted: neither the object the edit started from nor one that is selected, holds a +/// selected object or sits inside a selected object (`select.globalEditExclude` leaves it out of +/// the edit). +fn global_edit_member(cx: &ToolContext, h: &Hit) -> Option { + let others = cx.global_edit.get(1..)?; + let member = h.ancestry.iter().chain([&h.leaf]).find(|id| others.iter().any(|(m, _)| m == *id)).copied()?; + let holds = cx.selection.objects.iter().any(|s| cx.doc.ancestry(*s).is_some_and(|a| a.contains(&member))); + let inside = cx.doc.ancestry(member).is_some_and(|a| a.iter().any(|id| cx.selection.contains(*id))); + (!holds && !inside).then_some(member) +} + /// Can a click make `id` the key object? `select.key` takes only a selected top-level object. In /// isolation mode a click can pick a sublayer (inside an isolated layer), a compound-path member /// (inside an isolated compound path) or an object inside another selected object (inside an @@ -1076,11 +1177,24 @@ pub(crate) fn handle_cursor(h: Handle, angle: f64) -> Cursor { mod tests; impl SelectionTool { - fn release_move(&mut self, cx: &ToolContext, backquote: bool, began: bool, deselect: Option, key: Option) -> Vec { + fn release_move( + &mut self, + cx: &ToolContext, + backquote: bool, + began: bool, + deselect: Option, + key: Option, + exclude: Option<(NodeId, NodeId)>, + ) -> Vec { self.state = State::Idle; self.measure = None; self.guides.clear(); self.moving = None; + // A Shift-click (no drag) on a highlighted object of the Global Edit leaves it out. + if let (false, Some((id, _))) = (began, exclude) { + self.last_move = None; + return vec![Action::Exec("select.globalEditExclude".into(), json!({ "id": id.0 }))]; + } let changed_mode = self.last_move.as_ref().is_some_and(|params| params.get("objects").is_some()) != backquote; let last = self.last_move.take().map(|mut params| { if backquote { @@ -1113,6 +1227,40 @@ impl SelectionTool { } } + /// A press on a 9-slice guide of the edited symbol starts dragging it; the drag and the + /// release go to it. + fn nine_slice_guides(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option> { + if let State::NineSlice(mut d) = self.state.clone() { + return Some(match ev.kind { + PointerKind::Drag => { + let out = d.drag(cx, ev.pos); + self.state = State::NineSlice(d); + out + } + PointerKind::Up => { + self.state = State::Idle; + d.finish() + } + _ => vec![], + }); + } + if !matches!(self.state, State::Idle) { + return None; + } + match ev.kind { + PointerKind::Down => { + let d = crate::nineslice::GuideDrag::hit(cx, ev)?; + self.state = State::NineSlice(d); + self.hover = None; + Some(vec![]) + } + // The clicks of a double-click on a guide belong to it: it neither edits the art nor + // leaves symbol editing mode. + PointerKind::DoubleClick if crate::nineslice::over_guide(cx, ev.pos) => Some(vec![]), + _ => None, + } + } + fn repeat_controls(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option> { if let State::Mirror(mut d) = self.state.clone() { match ev.kind { @@ -1220,11 +1368,11 @@ impl SelectionTool { fn press_widgets(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point) -> Option> { // 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); @@ -1238,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![]); @@ -1286,7 +1438,7 @@ impl SelectionTool { /// grabs the selection by that art (at `grab`), as a press on its visible part does. fn press_nothing(&mut self, cx: &ToolContext, p: Point, grab: Point, m: Mods) { self.state = if !m.shift && selected_hidden_at(cx.doc, p, cx.selection_hit_options(), &cx.selection.objects).is_some() { - State::Moving { start: grab, press: p, hold: grab, began: false, deselect: None, key: None } + State::Moving { start: grab, press: p, hold: grab, began: false, deselect: None, key: None, exclude: None } } else { State::Marquee { start: p, cur: p, toggle: m.shift, enclosed: false } }; @@ -1299,14 +1451,25 @@ impl SelectionTool { m: Mods, backquote: bool, (start, press, hold, began): (Point, Point, Point, bool), + exclude: Option<(NodeId, NodeId)>, ) -> Vec { let mut out = vec![]; if !began { if p.distance(press) < Self::drag_threshold(cx) { return out; } + // A Shift-drag from a highlighted object of the Global Edit selects it and moves it + // with the selection: its snap targets are gathered for the selection with it. + self.moving = Some(match exclude { + Some((_, top)) => { + out.push(Action::Exec("select.toggle".into(), json!({ "id": top.0 }))); + let mut selection = cx.selection.clone(); + selection.add(top); + MoveSnap::new(&ToolContext { selection: &selection, ..*cx }) + } + None => MoveSnap::new(cx), + }); out.push(Action::Begin(if m.alt { "Copy".into() } else { "Move".into() })); - self.moving = Some(MoveSnap::new(cx)); } let mut d = move_delta(start, p, m.shift, cx.constrain_angle); let unsnapped = d; @@ -1315,7 +1478,7 @@ impl SelectionTool { } // Shift has already constrained `d`: any change is a snap. self.snapped = (d - unsnapped).hypot() > 1e-9; - self.state = State::Moving { start, press, hold, began: true, deselect: None, key: None }; + self.state = State::Moving { start, press, hold, began: true, deselect: None, key: None, exclude: None }; self.measure = cx.measurement_labels.then(|| (p, cx.offset_label(d.x, d.y))); let mut params = json!({ "matrix": matrix_json(Affine::translate(d)), "copy": m.alt }); if backquote { diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 4b41a8592a..6638083aca 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -1004,6 +1004,53 @@ fn shift_click_toggles_an_object_on_release() { assert!(t.pointer(&cx2, &shift(PointerKind::Up, 150.0, 150.0)).is_empty()); } +/// A Shift-drag that starts on a highlighted object of the Global Edit selects that object and +/// moves it; only a Shift-click leaves it out of the edit. +#[test] +fn shift_drag_on_a_global_edit_match_selects_and_moves_it() { + let (d, a, b) = two_rects(Rect::new(300.0, 100.0, 400.0, 200.0)); + let p = paint(); + let s = Selection::default(); + let members = [(a, Affine::IDENTITY), (b, Affine::IDENTITY)]; + let cx = ToolContext { global_edit: &members, ..cx(&d, &s, &p) }; + let shift = |kind, x, y| ev(kind, x, y).with_mods(Mods { shift: true, ..Mods::default() }); + let mut t = SelectionTool::default(); + assert!(t.pointer(&cx, &shift(PointerKind::Down, 350.0, 150.0)).is_empty()); + let mut actions = t.pointer(&cx, &shift(PointerKind::Drag, 390.0, 150.0)); + assert_eq!(actions[..2], [Action::Exec("select.toggle".into(), json!({"id": b.0})), Action::Begin("Move".into())]); + actions.extend(t.pointer(&cx, &shift(PointerKind::Drag, 395.0, 150.0))); + actions.extend(t.pointer(&cx, &shift(PointerKind::Up, 395.0, 150.0))); + assert!( + actions.iter().any(|a| matches!(a, Action::Preview(c, v) if c == "object.transform" && v["matrix"][4].as_f64().is_some_and(|x| x > 39.0))), + "moved right: {actions:?}" + ); + assert_eq!(actions.last(), Some(&Action::Commit)); + assert!(!actions.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.globalEditExclude")), "{actions:?}"); + // A Shift-click on it leaves it out instead. + let mut t = SelectionTool::default(); + assert!(t.pointer(&cx, &shift(PointerKind::Down, 350.0, 150.0)).is_empty()); + assert_eq!(t.pointer(&cx, &shift(PointerKind::Up, 350.0, 150.0)), vec![Action::Exec("select.globalEditExclude".into(), json!({"id": b.0}))]); +} + +/// The first preview of a Shift-drag from a Global Edit match snaps, the match's bounds taken in +/// with the selection's: with Snap to Grid, a move of 13 right brings the right edge (413) onto +/// the gridline 414. +#[test] +fn shift_drag_on_a_global_edit_match_snaps_from_its_first_event() { + let (d, a, b) = two_rects(Rect::new(300.0, 100.0, 400.0, 200.0)); + let p = paint(); + let s = Selection::default(); + let members = [(a, Affine::IDENTITY), (b, Affine::IDENTITY)]; + let cx = ToolContext { global_edit: &members, snap_to_grid: true, ..cx(&d, &s, &p) }; + let shift = |kind, x, y| ev(kind, x, y).with_mods(Mods { shift: true, ..Mods::default() }); + let mut t = SelectionTool::default(); + assert!(t.pointer(&cx, &shift(PointerKind::Down, 350.0, 150.0)).is_empty()); + let actions = t.pointer(&cx, &shift(PointerKind::Drag, 363.0, 150.0)); + let Some(Action::Preview(_, v)) = actions.get(2) else { panic!("{actions:?}") }; + let m = Vec2::new(v["matrix"][4].as_f64().unwrap(), v["matrix"][5].as_f64().unwrap()); + assert!(moved_by(m, (14.0, 0.0)), "{m:?}"); +} + /// #541: a click on one object of a selection of several makes it the key object; a click on /// the key again lets it go. A drag moves them all, a lone object has no key unless ruler /// guides are selected with it. @@ -1824,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(); diff --git a/crates/tools/src/text.rs b/crates/tools/src/text.rs index 3e854231d5..646dbd6384 100644 --- a/crates/tools/src/text.rs +++ b/crates/tools/src/text.rs @@ -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, u8), /// Styled copy of the last copied range (pasting the same plain text keeps its styles). diff --git a/crates/tools/src/text/ports.rs b/crates/tools/src/text/ports.rs index d9c027fbc1..554a1cd611 100644 --- a/crates/tools/src/text/ports.rs +++ b/crates/tools/src/text/ports.rs @@ -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 diff --git a/crates/tools/src/text/tests.rs b/crates/tools/src/text/tests.rs index ab3229809a..3c17411720 100644 --- a/crates/tools/src/text/tests.rs +++ b/crates/tools/src/text/tests.rs @@ -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"); diff --git a/crates/tools/src/text/tool.rs b/crates/tools/src/text/tool.rs index c983205da3..9014f540e6 100644 --- a/crates/tools/src/text/tool.rs +++ b/crates/tools/src/text/tool.rs @@ -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 { + 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 { 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![]; diff --git a/crates/tools/src/touchtype.rs b/crates/tools/src/touchtype.rs index 7f8e06ea2d..c1184d72a6 100644 --- a/crates/tools/src/touchtype.rs +++ b/crates/tools/src/touchtype.rs @@ -64,7 +64,7 @@ struct CharBox { ex: Vec2, ey: Vec2, /// Whether the tool moves it along its line by kerning: a character comes before it on its - /// line and it is not right-to-left. + /// line in logical order. kerned: bool, /// Its style as the Character panel shows it (horizontal scale with the object transform). style: CharStyle, @@ -184,7 +184,7 @@ fn char_box(t: &TextObject, lay: &TextLayout, gi: usize) -> Option { up: unit(linear(m * g.unturned, Vec2::new(0.0, -1.0))), ex, ey, - kerned: !g.rtl && lay.glyphs.iter().any(|h| h.line == g.line && h.len > 0 && h.byte + h.len == g.byte), + kerned: lay.glyphs.iter().any(|h| h.line == g.line && h.len > 0 && h.byte + h.len == g.byte && h.rtl == g.rtl), style: t.effective_char_style(&style)?, }) } diff --git a/crates/tools/src/touchtype/tests.rs b/crates/tools/src/touchtype/tests.rs index 5556efda02..99388178ec 100644 --- a/crates/tools/src/touchtype/tests.rs +++ b/crates/tools/src/touchtype/tests.rs @@ -384,3 +384,48 @@ fn the_tool_is_made_by_its_id() { t.pointer(&cx, &PointerEvent::new(PointerKind::Up, at.x, at.y)); assert_eq!(t.options(), json!({"id": id.0, "start": 0})); } + +#[test] +fn touch_type_rtl_middle_character_can_drag_and_nudge_along_its_line() { + use vectorcraft_text::test_fonts::{RIGHT_TO_LEFT_OPTICAL_FAMILY, right_to_left_optical_font}; + + // The process-wide database deduplicates the same synthetic face across tests. + FontDb::global().add_font(right_to_left_optical_font().unwrap()); + let mut d = Document::new(500.0, 500.0); + let layer = d.layers[0].id; + let id = d.alloc_id(); + let style = CharStyle { font_family: RIGHT_TO_LEFT_OPTICAL_FAMILY.into(), size: 100.0, ..Default::default() }; + let text = TextObject::point(Point::new(300.0, 250.0), "אבא", style); + let lay = vectorcraft_text::layout(FontDb::global(), &text); + assert_eq!(lay.glyphs.len(), 3); + assert!(lay.glyphs.iter().all(|g| g.rtl)); + d.insert(Some(layer), 0, Node::new(id, NodeKind::Text(Box::new(text)))).unwrap(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut tool = TouchTypeTool { target: Some((id, 2)), ..Default::default() }; + let q = quad(&tool, &cx); + let acts = drag(&mut tool, &cx, q[3], q[3] + Vec2::new(-5.0, -3.0)); + let params = preview(&acts[1]); + assert!(close(params["dx"].as_f64().unwrap(), 5.0) && close(params["dy"].as_f64().unwrap(), 3.0), "{params}"); + let acts = tool.key(&cx, ToolKey::Left, Mods::default()); + assert_eq!(acts.len(), 1); + let Action::Exec(command, params) = &acts[0] else { panic!("{acts:?}") }; + assert_eq!(command, "text.touchType"); + assert!(close(params["dx"].as_f64().unwrap(), 1.0), "left is forward in reading order: {params}"); + tool.target = Some((id, 0)); + assert!(tool.key(&cx, ToolKey::Left, Mods::default()).is_empty(), "the first logical character has no preceding character to kern"); +} + +#[test] +fn touch_type_direction_boundary_offers_only_vertical_movement() { + let text = TextObject::point(Point::new(100.0, 200.0), "abc אבג", CharStyle { size: 40.0, ..Default::default() }); + let lay = vectorcraft_text::layout(FontDb::global(), &text); + let at = lay.glyphs.iter().position(|g| g.byte == 4).unwrap(); + let b = char_box(&text, &lay, at).unwrap(); + assert!(!b.kerned, "the previous logical character has a different reading direction"); + let params = TouchTypeTool::nudge_params(NodeId(1), &text, &b, -5.0, -3.0); + assert!(params.get("dx").is_none(), "{params}"); + assert!(params.get("dy").is_some(), "{params}"); +} diff --git a/crates/tools/src/xform.rs b/crates/tools/src/xform.rs index de9c9c0cbe..915eb35e8a 100644 --- a/crates/tools/src/xform.rs +++ b/crates/tools/src/xform.rs @@ -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}; diff --git a/crates/tools/src/xform/freeform.rs b/crates/tools/src/xform/freeform.rs index d2c04aa2a8..89c6faa933 100644 --- a/crates/tools/src/xform/freeform.rs +++ b/crates/tools/src/xform/freeform.rs @@ -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 { 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] diff --git a/crates/tools/src/xform/gradient.rs b/crates/tools/src/xform/gradient.rs index 2631514343..7a9b59e2dc 100644 --- a/crates/tools/src/xform/gradient.rs +++ b/crates/tools/src/xform/gradient.rs @@ -511,6 +511,17 @@ impl Tool for GradientTool { && cx.gradient_stop.is_some_and(|i| Annotator::of(cx).is_some_and(|a| i < a.gradient.stops.len())) } + /// A dropped drag is canceled as by Escape. A dropped click does nothing, and the line Lines + /// mode is drawing stays open. + fn drop_press(&mut self, cx: &ToolContext) -> Vec { + if self.busy() { + return self.key(cx, ToolKey::Escape, Mods::default()); + } + (self.gesture, self.free) = (None, None); + self.guides.clear(); + vec![] + } + fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec { if key == ToolKey::Escape && self.busy() { self.gesture = None; diff --git a/crates/tools/src/xform/measure.rs b/crates/tools/src/xform/measure.rs index 3f2b350e01..140697dd6a 100644 --- a/crates/tools/src/xform/measure.rs +++ b/crates/tools/src/xform/measure.rs @@ -23,6 +23,28 @@ pub fn measure(a: Point, b: Point) -> (f64, f64, f64, f64) { (d.hypot(), (-d.y).atan2(d.x).to_degrees() + 0.0, d.x, d.y) } +/// The end of a measurement from `a` with the pointer at `p`: `p` snapped as a drawing tool snaps +/// it. With Shift held, the end stays on the 45° step from the Constrain Angle nearest the +/// pointer's direction: `p` is projected onto the step, then snapped along it as the Line Segment +/// tool snaps a Shift-drawn end. With Snap to Point alone, the point `p` snaps to (an anchor, or +/// in line with a ruler guide) is projected instead. +pub(crate) fn end_point(cx: &ToolContext, a: Point, p: Point, shift: bool) -> Point { + if !shift { + return crate::guides::snap_draw(cx, p, &[]).0; + } + let d = vectorcraft_geom::constrain_angle_from(p - a, 45.0, cx.constrain_angle); + let len = d.hypot(); + if len < 1e-12 { + return a; + } + let u = d / len; + let to_point = cx.snap_to_point && !(cx.smart_guides || cx.snap_to_grid || cx.snap_to_pixel); + let s = if to_point { crate::guides::snap_draw(cx, p, &[]).0 } else { p }; + let q = a + u * (s - a).dot(u); + let leave = crate::guides::Leave::segment(cx, a, true); + crate::guides::PointSnap::new(cx, || crate::guides::Targets::collect(cx.doc, &[], None)).snap_from(cx, q, Some(&leave)).0 +} + impl Tool for MeasureTool { fn id(&self) -> &'static str { "measure" @@ -42,12 +64,7 @@ impl Tool for MeasureTool { } 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, end_point(cx, a, ev.pos, ev.mods.shift))); } self.dragging = ev.kind == PointerKind::Drag; } @@ -141,6 +158,89 @@ mod tests { assert!(ov.iter().any(|o| matches!(o, Overlay::Line { .. })), "the measured line stays"); } + /// A Shift-drag snaps its end point as a drag without Shift does, then projects it onto its + /// 45° step: onto the grid with Snap to Grid, in line with an anchor with Smart Guides. With + /// no snapping, the end is the pointer projected onto the step. + #[test] + fn shift_drag_snaps_its_end_point() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = 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 = MeasureTool::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}"); + // Near 45°: (31.4, 27.7) snaps to (27, 27). + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 31.4, 27.7).with_mods(shift)); + let o = t.options(); + assert!((o["dx"].as_f64().unwrap() - 27.0).abs() < 1e-9, "{o}"); + assert!((o["dy"].as_f64().unwrap() - 27.0).abs() < 1e-9, "{o}"); + // No snapping: the pointer is projected onto 0°, so the measurement is 37.3 pt. + cx.snap_to_grid = false; + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 37.3, 12.1).with_mods(shift)); + let o = t.options(); + assert!((o["distance"].as_f64().unwrap() - 37.3).abs() < 1e-9, "{o}"); + assert!(o["dy"].as_f64().unwrap().abs() < 1e-9, "{o}"); + // Snap to Point alone: the end snaps to the anchor at (200, 200) and is projected onto + // 0°, so it ends in line with it: (200, 203). + assert!(cx.snap_to_point); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 203.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 201.0, 201.0).with_mods(shift)); + let o = t.options(); + assert!((o["dx"].as_f64().unwrap() + 100.0).abs() < 1e-9, "{o}"); + assert!(o["dy"].as_f64().unwrap().abs() < 1e-9, "{o}"); + // An anchor on the 45° step: the end lands on it. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 101.0, 100.0).with_mods(shift)); + let o = t.options(); + assert!((o["dx"].as_f64().unwrap() - 100.0).abs() < 1e-9, "{o}"); + assert!((o["dy"].as_f64().unwrap() - 100.0).abs() < 1e-9, "{o}"); + // Smart Guides: from (300, 300), Shift keeps the end at 0° and it lands in line with x = 200. + cx.snap_to_grid = false; + cx.smart_guides = true; + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 300.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 203.0, 303.0).with_mods(shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 203.0, 303.0).with_mods(shift)); + let o = t.options(); + assert!((o["distance"].as_f64().unwrap() - 100.0).abs() < 1e-9, "{o}"); + assert!(o["dy"].as_f64().unwrap().abs() < 1e-9, "{o}"); + // At 45°, the end slides along the step to where it meets x = 200: (200, 220). + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 320.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 203.0, 222.5).with_mods(shift)); + let o = t.options(); + assert!((o["dx"].as_f64().unwrap() + 100.0).abs() < 1e-9, "{o}"); + assert!((o["dy"].as_f64().unwrap() + 100.0).abs() < 1e-9, "{o}"); + } + + /// With Snap to Point alone, a Shift-drag's end slides along its 45° step to a ruler guide. + #[test] + fn shift_drag_meets_a_ruler_guide() { + let (mut d, _) = doc_with_rect(); + d.guides.push(vectorcraft_doc::Guide::new(true, 50.0)); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + assert!(cx.snap_to_point); + let shift = Mods { shift: true, ..Mods::default() }; + let mut t = MeasureTool::default(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 51.0, 49.0).with_mods(shift)); + let o = t.options(); + assert!((o["dx"].as_f64().unwrap() - 50.0).abs() < 1e-9, "{o}"); + assert!((o["dy"].as_f64().unwrap() - 50.0).abs() < 1e-9, "{o}"); + } + /// Escape during a drag ends it and brings back the result of the drag before (none at /// first); the release after it measures nothing. #[test] diff --git a/crates/tools/src/xform/wand.rs b/crates/tools/src/xform/wand.rs index 530c9302d5..41f42718a7 100644 --- a/crates/tools/src/xform/wand.rs +++ b/crates/tools/src/xform/wand.rs @@ -3,7 +3,8 @@ //! Magic Wand: click an object to select every object with similar attributes. The matching and //! its settings (Magic Wand panel) live in the engine's `select.magicWand` command; Shift adds, //! Alt subtracts. Lasso: freehand loop selecting anchor points inside it (direct-selection -//! style); Shift adds, Alt subtracts. +//! style), and picking the gradient mesh points inside it with their meshes selected (the +//! tool's `meshPoints` option, which a solid fill colour recolours); Shift adds, Alt subtracts. use std::collections::BTreeSet; @@ -13,6 +14,7 @@ use vectorcraft_doc::{AnchorRef, NodeId, NodeKind}; use vectorcraft_geom::Point; use super::paint_owner; +use crate::meshedit::{MeshEdit, grid_of}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; #[derive(Default)] @@ -67,6 +69,8 @@ pub fn point_in_polygon(poly: &[Point], p: Point) -> bool { pub struct LassoTool { points: Vec, active: bool, + /// The picked gradient mesh points. + mesh: MeshEdit, } fn anchors_json(v: &BTreeSet) -> Value { @@ -105,7 +109,11 @@ impl Tool for LassoTool { } // Anchors inside the loop for every editable path the Lasso may pick. let mut hits: Vec<(NodeId, BTreeSet)> = vec![]; + let mut inside: Vec<(NodeId, usize)> = vec![]; crate::draw2::walk_pickable(cx, |n| { + if let Some(grid) = grid_of(n) { + inside.extend(grid.points.iter().enumerate().filter(|(_, q)| point_in_polygon(&poly, q.p)).map(|(i, _)| (n.id, i))); + } if let NodeKind::Path { path, .. } = &n.kind { let v: BTreeSet = path.anchors().filter(|(_, _, a)| point_in_polygon(&poly, a.p)).map(|(s, i, _)| (s, i)).collect(); @@ -116,6 +124,14 @@ impl Tool for LassoTool { }); let editable = cx.doc.editable(); hits.retain(|(id, _)| editable(*id) && cx.doc.is_visible(*id)); + // The mesh points inside the loop are picked, and their meshes selected whole; + // Alt deselects a mesh only when it loses its last picked point. + inside.retain(|(id, _)| editable(*id) && cx.doc.is_visible(*id)); + for (id, any) in self.mesh.lasso(&inside, add, sub) { + if any != sub { + hits.push((id, BTreeSet::new())); + } + } let items: Vec = hits.iter().map(|(id, v)| json!({ "id": id.0, "anchors": anchors_json(v) })).collect(); let mode = if sub { "subtract" @@ -138,11 +154,16 @@ impl Tool for LassoTool { vec![] } - fn overlays(&self, _cx: &ToolContext) -> Vec { - if !self.active || self.points.len() < 2 { - return vec![]; + fn options(&self) -> Value { + self.mesh.options() + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let mut out = self.mesh.overlays(cx, &|id| cx.selection.contains(id)); + if self.active && self.points.len() >= 2 { + out.push(Overlay::Path { path: super::polygon(&self.points, false), color: [0x40, 0x40, 0x40], width: 1.0, dashed: true }); } - vec![Overlay::Path { path: super::polygon(&self.points, false), color: [0x40, 0x40, 0x40], width: 1.0, dashed: true }] + out } fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { @@ -222,4 +243,44 @@ mod tests { assert_eq!(v["mode"], "set"); assert!(point_in_polygon(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(0.0, 10.0)], Point::new(2.0, 2.0))); } + + /// A Lasso loop round a corner of a path warped by a mesh envelope still selects the path's + /// anchor there, besides picking the envelope's grid point (#5351). + #[test] + fn lasso_keeps_picking_the_anchors_of_an_envelopes_path() { + use std::sync::Arc; + use vectorcraft_doc::Node; + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, grid_points}; + use vectorcraft_geom::{Affine, Rect}; + let (mut d, a) = doc_with_rect(); + let rect = d.node(a).cloned().unwrap(); + let kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points: grid_points(Rect::new(100.0, 100.0, 200.0, 200.0), 1, 1), handles: vec![] }; + let env = NodeKind::Envelope { + content: vec![Arc::new(rect)], + kind: Box::new(kind), + fidelity: 50.0, + editing: false, + options: EnvelopeOptions::NEW, + frame: Box::new(Affine::IDENTITY), + }; + d.remove(a).unwrap(); + let e = d.alloc_id(); + let l = d.layers[0].id; + d.insert(Some(l), 0, Node::new(e, env)).unwrap(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = LassoTool::default(); + // A triangle around the top-left corner (100,100) only. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 80.0, 80.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 140.0, 80.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 80.0, 140.0)); + let r = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 80.0, 140.0)); + let Some(Action::Exec(c, v)) = r.first() else { panic!("a selection command: {r:?}") }; + assert_eq!(c, "select.anchorsMany"); + let items = v["items"].as_array().unwrap(); + let path = items.iter().find(|it| it["id"] == a.0).expect("the warped path's anchor is selected"); + assert_eq!(path["anchors"].as_array().unwrap().len(), 1); + assert!(items.iter().any(|it| it["id"] == e.0), "the envelope is selected with its grid point"); + assert_eq!(t.options()["meshPoints"].as_array().unwrap().len(), 1); + } } diff --git a/crates/trace/src/mosaic.rs b/crates/trace/src/mosaic.rs index b8bd46a370..74ded42b50 100644 --- a/crates/trace/src/mosaic.rs +++ b/crates/trace/src/mosaic.rs @@ -7,13 +7,14 @@ const MAX_SIDE: u32 = 4096; /// Average colour (straight RGBA) of each of `cols` × `rows` tiles covering `img`, row by row. /// Transparent pixels count by their alpha, so a tile over transparency fades out. Tiles over the -/// same pixels (more tiles than pixels) are averaged once, and a raster whose bytes are not -/// `width * height * 4` gives transparent tiles. +/// same pixels (more tiles than pixels) are averaged once, and an empty raster or one whose bytes +/// are not `width * height * 4` gives transparent tiles. pub fn mosaic(img: &Raster, cols: u32, rows: u32) -> Vec<[u8; 4]> { let (cols, rows) = (cols.clamp(1, MAX_SIDE), rows.clamp(1, MAX_SIDE)); let tiles = cols as usize * rows as usize; let (w, h) = (img.width as usize, img.height as usize); - if w.checked_mul(h).and_then(|n| n.checked_mul(4)) != Some(img.rgba.len()) { + // An empty raster has nothing to average (its rows would still be walked, up to 2^32 of them). + if w == 0 || h == 0 || w.checked_mul(h).and_then(|n| n.checked_mul(4)) != Some(img.rgba.len()) { return vec![[0; 4]; tiles]; } let mut out = Vec::with_capacity(tiles); @@ -89,6 +90,9 @@ mod tests { // Bytes that are not the raster's size: transparent. let short = Raster { width: 4, height: 4, rgba: vec![] }; assert_eq!(mosaic(&short, 2, 2), vec![[0; 4]; 4]); + // No pixels at all, however tall: transparent, with no rows walked. + let empty = Raster { width: 0, height: u32::MAX, rgba: vec![] }; + assert_eq!(mosaic(&empty, 2, 2), vec![[0; 4]; 4]); // Transparency. let clear = Raster::from_fn(2, 2, |_, _| [9, 9, 9, 0]); assert_eq!(mosaic(&clear, 1, 1), vec![[0, 0, 0, 0]]); diff --git a/crates/trace/src/quantize.rs b/crates/trace/src/quantize.rs index a7dac9b2a6..9452671def 100644 --- a/crates/trace/src/quantize.rs +++ b/crates/trace/src/quantize.rs @@ -34,8 +34,13 @@ pub(crate) fn luma(p: [u8; 4]) -> u8 { ((p[0] as u32 * 299 + p[1] as u32 * 587 + p[2] as u32 * 114 + 500) / 1000) as u8 } -/// Reduce `img` to a palette according to `params.mode`. +/// Reduce `img` to a palette according to `params.mode`. A raster whose bytes are not +/// `width * height * 4` (its fields are public) has no pixels to reduce: no labels, no palette. pub fn quantize(img: &Raster, params: &TraceParams) -> Quantized { + let want = (img.width as usize).checked_mul(img.height as usize).and_then(|n| n.checked_mul(4)); + if want != Some(img.rgba.len()) { + return Quantized { labels: vec![], palette: vec![] }; + } quantize_keeping(img, params).0 } diff --git a/crates/trace/src/quantize/palette.rs b/crates/trace/src/quantize/palette.rs index 8f89a7c960..accffc87e5 100644 --- a/crates/trace/src/quantize/palette.rs +++ b/crates/trace/src/quantize/palette.rs @@ -202,13 +202,9 @@ const FLAT_BINS: usize = 96; /// Document Library: the `k` swatches (at most) that the most pixels are nearest to (see /// [`nearest_library`]). fn library_colors(used: &[Used], swatches: &[[u8; 3]], k: usize) -> Vec<[f64; 3]> { - let mut all: Vec<[f64; 3]> = vec![]; - for s in swatches { - let c = s.map(f64::from); - if !all.contains(&c) { - all.push(c); - } - } + // Each colour once, in their order: looked up in a set, not in the colours kept so far. + let mut seen = std::collections::HashSet::new(); + let all: Vec<[f64; 3]> = swatches.iter().filter(|s| seen.insert(**s)).map(|s| s.map(f64::from)).collect(); let mut weight = vec![0.0; all.len()]; let all_labs = labs(&all); for (_, c, n) in used { diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index f5a10d494a..bcc2242b32 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -428,6 +428,29 @@ fn a_cut_out_edge_leaves_the_color_of_the_art_inside_it_alone() { assert_eq!(q.palette.get(q.labels[12] as usize), Some(&[255, 255, 255]), "{q:?}"); } +#[test] +fn a_library_of_many_repeated_swatches_is_read_once_per_color() { + let img = Raster::from_fn(2, 1, |x, _| if x == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + // 200,000 swatches of 50,000 distinct colours: compared against those kept so far, billions of steps. + let swatches: Vec<[u8; 3]> = (0..200_000u32) + .map(|i| { + let c = i % 50_000; + [(c >> 16) as u8, (c >> 8) as u8, c as u8] + }) + .collect(); + let params = TraceParams { mode: Mode::Color, palette: Palette::DocumentLibrary, swatches, colors: 2, ..TraceParams::default() }; + let start = std::time::Instant::now(); + let q = quantize(&img, ¶ms); + assert!(start.elapsed() < std::time::Duration::from_secs(30), "{:?}", start.elapsed()); + assert_eq!(q.labels.len(), 2); +} + +#[test] +fn a_raster_whose_bytes_are_not_its_size_quantizes_to_nothing() { + let short = Raster { width: 60_000, height: 60_000, rgba: vec![0; 4] }; + assert_eq!(quantize(&short, &TraceParams::default()), Quantized { labels: vec![], palette: vec![] }); +} + #[test] fn a_semi_transparent_stripe_beside_a_cut_out_edge_keeps_its_own_color() { // Columns: transparent, a half-opaque gray edge (white blended with the background), a diff --git a/crates/ui-egui/src/addons.rs b/crates/ui-egui/src/addons.rs index 65210c6d22..92895fea0a 100644 --- a/crates/ui-egui/src/addons.rs +++ b/crates/ui-egui/src/addons.rs @@ -1,12 +1,13 @@ -//! VectorCraft's built-in add-ons in the interface: each has a panel and a submenu at the top of -//! Object › Plug-ins, and acts through its engine commands (`addon..*`). +//! The module defines VectorCraft's built-in add-on menus and panels. Object › Plug-ins lists their tools and commands. pub mod arrange; pub mod cleanup; pub mod color; pub mod document; +pub mod enclosing_lasso; pub mod pathtools; pub mod pen; +pub mod typetools; use crate::menus::Item; @@ -17,8 +18,10 @@ pub fn plugin_menu() -> Vec { Item::Sub("Artwork Cleanup", cleanup::menu()), Item::Sub("Color Effects", color::menu()), Item::Sub("Document Tools", document::menu()), + Item::Sub("Enclosing Lasso", enclosing_lasso::menu()), Item::Sub("Path Precision Tools", pathtools::menu()), Item::Sub("Smart Pen", pen::menu()), + Item::Sub("Type Tools", typetools::menu()), Item::Sep, ] } diff --git a/crates/ui-egui/src/addons/enclosing_lasso.rs b/crates/ui-egui/src/addons/enclosing_lasso.rs new file mode 100644 index 0000000000..f0b8e959c3 --- /dev/null +++ b/crates/ui-egui/src/addons/enclosing_lasso.rs @@ -0,0 +1,8 @@ +use serde_json::json; +use vectorcraft_tools::addons::enclosing_lasso; + +use crate::menus::Item; + +pub fn menu() -> Vec { + vec![Item::Cmd("Enclosing Lasso Tool", "tool.select", json!({"tool": enclosing_lasso::ID}))] +} diff --git a/crates/ui-egui/src/addons/typetools.rs b/crates/ui-egui/src/addons/typetools.rs new file mode 100644 index 0000000000..f9bfa3ca36 --- /dev/null +++ b/crates/ui-egui/src/addons/typetools.rs @@ -0,0 +1,96 @@ +//! Type Tools in the interface: its submenu (Object › Plug-ins › Type Tools) and Text Tweaker's +//! dialog, which picks an attribute, its start and end values and a shape, previews on the canvas +//! and runs `addon.type.textTweaker` on OK. + +use egui::Ui; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::dialogs::{DialogSpec, form}; +use crate::menus::Item; +use crate::state::Dialog; +use crate::widgets; + +/// The command the dialog runs, and its kind. +pub const COMMAND: &str = "addon.type.textTweaker"; +pub const KIND: &str = "textTweaker"; +/// An attribute: (param, label, unit, decimals, values taken, default start and end), as the +/// command takes it. +type Attribute = (&'static str, &'static str, &'static str, usize, (f64, f64), (f64, f64)); + +const ATTRIBUTES: [Attribute; 8] = [ + ("size", "Font Size", "pt", 1, (0.1, 1296.0), (12.0, 36.0)), + ("baselineShift", "Baseline Shift", "pt", 1, (-1296.0, 1296.0), (0.0, 12.0)), + ("rotation", "Character Rotation", "°", 1, (-360.0, 360.0), (0.0, 30.0)), + ("hScale", "Horizontal Scale", "%", 0, (1.0, 10000.0), (100.0, 150.0)), + ("vScale", "Vertical Scale", "%", 0, (1.0, 10000.0), (100.0, 150.0)), + ("tracking", "Tracking", "", 0, (-1000.0, 10000.0), (0.0, 200.0)), + ("leading", "Leading", "pt", 1, (0.1, 5000.0), (12.0, 36.0)), + ("strokeWidth", "Stroke Weight", "pt", 2, (0.0, 1000.0), (0.0, 2.0)), +]; +const SHAPES: [(&str, &str); 5] = [("straight", "Straight"), ("ease", "Ease In Out"), ("bow", "Bow"), ("spike", "Spike"), ("random", "Random")]; +/// The seeds the dialog offers. +const SEEDS: u64 = 1_000_000; +const LABEL_W: f32 = 90.0; +const FIELD_W: f32 = 90.0; + +/// Object › Plug-ins › Type Tools. +pub fn menu() -> Vec { + vec![Item::Cmd("Text Tweaker…", COMMAND, Value::Null)] +} + +/// The attribute row of param `key` (the first, Font Size, for an unknown one). +fn attribute(key: &str) -> &'static Attribute { + ATTRIBUTES.iter().find(|a| a.0 == key).unwrap_or(&ATTRIBUTES[0]) +} + +/// The dialog's fields to start with: Font Size from 12 to 36 pt in a straight ramp, and a new +/// seed each time the document has changed, so running it again varies a random result. +pub(crate) fn fields(app: &VectorcraftApp) -> Value { + let seed = app.session.active().map_or(0, |st| st.revision % SEEDS); + json!({ + "attribute": "size", "__shown": "size", "from": 12, "to": 36, "shape": "straight", "seed": seed, "skipSpaces": true, + }) +} + +pub(crate) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Text Tweaker").to_string(), body, confirm, preview: true, min_width: 320.0, ..DialogSpec::FORM }; + +fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + let widths = (LABEL_W, 170.0); + let options: Vec<(&str, &str)> = ATTRIBUTES.iter().map(|a| (a.0, a.1)).collect(); + form::choice(ui, d, "attribute", tl!("Attribute:"), widths, &options); + let &(key, _, unit, decimals, (lo, hi), (from, to)) = attribute(&d.str("attribute")); + // Another attribute starts from its own values. + if d.str("__shown") != key { + d.fields.insert("__shown".into(), json!(key)); + d.fields.insert("from".into(), json!(from)); + d.fields.insert("to".into(), json!(to)); + } + for (field, label) in [("from", tl!("From:")), ("to", tl!("To:"))] { + widgets::label_row(ui, label, LABEL_W, |ui| { + if let Some(v) = widgets::range_field(ui, ("text-tweaker", field), d.f64(field, lo), lo..=hi, unit, decimals, FIELD_W) { + d.fields.insert(field.into(), json!(v)); + } + }); + } + form::choice(ui, d, "shape", tl!("Shape:"), widths, &SHAPES); + ui.add_enabled_ui(d.str("shape") == "random", |ui| { + widgets::label_row(ui, tl!("Seed:"), LABEL_W, |ui| { + if let Some(v) = widgets::range_field(ui, ("text-tweaker", "seed"), d.f64("seed", 0.0), 0.0..=(SEEDS - 1) as f64, "", 0, FIELD_W) { + d.fields.insert("seed".into(), json!(v as u64)); + } + }); + }); + form::check(ui, d, "skipSpaces", tl!("Skip Spaces")); + form::preview(app, ui, d, "Text Tweaker", COMMAND, form::params(d)); + false +} + +/// OK: run the command (keep its preview) and close. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + form::commit_preview(app, COMMAND, form::params(d)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/typetools/tests.rs b/crates/ui-egui/src/addons/typetools/tests.rs new file mode 100644 index 0000000000..36e3ef2f31 --- /dev/null +++ b/crates/ui-egui/src/addons/typetools/tests.rs @@ -0,0 +1,62 @@ +use serde_json::json; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_engine::Session; + +use super::KIND; +use crate::tests_labels::painted_text; +use crate::{VectorcraftApp, menus}; + +/// An app with one type object, selected. +fn app() -> (VectorcraftApp, NodeId) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = NodeId(app.run("text.create", json!({"x": 40, "y": 100, "text": "abc", "size": 20})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [id.0]})).unwrap(); + (app, id) +} + +fn sizes(app: &VectorcraftApp, id: NodeId) -> Vec { + match &app.session.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().flat_map(|r| r.text.chars().map(|_| r.style.size).collect::>()).collect(), + _ => panic!("not text"), + } +} + +fn open(app: &mut VectorcraftApp) { + let entries = menus::menu_entries(app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Type Tools"] && e.label == "Text Tweaker…").unwrap(); + let (id, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(app, &id, p); +} + +#[test] +fn text_tweaker_opens_its_dialog_previews_and_runs_on_ok() { + let (mut app, id) = app(); + open(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Text Tweaker", "Attribute:", "Font Size", "From:", "To:", "Shape:", "Straight", "Seed:", "Skip Spaces", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(sizes(&app, id), [12.0, 24.0, 36.0], "previewed"); + crate::dialogs::cancel(&mut app); + assert_eq!(sizes(&app, id), [20.0; 3], "rolled back"); + open(&mut app); + let n = app.session.doc().unwrap().history.undo.len(); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1, "one undo step"); + assert_eq!(sizes(&app, id), [12.0, 24.0, 36.0]); +} + +#[test] +fn another_attribute_starts_from_its_own_values() { + let (mut app, _) = app(); + open(&mut app); + app.ui.dialog.as_mut().unwrap().fields.insert("attribute".into(), json!("rotation")); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["from"].clone(), d.fields["to"].clone()), (json!(0.0), json!(30.0))); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 404eaa81b7..7cbe32d1eb 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -54,6 +54,7 @@ impl VectorcraftApp { // ([`place::place_from_cursor`]). session.place_cursor_requests = true; let views = session.documents().iter().map(View::of).collect(); + let known = session.documents().iter().map(|d| d.uid).collect(); Self { session, ui: UiState::default(), @@ -85,6 +86,7 @@ impl VectorcraftApp { hover_cursor: None, presented: None, panes: Default::default(), + windows: crate::doc_windows::Windows::new(known), }, perf: Perf::default(), dock_rt: Default::default(), @@ -348,6 +350,7 @@ impl VectorcraftApp { } crate::keymap::note_os(ctx); shortcut_editor::sync(&self.ui); + crate::panels::actions::sync_function_keys(&self.ui); prefs_dialog::apply_runtime(self, ctx); // The OS title bar (and the taskbar / Alt-Tab entry) follows the active file; with the // system title bar this is where the document name lives, as the in-app mark is hidden. @@ -427,18 +430,32 @@ impl VectorcraftApp { } /// The canvas panel's body: the document tabs, the canvas (a pane for each document while - /// Window › Arrange › Tile is on) and the isolation bar over it. + /// Window › Arrange › Tile is on) and the isolation bar over it. While the current document is + /// in a floating window, the tab strip's document draws as a pane. pub(crate) fn canvas_area(&mut self, ui: &mut egui::Ui) { let t = theme::Tokens::get(ui.ctx()); ui.painter().rect_filled(ui.max_rect(), 0.0, t.pasteboard); + self.canvas.windows.strip = None; if self.ui.screen_mode < 3 { chrome::doc_tabs(self, ui); } + self.canvas.windows.area = Some(ui.available_rect_before_wrap()); + let floats = crate::doc_windows::current_floats(self); if !canvas::tiled_area(self, ui) { - canvas::show(self, ui); + if floats { + let rect = ui.available_rect_before_wrap(); + if let Some(i) = crate::doc_windows::tab_document(self) + && canvas::pane(self, ui, i, rect) + { + chrome::show_document(self, i); + } + } else { + canvas::show(self, ui); + } } // Over the canvas inside the rulers, so the rulers and scroll bars stay uncovered. if self.ui.screen_mode < 3 + && !floats && !menus::home_showing(self) && let Some(area) = self.canvas_rect { @@ -510,6 +527,7 @@ impl VectorcraftApp { panels::library_panel::tidy(self); // The canvas and the panels: one docking layout. Tab hides the panels but not the canvas. egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.pasteboard)).show(ui, |ui| panel_docking::show(self, ui)); + crate::doc_windows::show(self, &ctx); dialogs::show(self, &ctx); updates_ui::show(self, &ctx); export_progress::show(self, &ctx); diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 632ef818b3..08e7960b3e 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -168,9 +168,21 @@ impl VectorcraftApp { if matches!(id, "dataset.select" | "dataset.next" | "dataset.prev") { self.ui.status.clear(); } - if matches!(id, "text.setStyle" | "text.setRangeStyle") - && let Some(font) = params.get("font").and_then(Value::as_str) - { + // A font applied with Character's font menu or Find Font's Change becomes the newest recent font. + // Find Font's Change records the family the text now carries (any name of it is stored as its + // own name), and only when it changed some text. + let applied = match id { + "text.setStyle" | "text.setRangeStyle" => params.get("font").and_then(Value::as_str).map(str::to_string), + "text.replaceFont" if v["runs"].as_u64().is_some_and(|n| n > 0) => { + let to = ¶ms["to"]; + to["family"].as_str().and_then(|family| { + let style = to["style"].as_str().unwrap_or("Regular"); + vectorcraft_text::FontDb::global().resolve(family, style).map(|(face, _)| face.family.clone()) + }) + } + _ => None, + }; + if let Some(font) = applied.as_deref() { let r = &mut self.ui.recent_fonts; r.retain(|f| !f.eq_ignore_ascii_case(font)); r.insert(0, font.to_string()); diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 5fd9dd8d07..0b87eb16b8 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -63,7 +63,7 @@ impl VectorcraftApp { /// Identify the document, modal dialog and focused widget that the current accepted input batch /// belongs to. - pub(super) fn input_generation(&self) -> InputGeneration { + pub(crate) fn input_generation(&self) -> InputGeneration { InputGeneration { document: self.session.active().map_or(0, |document| document.uid), dialog: self.ui.dialog.as_ref().map(|dialog| egui::Id::unique(&dialog.kind)), diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 6bcfdfd3f2..2854e11d6a 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -175,6 +175,12 @@ impl VectorcraftApp { /// injected until the batch was actually applied, so a burst of hidden ticks cannot queue /// several steps of a drag or replay them together later. pub fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + self.fill_raw_input(ctx, raw); + crate::font_menu::sync_wheel_target(self, ctx, raw.viewport_id); + crate::font_menu::take_raw_wheel(ctx, raw); + } + + fn fill_raw_input(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { // Both hosts call this hook once per host iteration, before deciding whether a UI pass // follows; it is the iteration boundary, not a UI-phase marker. self.begin_host_iteration(); diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index fd38968d2d..0100ed100b 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -1,7 +1,8 @@ use super::{Value, VectorcraftApp, View, ViewInfo, panels}; impl VectorcraftApp { - /// Keep `views` aligned with the session's documents (a new one starts at its saved view). + /// Keep `views` aligned with the session's documents (a new one starts at its saved view, and + /// opens in a floating window while Open Documents As Tabs is cleared). pub fn sync_views(&mut self) { let docs = self.session.documents(); self.views.truncate(docs.len()); @@ -9,6 +10,7 @@ impl VectorcraftApp { for (view, doc) in self.views.iter_mut().zip(docs) { view.artboard = view.artboard.min(doc.doc.artboards.len().saturating_sub(1)); } + crate::doc_windows::opened(self); // Undo can remove the Artboard tool's active or additionally selected boards. Repair only // invalid indices: valid multiselection, drag state and tool options must survive history. if self.session.tool_id() != "artboard" || self.session.tool_busy() { diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 1e50de2284..7361003777 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -60,6 +60,8 @@ pub struct CanvasCache { pub presented: Option, /// Window › Arrange › Tile: the renders the panes of the other documents draw. pub panes: canvas::Panes, + /// Window › Arrange › Float in Window: what the floating document windows keep between frames. + pub windows: crate::doc_windows::Windows, } /// [`CanvasCache::slices`]: the layout of the slices of (document uid, revision). diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e501273d59..1330cae2b9 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -61,7 +61,7 @@ use outline::{OVERLAY_MAX_ANCHORS, c32, node_outline, walk_drawn}; use overlays::selected_anchor; use overlays::{HandleLook, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay}; pub use panes::Panes; -pub(crate) use panes::{consolidate, tile, tiled_area}; +pub(crate) use panes::{consolidate, pane, tile, tiled_area}; use raster::{changed_pixels, pixel_region, upload}; pub(crate) use raster::{color_image, color_image_owned}; use task_bar::task_bar; @@ -70,8 +70,8 @@ pub use tool_overlays::HiddenChars; #[cfg(test)] use tool_overlays::{DIAL_RADIUS, HiddenMarks}; use tool_overlays::{ - grid_repeat_overlay, hidden_chars_overlay, live_paint_gap_overlays, mirror_axis_overlay, original_path_overlay, print_tiling_overlay, - rotate_view_dial, shaper_widget_overlay, slice_overlay, thread_overlays, + grid_repeat_overlay, hidden_chars_overlay, live_paint_gap_overlays, mirror_axis_overlay, nine_slice_overlay, original_path_overlay, + print_tiling_overlay, rotate_view_dial, shaper_widget_overlay, slice_overlay, thread_overlays, }; pub(crate) use view::animated_zoom; pub use view::fit; @@ -325,6 +325,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if app.ui.view.guides { guide_lines(app, &painter, &xf, rect, &t); } + nine_slice_overlay(app, &painter, &xf); if !app.session.slices_hidden() { slice_overlay(app, &painter, &xf); @@ -653,7 +654,15 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { app.canvas.shown = Some((doc.clone(), opts.clone())); app.perf.render_ms = now_ms() - t0; } - (Some(worker), true, None) => worker.submit(crate::render_worker::Job { key: key.clone(), doc: doc.clone(), w, h, view, opts }), + (Some(worker), true, None) => worker.submit(crate::render_worker::Job { + key: key.clone(), + doc: doc.clone(), + w, + h, + view, + opts, + scope: vectorcraft_engine::file_access::ScopeHandle::capture(), + }), _ => { let t0 = now_ms(); let img = app.canvas.renderer.render(doc, w, h, view, &opts); diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 1c14379e28..3f3c156edd 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -149,10 +149,22 @@ pub(super) type FrameMove = (Pos2, Option, Option); /// move (empty when the pen read neither), if any. The last move is the pointer's position; the /// tilt and rotation the feed kept for it come second, if any. A mouse's moves count too, with no /// pressure: a fast mouse stroke otherwise keeps one position a frame, a sample every few pixels, -/// too few for a low Fidelity to follow the hand (#3328). -pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>) -> (Vec, Option) { +/// too few for a low Fidelity to follow the hand (#3328). With `release`, the moves stop at that +/// button's button-up in this frame, if it came: the moves after it are hover, and the button-up's +/// position is the pointer's. The last move before it is left out only when it is at that +/// position; its tilt and rotation come second either way. +pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>, release: Option) -> (Vec, Option) { let samples = stylus.map(StylusFeed::take_moves).unwrap_or_default(); ui.input(|i| { + // How many of the frame's moves came before the button-up, and where it came, if it came. + let before_up = release.and_then(|b| { + i.events.iter().enumerate().find_map(|(k, e)| match e { + egui::Event::PointerButton { pos, button, pressed: false, .. } if *button == b => { + Some((i.events.iter().take(k).filter(|e| matches!(e, egui::Event::PointerMoved(_))).count(), *pos)) + } + _ => None, + }) + }); let mut moves = vec![]; if i.events.iter().any(|e| matches!(e, egui::Event::Touch { .. })) { let mut force = None; @@ -173,7 +185,20 @@ pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>) -> (Vec { + moves.truncate(n); + let pose = moves.last().and_then(|&(_, _, q)| q); + if moves.last().is_some_and(|&(p, _, _)| p == up_at) { + moves.pop(); + } + pose + } + None => moves.pop().and_then(|(_, _, q)| q), + }; // A burst of events (a stalled frame) is thinned to a bounded count. const MAX: usize = 64; if moves.len() > MAX { @@ -188,9 +213,11 @@ pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>) -> (Vec (Vec, Option) { - let (moves, last_pose) = frame_moves(ui, app.services.stylus.as_ref()); +/// position come second, for every tool. With `released`, only the moves before the primary +/// button-up count. +pub(super) fn tool_frame_moves(ui: &Ui, app: &VectorcraftApp, released: bool) -> (Vec, Option) { + let release = released.then_some(egui::PointerButton::Primary); + let (moves, last_pose) = frame_moves(ui, app.services.stylus.as_ref(), release); (if app.session.tool_wants_samples() { moves } else { vec![] }, last_pose) } @@ -203,15 +230,11 @@ pub fn mods(m: egui::Modifiers, space: bool) -> Mods { pub(super) fn drop_press(app: &mut VectorcraftApp, ui: &Ui, view: vectorcraft_engine::ViewInfo) { match ui.data(|d| d.get_temp::(drag_id())) { Some(Drag::Tool | Drag::Art) => { - // The tool's mouse-up returns it to rest. A move waiting over a panel is still live - // and would otherwise outlive the drag that owns it (#2826). - // Nothing to roll back without a document; the tool still gets its mouse-up. - let _ = app.session.cancel_interaction(); - dispatch( - app, - &PointerEvent { kind: PointerKind::Up, pos: Point::ZERO, mods: Mods::default(), backquote: false, pressure: 1.0, pen: None }, - view, - ); + // The tool drops the press, and a mouse-up returns it to rest with the options it had + // when the press began. A move waiting over a panel is still live and would otherwise outlive the drag that + // owns it (#2826). + let r = app.session.drop_tool_press(view); + apply_requests(app, r.map(|()| vec![])); egui::DragAndDrop::clear_payload(ui.ctx()); } Some(_) => {} diff --git a/crates/ui-egui/src/canvas/fill.rs b/crates/ui-egui/src/canvas/fill.rs index 2f45f23ba9..779f6d352e 100644 --- a/crates/ui-egui/src/canvas/fill.rs +++ b/crates/ui-egui/src/canvas/fill.rs @@ -98,7 +98,15 @@ pub(super) fn fill_uncovered( let Some(worker) = app.canvas.fill_worker.as_mut().filter(|_| !gaps.is_empty()) else { return }; if !app.canvas.fill.as_ref().is_some_and(|f| covers(&f.key)) && !worker.pending.as_ref().is_some_and(covers) { let (w, h, view) = fill_view(key); - worker.submit(crate::render_worker::Job { key: key.clone(), doc: doc.clone(), w, h, view, opts }); + worker.submit(crate::render_worker::Job { + key: key.clone(), + doc: doc.clone(), + w, + h, + view, + opts, + scope: vectorcraft_engine::file_access::ScopeHandle::capture(), + }); } let Some(f) = app.canvas.fill.as_ref().filter(|f| usable(&f.key)) else { return }; let to_uv = Affine::scale_non_uniform(1.0 / f64::from(f.size.0.max(1)), 1.0 / f64::from(f.size.1.max(1))) * f.view * screen_to_doc; diff --git a/crates/ui-egui/src/canvas/home.rs b/crates/ui-egui/src/canvas/home.rs index 2987a03c55..d73a5c5bb8 100644 --- a/crates/ui-egui/src/canvas/home.rs +++ b/crates/ui-egui/src/canvas/home.rs @@ -74,7 +74,7 @@ fn recent(app: &mut VectorcraftApp, ui: &mut Ui) { for path in files { if recent_row(ui, &path).clicked() { // A failure is reported to the user there. - let _ = crate::io::open_recent_reporting(app, &path); + let _ = crate::io::open_reporting(app, &path); } } } diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 87b35a7c93..3775edeb86 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -382,7 +382,7 @@ fn drag_held(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Pos2) // or the web, a finger) and a macOS pen's moves carry their own pressure; a // mouse's, a pen's on X11 among them, take the host's latest. Other tools get // the last position only, so a costly drag preview runs once a frame. - let (moves, last_pose) = tool_frame_moves(ui, app); + let (moves, last_pose) = tool_frame_moves(ui, app, false); // A frame whose pointer ends where the last one did still moved in between. let backquote = ui.input(|i| i.key_down(egui::Key::Backtick)); let mods_changed = tool_drag_mods_changed(ui, mods(m, space), backquote); @@ -467,8 +467,9 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po // tools commit the last preview, which should be where the pointer let go // (#834). Only once the press has dragged, so a click's jitter stays a click // (the Pen's corner anchor, no nudge with Direct Selection). A tool that builds a - // stroke from the drag's samples gets the frame's other moves before it. - let (moves, last_pose) = tool_frame_moves(ui, app); + // stroke from the drag's samples gets the frame's other moves before it, up to the + // button-up: the moves after it are hover. + let (moves, last_pose) = tool_frame_moves(ui, app, true); let pen = move_pose(app, &xf, last_pose); if let Some(last) = last_drag { let backquote = ui.input(|i| i.key_down(egui::Key::Backtick)); diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index f8c9b95f55..b98e186481 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -298,18 +298,33 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: rotate_all_widget(p, xf, tool, &st.doc, &st.selection); } -/// The Rotate All widget (Selection and Objects on Path tools, one Objects on Path group -/// selected): joined by a line to the first object's attachment point. It stays while dragged. +/// The Rotate All and Space widgets (Selection and Objects on Path tools, one Objects on Path +/// group selected). The Rotate All widget is joined by a line to the first object's attachment +/// point. It stays while dragged. fn rotate_all_widget(p: &egui::Painter, xf: &Xf, tool: &str, doc: &vectorcraft_doc::Document, selection: &vectorcraft_doc::Selection) { use vectorcraft_tools::objects_on_path::{ROTATE_ALL_RADIUS_PX, RotateAllWidget}; if !matches!(tool, "selection" | "objectsOnPath") { return; } - let Some(w) = RotateAllWidget::of(doc, selection, xf.zoom) else { return }; - let (on, c, color) = (xf.to_screen(w.pivot), xf.to_screen(w.at), c32(doc.layer_color(w.group))); + if let Some(w) = RotateAllWidget::of(doc, selection, xf.zoom) { + let (on, c, color) = (xf.to_screen(w.pivot), xf.to_screen(w.at), c32(doc.layer_color(w.group))); + p.line_segment([on, c], Stroke::new(1.0, color)); + p.circle_filled(c, ROTATE_ALL_RADIUS_PX, Color32::WHITE); + p.circle_stroke(c, ROTATE_ALL_RADIUS_PX, Stroke::new(1.0, color)); + } + space_widget(p, xf, doc, selection); +} + +/// The Space widget (beside the Rotate All widget, with two or more objects on the path): a square +/// joined by a line to the last object's attachment point. It stays while dragged. +fn space_widget(p: &egui::Painter, xf: &Xf, doc: &vectorcraft_doc::Document, selection: &vectorcraft_doc::Selection) { + use vectorcraft_tools::objects_on_path::{SPACE_HALF_PX, SpaceWidget}; + let Some(w) = SpaceWidget::of(doc, selection, xf.zoom) else { return }; + let (on, c, color) = (xf.to_screen(w.last), xf.to_screen(w.at), c32(doc.layer_color(w.group))); + let r = egui::Rect::from_center_size(c, vec2(2.0 * SPACE_HALF_PX, 2.0 * SPACE_HALF_PX)); p.line_segment([on, c], Stroke::new(1.0, color)); - p.circle_filled(c, ROTATE_ALL_RADIUS_PX, Color32::WHITE); - p.circle_stroke(c, ROTATE_ALL_RADIUS_PX, Stroke::new(1.0, color)); + p.rect_filled(r, 0.0, Color32::WHITE); + p.rect_stroke(r, 0.0, Stroke::new(1.0, color), StrokeKind::Inside); } /// Record where the Type tool's IME candidate window goes this pass, if it has an editor. diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 43e2e4e601..5876537c3b 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -140,79 +140,98 @@ pub(crate) fn cells(n: usize, area: egui::Rect) -> Vec { (0..n).map(|i| egui::Rect::from_min_max(pos2(x(i % cols), y(i / cols)), pos2(x(i % cols + 1), y(i / cols + 1)))).collect() } -/// `window.arrange.tile`: every open document in a pane of its own, each fitted to its pane. +/// `window.arrange.tile`: every open document in a pane of its own, each fitted to its pane. With +/// fewer than two documents open (when the menu item is grayed out) it leaves the view and `tiled` as +/// they are. The documents in floating windows come back under the tabs for it. pub(crate) fn tile(app: &mut VectorcraftApp) -> Result { - app.sync_views(); let n = app.session.documents().len(); - app.ui.tiled = n > 0; - if n > 0 { - app.ui.home = None; + if n < 2 { + return Ok(json!({"tiled": app.ui.tiled, "panes": n})); } + app.sync_views(); + crate::doc_windows::dock_all(app); + app.ui.tiled = true; + app.ui.home = None; for v in &mut app.views { v.fitted = false; } Ok(json!({"tiled": app.ui.tiled, "panes": n})) } -/// `window.arrange.consolidateAllWindows`: one document at a time again, under its tab. +/// `window.arrange.consolidateAllWindows`: one document at a time again, under its tab, the +/// documents in floating windows included. pub(crate) fn consolidate(app: &mut VectorcraftApp) -> Result { app.ui.tiled = false; + crate::doc_windows::dock_all(app); app.canvas.panes.clear(); - Ok(json!({"tiled": false})) + Ok(json!({"tiled": false, "floating": []})) } -/// Draw the document area as panes while Tile is on and more than one document is open, outside -/// the Home screen and Presentation Mode. False when it did not: the caller draws the canvas. +/// Draw the document area as panes while Tile is on and more than one document is under the tabs, +/// outside the Home screen and Presentation Mode. False when it did not: the caller draws the +/// canvas. The documents in floating windows have no pane. pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { - let n = app.session.documents().len(); - if n == 0 { + if app.session.documents().is_empty() { app.ui.tiled = false; } + let docked = crate::doc_windows::docked(app); + let n = docked.len(); let tiling = app.ui.tiled && n > 1 && app.ui.screen_mode < 3 && !crate::menus::home_showing(app); - let Some(active) = app.session.active_index().filter(|_| tiling) else { - if !app.canvas.panes.shown.is_empty() || !app.canvas.panes.last.is_empty() { + if !tiling { + // The floating windows draw their panes from the same renders. + if app.ui.floating.is_empty() && (!app.canvas.panes.shown.is_empty() || !app.canvas.panes.last.is_empty()) { app.canvas.panes.clear(); } + app.canvas.panes.last.clear(); return false; - }; + } + // The current document's pane is the canvas, unless it is in a floating window. + let active = app.session.active_index().filter(|a| docked.contains(a)); app.sync_views(); let live: Vec = app.session.documents().iter().map(|d| d.uid as usize).collect(); app.canvas.panes.shown.retain(|uid, _| live.contains(uid)); app.canvas.panes.pending.retain(|uid, _| live.contains(uid)); app.canvas.panes.fits.retain(|uid, _| live.contains(uid)); - // A document opened or closed changes the grid, and so does coming back to the panes from one - // document: each document fits its new pane. - if app.canvas.panes.last.len() != n { - for v in &mut app.views { - v.fitted = false; + // A document opened, closed, floated or docked changes the grid, and so does coming back to the + // panes from one document: each document fits its new pane. + if app.canvas.panes.last.iter().map(|(i, _)| *i).ne(docked.iter().copied()) { + for i in &docked { + if let Some(v) = app.views.get_mut(*i) { + v.fitted = false; + } } } let t = Tokens::get(ui.ctx()); let ppp = ui.ctx().pixels_per_point(); - let cells = cells(n, ui.available_rect_before_wrap()); - let areas: Vec = cells.iter().map(|c| view_rects(app, *c, ppp).1).collect(); + let cells: Vec<(usize, egui::Rect)> = docked.iter().copied().zip(cells(n, ui.available_rect_before_wrap())).collect(); + let mut areas: Vec> = vec![None; app.session.documents().len()]; + for (i, cell) in &cells { + if let Some(a) = areas.get_mut(*i) { + *a = Some(view_rects(app, *cell, ppp).1); + } + } let unfitted = refit_resized(app, &areas); let mut activate = None; // The other panes first, so that what the canvas draws past its pane (the Contextual Task Bar) // stays over them. - for (i, cell) in cells.iter().copied().enumerate().filter(|(i, _)| *i != active) { + for (i, cell) in cells.iter().copied().filter(|(i, _)| Some(*i) != active) { if pane(app, ui, i, cell) { activate = Some(i); } ui.painter().rect_stroke(cell, 0.0, Stroke::new(1.0, t.border), StrokeKind::Inside); } - if let Some(cell) = cells.get(active).copied() { + if let Some((_, cell)) = cells.iter().copied().find(|(i, _)| Some(*i) == active) { let mut canvas = ui.new_child(egui::UiBuilder::new().max_rect(cell)); super::show(app, &mut canvas); ui.painter().rect_stroke(cell, 0.0, Stroke::new(1.5, t.accent), StrokeKind::Inside); } // Note the fits this frame made, for `refit_resized`. for ((i, area), was_unfitted) in areas.iter().enumerate().zip(unfitted) { - if let (true, Some(v), Some(d)) = (was_unfitted, app.views.get(i).filter(|v| v.fitted), app.session.documents().get(i)) { + if let (Some(area), true, Some(v), Some(d)) = (area, was_unfitted, app.views.get(i).filter(|v| v.fitted), app.session.documents().get(i)) { app.canvas.panes.fits.insert(d.uid as usize, (area.size(), v.zoom, v.center)); } } - app.canvas.panes.last = cells.into_iter().enumerate().collect(); + app.canvas.panes.last = cells; if let Some(i) = activate { crate::chrome::show_document(app, i); } @@ -220,14 +239,15 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { } /// Unfit each document whose view is still where a pane fit left it when its view's area (in -/// `areas`, by document index) has changed size, as when the window or a panel is resized: it -/// fits its pane again. A view zoomed or scrolled since keeps its place. → which views are -/// unfitted now. -fn refit_resized(app: &mut VectorcraftApp, areas: &[egui::Rect]) -> Vec { +/// `areas`, by document index; None for a document without a pane) has changed size, as when the +/// window or a panel is resized: it fits its pane again. A view zoomed or scrolled since keeps its +/// place. → which views are unfitted now. +fn refit_resized(app: &mut VectorcraftApp, areas: &[Option]) -> Vec { let fits = &app.canvas.panes.fits; let docs = app.session.documents(); for ((v, d), area) in app.views.iter_mut().zip(docs).zip(areas) { - if let Some((size, zoom, center)) = fits.get(&(d.uid as usize)) + if let Some(area) = area + && let Some((size, zoom, center)) = fits.get(&(d.uid as usize)) && *size != area.size() && *zoom == v.zoom && *center == v.center @@ -251,8 +271,9 @@ fn fit_pane(v: &mut View, doc: &vectorcraft_doc::Document, rect: egui::Rect) { /// The pane of document `i`, not the current one, in `cell`: its paper, art, grid, artboards, /// guides and selected objects, and its rulers and the room of the canvas's scroll bars, so the /// document stays where it is when the pane becomes the canvas. True when a press in the pane asks -/// for its document to become the current one. -fn pane(app: &mut VectorcraftApp, ui: &Ui, i: usize, cell: egui::Rect) -> bool { +/// for its document to become the current one. A floating document's window draws its document +/// with this too ([`crate::doc_windows`]). +pub(crate) fn pane(app: &mut VectorcraftApp, ui: &Ui, i: usize, cell: egui::Rect) -> bool { let t = Tokens::get(ui.ctx()); let ppp = ui.ctx().pixels_per_point(); let (full, rect) = view_rects(app, cell, ppp); diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 49bca99389..cdd6add6dc 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -151,7 +151,7 @@ fn consolidate_all_windows_shows_one_document_again() { app.run("window.arrange.tile", json!({})).unwrap(); frame(&mut app, &ctx, vec![]); assert_eq!(panes(&app).0.len(), 2); - assert_eq!(app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(), json!({"tiled": false})); + assert_eq!(app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(), json!({"tiled": false, "floating": []})); frame(&mut app, &ctx, vec![]); assert!(panes(&app).0.is_empty() && app.canvas.panes.shown.is_empty()); assert_eq!(app.canvas_rect, Some(tabbed), "the current document fills the document area again"); @@ -179,6 +179,18 @@ fn arrange_items_follow_the_open_documents() { assert!(!app.ui.tiled); } +#[test] +fn tile_with_one_document_leaves_the_next_one_under_its_tab() { + let mut app = app_with(1); + let ctx = egui::Context::default(); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": false, "panes": 1})); + assert!(!app.ui.tiled); + assert!(!enabled(&app, "window.arrange.consolidateAllWindows")); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert!(panes(&app).0.is_empty(), "the second document opens under its tab"); +} + #[test] fn closing_a_document_while_tiled_tiles_the_others() { let mut app = app_with(3); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 836049278c..0c9462818e 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -3159,6 +3159,65 @@ fn grid_repeat_handles_set_rows_and_spacing_in_one_undo_step_each() { assert_eq!((grid(&app).0, grid(&app).2), (5, 10.0), "the spacing's own undo step"); } +/// While a symbol with 9-slice guides is edited, the canvas draws its four guides dotted across +/// its art, with ruler guides hidden too, and none once the mode ends. Dragging the left guide in +/// a zoomed view moves that guide alone, as one undo step. +#[test] +fn the_edited_symbols_nine_slice_guides_are_drawn_and_dragged_on_the_canvas() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + app.run("symbol.new", json!({"name": "Box", "nineSlice": true})).unwrap(); + app.select_tool("selection"); + app.ui.task_bar = false; + app.ui.view.rulers = false; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.view_mut().unwrap().zoom = 1.5; + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + // The dots drawn along the guide from document point `a` to `b`. + let dots = |app: &mut VectorcraftApp, a: Point, b: Point| { + let (a, b) = (xf.to_screen(a), xf.to_screen(b)); + let on = |q: Pos2| { + let (d, len) = (b - a, (b - a).length()); + let t = (q - a).dot(d) / (len * len); + (-0.01..=1.01).contains(&t) && (a + d * t).distance(q) < 0.01 + }; + shapes(app, &ctx).into_iter().filter(|s| matches!(s, Shape::LineSegment { points: [p, q], .. } if on(*p) && on(*q))).count() + }; + let guides = [ + (Point::new(125.0, 100.0), Point::new(125.0, 200.0)), + (Point::new(100.0, 125.0), Point::new(200.0, 125.0)), + (Point::new(175.0, 100.0), Point::new(175.0, 200.0)), + (Point::new(100.0, 175.0), Point::new(200.0, 175.0)), + ]; + assert_eq!(dots(&mut app, guides[0].0, guides[0].1), 0, "not while the instance is only selected"); + app.run("symbol.edit", json!({})).unwrap(); + app.ui.view.guides = false; + for (a, b) in guides { + assert!(dots(&mut app, a, b) > 10, "a dotted guide from {a:?} to {b:?}"); + } + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let from = xf.to_screen(Point::new(125.0, 150.0)); + let to = xf.to_screen(Point::new(110.0, 160.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]); + for k in 1..=4 { + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from + (to - from) * k as f32 / 4.0)]); + } + frame(&mut app, &ctx, vec![button(to, false)]); + let guides_now = |app: &VectorcraftApp| app.session.active().unwrap().doc.symbol_nine_slice("Box").unwrap(); + let g = guides_now(&app); + assert!((g.left - 0.1).abs() < 1e-3 && (g.top, g.right, g.bottom) == (0.25, 0.25, 0.25), "{g:?}"); + assert!(app.session.active().unwrap().doc.symbol_edit.is_some(), "still editing the symbol"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(guides_now(&app).left, 0.25, "one undo step"); + app.run("edit.redo", json!({})).unwrap(); + assert!((guides_now(&app).left - 0.1).abs() < 1e-3); + app.run("symbol.exitEditing", json!({})).unwrap(); + assert_eq!(dots(&mut app, Point::new(110.0, 100.0), Point::new(110.0, 200.0)), 0, "none outside the mode"); +} + #[test] fn top_bounding_box_handle_scales_a_default_mirror_repeat() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -3965,6 +4024,41 @@ fn a_selected_objects_on_path_group_shows_its_rotate_all_widget() { assert_eq!(widgets(&mut app), 0, "an object in the group, not the group"); } +/// A selected Objects on Path group of two or more objects shows its Space widget, a white square +/// beyond its last object, with the Selection and Objects on Path tools. +#[test] +fn a_selected_objects_on_path_group_shows_its_space_widget() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = |v: serde_json::Value| v["id"].as_u64().unwrap(); + let line = id(app.session.execute("shape.line", &json!({"x1": 20, "y1": 200, "x2": 380, "y2": 200})).unwrap()); + let a = id(app.session.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()); + let b = id(app.session.execute("shape.rectangle", &json!({"x": 80, "y": 40, "width": 20, "height": 20})).unwrap()); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let g = id(app.session.execute("object.objectsOnPath.attach", &json!({"path": line})).unwrap()); + let ctx = egui::Context::default(); + let widgets = |app: &mut VectorcraftApp| { + let side = 2.0 * vectorcraft_tools::objects_on_path::SPACE_HALF_PX; + shapes(app, &ctx) + .iter() + .filter(|s| matches!(s, Shape::Rect(r) if r.rect.width() == side && r.rect.height() == side && r.fill == Color32::WHITE)) + .count() + }; + app.select_tool("selection"); + assert_eq!(widgets(&mut app), 1); + app.select_tool("objectsOnPath"); + assert_eq!(widgets(&mut app), 1); + app.select_tool("directSelection"); + assert_eq!(widgets(&mut app), 0); + app.select_tool("selection"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + assert_eq!(widgets(&mut app), 0, "an object in the group, not the group"); + // With one object on the path there is no space to set. + app.run("edit.clear", json!({"ids": [b]})).unwrap(); + app.run("select.set", json!({"ids": [g]})).unwrap(); + assert_eq!(widgets(&mut app), 0, "one object"); +} + /// The shapes Type → Show Hidden Characters draws in one frame, seen through `xf`. fn hidden_chars(app: &mut VectorcraftApp, ctx: &egui::Context, xf: &Xf) -> Vec { let raw = egui::RawInput { screen_rect: Some(xf.rect), ..Default::default() }; @@ -6519,6 +6613,85 @@ fn a_drag_ends_where_the_button_went_up_in_its_frame() { assert!(app.session.active().unwrap().interaction.is_none(), "committed"); } +/// The moves that come after the button-up in the release's frame are hover: a stroke built from +/// the drag's samples does not take them. +#[test] +fn moves_after_the_button_up_do_not_join_the_stroke() { + use egui::{Event, Modifiers}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let center = app.canvas_rect.unwrap().center(); + app.select_tool("pencil"); + let a = center - vec2(100.0, 0.0); + let end = a + vec2(120.0, 0.0); + frame(&mut app, &ctx, vec![Event::PointerMoved(a)]); + frame(&mut app, &ctx, vec![button(a, true)]); + for x in [20.0, 40.0, 60.0] { + frame(&mut app, &ctx, vec![Event::PointerMoved(a + vec2(x, 0.0))]); + } + let hover = [end + vec2(30.0, 100.0), end + vec2(60.0, 120.0), end + vec2(90.0, 140.0)]; + let mut events = vec![Event::PointerMoved(a + vec2(90.0, 0.0)), Event::PointerMoved(end), button(end, false)]; + events.extend(hover.map(Event::PointerMoved)); + frame(&mut app, &ctx, events); + let st = app.session.active().unwrap(); + let r = st.doc.node(st.selection.objects[0]).unwrap().geometric_bounds().unwrap(); + let (left, right) = (xf.to_doc(a), xf.to_doc(end)); + assert!((r.x0 - left.x).abs() < 1.0 && (r.x1 - right.x).abs() < 1.0 && r.height() < 1.0, "the stroke stops at the release: {r:?}"); +} + +/// [`frame_moves`] with a release keeps the moves before the button-up, and the pose the feed kept +/// for the last of them. +#[test] +fn frame_moves_stop_at_the_button_up() { + let ctx = egui::Context::default(); + let (a, b, c, d) = (pos2(10.0, 20.0), pos2(20.0, 30.0), pos2(30.0, 40.0), pos2(40.0, 50.0)); + let up = egui::Event::PointerButton { pos: b, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + let events = vec![egui::Event::PointerMoved(a), egui::Event::PointerMoved(b), up, egui::Event::PointerMoved(c), egui::Event::PointerMoved(d)]; + let feed = StylusFeed::default(); + let at_b = PenPose { tilt: Some([20.0, 0.0]), rotation: None }; + let after = PenPose { tilt: Some([50.0, 0.0]), rotation: None }; + for (p, pose) in [(0.4, PenPose::default()), (0.6, at_b), (0.7, after), (0.8, after)] { + feed.set_move(crate::stylus::PenSample { pressure: p, pose, ..Default::default() }); + } + let (mut moves, mut last) = (vec![], None); + let release = Some(egui::PointerButton::Primary); + let mut out = + ctx.run_ui(egui::RawInput { events: events.clone(), ..Default::default() }, |ui| (moves, last) = frame_moves(ui, Some(&feed), release)); + out.textures_delta.clear(); + assert_eq!(moves, [(a, Some(0.4), Some(PenPose::default()))], "the moves after the button-up are left out"); + assert_eq!(last, Some(at_b), "the pose is the last move's before the button-up"); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| moves = frame_moves(ui, None, None).0); + out.textures_delta.clear(); + assert_eq!(moves, [(a, None, None), (b, None, None), (c, None, None)], "without a release every move counts"); +} + +/// A button-up away from the last move before it keeps that move: the release takes only its own +/// position, and the pose is still the last move's. +#[test] +fn frame_moves_keep_the_last_move_when_the_button_went_up_elsewhere() { + let ctx = egui::Context::default(); + let (a, b, up_at, c) = (pos2(10.0, 20.0), pos2(20.0, 30.0), pos2(25.0, 35.0), pos2(30.0, 40.0)); + let up = egui::Event::PointerButton { pos: up_at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + let events = vec![egui::Event::PointerMoved(a), egui::Event::PointerMoved(b), up, egui::Event::PointerMoved(c)]; + let feed = StylusFeed::default(); + let at_b = PenPose { tilt: Some([20.0, 0.0]), rotation: None }; + for (p, pose) in [(0.4, PenPose::default()), (0.6, at_b), (0.7, PenPose::default())] { + feed.set_move(crate::stylus::PenSample { pressure: p, pose, ..Default::default() }); + } + let (mut moves, mut last) = (vec![], None); + let release = Some(egui::PointerButton::Primary); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| (moves, last) = frame_moves(ui, Some(&feed), release)); + out.textures_delta.clear(); + assert_eq!(moves, [(a, Some(0.4), Some(PenPose::default())), (b, Some(0.6), Some(at_b))], "the move before the button-up is kept"); + assert_eq!(last, Some(at_b), "the pose is the last move's before the button-up"); +} + #[test] fn frame_moves_keeps_touch_feed_and_mouse_samples_with_their_pressure() { let ctx = egui::Context::default(); @@ -6527,7 +6700,7 @@ fn frame_moves_keeps_touch_feed_and_mouse_samples_with_their_pressure() { let c = pos2(30.0, 40.0); let events = vec![egui::Event::PointerMoved(a), egui::Event::PointerMoved(b), egui::Event::PointerMoved(c)]; let mut mouse = vec![]; - let mut out = ctx.run_ui(egui::RawInput { events: events.clone(), ..Default::default() }, |ui| mouse = frame_moves(ui, None).0); + let mut out = ctx.run_ui(egui::RawInput { events: events.clone(), ..Default::default() }, |ui| mouse = frame_moves(ui, None, None).0); out.textures_delta.clear(); // A mouse keeps its moves too, without a pressure or a pose. assert_eq!(mouse, [(a, None, None), (b, None, None)], "the last move follows the normal pointer path"); @@ -6538,7 +6711,8 @@ fn frame_moves_keeps_touch_feed_and_mouse_samples_with_their_pressure() { feed.set_move(crate::stylus::PenSample { pressure: p, pose, ..Default::default() }); } let (mut samples, mut last) = (vec![], None); - let mut out = ctx.run_ui(egui::RawInput { events: events.clone(), ..Default::default() }, |ui| (samples, last) = frame_moves(ui, Some(&feed))); + let mut out = + ctx.run_ui(egui::RawInput { events: events.clone(), ..Default::default() }, |ui| (samples, last) = frame_moves(ui, Some(&feed), None)); out.textures_delta.clear(); assert_eq!( samples, @@ -6546,17 +6720,17 @@ fn frame_moves_keeps_touch_feed_and_mouse_samples_with_their_pressure() { "paired from the end, each with its own pose; a lift's 0 is no pressure" ); assert_eq!(last, Some(leaning), "the last move's pose comes with the moves"); - let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| (samples, last) = frame_moves(ui, Some(&feed))); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| (samples, last) = frame_moves(ui, Some(&feed), None)); out.textures_delta.clear(); assert_eq!(samples, [(a, None, None), (b, None, None)], "the moves were taken: a mouse's moves again"); assert_eq!(last, None); let events = [pen(egui::TouchPhase::Move, a, 0.2), pen(egui::TouchPhase::Move, b, 0.8), pen(egui::TouchPhase::Move, c, 0.6)].concat(); let mut samples = vec![]; - let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| samples = frame_moves(ui, None).0); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| samples = frame_moves(ui, None, None).0); out.textures_delta.clear(); assert_eq!(samples, [(a, Some(0.2), None), (b, Some(0.8), None)], "the last sample follows the normal pointer path"); let events = (0..200).flat_map(|n| pen(egui::TouchPhase::Move, pos2(n as f32, 0.0), 0.5)).collect(); - let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| samples = frame_moves(ui, None).0); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| samples = frame_moves(ui, None, None).0); out.textures_delta.clear(); assert!(samples.len() <= 64, "a stalled frame stays bounded"); } @@ -6584,10 +6758,41 @@ fn long_touch_drops_a_tool_press_without_committing_art() { tick(&mut app, 1.5, vec![]); assert!(matches!(ctx.data(|d| d.get_temp::(drag_id())), Some(Drag::Gesture)), "long touch drops the tool drag"); assert!(app.session.active().unwrap().interaction.is_none()); + assert!(app.ui.dialog.is_none(), "the dropped press is not a click that opens the size dialog"); tick(&mut app, 1.6, pen(egui::TouchPhase::End, pos, 0.5)); assert!(app.session.active().unwrap().doc.art_bounds().is_none(), "releasing cannot commit the cancelled press"); } +/// A canceled touch drops the tool's drag: the options the drag changed (the Polygon tool's +/// sides) are put back and not stored, and nothing is drawn. +#[test] +fn a_canceled_touch_drops_the_drag_without_keeping_its_options() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.touch_gestures = true; + app.session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + app.select_tool("polygon"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let start = xf.to_screen(Point::new(200.0, 200.0)); + frame(&mut app, &ctx, pen(egui::TouchPhase::Start, start, 0.5)); + frame(&mut app, &ctx, pen(egui::TouchPhase::Move, start + vec2(60.0, 40.0), 0.5)); + assert!(matches!(ctx.data(|d| d.get_temp::(drag_id())), Some(Drag::Tool))); + assert!(app.session.active().unwrap().interaction.is_some(), "the drag previews the polygon"); + let view = app.view_info(); + assert_eq!(app.session.tool_options()["sides"], json!(6)); + app.session.tool_key(vectorcraft_tools::ToolKey::Up, Mods::default(), view).unwrap(); + assert_eq!(app.session.tool_options()["sides"], json!(7)); + frame(&mut app, &ctx, pen(egui::TouchPhase::Cancel, start + vec2(60.0, 40.0), 0.5)); + assert!(!app.session.tool_busy(), "the tool is at rest"); + let st = app.session.active().unwrap(); + assert!(st.interaction.is_none() && st.doc.art_bounds().is_none(), "nothing is drawn"); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.tool_options()["sides"], json!(6), "the tool has its sides from before the press"); + let stored = app.session.prefs.tool_settings.get("polygon").and_then(|o| o.get("sides")); + assert_eq!(stored, None, "the dropped drag's sides are not stored"); +} + /// #2826: a second finger drops a move waiting over a panel, so its interaction doesn't /// outlive the drag that began it. #[test] @@ -7141,7 +7346,7 @@ fn only_the_freehand_tools_get_every_move_of_a_frame() { { app.select_tool(tool); let mut moves = vec![]; - let mut out = ctx.run_ui(egui::RawInput { events: events.clone(), ..Default::default() }, |ui| moves = tool_frame_moves(ui, &app).0); + let mut out = ctx.run_ui(egui::RawInput { events: events.clone(), ..Default::default() }, |ui| moves = tool_frame_moves(ui, &app, false).0); out.textures_delta.clear(); assert_eq!(moves.len(), if every { 19 } else { 0 }, "{tool}"); } diff --git a/crates/ui-egui/src/canvas/tool_overlays.rs b/crates/ui-egui/src/canvas/tool_overlays.rs index bbb8bf5f0f..7b88244f68 100644 --- a/crates/ui-egui/src/canvas/tool_overlays.rs +++ b/crates/ui-egui/src/canvas/tool_overlays.rs @@ -166,6 +166,23 @@ pub(super) fn original_path_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: } } +/// The 9-slice guides of the symbol edited in symbol editing mode: four thin dotted lines across +/// its art's box, with any tool, whether ruler guides are shown or hidden. The Selection tool drags +/// them ([`vectorcraft_tools::nineslice`]) at the places drawn here. +pub(super) fn nine_slice_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { + let Some(e) = app.session.active().and_then(|st| st.doc.edited_nine_slice()) else { return }; + let color = Tokens::get(p.ctx()).selection; + for (_, a, b) in e.lines() { + let (a, b) = (xf.to_screen(a), xf.to_screen(b)); + if !a.is_finite() || !b.is_finite() { + continue; + } + if let Some((a, b)) = clip_segment(a, b, xf.rect) { + p.extend(Shape::dashed_line(&[a, b], Stroke::new(1.0, color), 2.0, 2.0)); + } + } +} + /// The slices (unless View → Hide Slices): user and object slices outlined in the Slices /// preferences' line colour, auto slices dashed and dimmer, each numbered at its top left (Show /// Slice Numbers); selected slices have a bolder outline. The layout is cached per revision. diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index c619748044..eecaa22fd3 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -27,10 +27,10 @@ pub use hints::{hint_bar, hint_strings}; pub use status_bar::status_bar; #[cfg(test)] use status_bar::{StatusReadoutWidths, status_readouts}; -pub(crate) use tabs::show_document; #[cfg(test)] use tabs::{CLOSE_BEFORE_TITLE, first_tab_shown, tab_title}; pub use tabs::{doc_tabs, isolation_bar, step_document}; +pub(crate) use tabs::{document_window_title, show_document, window_tab}; /// The application bar's height, in points (compact, as in PhotoCraft). pub const APP_BAR_HEIGHT: f32 = 32.0; diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index cd0fad1f3c..cac5949161 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -19,6 +19,57 @@ pub(super) fn doc_tab_title(app: &VectorcraftApp, i: usize, d: &vectorcraft_engi tab_title(d, zoom, view.is_some_and(|v| v.outline), app.session.prefs.display_print_size) } +/// The title of document `i`'s floating window ([`crate::doc_windows`]): its tab's title. +pub(crate) fn document_window_title(app: &VectorcraftApp, i: usize) -> Option { + let d = app.session.documents().get(i)?; + Some(doc_tab_title(app, i, d)) +} + +/// The height of the tab strip and the size of a tab's title, in points: larger with User +/// Interface › Large Tabs. +fn tab_size(app: &VectorcraftApp) -> (f32, f32) { + if app.session.prefs.large_tabs { (44.0, 14.0) } else { (35.0, 12.5) } +} + +/// The tab at the top of document `i`'s floating OS window ([`crate::doc_windows`]): a strip with +/// the document's tab, as the main window's strip draws it but without its ×. → the tab's +/// response, which senses clicks and drags. +pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, i: usize) -> egui::Response { + let t = Tokens::get(ui.ctx()); + let (height, title_size) = tab_size(app); + let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover()); + ui.painter().rect_filled(strip, 0.0, t.tab_strip); + ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); + let title = document_window_title(app, i).unwrap_or_default(); + let galley = ui.painter().layout_no_wrap(title, theme::semibold(title_size), t.text_strong); + let r = egui::Rect::from_min_size(strip.min, vec2((galley.size().x + 28.0).min(strip.width()), strip.height() - 1.0)); + ui.painter().rect_filled(r, 0.0, t.panel); + ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.5, t.border)); + ui.painter().galley(egui::pos2(r.left() + 14.0, r.center().y - galley.size().y / 2.0), galley, t.text); + ui.interact(r, ui.scope_id().with("window-tab"), Sense::click_and_drag()) +} + +/// While document tab `r` is dragged off the tab `strip` far enough to float its document, an +/// outline under the pointer where its window will open; → the window's top-left corner when the +/// drag ends there. +fn tear_off(ui: &Ui, resp: &egui::Response, strip: egui::Rect) -> Option { + use crate::doc_windows::{GRAB, torn_off}; + if resp.dragged() + && let Some(p) = resp.interact_pointer_pos().filter(|p| torn_off(strip, *p)) + { + let t = Tokens::get(ui.ctx()); + let ghost = egui::Rect::from_min_size(p - GRAB, vec2(240.0, 160.0)); + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, ui.scope_id().with("tab-tear-off"))); + painter.rect_filled(ghost, 0.0, t.accent.gamma_multiply(0.12)); + painter.rect_stroke(ghost, 0.0, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); + } + if !resp.drag_stopped() { + return None; + } + let p = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos()))?; + torn_off(strip, p).then_some(p - GRAB) +} + /// Whether a document tab's × comes before its title (macOS) rather than after it (Windows, /// Linux and the web). pub(super) const CLOSE_BEFORE_TITLE: bool = cfg!(target_os = "macos"); @@ -37,24 +88,30 @@ pub(super) fn first_tab_shown(widths: &[f32], active: Option, room: f32) /// Document tab strip: "Name* @ 66.67% (RGB/Preview)". User Interface › Large Tabs makes the tabs /// taller, with larger titles. Tabs that don't fit are reached from a » button at the strip's /// right end, which lists every open document, and the active tab is always in view (#746). +/// Documents in floating windows have no tab ([`crate::doc_windows`]); while the current document +/// is in one, the tab of the document the strip shows is the highlighted one. A tab dragged more +/// than [`crate::doc_windows::TEAR_OFF`] above or below the strip floats its document in a window +/// under the pointer. pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { /// The width of the » button. const MORE: f32 = 30.0; let t = Tokens::get(ui.ctx()); - let (height, title_size) = if app.session.prefs.large_tabs { (44.0, 14.0) } else { (35.0, 12.5) }; + let (height, title_size) = tab_size(app); let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover()); + app.canvas.windows.strip = Some(strip); ui.painter().rect_filled(strip, 0.0, t.tab_strip); ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); // On the Home screen no tab is the current one. - let active = app.session.active_index().filter(|_| app.ui.home.is_none()); - let tabs: Vec<(String, std::sync::Arc)> = app - .session - .documents() + let shown = crate::doc_windows::tab_document(app).filter(|_| app.ui.home.is_none()); + // The documents under the tabs, by index; `active` is the position of the highlighted one. + let docked = crate::doc_windows::docked(app); + let active = docked.iter().position(|i| Some(*i) == shown); + let tabs: Vec<(String, std::sync::Arc)> = docked .iter() - .enumerate() + .filter_map(|i| Some((*i, app.session.documents().get(*i)?))) .map(|(i, d)| { let title = doc_tab_title(app, i, d); - let color = if Some(i) == active { t.text_strong } else { t.text_dim }; + let color = if Some(i) == shown { t.text_strong } else { t.text_dim }; (title.clone(), ui.painter().layout_no_wrap(title, theme::semibold(title_size), color)) }) .collect(); @@ -65,14 +122,16 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let mut x = strip.left(); let mut activate = None; let mut close = None; + let mut float = None; let mut hovering_art = false; - for (i, ((_, galley), w)) in tabs.iter().zip(&widths).enumerate().skip(first) { - if x + w > strip.left() + room && Some(i) != active { + for (k, ((_, galley), w)) in tabs.iter().zip(&widths).enumerate().skip(first) { + if x + w > strip.left() + room && Some(k) != active { break; } - let is_active = Some(i) == active; + let Some(&i) = docked.get(k) else { break }; + let is_active = Some(k) == active; let r = egui::Rect::from_min_size(egui::pos2(x, strip.top()), vec2(*w, strip.height() - 1.0)); - let resp = ui.interact(r, ui.scope_id().with(("tab", i)), Sense::click()); + let resp = ui.interact(r, ui.scope_id().with(("tab", i)), Sense::click_and_drag()); if is_active { ui.painter().rect_filled(r, 0.0, t.panel); } else if resp.hovered() { @@ -91,14 +150,18 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { close = Some(i); } else if resp.clicked() { activate = Some(i); + } else if let Some(at) = tear_off(ui, &resp, strip) { + float = Some((i, at)); } x += w; } crate::document_drag::finish_tabs(ui.ctx(), hovering_art); - // The » button: every open document, the active one checked. The list scrolls once it - // reaches the bottom of the window, so every document of a large session stays reachable - // (#4017). + // The » button: every open document, floating ones included, the active one checked. The list + // scrolls once it reaches the bottom of the window, so every document of a large session stays + // reachable (#4017). if overflow { + let current = app.session.active_index().filter(|_| app.ui.home.is_none()); + let titles: Vec = (0..app.session.documents().len()).map(|i| document_window_title(app, i).unwrap_or_default()).collect(); let more = egui::Rect::from_min_max(egui::pos2(strip.right() - MORE, strip.top()), egui::pos2(strip.right(), strip.bottom() - 1.0)); let resp = ui.interact(more, ui.scope_id().with("tabs-more"), Sense::click()); ui.painter().rect_filled(more, 0.0, if resp.hovered() { t.hover.gamma_multiply(0.4) } else { t.tab_strip }); @@ -106,8 +169,8 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let resp = resp.on_hover_text(tl!("Show all open documents")); egui::Popup::menu(&resp).show(|ui| { widgets::menu_scroll(ui, |ui| { - for (i, (title, _)) in tabs.iter().enumerate() { - if widgets::menu_item_name(ui, title, true, Some(i) == active) { + for (i, title) in titles.iter().enumerate() { + if widgets::menu_item_name(ui, title, true, Some(i) == current) { activate = Some(i); ui.close(); } @@ -119,6 +182,10 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { if let Err(e) = crate::unsaved::close(app, i) { app.status(e); } + } else if let Some((i, at)) = float { + if let Err(e) = app.run("window.arrange.floatInWindow", json!({"index": i, "at": [at.x, at.y]})) { + app.status(e); + } } else if let Some(i) = activate { show_document(app, i); } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index c374b62eec..d3278e97ea 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -200,6 +200,9 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { "rect": [c.left(), c.top(), c.width(), c.height()], "active": app.session.active_index() == Some(*i), })).collect::>(), + // Window › Arrange › Float in Window: the documents in floating windows, by index. While + // the current one floats, `canvasRect` is in its window's coordinates. + "floating": (0..app.session.documents().len()).filter(|i| crate::doc_windows::is_floating(app, *i)).collect::>(), "window": [r.width(), r.height()], "documents": app.session.documents().iter().map(|d| json!({"title": d.title(), "dirty": d.is_dirty()})).collect::>(), "activeDocument": app.session.active_index(), @@ -267,7 +270,10 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques "ui.menu.list" => ok(serde_json::to_value(crate::menus::menu_entries(app)).unwrap_or_default()), "ui.contextMenu.list" => ok(serde_json::to_value(crate::menus::context_entries(app)).unwrap_or_default()), "ui.tool.select" => wrap(app.run("tool.select", json!({"tool": s("tool").unwrap_or("")}))), - "ui.tool.list" => ok(serde_json::to_value(vectorcraft_tools::TOOL_GROUPS).unwrap_or_default()), + "ui.tool.list" => { + let groups: Vec<_> = vectorcraft_tools::TOOL_GROUPS.iter().chain(vectorcraft_tools::addons::GROUPS).copied().collect(); + ok(serde_json::to_value(groups).unwrap_or_default()) + } "ui.pointer" => pointer_events(app, ctx, req), "ui.key" => { let Some(k) = s("key").and_then(key_from) else { return err("unknown or missing `key`") }; diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index ded29508ad..d084d7ee04 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -11,6 +11,23 @@ fn input_request(app: &mut VectorcraftApp, method: &str, params: Value) -> Value r } +#[test] +fn control_lists_and_selects_optional_addon_tools() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + let listed = input_request(&mut app, "ui.tool.list", json!({})); + assert_eq!(listed["ok"], true); + let groups = listed["result"].as_array().unwrap(); + for tool in vectorcraft_tools::addons::GROUPS.iter().flat_map(|group| group.iter()) { + let matching: Vec<_> = groups.iter().flat_map(|group| group.as_array().unwrap()).filter(|entry| entry["id"] == tool.id).collect(); + assert_eq!(matching.len(), 1, "{}", tool.id); + assert_eq!(matching[0]["label"], tool.label); + assert!(matching[0]["shortcut"].is_null()); + let selected = input_request(&mut app, "ui.tool.select", json!({"tool": tool.id})); + assert_eq!(selected["ok"], true, "{selected}"); + assert_eq!(selected["result"]["tool"], tool.id); + } +} + #[test] fn ui_set_turns_the_image_trace_preview_off_and_on() { let mut app = VectorcraftApp::new(Session::new(), Services::default()); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6221e6d90b..d68217e52a 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -8,6 +8,7 @@ mod about; pub mod action_batch; +pub mod action_new; pub mod action_set_options; pub mod artboard_options; pub mod blend_options; @@ -361,6 +362,7 @@ registry! { Package: [package::KIND] => package::SPEC, ActionBatch: [action_batch::KIND] => action_batch::SPEC, ActionSetOptions: [action_set_options::KIND] => action_set_options::SPEC, + ActionNew: [action_new::KIND] => action_new::SPEC, SliceOptions: [slices::OPTIONS] => slices::OPTIONS_SPEC, DivideSlices: [slices::DIVIDE] => slices::DIVIDE_SPEC, EpsOptions: [eps_options::KIND] => eps_options::SPEC, @@ -408,6 +410,7 @@ registry! { DivideDashes: [crate::addons::pathtools::dashes::KIND] => crate::addons::pathtools::dashes::SPEC, NearestSwatch: [crate::addons::color::nearest::KIND] => crate::addons::color::nearest::SPEC, SwatchLegend: [crate::addons::color::legend::KIND] => crate::addons::color::legend::SPEC, + TextTweaker: [crate::addons::typetools::KIND] => crate::addons::typetools::SPEC, ArrangeTools: [crate::addons::arrange::GRID, crate::addons::arrange::REPLACE, crate::addons::arrange::SIZE, crate::addons::arrange::OPACITY, crate::addons::arrange::SORT] => crate::addons::arrange::SPEC, ShortcutImport: [shortcut_import::KIND] => DialogSpec::window(shortcut_import::show, shortcut_import::confirm), } diff --git a/crates/ui-egui/src/dialogs/action_new.rs b/crates/ui-egui/src/dialogs/action_new.rs new file mode 100644 index 0000000000..dab6013e1d --- /dev/null +++ b/crates/ui-egui/src/dialogs/action_new.rs @@ -0,0 +1,120 @@ +//! Actions panel › Create New Action (and ≡ › New Action…): the name, set, function key and color +//! of a new action. Record adds the action and starts recording into it (`ui.action.new`). +//! +//! Fields: `set` (the index of the set the action goes into), `name`, `key` (0 for none, 1 to 15 +//! for F1 to F15), `cmd` (Ctrl, Command on macOS), `shift`, `color` (a value of +//! [`crate::panels::actions::COLORS`], `""` for none). An invalid set or function key is an error: +//! Record then adds nothing and the dialog stays open. + +use serde_json::{Value, json}; + +use super::DialogSpec; +use crate::panels::actions::{COLORS, FUNCTION_KEYS, FunctionKey}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of New Action. +pub const KIND: &str = "actionNew"; + +/// The width of the label column. +const LABEL_W: f32 = 90.0; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("New Action").into(), + body, + confirm, + ok: Some("Record"), + ok_enabled: Some(|_, d| !d.str("name").trim().is_empty()), + min_width: 340.0, + ..DialogSpec::FORM +}; + +/// Whether New Action can open: there is a set to put the action in and nothing is recording. +pub fn can_open(app: &VectorcraftApp) -> bool { + !app.ui.action_sets.is_empty() && app.ui.recording.is_none() +} + +/// Opens New Action for the current set, else the first set, named "Action N" with the first +/// number from the set's action count plus one that no action of the set uses, with no function +/// key and no color. +pub fn open(app: &mut VectorcraftApp) -> Result<(), String> { + if app.ui.recording.is_some() { + return Err("an action is already recording".into()); + } + let len = app.ui.action_sets.len(); + let set = app.ui.action_set.filter(|&s| s < len).unwrap_or(0); + let Some(s) = app.ui.action_sets.get(set) else { return Err("no such action set".into()) }; + let taken = |n: usize| s.actions.iter().any(|a| a.name == format!("Action {n}")); + let n = (s.actions.len() + 1..).find(|&n| !taken(n)).unwrap_or(1); + let fields = json!({"set": set, "name": format!("Action {n}"), "key": 0, "cmd": false, "shift": false, "color": ""}); + app.ui.dialog = Some(Dialog::new(KIND, fields)); + Ok(()) +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + widgets::label_row(ui, "Name:", LABEL_W, |ui| { + super::form::text(ui, d, "name", 200.0); + }); + let names: Vec<&str> = app.ui.action_sets.iter().map(|s| s.name.as_str()).collect(); + let set = d.fields.get("set").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); + let shown = set.and_then(|s| names.get(s)).copied().unwrap_or_default(); + widgets::label_row(ui, "Action Set:", LABEL_W, |ui| { + if let Some(i) = widgets::dropdown_names(ui, "action-new-set", shown, &names, 200.0) { + d.fields.insert("set".into(), json!(i)); + } + }); + key_and_color(ui, d); + false +} + +/// The Function Key and Color rows of New Action and Action Options show errors for invalid keys. +pub(super) fn key_and_color(ui: &mut egui::Ui, d: &mut Dialog) { + let key = d.fields.get("key").and_then(Value::as_u64).unwrap_or(0); + let none = tl!("None"); + let keys: Vec = std::iter::once(none.to_string()).chain((1..=FUNCTION_KEYS).map(|n| format!("F{n}"))).collect(); + let labels: Vec<&str> = keys.iter().map(String::as_str).collect(); + let shown = usize::try_from(key).ok().and_then(|k| labels.get(k)).copied().unwrap_or(none); + let modifier = if crate::keymap::platform() == craft_keymap::Platform::Mac { "⌘" } else { "Ctrl" }; + widgets::label_row(ui, "Function Key:", LABEL_W, |ui| { + if let Some(i) = widgets::dropdown_names(ui, "action-key", shown, &labels, 70.0) { + d.fields.insert("key".into(), json!(i)); + } + super::form::check(ui, d, "cmd", modifier); + super::form::check(ui, d, "shift", "Shift"); + }); + let picked = FunctionKey::from_params(&json!({"key": key, "cmd": d.bool("cmd"), "shift": d.bool("shift")})); + if let Ok(Some(k)) = picked + && let Some(message) = crate::panels::actions::key_error(k) + { + widgets::label_row(ui, "", LABEL_W, |ui| { + ui.label(crate::i18n::msg(&message)); + }); + } + let colors: Vec<(&str, &str)> = std::iter::once(("", "None")).chain(COLORS).collect(); + super::form::choice(ui, d, "color", "Color:", (LABEL_W, 120.0), &colors); +} + +/// The function key and color params the dialog's fields give, as `ui.action.new` and +/// `ui.action.options` take them. +pub(super) fn key_and_color_params(d: &Dialog) -> Value { + json!({ + "key": d.fields.get("key").and_then(Value::as_u64).unwrap_or(0), + "cmd": d.bool("cmd"), + "shift": d.bool("shift"), + "color": d.str("color"), + }) +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let name = d.str("name").trim().to_string(); + // Record is disabled without a name; `ui.dialog.confirm` keeps the dialog open the same way. + if name.is_empty() { + return Ok(Value::Null); + } + let mut p = key_and_color_params(d); + p["set"] = d.fields.get("set").cloned().unwrap_or(Value::Null); + p["name"] = json!(name); + app.run(crate::panels::actions::NEW_ACTION, p)?; + app.ui.dialog = None; + Ok(Value::Null) +} diff --git a/crates/ui-egui/src/dialogs/action_set_options.rs b/crates/ui-egui/src/dialogs/action_set_options.rs index 568ea41c0b..f4c2ecdedf 100644 --- a/crates/ui-egui/src/dialogs/action_set_options.rs +++ b/crates/ui-egui/src/dialogs/action_set_options.rs @@ -2,10 +2,12 @@ //! the name of a new action set, of the current one, or of the selected action. //! //! Fields: `set` (the index of the set renamed, or of the action's set; none for a new set), -//! `action` (the index of the action renamed, in `set`; none for a set) and `name`. OK adds the set -//! and makes it the current one, renames the set, or renames the action (`ui.action.rename`). A -//! `set` or `action` field that is not the index of a set or action is an error, OK then changes -//! no set or action, and the dialog stays open. +//! `action` (the index of the action renamed, in `set`; none for a set) and `name`. Action Options +//! also holds the action's function key and color, as New Action does (`key`, `cmd`, `shift`, +//! `color`, see [`super::action_new`]). OK adds the set and makes it the current +//! one, renames the set, or changes the action's name, function key and color +//! (`ui.action.options`). An invalid `set`, `action` or function key is an error. OK then changes no set or +//! action, and the dialog stays open. use serde_json::{Value, json}; @@ -43,17 +45,26 @@ pub fn open(app: &mut VectorcraftApp, set: usize) { } } -/// Open Action Options for the action at `action` in set `set`, if there is one. +/// Open Action Options for the action at `action` in set `set`, if there is one, with its name, +/// function key and color. pub fn open_action(app: &mut VectorcraftApp, set: usize, action: usize) { if let Some(a) = app.ui.action_sets.get(set).and_then(|s| s.actions.get(action)) { - app.ui.dialog = Some(Dialog::new(KIND, json!({"set": set, "action": action, "name": a.name}))); + let (key, cmd, shift) = a.key.map_or((0, false, false), |k| (k.key, k.cmd, k.shift)); + let color = a.color.clone().unwrap_or_default(); + let fields = json!({"set": set, "action": action, "name": a.name, "key": key, "cmd": cmd, "shift": shift, "color": color}); + app.ui.dialog = Some(Dialog::new(KIND, fields)); } } -fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - widgets::label_row(ui, "Name:", 50.0, |ui| { +fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + // Action Options lines its rows up with the Function Key and Color rows. + let action = d.fields.contains_key("action") && d.fields.contains_key("key"); + widgets::label_row(ui, "Name:", if action { 90.0 } else { 50.0 }, |ui| { super::form::text(ui, d, "name", 200.0); }); + if action { + super::action_new::key_and_color(ui, d); + } false } @@ -65,7 +76,12 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } // The fields the dialog holds choose what OK does, as they choose its heading. if d.fields.contains_key("action") { - app.run(crate::panels::actions::RENAME_ACTION, json!({"set": d.fields.get("set"), "action": d.fields.get("action"), "name": name}))?; + // A dialog without the key fields (made by `ui.dialog.set`) keeps the key and color. + let mut p = if d.fields.contains_key("key") { super::action_new::key_and_color_params(d) } else { json!({}) }; + p["set"] = d.fields.get("set").cloned().unwrap_or(Value::Null); + p["action"] = d.fields.get("action").cloned().unwrap_or(Value::Null); + p["name"] = json!(name); + app.run(crate::panels::actions::ACTION_OPTIONS, p)?; } else if let Some(set) = d.fields.get("set") { let s = set.as_u64().and_then(|i| usize::try_from(i).ok()).and_then(|i| app.ui.action_sets.get_mut(i)).ok_or("no such action set")?; s.name = name; diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 7f9ead375d..38c425a81b 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -29,6 +29,31 @@ const SWITCHES: &[&str] = &["underline", "strikethrough", "standardVerticalRoman const ADVANCED: &[&str] = &["h_scale", "v_scale", "baseline_shift", "rotation", "language"]; /// The number fields of Advanced Character Formats. const ADVANCED_NUMBERS: &[&str] = &["h_scale", "v_scale", "baseline_shift", "rotation"]; +/// The attributes of Character Color. +const COLOR: &[&str] = &["fill", "stroke", "stroke_width", "overprint_fill", "overprint_stroke"]; +/// The fields of Character Color: the fill and stroke paints, their tints in percent, the stroke +/// weight in points and the two overprint checkboxes. +const COLOR_FIELDS: &[&str] = &["fill", "fill_tint", "stroke", "stroke_tint", "stroke_width", "overprint_fill", "overprint_stroke"]; +/// The on, off or unset checkboxes of OpenType Features and the feature tag each one sets. +const OT_SWITCHES: &[(&str, &str)] = &[ + ("ot_liga", "liga"), + ("ot_calt", "calt"), + ("ot_dlig", "dlig"), + ("ot_swsh", "swsh"), + ("ot_salt", "salt"), + ("ot_titl", "titl"), + ("ot_ordn", "ordn"), + ("ot_frac", "frac"), +]; +/// The feature tags the Figure menu sets. +const FIGURE_TAGS: [&str; 4] = ["tnum", "onum", "pnum", "lnum"]; +/// The values of the Figure field, in the order of the OpenType panel's Figure menu. +const FIGURE_VALUES: [&str; 5] = ["default", "tabularLining", "proportionalLining", "proportionalOldstyle", "tabularOldstyle"]; +/// The values of the Position field, in the order of the OpenType panel's Position menu. +const POSITION_VALUES: [&str; 5] = ["default", "superscript", "subscript", "numerator", "denominator"]; +/// The fields of OpenType Features. +const OT_FIELDS: &[&str] = + &["ot_figure", "ot_position", "ot_liga", "ot_calt", "ot_dlig", "ot_swsh", "ot_salt", "ot_titl", "ot_ordn", "ot_frac", "ot_sets"]; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Character Style Options").into(), @@ -55,6 +80,24 @@ pub(super) const SPEC: DialogSpec = DialogSpec { "baseline_shift", "rotation", "language", + "fill", + "fill_tint", + "stroke", + "stroke_tint", + "stroke_width", + "overprint_fill", + "overprint_stroke", + "ot_figure", + "ot_position", + "ot_liga", + "ot_calt", + "ot_dlig", + "ot_swsh", + "ot_salt", + "ot_titl", + "ot_ordn", + "ot_frac", + "ot_sets", "section", ] }, @@ -73,6 +116,7 @@ pub fn open(app: &mut VectorcraftApp, name: &str) -> Result { fields.insert("__smallCapsSize".into(), json!(doc.setup.small_caps_size)); fields.insert("__superscript".into(), json!(doc.setup.superscript)); fields.insert("__subscript".into(), json!(doc.setup.subscript)); + fields.insert("__swatches".into(), swatch_choices(doc)); fields.insert("section".into(), json!("general")); fields.insert("preview".into(), json!(true)); app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); @@ -100,6 +144,76 @@ pub(crate) fn fields_from_attrs(attrs: &Map) -> Map Value { + if paint.get("swatch").is_some_and(Value::is_string) { + json!(vectorcraft_color::tint_percent(paint.get("tint").and_then(Value::as_f64).unwrap_or(1.0) as f32)) + } else { + json!("") + } +} + +/// The swatches Character Color offers, as `[name, paint]` pairs in the Swatches panel's order, the +/// built-in Registration swatch first: a global color or a tint of one as a paint linked to it, any +/// other solid color as that color. +pub(crate) fn swatch_choices(doc: &vectorcraft_doc::Document) -> Value { + let registration = vectorcraft_color::swatch::registration(); + let builtin = (!doc.swatches_iter().any(|w| w.name == registration.name)).then_some(registration); + let choices = builtin.into_iter().chain(doc.swatches_iter()).filter_map(|w| { + let paint = match (doc.swatch_link(&w.name), &w.paint) { + (Some((base, tint)), _) => doc.tint_paint(&base, tint)?, + (None, vectorcraft_color::Paint::Solid { .. }) => w.paint.clone(), + _ => return None, + }; + Some(json!([w.name, paint])) + }); + Value::Array(choices.collect()) +} + +/// A feature tag without its `-` or `+`. +fn bare(tag: &str) -> &str { + tag.trim_start_matches(['-', '+']) +} + +/// The OpenType Features fields for a style's `features`: each control is unset unless the list +/// names one of its tags, on or off. Figure is also unset when the list turns one of its tags on +/// or off against every Figure menu entry, for example `pnum` alone. +fn opentype_fields(features: Option<&Value>) -> Map { + let tags: Vec<&str> = features.and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); + let names = |set: &[&str]| tags.iter().any(|t| set.contains(&bare(t))); + let f = vectorcraft_text::OtFeatures::from_tags(tags.iter().copied()); + let mut fields = Map::new(); + for (field, tag) in OT_SWITCHES { + let last = tags.iter().rev().find(|t| bare(t) == *tag); + fields.insert((*field).into(), last.map_or(Value::Null, |t| json!(!t.starts_with('-')))); + } + let last_on = |tag: &str| tags.iter().rev().find(|t| bare(t) == tag).map(|t| !t.starts_with('-')); + let figure = names(&FIGURE_TAGS) + .then(|| FIGURE_VALUES.get(crate::panels::opentype::figure(&f))) + .flatten() + .filter(|v| figure_tags(v).iter().all(|t| last_on(bare(t)).is_none_or(|on| on != t.starts_with('-')))); + fields.insert("ot_figure".into(), figure.map_or(Value::Null, |v| json!(v))); + let position = + names(&crate::panels::opentype::POSITION_TAGS).then(|| crate::panels::opentype::position(&f).and_then(|i| POSITION_VALUES.get(i))).flatten(); + fields.insert("ot_position".into(), position.map_or(Value::Null, |v| json!(v))); + let sets: Vec = vectorcraft_text::EXTRA_FEATURES[..20] + .iter() + .filter_map(|set| tags.iter().rev().find(|t| bare(t) == *set).map(|t| if t.starts_with('-') { format!("-{set}") } else { set.to_string() })) + .collect(); + fields.insert("ot_sets".into(), if sets.is_empty() { Value::Null } else { json!(sets) }); fields } @@ -136,6 +250,8 @@ fn optional_number(d: &Dialog, key: &str) -> Result, String> { "v_scale" => tl!("Vertical Scale"), "baseline_shift" => tl!("Baseline Shift"), "rotation" => tl!("Character Rotation"), + "fill_tint" | "stroke_tint" => tl!("Tint"), + "stroke_width" => tl!("Weight"), _ => return Err("unknown character style number field".into()), }; match d.fields.get(key) { @@ -160,6 +276,15 @@ fn optional_number(d: &Dialog, key: &str) -> Result, String> { if key == "baseline_shift" && !(min..=max).contains(&n) { return Err(format!("{label} must be a number from {min} to {max}")); } + // Weight from 0 to the document limit, a tint from 0% to 100%. + let (min, max) = match key { + "stroke_width" => (0.0, max), + "fill_tint" | "stroke_tint" => (0.0, 100.0), + _ => (min, max), + }; + if ["stroke_width", "fill_tint", "stroke_tint"].contains(&key) && !(min..=max).contains(&n) { + return Err(format!("{label} must be a number from {min} to {max}")); + } // An angle from -180 to 180 degrees, as text.setFormat stores it. let n = if key == "rotation" { (n + 180.0).rem_euclid(360.0) - 180.0 } else { n }; Ok(Some(json!(n))) @@ -249,9 +374,121 @@ pub(crate) fn edited_attrs(d: &Dialog) -> Result, String> { } } advanced_attrs(d, &original, &original_fields, &mut attrs)?; + color_attrs(d, &original, &original_fields, &mut attrs)?; + opentype_attrs(d, &original, &original_fields, &mut attrs); Ok(attrs) } +/// Write the Character Color fields of `d` into `attrs`: an unset paint, weight or checkbox +/// leaves its attribute unset, and a field still as it opened keeps the original value, a +/// gradient or pattern paint included. +fn color_attrs( + d: &Dialog, + original: &Map, + original_fields: &Map, + attrs: &mut Map, +) -> Result<(), String> { + let reset = d.bool("__resetColor"); + for key in COLOR { + attrs.remove(*key); + } + let unchanged = |key: &str| !reset && d.fields.get(key) == original_fields.get(key); + for key in ["fill", "stroke"] { + let tint_key = format!("{key}_tint"); + if unchanged(key) && unchanged(&tint_key) { + if let Some(value) = original.get(key) { + attrs.insert(key.into(), value.clone()); + } + continue; + } + let Some(mut paint) = d.fields.get(key).filter(|v| v.is_object()).cloned() else { continue }; + if paint.get("swatch").is_some_and(Value::is_string) + && let Some(Value::Number(tint)) = optional_number(d, &tint_key)? + && let Some(tint) = tint.as_f64() + { + paint["tint"] = json!(tint / 100.0); + } + attrs.insert(key.into(), paint); + } + if unchanged("stroke_width") { + if let Some(value) = original.get("stroke_width") { + attrs.insert("stroke_width".into(), value.clone()); + } + } else if let Some(v) = optional_number(d, "stroke_width")? { + attrs.insert("stroke_width".into(), v); + } + for key in ["overprint_fill", "overprint_stroke"] { + let value = if unchanged(key) { original.get(key).cloned() } else { d.fields.get(key).filter(|v| v.is_boolean()).cloned() }; + if let Some(value) = value { + attrs.insert(key.into(), value); + } + } + Ok(()) +} + +/// The tags a Figure field value sets: its figure features on and the others off. +fn figure_tags(value: &str) -> &'static [&'static str] { + match value { + "tabularLining" => &["tnum", "lnum", "-onum", "-pnum"], + "proportionalLining" => &["pnum", "lnum", "-tnum", "-onum"], + "proportionalOldstyle" => &["onum", "pnum", "-tnum", "-lnum"], + "tabularOldstyle" => &["onum", "tnum", "-pnum", "-lnum"], + "default" => &["-tnum", "-onum", "-pnum", "-lnum"], + _ => &[], + } +} + +/// Write the OpenType Features fields of `d` into `attrs`. When every field is still as it +/// opened, the original `features` list stays as it is. Otherwise each changed control replaces +/// the tags it sets in the original list, which keeps every other tag, and an unset control +/// removes them; a list left empty leaves `features` unset. +fn opentype_attrs(d: &Dialog, original: &Map, original_fields: &Map, attrs: &mut Map) { + let reset = d.bool("__resetOpenType"); + attrs.remove("features"); + let unchanged = |key: &str| !reset && d.fields.get(key) == original_fields.get(key); + if OT_FIELDS.iter().all(|key| unchanged(key)) { + if let Some(value) = original.get("features") { + attrs.insert("features".into(), value.clone()); + } + return; + } + let mut tags: Vec = if reset { + vec![] + } else { + original.get("features").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect() + }; + for (field, tag) in OT_SWITCHES { + if !unchanged(field) { + tags.retain(|t| bare(t) != *tag); + if let Some(on) = d.fields.get(*field).and_then(Value::as_bool) { + tags.push(if on { (*tag).to_string() } else { format!("-{tag}") }); + } + } + } + if !unchanged("ot_figure") { + tags.retain(|t| !FIGURE_TAGS.contains(&bare(t))); + tags.extend(figure_tags(&d.str("ot_figure")).iter().map(|t| t.to_string())); + } + if !unchanged("ot_position") { + let position_tags = crate::panels::opentype::POSITION_TAGS; + tags.retain(|t| !position_tags.contains(&bare(t))); + if let Some(i) = POSITION_VALUES.iter().position(|v| *v == d.str("ot_position")) { + for (k, tag) in position_tags.iter().enumerate() { + tags.push(if k + 1 == i { (*tag).to_string() } else { format!("-{tag}") }); + } + } + } + if !unchanged("ot_sets") { + let sets = &vectorcraft_text::EXTRA_FEATURES[..20]; + tags.retain(|t| !sets.contains(&bare(t))); + let listed = d.fields.get("ot_sets").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str); + tags.extend(listed.filter(|t| sets.contains(&bare(t))).map(str::to_string)); + } + if !tags.is_empty() { + attrs.insert("features".into(), json!(tags)); + } +} + /// Write the Advanced Character Formats fields of `d` into `attrs`: a filled field sets its /// attribute, an empty one leaves it unset, and a field still as it opened keeps the original /// value, an explicit default or a language tag not in the list included. @@ -328,9 +565,27 @@ pub(crate) fn reset_advanced(d: &mut Dialog) { d.fields.insert("language".into(), Value::Null); } -/// Whether the section `d` shows has a Reset Panel: Basic or Advanced Character Formats. +/// Reset Panel in Character Color: its paints, tints, weight and overprint checkboxes become unset. +pub(crate) fn reset_color(d: &mut Dialog) { + d.fields.insert("__resetColor".into(), json!(true)); + for key in COLOR_FIELDS { + let unset = if ["fill_tint", "stroke_tint", "stroke_width"].contains(key) { json!("") } else { Value::Null }; + d.fields.insert((*key).into(), unset); + } +} + +/// Reset Panel in OpenType Features: every control becomes unset, and the style's `features` +/// with it. +pub(crate) fn reset_opentype(d: &mut Dialog) { + d.fields.insert("__resetOpenType".into(), json!(true)); + for key in OT_FIELDS { + d.fields.insert((*key).into(), Value::Null); + } +} + +/// Whether the section `d` shows has a Reset Panel: every section but General. pub(crate) fn can_reset(d: &Dialog) -> bool { - ["basic", "advanced"].contains(&d.str("section").as_str()) + ["basic", "advanced", "color", "opentype"].contains(&d.str("section").as_str()) } /// Reset Panel: clear the settings of the section `d` shows. @@ -338,6 +593,8 @@ pub(crate) fn reset_section(d: &mut Dialog) { match d.str("section").as_str() { "basic" => reset_basic(d), "advanced" => reset_advanced(d), + "color" => reset_color(d), + "opentype" => reset_opentype(d), _ => {} } } @@ -355,7 +612,13 @@ pub fn reset_panel(app: &mut VectorcraftApp) -> Result { /// The section list of Character Style Options and New Character Style. pub(crate) fn section_list(ui: &mut egui::Ui, d: &mut Dialog) { ui.vertical(|ui| { - for (id, label) in [("general", tl!("General")), ("basic", tl!("Basic Character Formats")), ("advanced", tl!("Advanced Character Formats"))] { + for (id, label) in [ + ("general", tl!("General")), + ("basic", tl!("Basic Character Formats")), + ("advanced", tl!("Advanced Character Formats")), + ("color", tl!("Character Color")), + ("opentype", tl!("OpenType Features")), + ] { if ui.selectable_label(d.str("section") == id, label).clicked() { d.fields.insert("section".into(), json!(id)); } @@ -363,7 +626,7 @@ pub(crate) fn section_list(ui: &mut egui::Ui, d: &mut Dialog) { }); } -/// The Reset Panel button, enabled on Basic and Advanced Character Formats. +/// The Reset Panel button, enabled on every section but General. pub(crate) fn reset_button(ui: &mut egui::Ui, d: &mut Dialog) { ui.add_enabled_ui(can_reset(d), |ui| { if ui.button(tl!("Reset Panel")).clicked() { @@ -471,6 +734,151 @@ pub(crate) fn advanced_body(ui: &mut egui::Ui, d: &mut Dialog) { }); } +/// An on, off or unset checkbox in its own grid row: a click on unset turns it on, on turns it +/// off, and off makes it unset. +fn switch(ui: &mut egui::Ui, d: &mut Dialog, key: &str, caption: &str, enabled: bool) { + ui.label(""); + let value = d.fields.get(key).and_then(Value::as_bool); + if crate::widgets::check3(ui, caption, value, enabled) { + let next = match value { + None => json!(true), + Some(true) => json!(false), + Some(false) => Value::Null, + }; + d.fields.insert(key.into(), next); + } + ui.end_row(); +} + +/// The Fill or Stroke menu (`key`): unset, None, or a swatch of the document. A paint no swatch +/// gives (a gradient, a pattern, a color from a file) shows as its description and stays as it +/// is until another entry is chosen. +fn paint_choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str) { + let swatches: Vec<(String, Value)> = d + .fields + .get("__swatches") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|pair| Some((pair.get(0)?.as_str()?.to_string(), pair.get(1)?.clone()))) + .collect(); + let current = d.fields.get(key).cloned().unwrap_or(Value::Null); + let none = tl!("None"); + let shown = if current.is_null() { + String::new() + } else if current.get("type").and_then(Value::as_str) == Some("none") { + none.to_string() + } else if let Some((name, _)) = swatches.iter().find(|(_, paint)| *paint == current) { + name.clone() + } else if let Some((name, _)) = swatches.iter().find(|(_, paint)| paint.get("swatch").is_some_and(|s| Some(s) == current.get("swatch"))) { + name.clone() + } else { + serde_json::from_value::(current).map(|p| p.label()).unwrap_or_default() + }; + let options: Vec<&str> = [" ", none].into_iter().chain(swatches.iter().map(|(name, _)| name.as_str())).collect(); + if let Some(i) = crate::widgets::dropdown_names(ui, (KIND, key), &shown, &options, 190.0) { + let paint = match i { + 0 => Value::Null, + 1 => json!({"type": "none"}), + _ => swatches.get(i - 2).map_or(Value::Null, |(_, paint)| paint.clone()), + }; + d.fields.insert(format!("{key}_tint"), tint_field(&paint)); + d.fields.insert(key.into(), paint); + } +} + +/// Character Color: the Fill and Stroke paints, the Tint of a paint linked to a global swatch, +/// the stroke Weight and Overprint Fill and Overprint Stroke, each unset or set. +pub(crate) fn color_body(ui: &mut egui::Ui, d: &mut Dialog) { + egui::Grid::new("character-style-color").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { + for (key, caption) in [("fill", tl!("Fill")), ("stroke", tl!("Stroke"))] { + ui.label(caption); + paint_choice(ui, d, key); + ui.end_row(); + let tint_key = format!("{key}_tint"); + ui.label(tl!("Tint")); + if d.fields.get(&tint_key).is_none_or(Value::is_null) { + d.fields.insert(tint_key.clone(), json!("")); + } + let linked = d.fields.get(key).and_then(|p| p.get("swatch")).is_some_and(Value::is_string); + ui.add_enabled_ui(linked, |ui| { + ui.horizontal(|ui| { + form::text(ui, d, &tint_key, 160.0); + ui.label("%"); + }); + }); + ui.end_row(); + } + ui.label(tl!("Weight")); + if d.fields.get("stroke_width").is_none_or(Value::is_null) { + d.fields.insert("stroke_width".into(), json!("")); + } + let stroked = d.fields.get("stroke").and_then(|p| p.get("type")).and_then(Value::as_str) != Some("none"); + ui.add_enabled_ui(stroked, |ui| { + ui.horizontal(|ui| { + form::text(ui, d, "stroke_width", 160.0); + ui.label("pt"); + }); + }); + ui.end_row(); + switch(ui, d, "overprint_fill", tl!("Overprint Fill"), true); + switch(ui, d, "overprint_stroke", tl!("Overprint Stroke"), true); + }); +} + +/// OpenType Features: the Figure and Position menus, the feature checkboxes and the stylistic +/// sets, each unset or set. +pub(crate) fn opentype_body(ui: &mut egui::Ui, d: &mut Dialog) { + let figures: Vec<(&str, &str)> = FIGURE_VALUES.into_iter().zip(crate::panels::opentype::FIGURES).collect(); + let positions: Vec<(&str, &str)> = POSITION_VALUES.into_iter().zip(crate::panels::opentype::POSITIONS).collect(); + egui::Grid::new("character-style-opentype").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { + ui.label(tl!("Figure:")); + choice(ui, d, "ot_figure", &figures); + ui.end_row(); + ui.label(tl!("Position:")); + choice(ui, d, "ot_position", &positions); + ui.end_row(); + for (key, caption) in [ + ("ot_liga", tl!("Standard Ligatures")), + ("ot_calt", tl!("Contextual Alternates")), + ("ot_dlig", tl!("Discretionary Ligatures")), + ("ot_swsh", tl!("Swash")), + ("ot_salt", tl!("Stylistic Alternates")), + ("ot_titl", tl!("Titling Alternates")), + ("ot_ordn", tl!("Ordinals")), + ("ot_frac", tl!("Fractions")), + ] { + switch(ui, d, key, caption, true); + } + }); + ui.add_space(6.0); + ui.label(tl!("Stylistic Sets")); + // Each set is on (`ssNN`), off (`-ssNN`) or unset (not listed), as the other checkboxes are. + let mut listed: Vec = + d.fields.get("ot_sets").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(); + let mut clicked = None; + egui::Grid::new("character-style-sets").num_columns(5).spacing([12.0, 4.0]).show(ui, |ui| { + for (i, set) in vectorcraft_text::EXTRA_FEATURES[..20].iter().enumerate() { + let value = listed.iter().find(|t| bare(t) == *set).map(|t| !t.starts_with('-')); + if crate::widgets::check3(ui, set, value, true) { + clicked = Some((*set, value)); + } + if i % 5 == 4 { + ui.end_row(); + } + } + }); + if let Some((set, value)) = clicked { + listed.retain(|t| bare(t) != set); + match value { + None => listed.push(set.to_string()), + Some(true) => listed.push(format!("-{set}")), + Some(false) => {} + } + d.fields.insert("ot_sets".into(), if listed.is_empty() { Value::Null } else { json!(listed) }); + } +} + fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.horizontal(|ui| { section_list(ui, d); @@ -480,6 +888,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { basic_body(ui, d); } else if d.str("section") == "advanced" { advanced_body(ui, d); + } else if d.str("section") == "color" { + color_body(ui, d); + } else if d.str("section") == "opentype" { + opentype_body(ui, d); } else { ui.horizontal(|ui| { ui.label(tl!("Style Name:")); @@ -841,6 +1253,236 @@ mod tests { assert!(!def.attrs.contains_key("v_scale")); } + /// The negated tags of the twenty stylistic sets: an explicit empty Stylistic Sets choice. + fn no_sets() -> Vec { + vectorcraft_text::EXTRA_FEATURES[..20].iter().map(|s| format!("-{s}")).collect() + } + + #[test] + fn color_and_opentype_fields_keep_unset_explicit_and_untouched_values() { + let d = dialog_for(json!({})); + for key in ["fill", "stroke", "overprint_fill", "overprint_stroke", "ot_figure", "ot_position", "ot_liga", "ot_frac", "ot_sets"] { + assert!(d.fields[key].is_null(), "{key}"); + } + assert_eq!((d.str("stroke_width"), d.str("fill_tint")), (String::new(), String::new())); + assert_eq!(edited_attrs(&d).unwrap(), Map::new()); + + let mut explicit = + vec!["-tnum", "-onum", "-pnum", "-lnum", "-sups", "-subs", "-numr", "-dnom", "-liga"].into_iter().map(String::from).collect::>(); + explicit.extend(no_sets()); + for original in [ + json!({"fill": {"type": "none"}, "stroke_width": 0.0, "overprint_fill": false, "features": explicit}), + json!({"stroke": {"type": "pattern", "pattern": "Dots"}, "fill": {"type": "solid", "color": {"model": "gray", "k": 0.5}}}), + json!({"features": ["zzzz", "dlig", "ss03"], "size": 9.0}), + ] { + let d = dialog_for(original.clone()); + assert_eq!(edited_attrs(&d).unwrap(), attrs(original.clone()), "{original}"); + } + let d = dialog_for(json!({"fill": {"type": "none"}, "overprint_fill": false, "features": explicit})); + assert_eq!(d.fields["fill"], json!({"type": "none"})); + assert_eq!(d.fields["overprint_fill"], json!(false)); + assert_eq!((d.str("ot_figure"), d.str("ot_position")), ("default".to_string(), "default".to_string())); + assert_eq!( + (d.fields["ot_liga"].clone(), d.fields["ot_dlig"].clone(), d.fields["ot_sets"].clone()), + (json!(false), Value::Null, json!(no_sets())) + ); + + // One changed control keeps every other tag, unknown ones included. + let mut d = dialog_for(json!({"features": ["zzzz", "dlig", "ss03"], "stroke": {"type": "pattern", "pattern": "Dots"}})); + assert_eq!((d.fields["ot_dlig"].clone(), d.fields["ot_sets"].clone()), (json!(true), json!(["ss03"]))); + d.fields.insert("ot_liga".into(), json!(false)); + d.fields.insert("overprint_stroke".into(), json!(true)); + assert_eq!( + edited_attrs(&d).unwrap(), + attrs(json!({"features": ["zzzz", "dlig", "ss03", "-liga"], "stroke": {"type": "pattern", "pattern": "Dots"}, "overprint_stroke": true})) + ); + d.fields.insert("ot_sets".into(), json!(["ss05", "ss03"])); + d.fields.insert("ot_figure".into(), json!("proportionalOldstyle")); + d.fields.insert("ot_position".into(), json!("numerator")); + d.fields.insert("ot_dlig".into(), Value::Null); + let features = edited_attrs(&d).unwrap()["features"].clone(); + // Sets the list leaves out stay unset, so text that uses the style keeps its own. + assert_eq!(features, json!(["zzzz", "-liga", "onum", "pnum", "-tnum", "-lnum", "-sups", "-subs", "numr", "-dnom", "ss05", "ss03"])); + let reopened = dialog_for(json!({"features": features})); + assert_eq!( + ["ot_figure", "ot_position", "ot_liga", "ot_dlig"].map(|k| reopened.fields[k].clone()), + [json!("proportionalOldstyle"), json!("numerator"), json!(false), Value::Null] + ); + assert_eq!(reopened.fields["ot_sets"], json!(["ss03", "ss05"])); + // Every control unset leaves the attribute unset. + let mut d = dialog_for(json!({"features": ["dlig"]})); + d.fields.insert("ot_dlig".into(), Value::Null); + assert_eq!(edited_attrs(&d).unwrap(), Map::new()); + } + + #[test] + fn figure_tags_no_menu_entry_matches_leave_the_figure_unset() { + for features in [json!(["pnum"]), json!(["lnum"]), json!(["onum", "lnum"]), json!(["tnum", "pnum"])] { + let mut d = dialog_for(json!({ "features": features })); + assert!(d.fields["ot_figure"].is_null(), "{features}"); + assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({ "features": features })), "{features}"); + d.fields.insert("ot_figure".into(), json!("default")); + assert_eq!(edited_attrs(&d).unwrap()["features"], json!(["-tnum", "-onum", "-pnum", "-lnum"]), "{features}"); + } + for (features, shown) in [(json!(["tnum"]), "tabularLining"), (json!(["-pnum"]), "default"), (json!(["pnum", "lnum"]), "proportionalLining")] + { + assert_eq!(dialog_for(json!({ "features": features })).str("ot_figure"), shown, "{features}"); + } + } + + #[test] + fn color_tint_and_weight_outside_their_limits_are_errors() { + let linked = json!({"type": "solid", "color": {"model": "gray", "k": 0.5}, "swatch": "Ink"}); + for (key, value, message) in [ + ("fill_tint", "150", "Tint must be a number from 0 to 100"), + ("stroke_tint", "-1", "Tint must be a number from 0 to 100"), + ("stroke_width", "-1", "Weight must be a number from 0 to 4000000"), + ("stroke_width", "thick", "Weight must be a number"), + ] { + let mut d = dialog_for(json!({"fill": linked, "stroke": linked})); + d.fields.insert(key.into(), json!(value)); + assert_eq!(edited_attrs(&d).unwrap_err(), message, "{key} {value}"); + } + let mut d = dialog_for(json!({"fill": linked})); + assert_eq!(d.fields["fill_tint"], json!(100.0)); + d.fields.insert("fill_tint".into(), json!("40")); + d.fields.insert("stroke_width".into(), json!("1.5")); + assert_eq!( + edited_attrs(&d).unwrap(), + attrs(json!({"fill": {"type": "solid", "color": {"model": "gray", "k": 0.5}, "swatch": "Ink", "tint": 0.4}, "stroke_width": 1.5})) + ); + } + + #[test] + fn reset_panel_in_color_and_opentype_clears_only_that_section() { + let original = json!({"size": 12.0, "h_scale": 90.0, "fill": {"type": "none"}, "stroke_width": 2.0, "overprint_stroke": true, "features": ["dlig", "zzzz"]}); + let mut d = dialog_for(original.clone()); + d.fields.insert("section".into(), json!("color")); + assert!(can_reset(&d)); + reset_section(&mut d); + assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"size": 12.0, "h_scale": 90.0, "features": ["dlig", "zzzz"]}))); + let mut d = dialog_for(original); + d.fields.insert("section".into(), json!("opentype")); + reset_section(&mut d); + assert!(d.fields["ot_dlig"].is_null()); + assert_eq!( + edited_attrs(&d).unwrap(), + attrs(json!({"size": 12.0, "h_scale": 90.0, "fill": {"type": "none"}, "stroke_width": 2.0, "overprint_stroke": true})) + ); + d.fields.insert("ot_frac".into(), json!(true)); + assert_eq!(edited_attrs(&d).unwrap()["features"], json!(["frac"])); + } + + #[test] + fn color_and_opentype_sections_show_their_controls() { + let mut d = dialog_for(json!({})); + let mut app = app(); + let shown = crate::tests_labels::painted_text(&mut app, |_, ui| section_list(ui, &mut d)); + for label in ["Character Color", "OpenType Features"] { + assert!(shown.contains(label), "{label}: {shown}"); + } + let shown = crate::tests_labels::painted_text(&mut app, |_, ui| color_body(ui, &mut d)); + for label in ["Fill", "Stroke", "Tint", "Weight", "Overprint Fill", "Overprint Stroke"] { + assert!(shown.contains(label), "{label}: {shown}"); + } + let shown = crate::tests_labels::painted_text(&mut app, |_, ui| opentype_body(ui, &mut d)); + for label in [ + "Figure:", + "Position:", + "Standard Ligatures", + "Contextual Alternates", + "Discretionary Ligatures", + "Swash", + "Stylistic Alternates", + "Titling Alternates", + "Ordinals", + "Fractions", + "Stylistic Sets", + "ss01", + "ss20", + ] { + assert!(shown.contains(label), "{label}: {shown}"); + } + assert!(!shown.contains("Small Caps"), "{shown}"); + } + + #[test] + fn color_and_features_preview_cancel_commit_and_new_style() { + let mut app = app(); + app.run("swatch.new", json!({"name": "Brand", "color": "#2050a0", "global": true})).unwrap(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "Text"})).unwrap()["id"].as_u64().unwrap(); + app.run("charStyle.apply", json!({"name": "Body", "id": id})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + let brand = json!(before.tint_paint("Brand", 1.0).unwrap()); + open(&mut app, "Body").unwrap(); + let choices = app.ui.dialog.as_ref().unwrap().fields["__swatches"].as_array().unwrap().clone(); + assert!(choices.contains(&json!(["Brand", brand]))); + let registration = vectorcraft_color::swatch::REGISTRATION; + assert_eq!(choices.first(), Some(&json!([registration, before.tint_paint(registration, 1.0).unwrap()]))); + let set = |app: &mut VectorcraftApp| { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("section".into(), json!("color")); + d.fields.insert("fill".into(), brand.clone()); + d.fields.insert("stroke".into(), brand.clone()); + d.fields.insert("stroke_tint".into(), json!("40")); + d.fields.insert("stroke_width".into(), json!("2")); + d.fields.insert("overprint_fill".into(), json!(true)); + d.fields.insert("ot_dlig".into(), json!(true)); + d.fields.insert("ot_figure".into(), json!("tabularLining")); + }; + set(&mut app); + assert!(crate::menus::enabled(&app, "ui.charStyleOptions.resetPanel")); + frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc.char_styles[0].attrs["fill"], brand); + super::super::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + + open(&mut app, "Body").unwrap(); + set(&mut app); + super::super::confirm(&mut app).unwrap(); + let state = app.session.doc().unwrap(); + assert_eq!(state.history.undo.len(), undo + 1); + let tint40 = state.doc.tint_paint("Brand", 0.4).unwrap(); + let def = state.doc.char_styles[0].attrs.clone(); + assert_eq!(def["stroke"], json!(tint40)); + assert_eq!(def["features"], json!(["dlig", "tnum", "lnum", "-onum", "-pnum"])); + let vectorcraft_doc::NodeKind::Text(t) = &state.doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { panic!("text") }; + for run in &t.runs { + assert_eq!( + (run.style.fill.clone(), run.style.stroke.clone(), run.style.stroke_width), + (state.doc.tint_paint("Brand", 1.0).unwrap(), tint40.clone(), 2.0) + ); + assert_eq!(run.style.features, ["dlig", "tnum", "lnum", "-onum", "-pnum"]); + } + open(&mut app, "Body").unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["stroke_tint"].clone(), d.str("ot_figure")), (json!(40.0), "tabularLining".to_string())); + super::super::cancel(&mut app); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); + + app.run("select.set", json!({"ids": []})).unwrap(); + app.run("ui.newCharStyle", json!({})).unwrap(); + { + let d = app.ui.dialog.as_mut().unwrap(); + assert!(d.fields["fill"].is_null() && d.fields["ot_sets"].is_null()); + d.fields.insert("name".into(), json!("Ink")); + d.fields.insert("section".into(), json!("opentype")); + d.fields.insert("ot_sets".into(), json!(["-ss02", "ss04"])); + d.fields.insert("ot_frac".into(), json!(false)); + } + assert!(crate::menus::enabled(&app, "ui.charStyleOptions.resetPanel")); + super::super::confirm(&mut app).unwrap(); + let doc = &app.session.doc().unwrap().doc; + let def = doc.char_styles.iter().find(|def| def.name == "Ink").unwrap(); + assert_eq!(def.attrs["features"], json!(["-frac", "-ss02", "ss04"])); + let vectorcraft_doc::NodeKind::Text(t) = &doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { panic!("text") }; + assert!(t.runs.iter().all(|r| r.style.style_name.as_deref() == Some("Body"))); + } + #[test] fn invalid_numbers_name_the_visible_field() { let mut d = Dialog::new(KIND, json!({})); diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 089ba61ea0..2dc8efd064 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -59,11 +59,16 @@ pub(super) const SPEC: DialogSpec = DialogSpec { ..DialogSpec::FORM }; -/// Does this dialog show a Preview checkbox? Only Grid Repeat Options does: the public page for -/// the grid options lists one, and the radial and mirror pages do not. (Cancel rolls a preview -/// back whichever dialog started it.) +/// Does this dialog show a Preview checkbox? Grid Repeat Options does: the public page for the +/// grid options lists one, and the radial and mirror pages do not. Type on a Path Options does +/// too (#5360), as public tutorials of the dialog show. (Cancel rolls a preview back whichever +/// dialog started it.) fn previews(d: &Dialog) -> bool { - d.str("__command") == "object.repeat.options" && d.fields.contains_key("gridType") + match d.str("__command").as_str() { + "object.repeat.options" => d.fields.contains_key("gridType"), + "type.pathOptions" => true, + _ => false, + } } /// The command the dialog runs and its parameters: the fields shown and the fixed ones. diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 1e1ad72fcf..85282add14 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -106,10 +106,10 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(Value::Null) } -/// The effects of the first selected object that `item` (an index or null) addresses. +/// The function reads effects at `item` (an index or null) from the targeted node or first selected object. fn target_effects(app: &VectorcraftApp, item: &Value) -> Vec { let Some(st) = app.session.active() else { return vec![] }; - let node = st.selection.objects.first().and_then(|id| st.doc.node(*id)); + let node = st.selection.subjects().first().and_then(|id| st.doc.node(*id)); node.and_then(|n| n.appearance.effects_at(item.as_u64().map(|i| i as usize))).cloned().unwrap_or_default() } @@ -550,7 +550,7 @@ fn scribble_fields(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc::Uni /// last previewed. fn transform_fields(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc::Unit) -> bool { ui.horizontal_top(|ui| { - ui.vertical(|ui| transform_each::sections(ui, d, unit)); + ui.vertical(|ui| transform_each::sections(ui, d, unit, true)); ui.add_space(16.0); ui.vertical(|ui| { widgets::subheader(ui, tl!("Options")); @@ -560,7 +560,7 @@ fn transform_fields(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc::Un form::check(ui, d, "strokes", tl!("Scale Strokes & Effects")); ui.horizontal(|ui| { widgets::dim_label(ui, tl!("Copies:")); - if let Some(n) = widgets::range_field(ui, "fx-copies", d.f64("copies", 0.0), 0.0..=1000.0, "", 0, 50.0) { + if let Some(n) = widgets::range_field_live(ui, "fx-copies", d.f64("copies", 0.0), 0.0..=1000.0, "", 0, 50.0) { d.fields.insert("copies".into(), json!(n)); } }); diff --git a/crates/ui-egui/src/dialogs/find_links/tests.rs b/crates/ui-egui/src/dialogs/find_links/tests.rs index 0c7f5d2e8c..36659c53be 100644 --- a/crates/ui-egui/src/dialogs/find_links/tests.rs +++ b/crates/ui-egui/src/dialogs/find_links/tests.rs @@ -63,6 +63,8 @@ fn opened_without(app: &mut VectorcraftApp, root: &Path, names: &[&str]) -> Vec< std::fs::create_dir_all(doc.parent().unwrap()).unwrap(); app.run("document.save", json!({"path": doc})).unwrap(); std::fs::remove_dir_all(root.join("orig")).unwrap(); + // Reopened: an open file would only come to the front (#3455). + app.run("file.close", json!({})).unwrap(); crate::io::open_path(app, &doc.to_string_lossy()).unwrap(); files } @@ -271,6 +273,7 @@ fn copy_leaves_placed_documents_where_they_are() { std::fs::create_dir_all(doc.parent().unwrap()).unwrap(); app.run("document.save", json!({"path": doc})).unwrap(); std::fs::remove_dir_all(root.join("orig")).unwrap(); + app.run("file.close", json!({})).unwrap(); crate::io::open_path(&mut app, &doc.to_string_lossy()).unwrap(); super::super::cancel(&mut app); app.run("ui.findLinksInFolder", json!({"folder": root.join("found")})).unwrap(); diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index ed6be47e86..47567e51e7 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -468,7 +468,10 @@ fn typed_number(x: f64) -> Value { /// the rows then scroll ([`super::modal::scrolled_rows`]). pub(super) fn schema_fields(app: &mut crate::VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, m: &Manifest) -> bool { let (changed, help) = schema_rows(ui, d, m); - if let Some(url) = help { + // The browser is another app: a click automation sent opens nothing. + if let Some(url) = help + && app.refuse_automation("the plug-in help button").is_ok() + { app.open_url(&url); } changed diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index c5b7d7e58a..16d22d4430 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -106,8 +106,11 @@ pub(crate) fn grid_from_data(v: &Value) -> Grid { /// columns past the data. pub(crate) fn data_from_grid(grid: &Grid) -> Value { let filled = |s: &String| !s.trim().is_empty(); - let rows = grid.iter().rposition(|r| r.iter().any(filled)).map_or(1, |i| i + 1).max(1); - let cols = grid.iter().take(rows).filter_map(|r| r.iter().rposition(filled)).max().map_or(1, |i| i + 1).max(1); + // At most a graph's rows and columns, as a file gives (`grid_from_text`): a grid sent by + // automation is any size, and the values are their product. + let grid = &grid[..grid.len().min(MAX_ROWS)]; + let rows = grid.iter().rposition(|r| r.iter().take(MAX_COLS).any(filled)).map_or(1, |i| i + 1).max(1); + let cols = grid.iter().take(rows).filter_map(|r| r.iter().take(MAX_COLS).rposition(filled)).max().map_or(1, |i| i + 1).max(1); let label = |s: &str| { let s = s.trim(); // A label typed in straight quotes (as the CSV form takes a number as a label) is the text inside. @@ -163,7 +166,7 @@ fn clean(s: &str) -> String { s.chars().map(|c| if matches!(c, '\t' | '\r' | '\n') { ' ' } else { c }).take(MAX_CELL).collect() } -fn cell(grid: &Grid, r: usize, c: usize) -> String { +fn cell(grid: &[Vec], r: usize, c: usize) -> String { grid.get(r).and_then(|row| row.get(c)).cloned().unwrap_or_default() } @@ -514,6 +517,16 @@ mod tests { assert_eq!(grid_from_text(&wide)[0].len(), MAX_COLS); } + #[test] + fn a_sheet_sent_wider_and_taller_than_a_graph_is_cut_to_one() { + // One long row and one long column: their product would be ten billion cells. + let mut grid: Grid = vec![vec!["1".to_string(); 100_000]]; + grid.extend((0..100_000).map(|_| vec!["2".to_string()])); + let p = data_from_grid(&grid); + assert_eq!(p["rows"].as_array().unwrap().len(), MAX_ROWS - 1); + assert_eq!(p["series"].as_array().unwrap().len(), MAX_COLS - 1); + } + #[test] fn transpose_switch_and_moves() { assert_eq!(transpose(&g(&[&["", "a", "b"], &["Q1", "1", "2"]])), g(&[&["", "Q1"], &["a", "1"], &["b", "2"]])); diff --git a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs index 19d5a13599..0f57b99f46 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs @@ -49,6 +49,8 @@ fn save_doc(app: &mut VectorcraftApp, path: &Path, font: &str, link: bool) { if link { std::fs::remove_file(&pic).unwrap(); } + // Opened afresh by `open`: an open file would only come to the front (#3455). + app.run("file.close", json!({})).unwrap(); } fn open(app: &mut VectorcraftApp, path: &Path) { @@ -135,6 +137,8 @@ fn find_fonts_opens_find_font_on_the_missing_font() { app.run("text.create", json!({"x": 10, "y": 80, "text": "Gone", "font": "Zz Missing Family"})).unwrap(); let doc = root.join("doc.vectorcraft"); app.run("document.save", json!({"path": doc.to_string_lossy()})).unwrap(); + // Opened afresh: an open file would only come to the front (#5369). + app.run("file.close", json!({})).unwrap(); open(&mut app, &doc); assert_eq!(kind(&app), Some(KIND)); app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); @@ -223,6 +227,7 @@ fn one_dialog_at_a_time_document_by_document() { super::super::cancel(&mut app); assert!(app.ui.dialog.is_none()); // A document closed before its turn is passed over. + app.run("file.closeAll", json!({})).unwrap(); open(&mut app, &a); open(&mut app, &b); let index = app.session.documents().iter().rposition(|d| d.path.as_deref() == Some(&*a.to_string_lossy())).unwrap(); @@ -295,6 +300,24 @@ fn a_search_folder_that_fails_is_not_tried_again() { assert_eq!(super::super::confirm(&mut app).err().as_deref(), Some("choose the font files to add")); } +/// Opening a file that is already open only brings its tab to the front: Missing Fonts, closed +/// once, is not asked again (#5369). +#[test] +fn reopening_an_open_document_does_not_ask_about_its_fonts_again() { + let root = folder("reopen"); + let mut app = app_for(&root); + let doc = root.join("doc.vectorcraft"); + save_doc(&mut app, &doc, "No Such Font Family", false); + open(&mut app, &doc); + assert_eq!(kind(&app), Some(KIND)); + super::super::cancel(&mut app); + app.run("file.new", json!({})).unwrap(); + open(&mut app, &doc); + frame(&mut app); + assert_eq!((app.session.documents().len(), app.session.active_index()), (2, Some(0))); + assert_eq!(kind(&app), None); +} + /// A placed document that Links › Edit Original opens asks about its fonts, as File › Open does. #[test] fn edit_original_asks_about_the_placed_documents_fonts() { @@ -302,7 +325,6 @@ fn edit_original_asks_about_the_placed_documents_fonts() { let mut app = app_for(&root); let badge = root.join("badge.vectorcraft"); save_doc(&mut app, &badge, "Badge Missing Family", false); - app.session.execute("file.close", &json!({})).unwrap(); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); app.run("file.place", json!({"path": badge.to_string_lossy(), "link": true})).unwrap(); let tabs = app.session.documents().len(); diff --git a/crates/ui-egui/src/dialogs/missing_links.rs b/crates/ui-egui/src/dialogs/missing_links.rs index 78affd3c24..81a19912a5 100644 --- a/crates/ui-egui/src/dialogs/missing_links.rs +++ b/crates/ui-egui/src/dialogs/missing_links.rs @@ -249,6 +249,8 @@ mod tests { for n in ["a.png", "b.png"] { std::fs::remove_file(dir.join(n)).unwrap(); } + // Reopened: an open file would only come to the front (#3455). + app.run("file.close", json!({})).unwrap(); crate::io::open_path(&mut app, &doc).unwrap(); (app, dir, doc) } @@ -344,6 +346,8 @@ mod tests { }; std::fs::write(&pic, png([0, 0, 200])).unwrap(); mark_modified(2); + // Reopened: an open file would only come to the front (#3455). + app.run("file.close", json!({})).unwrap(); crate::io::open_path(&mut app, &doc).unwrap(); let d = app.ui.dialog.as_ref().expect("asks"); assert_eq!((d.kind.as_str(), d.str("__command")), (super::super::confirm::KIND, "links.update".to_string())); @@ -353,6 +357,7 @@ mod tests { app.run("prefs.set", json!({"key": "updateLinks", "value": "manually"})).unwrap(); std::fs::write(&pic, png([0, 200, 0])).unwrap(); mark_modified(4); + app.session.execute("file.close", &json!({})).unwrap(); crate::io::open_path(&mut app, &doc).unwrap(); assert!(app.ui.dialog.is_none()); assert_eq!(app.run("links.check", json!({})).unwrap()["modified"], 1); diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs index ad839f345d..3a769670f5 100644 --- a/crates/ui-egui/src/dialogs/new_text_style.rs +++ b/crates/ui-egui/src/dialogs/new_text_style.rs @@ -42,6 +42,7 @@ pub fn open(app: &mut VectorcraftApp, para: bool, target: Value) -> Result bool { super::char_style_options::basic_body(ui, d); } else if d.str("section") == "advanced" { super::char_style_options::advanced_body(ui, d); + } else if d.str("section") == "color" { + super::char_style_options::color_body(ui, d); + } else if d.str("section") == "opentype" { + super::char_style_options::opentype_body(ui, d); } else { ui.vertical(|ui| { grid(ui, |ui| { diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 70e69a78c5..5efa3ef6e3 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -15,7 +15,11 @@ //! saturation wheel with a marker per new colour (drag one; with linked handles they all turn and //! scale together), a brightness slider, the harmony rules, and the color sliders with their mode //! menu, whose Global Adjust shows Saturation, Brightness, Temperature and Luminosity (-100% to -//! 100%, 0% changes nothing), which change every new color at once. The preset menu sets up a 1, 2 or 3 +//! 100%, 0% changes nothing), which change every new color at once. The buttons beside the wheel +//! show the new colors on the smooth wheel, on a segmented wheel (solid patches of 24 hues by 5 +//! saturations; its markers move as freely) or as color bars (one per new color, in row order: click +//! one to select it for the sliders, drag one to move its row, which changes no color); the dialog +//! opens on the smooth wheel. The preset menu sets up a 1, 2 or 3 //! colour job or a library. Opened on a colour group (Edit or Apply Color Group), OK also rewrites //! the group with the new colours (renamed by `groupName`); without art only the group changes. //! Opened on colours alone (the Color Guide's Edit or Apply Colors without art), OK saves the new @@ -28,8 +32,8 @@ //! `sliderMode` (`hsb`, `rgb`, `cmyk`, `lab` or `tint`; unset: the row color's own model, HSB for //! a gray and Tint for a spot color; `global`: Global Adjust, on the Edit tab), `globalAdjust` //! (`{saturation, brightness, temperature, luminosity}` in percent, sent as `recolor.apply`'s -//! `globalAdjust` in every slider mode). Changing `colors`, a preserve flag or `limitTo` reduces -//! the rows again. +//! `globalAdjust` in every slider mode), `display` (the Edit tab's `smooth`, `segmented` or `bars`; +//! unset: `smooth`). Changing `colors`, a preserve flag or `limitTo` reduces the rows again. use egui::{Rect, Sense, Ui, pos2, vec2}; use serde_json::{Value, json}; @@ -65,6 +69,9 @@ const CMD: &str = "recolor.apply"; const CURRENT_W: f32 = 250.0; /// Diameter of the Edit tab's colour wheel. const WHEEL: f32 = 220.0; +/// Height of the Edit tab's color bars area (the wheel with its Brightness slider), and of a bar. +const BARS_H: f32 = WHEEL + 31.0; +const BAR_H: f32 = 22.0; /// Height of the rows table, and of either tab (so switching tabs doesn't resize the dialog). const TABLE_H: f32 = 182.0; const TAB_H: f32 = 400.0; @@ -971,7 +978,29 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value }); ui.add_space(8.0); let colors: Vec = active.iter().filter_map(|&i| to_color(&rows[i])).collect(); - let w = widgets::harmony_wheel(ui, "recolor-wheel", WHEEL, &colors, base.and_then(|b| active.iter().position(|&i| i == b))); + let marked = base.and_then(|b| active.iter().position(|&i| i == b)); + let display = d.str("display"); + let mut w = widgets::WheelResponse::default(); + ui.horizontal(|ui| { + // The display buttons, beside the wheel so the tab keeps its height. + ui.vertical(|ui| { + for (id, icon, tip) in [ + ("smooth", "circle", tl!("Show smooth color wheel")), + ("segmented", "dc-polar-grid", tl!("Show segmented color wheel")), + ("bars", "dc-list-view", tl!("Show color bars")), + ] { + let on = display == id || (id == "smooth" && !matches!(display.as_str(), "segmented" | "bars")); + if widgets::icon_button(ui, icon, tip, on, 24.0).clicked() { + d.fields.insert("display".into(), json!(id)); + } + } + }); + ui.vertical(|ui| match display.as_str() { + "segmented" => w = widgets::segmented_wheel(ui, "recolor-wheel", WHEEL, &colors, marked), + "bars" => changed |= color_bars(ui, d, rows, &active, base), + _ => w = widgets::harmony_wheel(ui, "recolor-wheel", WHEEL, &colors, marked), + }); + }); if let Some(k) = w.pressed { d.fields.insert("__sel".into(), json!([active[k]])); } @@ -1023,6 +1052,85 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value changed } +/// The Edit tab's color bars: a solid bar per row of `active` with its new color, in row order, the +/// base row's framed, scrolling past the wheel's height. A click on a bar selects its row (the +/// sliders under it edit that row's new color); a drag moves the bar's row to where the line under +/// the pointer shows, keeping every new color. Returns true when the rows moved. +fn color_bars(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value], active: &[usize], base: Option) -> bool { + let t = Tokens::get(ui.ctx()); + let mut rects: Vec = Vec::with_capacity(active.len()); + let (mut dragging, mut released, mut dropped) = (None, None, None); + // The area is given its full height first: in the row beside the display buttons a scroll area + // alone is only as tall as the room the row has. + let area = vec2(ui.available_width(), BARS_H); + ui.allocate_ui_with_layout(area, egui::Layout::top_down(egui::Align::Min), |ui| { + ui.set_min_size(area); + egui::ScrollArea::vertical().id_salt("recolor-bars").max_height(BARS_H).show(ui, |ui| { + ui.set_min_height(BARS_H); + ui.set_width(ui.available_width()); + if active.is_empty() { + ui.add_space(8.0); + widgets::dim_label(ui, tl!("No colors to recolor (preserved colors are left out).")); + } + for (n, &i) in active.iter().enumerate() { + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width() - 4.0, BAR_H), Sense::click_and_drag()); + chip(ui, r, to_color(&rows[i]).unwrap_or_default(), false); + if Some(i) == base { + ui.painter().rect_stroke(r, 2.0, egui::Stroke::new(2.0, t.accent), egui::StrokeKind::Inside); + } + let name = format!("{} {}", tl!("Color"), i + 1); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), &name)); + if resp.clicked() || resp.drag_started() { + d.fields.insert("__sel".into(), json!([i])); + } + if resp.dragged() { + dragging = Some(n); + } + if resp.drag_stopped() { + released = Some(n); + } + rects.push(r); + resp.on_hover_text(rows[i]["to"].as_str().unwrap_or_default()); + } + // The place a dragged bar goes: before the first bar whose middle is below the pointer. + let at = ui.input(|i| i.pointer.latest_pos()).map(|p| rects.iter().filter(|r| r.center().y < p.y).count()); + if let (Some(n), Some(to)) = (dragging, at) + && to != n + && to != n + 1 + { + let y = rects.get(to).map_or_else(|| rects.last().map_or(0.0, |r| r.bottom() + 1.5), |r| r.top() - 1.5); + let x = rects.first().map_or(ui.max_rect().x_range(), |r| r.x_range()); + ui.painter().hline(x, y, egui::Stroke::new(2.0, t.accent)); + } + dropped = released.zip(at); + }); + }); + let Some(moved) = dropped.and_then(|(n, to)| move_bar(rows, active, n, to)) else { return false }; + d.fields.insert("__sel".into(), json!([moved])); + // The slider values held are those of a row index that may now hold another row. + d.fields.remove(COMPS); + true +} + +/// Move the row of the `from`th active row (of `active`, ascending row indexes) to before the +/// `to`th, or after the last for `active.len()`; the rows between shift by one. Returns the row's +/// new index, or `None` when it stays where it is. +fn move_bar(rows: &mut [Value], active: &[usize], from: usize, to: usize) -> Option { + let &src = active.get(from)?; + if to == from || to == from + 1 || to > active.len() { + return None; + } + if to > from { + let dst = active[to - 1]; + rows[src..=dst].rotate_left(1); + Some(dst) + } else { + let dst = active[to]; + rows[dst..=src].rotate_right(1); + Some(dst) + } +} + /// Give the rows `active` the colours of `rule` from the base colour `b` of row `base` (the base row /// first, then the others in order, the rule's colours repeating), each in its row's model. A row /// whose new color changes loses its tint. diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 26c01f052d..924f8c4078 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -175,6 +175,13 @@ fn has_warnings(r: &Value) -> bool { r["warnings"].as_array().is_some_and(|w| !w.is_empty()) } +/// The preview page's name from the document's title `stem`: one file name in the preview folder. +/// `file_stem` gives back a title it can't take a stem of ("../.."), so one with a separator or of +/// dots only is "Untitled". +pub(super) fn preview_name(stem: &str) -> &str { + if stem.trim().is_empty() || stem.contains(['/', '\\']) || stem.chars().all(|c| c == '.') { "Untitled" } else { stem } +} + /// `file.saveForWeb.browser`: the HTML page and its images in a new temporary folder, opened in the /// default browser (desktop). When the export has warnings, the status bar shows the first in /// place of "Opened …". @@ -182,9 +189,10 @@ pub(crate) fn browser_preview(app: &mut VectorcraftApp, p: &Value) -> Result bool { f.options.iter().any(|o| o.name == "separateArtboards") } -/// The options the dialog shows: arrays and objects are for agents, and a page range replaces the -/// single artboard choice; none for a format with its own dialog. A `.ait` template has no -/// Version: Save as Template writes it PDF-compatible only. +/// The options the dialog shows: arrays and objects are for agents, as is a native file's +/// `precision`, and a page range replaces the single artboard choice; none for a format with its +/// own dialog. A `.ait` template has no Version: Save as Template writes it PDF-compatible only. fn shown(f: &Format) -> impl Iterator { let range = f.options.iter().any(|o| o.name == "range"); let separate = separates(f); let options = if own_dialog(f) { &[][..] } else { f.options }; options.iter().filter(move |o| { !(matches!(o.ty, "array" | "object") + || o.name == "precision" || (range && o.name == "artboard") || (separate && o.name == "range") || (matches!(f.id, "ai" | "ait") && o.name == "useArtboards") diff --git a/crates/ui-egui/src/dialogs/save_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index e5483a935f..1f33575e70 100644 --- a/crates/ui-egui/src/dialogs/save_options/tests.rs +++ b/crates/ui-egui/src/dialogs/save_options/tests.rs @@ -268,6 +268,18 @@ fn the_ait_template_options_have_no_version_row() { assert!(!names("ait").contains(&"aiVersion"), "{:?}", names("ait")); } +/// The native options dialog has no row for `precision`, which agents give with the save +/// command; the rows it has stay. +#[test] +fn the_native_options_have_no_precision_row() { + for id in ["vectorcraft", "template"] { + let f = fileio::format(id).unwrap(); + assert!(f.options.iter().any(|o| o.name == "precision"), "{id}"); + let names: Vec<&str> = shown(f).map(|o| o.name).collect(); + assert!(!names.contains(&"precision") && names.contains(&"version") && names.contains(&"compress"), "{id}: {names:?}"); + } +} + /// A name typed in the Save as Template panel with a Save As format's extension has it /// replaced with the template's, as Save As replaces the extension of a format it doesn't write. #[test] diff --git a/crates/ui-egui/src/dialogs/tests_save_for_web.rs b/crates/ui-egui/src/dialogs/tests_save_for_web.rs index 8b4d4e05e9..c76ed412fa 100644 --- a/crates/ui-egui/src/dialogs/tests_save_for_web.rs +++ b/crates/ui-egui/src/dialogs/tests_save_for_web.rs @@ -317,6 +317,21 @@ fn the_web_downloads_and_has_no_browser_preview() { assert!(app.run("file.saveForWeb.browser", json!({})).is_err()); } +#[test] +fn preview_in_browser_stays_in_its_folder_and_is_the_persons_to_open() { + for (title, name) in + [("Poster", "Poster"), ("../..", "Untitled"), ("..", "Untitled"), ("a/..", "Untitled"), ("..\\x", "Untitled"), (" ", "Untitled")] + { + assert_eq!(save_for_web::preview_name(title), name, "{title}"); + } + let dir = vectorcraft_testkit::temp_dir("sfw-browser-automation"); + let (mut app, log) = app(&dir, false); + app.ui.answering_control = true; + assert!(app.run("file.saveForWeb.browser", json!({"format": "jpg"})).unwrap_err().contains("opens another app")); + app.ui.answering_control = false; + assert!(!log.borrow().iter().any(|l| l.starts_with("open ")), "{:?}", log.borrow()); +} + #[test] fn preview_in_browser_opens_the_page() { let dir = vectorcraft_testkit::temp_dir("sfw-browser"); diff --git a/crates/ui-egui/src/dialogs/transform_each.rs b/crates/ui-egui/src/dialogs/transform_each.rs index f18cd7ece8..71f5145a22 100644 --- a/crates/ui-egui/src/dialogs/transform_each.rs +++ b/crates/ui-egui/src/dialogs/transform_each.rs @@ -78,7 +78,7 @@ const MAX_SCALE: f64 = 100_000.0; /// `scaleH` and `scaleV` (rails 0–200 %) and for `moveH` and `moveV` (rails ±1000 pt, fields in /// `units`), and an angle dial for `rotate` (counter-clockwise). The fields take values past the /// rails. -pub(super) fn sections(ui: &mut egui::Ui, d: &mut Dialog, units: vectorcraft_doc::Unit) { +pub(super) fn sections(ui: &mut egui::Ui, d: &mut Dialog, units: vectorcraft_doc::Unit, live: bool) { let rail = Tokens::get(ui.ctx()).input_border; let track = move |_| rail; let axes = |h, v| [(h, tl!("Horizontal:")), (v, tl!("Vertical:"))]; @@ -87,7 +87,12 @@ pub(super) fn sections(ui: &mut egui::Ui, d: &mut Dialog, units: vectorcraft_doc widgets::label_row(ui, label, LABEL_W, |ui| { let shown = widgets::SliderValue::field(d.f64(key, 100.0).clamp(-MAX_SCALE, MAX_SCALE), 0.0..=200.0, "%", 2); form::slider_rail_valued(ui, d, key, label, 0.0..=200.0, Some(shown), &track); - if let Some(n) = widgets::range_field(ui, ("te", key), d.f64(key, 100.0), -MAX_SCALE..=MAX_SCALE, "%", 2, FIELD_W) { + let value = if live { + widgets::range_field_live(ui, ("te", key), d.f64(key, 100.0), -MAX_SCALE..=MAX_SCALE, "%", 2, FIELD_W) + } else { + widgets::range_field(ui, ("te", key), d.f64(key, 100.0), -MAX_SCALE..=MAX_SCALE, "%", 2, FIELD_W) + }; + if let Some(n) = value { d.fields.insert(key.into(), json!(n)); } }); @@ -97,14 +102,25 @@ pub(super) fn sections(ui: &mut egui::Ui, d: &mut Dialog, units: vectorcraft_doc widgets::label_row(ui, label, LABEL_W, |ui| { let shown = form::length_value(d, key, units, -1000.0..=1000.0); form::slider_rail_valued(ui, d, key, label, -1000.0..=1000.0, shown, &track); - form::length(ui, d, key, units, FIELD_W); + if live { + if let Some(n) = widgets::num_field_live(ui, ("dlg-len", key), Some(d.f64(key, 0.0)), units, FIELD_W) { + d.fields.insert(key.into(), json!(n)); + } + } else { + form::length(ui, d, key, units, FIELD_W); + } }); } widgets::subheader(ui, tl!("Rotate")); widgets::label_row(ui, tl!("Angle:"), LABEL_W, |ui| { let angle = d.f64("rotate", 0.0); let dialed = widgets::angle_dial(ui, "te-dial", angle, 28.0); - if let Some(a) = widgets::plain_field(ui, ("te", "rotate"), angle, "°", 2, FIELD_W).or(dialed) { + let typed = if live { + widgets::plain_field_live(ui, ("te", "rotate"), angle, "°", 2, FIELD_W) + } else { + widgets::plain_field(ui, ("te", "rotate"), angle, "°", 2, FIELD_W) + }; + if let Some(a) = typed.or(dialed) { d.fields.insert("rotate".into(), json!(a)); } }); @@ -128,7 +144,7 @@ pub(super) fn reflect_options(ui: &mut egui::Ui, d: &mut Dialog) { fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let units = app.session.general_unit(); ui.horizontal_top(|ui| { - ui.vertical(|ui| sections(ui, d, units)); + ui.vertical(|ui| sections(ui, d, units, false)); ui.add_space(16.0); ui.vertical(|ui| { widgets::subheader(ui, tl!("Options")); diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs new file mode 100644 index 0000000000..6c70eb4491 --- /dev/null +++ b/crates/ui-egui/src/doc_windows.rs @@ -0,0 +1,679 @@ +//! Window › Arrange › Float in Window, Float All in Windows and Cascade: documents in floating +//! windows of their own, out of the tab strip, until Consolidate All Windows. On the desktop each +//! window is an OS window; on the web, on Wayland and wherever egui draws every viewport inside +//! the main window, it is a window inside the app's window, as floating panels are +//! ([`crate::panel_docking`]). The current document's window holds the canvas +//! ([`crate::canvas::show`]); each other window draws its document as a Tile pane does +//! ([`crate::canvas::pane`]), and a press in it makes its document the current one. +//! +//! A document tab dragged off the tab strip floats its document in a window under the pointer, +//! and a document window dragged onto the tab strip by its title bar (an OS window by the tab at +//! its top) goes back under the tabs. +//! +//! With Preferences › User Interface › Open Documents As Tabs cleared, each document opened or +//! created afterwards opens in a floating window ([`opened`]). + +use serde_json::{Value, json}; + +use crate::VectorcraftApp; + +/// How far above or below the tab strip, in points, a dragged document tab must be released to +/// float its document. +pub(crate) const TEAR_OFF: f32 = 24.0; +/// Where a torn-off document's window opens: this far up and left of the pointer, so the pointer +/// is over its title bar. +pub(crate) const GRAB: egui::Vec2 = egui::vec2(40.0, 12.0); +/// How far apart Cascade sets the windows, down and to the right, in points. +pub(crate) const CASCADE_STEP: f32 = 30.0; +/// How far the first cascaded window is from the document area's top-left corner, in points. +const CASCADE_MARGIN: f32 = 24.0; +/// The smallest size of a document window, in points. +const MIN_SIZE: egui::Vec2 = egui::vec2(240.0, 180.0); + +/// A document in a floating window. +#[derive(Clone, Debug)] +pub struct DocWindow { + /// The document ([`vectorcraft_engine::DocState::uid`]). + pub uid: u64, + /// Where the window goes, in the main window's points. + pub place: egui::Rect, + /// The window's own number ([`Windows::opened`]): a document floated again gets a new window, + /// which opens where it is asked to, not where its last window was. + number: u32, + /// Counts the moves Cascade gives the window after it opened. + generation: u32, + /// The OS window's position on the screen when it opened or last moved, and the generation of + /// that move. Repeated each frame, so egui sees an unchanged window. + screen: Option<(egui::Pos2, u32)>, + /// Its OS window had the keyboard focus in the last frame. + focused: bool, + /// Where the last frame drew its document, in its window's coordinates. + pub(crate) body: Option, + /// The size of the body its document was last fitted to, and the zoom and center that fit + /// gave: a window resized while its view is still there fits its document again. + fit: Option, + /// While its OS window's tab is dragged: where the pointer is from the window's top-left + /// corner, on the screen. + grab: Option, +} + +/// [`DocWindow::fit`]: a body size, and a view's zoom and center. +type Fit = (egui::Vec2, f64, vectorcraft_geom::Point); + +impl DocWindow { + fn new(uid: u64, place: egui::Rect) -> Self { + Self { uid, place, number: 0, generation: 0, screen: None, focused: false, body: None, fit: None, grab: None } + } +} + +/// What the document windows keep between frames. +#[derive(Default)] +pub struct Windows { + /// The document area of the main window (the tabs and the canvas) in its last frame. + pub(crate) area: Option, + /// The current document (its uid) when the windows were last drawn: a floating document that + /// becomes the current one comes to the front. + current: Option, + /// While Presentation Mode is on: the floating documents (their uids) it has shown. + presented: Option>, + /// The main window's tab strip in its last frame, while it was drawn. + pub(crate) strip: Option, + /// Counts the windows opened ([`DocWindow::number`]). + opened: u32, + /// The open documents (their uids) when [`opened`] last ran, or when the app started. + known: Vec, +} + +impl Windows { + /// No windows yet, with `known` (uids) the documents open when the app starts: they keep their + /// tabs, whatever Open Documents As Tabs says. + pub(crate) fn new(known: Vec) -> Self { + Self { known, ..Default::default() } + } +} + +/// Whether a document tab dragged from `strip` to `p` has left it far enough to float. +pub(crate) fn torn_off(strip: egui::Rect, p: egui::Pos2) -> bool { + p.y > strip.bottom() + TEAR_OFF || p.y < strip.top() - TEAR_OFF +} + +/// Whether document `i` is in a floating window. +pub(crate) fn is_floating(app: &VectorcraftApp, i: usize) -> bool { + app.session.documents().get(i).is_some_and(|d| app.ui.floating.iter().any(|w| w.uid == d.uid)) +} + +/// The documents under the tab strip, by index, in tab order. +pub(crate) fn docked(app: &VectorcraftApp) -> Vec { + (0..app.session.documents().len()).filter(|i| !is_floating(app, *i)).collect() +} + +/// The document the tab strip shows: the current one when it is under the tabs, else the tabbed +/// document that was current last, else the first tabbed one. +pub(crate) fn tab_document(app: &VectorcraftApp) -> Option { + let docked = docked(app); + let active = app.session.active_index(); + if let Some(a) = active.filter(|a| docked.contains(a)) { + return Some(a); + } + let last = app.ui.tab_document.and_then(|uid| app.session.documents().iter().position(|d| d.uid == uid)); + last.filter(|i| docked.contains(i)).or(docked.first().copied()) +} + +/// Whether the current document is in a floating window, outside the Home screen and Presentation +/// Mode: the main window's canvas then draws the tab strip's document as a pane. +pub(crate) fn current_floats(app: &VectorcraftApp) -> bool { + app.session.active_index().is_some_and(|i| is_floating(app, i)) && !crate::menus::home_showing(app) && !presenting(app) +} + +/// Whether Presentation Mode is on: the main window shows the current document, and the floating +/// windows are hidden until it ends. +fn presenting(app: &VectorcraftApp) -> bool { + app.ui.screen_mode >= 3 +} + +/// The places Cascade gives `n` windows in `area`: each the same size, the first near the area's +/// top-left corner and each next one [`CASCADE_STEP`] further down and to the right, starting +/// again at the corner when the next one would leave the area. Every place lies inside `area`. +pub(crate) fn cascade_places(area: egui::Rect, n: usize) -> Vec { + let size = (area.size() * 0.6).max(MIN_SIZE).min(area.size()); + let room = (area.size() - size).min_elem().max(0.0); + let steps = if room > CASCADE_MARGIN { ((room - CASCADE_MARGIN) / CASCADE_STEP).floor() as usize + 1 } else { 1 }; + (0..n) + .map(|k| { + let offset = (CASCADE_MARGIN + (k % steps) as f32 * CASCADE_STEP).min(room); + egui::Rect::from_min_size(area.min + egui::vec2(offset, offset), size) + }) + .collect() +} + +/// The document area windows open in: the main window's last one, else a 1200 × 800 area. +fn area(app: &VectorcraftApp) -> egui::Rect { + app.canvas.windows.area.filter(|r| r.is_positive()).unwrap_or(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))) +} + +/// Float documents `docs` (indices), each at the next cascade place after the windows already +/// open. Each fits its window. +fn float(app: &mut VectorcraftApp, docs: &[usize]) { + app.sync_views(); + place(app, docs); +} + +/// The documents opened or created since the last call: each one opened while Preferences › User +/// Interface › Open Documents As Tabs was cleared ([`vectorcraft_engine::DocState::opened_as_tab`]) +/// opens in a floating window of its own, at the next cascade place. Documents already open stay +/// where they are. Called by [`VectorcraftApp::sync_views`]. +pub(crate) fn opened(app: &mut VectorcraftApp) { + let docs = app.session.documents(); + let known = &app.canvas.windows.known; + if known.len() == docs.len() && known.iter().zip(docs).all(|(u, d)| *u == d.uid) { + return; + } + let new: Vec = docs.iter().enumerate().filter(|(_, d)| !d.opened_as_tab && !known.contains(&d.uid)).map(|(i, _)| i).collect(); + app.canvas.windows.known = docs.iter().map(|d| d.uid).collect(); + if !new.is_empty() { + place(app, &new); + } +} + +/// [`float`] for documents whose views exist. +fn place(app: &mut VectorcraftApp, docs: &[usize]) { + let first = app.ui.floating.len(); + let places = cascade_places(area(app), first + docs.len()); + for (k, i) in docs.iter().enumerate() { + let Some(uid) = app.session.documents().get(*i).map(|d| d.uid) else { continue }; + if app.ui.floating.iter().any(|w| w.uid == uid) { + continue; + } + let place = places.get(first + k).copied().unwrap_or(egui::Rect::from_min_size(egui::Pos2::ZERO, MIN_SIZE)); + app.canvas.windows.opened = app.canvas.windows.opened.wrapping_add(1); + let mut w = DocWindow::new(uid, place); + w.number = app.canvas.windows.opened; + app.ui.floating.push(w); + if let Some(v) = app.views.get_mut(*i) { + v.fitted = false; + } + } + if !docs.is_empty() { + app.ui.home = None; + } +} + +/// The floating documents' indices, in the order their windows opened. +fn floating_indices(app: &VectorcraftApp) -> Vec { + app.ui.floating.iter().filter_map(|w| app.session.documents().iter().position(|d| d.uid == w.uid)).collect() +} + +/// The open document `p`'s `index` names: `Ok(None)` without one. +fn document_param(app: &VectorcraftApp, p: &Value) -> Result, String> { + match p.get("index") { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_u64() + .and_then(|i| usize::try_from(i).ok()) + .filter(|i| *i < app.session.documents().len()) + .map(Some) + .ok_or_else(|| "no such document".to_string()), + } +} + +/// `window.arrange.floatInWindow`: the current document, or document `index`, leaves the tab strip +/// for a floating window of its own, with its top-left corner at `at` (`[x, y]` in the main +/// window's points) when given, else at the next cascade place. A document already floating stays +/// where it is. Document `index` becomes the current one. Returns `{floating}`. +pub(crate) fn float_in_window(app: &mut VectorcraftApp, p: &Value) -> Result { + let index = document_param(app, p)?; + let at = p + .get("at") + .and_then(Value::as_array) + .and_then(|a| Some(egui::pos2(a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32))) + .filter(|at| at.is_finite()); + if let Some(i) = index.or(app.session.active_index()).filter(|i| !is_floating(app, *i)) { + float(app, &[i]); + if let (Some(at), Some(w)) = (at, app.ui.floating.last_mut()) { + w.place = egui::Rect::from_min_size(at, w.place.size()); + } + } + if let Some(i) = index { + crate::chrome::show_document(app, i); + } + Ok(json!({ "floating": floating_indices(app) })) +} + +/// `window.arrange.consolidateAllWindows` with an `index`: document `index`, floating or not, +/// goes back under its tab, fitted there, and becomes the current one; the other windows and Tile +/// stay as they are. Returns `{tiled, floating}`. +pub(crate) fn dock(app: &mut VectorcraftApp, p: &Value) -> Result { + let Some(i) = document_param(app, p)? else { + return Err("no such document".into()); + }; + if is_floating(app, i) { + let uid = app.session.documents().get(i).map(|d| d.uid); + app.ui.floating.retain(|w| Some(w.uid) != uid); + if let Some(v) = app.views.get_mut(i) { + v.fitted = false; + } + } + crate::chrome::show_document(app, i); + Ok(json!({ "tiled": app.ui.tiled, "floating": floating_indices(app) })) +} + +/// `window.arrange.floatAllInWindows`: every document under the tab strip goes to a floating window +/// of its own. Returns `{floating}`. +pub(crate) fn float_all(app: &mut VectorcraftApp) -> Result { + let docked = docked(app); + float(app, &docked); + Ok(json!({ "floating": floating_indices(app) })) +} + +/// `window.arrange.cascade`: every document in a floating window, the windows stacked from the +/// document area's upper left to its lower right in tab order, each fitted to its window, the +/// current document's in front. Returns `{floating}`. +pub(crate) fn cascade(app: &mut VectorcraftApp) -> Result { + app.ui.tiled = false; + let docked = docked(app); + float(app, &docked); + let order: Vec = app.session.documents().iter().map(|d| d.uid).collect(); + app.ui.floating.sort_by_key(|w| order.iter().position(|u| *u == w.uid)); + let places = cascade_places(area(app), app.ui.floating.len()); + for (w, place) in app.ui.floating.iter_mut().zip(places) { + w.place = place; + w.generation += 1; + } + for v in &mut app.views { + v.fitted = false; + } + // The current document's window comes to the front. + app.canvas.windows.current = None; + Ok(json!({ "floating": floating_indices(app) })) +} + +/// Every floating document back under the tab strip ([`crate::canvas::consolidate`], Tile), each +/// fitted to where it shows. +pub(crate) fn dock_all(app: &mut VectorcraftApp) { + let floating = floating_indices(app); + for i in floating { + if let Some(v) = app.views.get_mut(i) { + v.fitted = false; + } + } + app.ui.floating.clear(); +} + +/// Whether the floating windows are OS windows: egui runs viewports of their own, the session is +/// not Wayland, where the main window cannot learn where its other windows are (craft-ui's docking +/// floats panels by the same rule), and no control channel is attached. With a control channel the +/// windows stay inside the main window, where `ui.click`, `ui.drag` and `ui.screenshot` reach them +/// and `canvasRect` is in the main window's coordinates. +fn native(app: &VectorcraftApp, ctx: &egui::Context) -> bool { + if ctx.embed_viewports() || app.control_rx.is_some() { + return false; + } + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + { + let set = |name: &str| std::env::var_os(name).is_some_and(|v| !v.is_empty()); + if set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET") { + // Under XWayland the main window reports where it is. + return ctx.input_for(egui::ViewportId::ROOT, |i| i.viewport().outer_rect.is_some()); + } + } + true +} + +/// The OS window of document window `uid`. +fn viewport_id(uid: u64) -> egui::ViewportId { + egui::ViewportId::from_hash_of(("vectorcraft-document-window", uid)) +} + +/// The id of document window `w` inside the main window: a new one for each window and each +/// Cascade move, so egui opens it at its new place and size. +fn window_id(w: &DocWindow) -> egui::Id { + egui::Id::unique(("vectorcraft-document-window", w.uid, w.number, w.generation)) +} + +/// What happened in a document window this frame. +#[derive(Default)] +struct Shown { + /// Its close button was pressed. + close: bool, + /// Its document asks to become the current one. + activate: bool, + /// It is being dragged over the main window's tab strip. + over_strip: bool, + /// It was dropped on the main window's tab strip: its document goes back under the tabs. + dock: bool, + /// Its OS window has the keyboard focus. + focused: bool, + /// Where it drew its document. + body: Option, + /// [`DocWindow::fit`] after this frame. + fit: Option, +} + +/// Draw the floating document windows, after the main window's canvas. Call once per frame from +/// the main window. +pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { + let live: Vec = app.session.documents().iter().map(|d| d.uid).collect(); + app.ui.floating.retain(|w| live.contains(&w.uid)); + let current = app.session.active().map(|d| d.uid); + if let Some(uid) = current.filter(|u| !app.ui.floating.iter().any(|w| w.uid == *u)) { + app.ui.tab_document = Some(uid); + } + // Presentation Mode fits each floating document it shows to the main window: back in their + // floating windows, those documents fit their windows again. + let presenting = presenting(app); + if presenting { + let shown = app.canvas.windows.presented.get_or_insert_default(); + if let Some(uid) = current.filter(|u| app.ui.floating.iter().any(|w| w.uid == *u) && !shown.contains(u)) { + shown.push(uid); + if let Some(v) = app.session.active_index().and_then(|i| app.views.get_mut(i)) { + v.fitted = false; + ctx.request_repaint(); + } + } + } else if let Some(shown) = app.canvas.windows.presented.take() { + for (d, v) in app.session.documents().iter().zip(app.views.iter_mut()) { + if shown.contains(&d.uid) { + v.fitted = false; + } + } + } + // While Presentation Mode hides the windows, `current` keeps the document whose window was in + // front, so a document made current meanwhile comes to the front when it ends. + if presenting { + return; + } + if app.ui.floating.is_empty() { + app.canvas.windows.current = current; + return; + } + let raise = current.filter(|u| app.canvas.windows.current != Some(*u)); + let native = native(app, ctx); + // Windows inside the main window that come back (after Presentation Mode) all go to the front + // in their old order, so the raise waits for the next frame. + let returning = !native + && app.ui.floating.iter().any(|w| { + let layer = egui::LayerId::new(egui::Order::Middle, window_id(w)); + ctx.memory(|m| m.area_rect(layer.id).is_some() && !m.areas().visible_last_frame(&layer)) + }); + if raise.is_some() && returning { + ctx.request_repaint(); + } else { + app.canvas.windows.current = current; + } + #[cfg(not(target_arch = "wasm32"))] + if native { + input::register(ctx, app.services.native_input_hook.clone(), app.ui.floating.iter().map(|w| viewport_id(w.uid)).collect()); + } + // While a dialog or other modal is open the windows take no input, as the main window behind + // it takes none: each draws its document as a pane, the current one included. + let blocked = crate::panel_docking::modal_open(app, ctx); + let mut close = None; + let mut activate = None; + let mut dock = None; + let mut over_strip = false; + for w in app.ui.floating.clone() { + let Some(i) = app.session.documents().iter().position(|d| d.uid == w.uid) else { continue }; + let shown = if native { + os_window(app, ctx, &w, (i, blocked), raise == Some(w.uid)) + } else { + app_window(app, ctx, &w, (i, blocked), raise == Some(w.uid)) + }; + if blocked { + continue; + } + if let Some(win) = app.ui.floating.iter_mut().find(|x| x.uid == w.uid) { + // The OS window took the keyboard: its document becomes the current one. + if shown.focused && !win.focused && app.session.active_index() != Some(i) { + activate = Some(i); + } + win.focused = shown.focused; + win.body = shown.body; + win.fit = shown.fit; + } + over_strip |= shown.over_strip; + if shown.close { + close = Some(i); + } else if shown.dock { + dock = Some(i); + } else if shown.activate && app.session.active_index() != Some(i) { + activate = Some(i); + } + } + // The tab strip a dragged window would go back under shows where it lands. + if let Some(strip) = app.canvas.windows.strip.filter(|_| over_strip) { + let t = crate::theme::Tokens::get(ctx); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("vectorcraft-document-dock"))); + painter.rect_filled(strip, 0.0, t.accent.gamma_multiply(0.12)); + painter.rect_stroke(strip, 0.0, egui::Stroke::new(2.0, t.accent), egui::StrokeKind::Inside); + } + if let Some(i) = close { + // The save prompt opens in the main window. + if let Err(e) = crate::unsaved::close(app, i) { + app.status(e); + } + if native && app.ui.dialog.is_some() { + ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Focus); + } + } else if let Some(i) = dock { + if let Err(e) = app.run("window.arrange.consolidateAllWindows", json!({ "index": i })) { + app.status(e); + } + if native { + ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Focus); + } + } else if let Some(i) = activate { + crate::chrome::show_document(app, i); + app.canvas.windows.current = app.session.active().map(|d| d.uid); + } +} + +/// Document `i`'s window body in `ui`: the canvas for the current document, else (and while +/// `blocked` by a modal) a pane. The document fits the body again when the body changed size since +/// `fit` and its view has not moved. → whether a press in the pane asks for its document to become +/// the current one, the body's rect and the fit after this frame. +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, (i, blocked): (usize, bool), fit: Option) -> (bool, egui::Rect, Option) { + let t = crate::theme::Tokens::get(ui.ctx()); + let rect = ui.available_rect_before_wrap(); + ui.painter().rect_filled(rect, 0.0, t.pasteboard); + if let (Some(v), Some((size, zoom, center))) = (app.views.get_mut(i), fit) + && size != rect.size() + && zoom == v.zoom + && center == v.center + { + v.fitted = false; + } + let was_fitted = app.views.get(i).is_some_and(|v| v.fitted); + let pressed = if !blocked && app.session.active_index() == Some(i) && !crate::menus::home_showing(app) { + crate::canvas::show(app, ui); + false + } else { + crate::canvas::pane(app, ui, i, rect) + }; + ui.advance_cursor_after_rect(rect); + let fit = match app.views.get(i) { + Some(v) if v.fitted && !was_fitted => Some((rect.size(), v.zoom, v.center)), + _ => fit, + }; + (pressed, rect, fit) +} + +/// Document `i`'s window `w` as an OS window of its own, `blocked` by a modal or not; `raise` +/// brings it to the front. The document's tab is at the top of the window, above its body. +fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, blocked): (usize, bool), raise: bool) -> Shown { + let vid = viewport_id(w.uid); + let origin = ctx.input(|inp| inp.viewport().inner_rect.map(|r| r.min)).filter(|p| p.is_finite()).unwrap_or(egui::Pos2::ZERO); + let screen = match w.screen { + Some((pos, generation)) if generation == w.generation => pos, + moved => { + let pos = origin + w.place.min.to_vec2(); + if moved.is_some() { + ctx.send_viewport_cmd_to(vid, egui::ViewportCommand::OuterPosition(pos)); + ctx.send_viewport_cmd_to(vid, egui::ViewportCommand::InnerSize(w.place.size())); + } + if let Some(win) = app.ui.floating.iter_mut().find(|x| x.uid == w.uid) { + win.screen = Some((pos, w.generation)); + } + pos + } + }; + if raise { + ctx.send_viewport_cmd_to(vid, egui::ViewportCommand::Focus); + } + let title = crate::chrome::document_window_title(app, i).unwrap_or_default(); + let builder = + egui::ViewportBuilder::default().with_title(title).with_position(screen).with_inner_size(w.place.size()).with_min_inner_size(MIN_SIZE); + let mut forwarded = (Vec::new(), None); + // The main window's tab strip on the screen. + let strip = app.canvas.windows.strip.map(|s| s.translate(origin.to_vec2())); + let shown = ctx.show_viewport_immediate(vid, builder, |ui, _| { + let (close, focused) = ui.input(|inp| (inp.viewport().close_requested(), inp.viewport().focused == Some(true))); + if close { + // The OS window stays until its document closes, which stops drawing it: a save prompt + // or a modal can keep the document open. + ui.ctx().send_viewport_cmd(egui::ViewportCommand::CancelClose); + } + let tab = crate::chrome::window_tab(app, ui, i); + let (over_strip, dock) = if blocked { (false, false) } else { drag_tab(app, ui, (w.uid, origin), &tab, strip) }; + let (pressed, rect, fit) = body(app, ui, (i, blocked), w.fit); + let activate = pressed || (!blocked && (tab.clicked() || tab.drag_started())); + // Keys the window's widgets left over run the main window's shortcuts and tool keys, as a + // floating panel's do. + if !blocked && !ui.memory(|m| m.focused().is_some()) { + forwarded = ui.input(|inp| { + let events: Vec = inp + .events + .iter() + .filter(|e| { + matches!(e, egui::Event::Key { .. } | egui::Event::Text(_) | egui::Event::Copy | egui::Event::Cut | egui::Event::Paste(_)) + }) + .cloned() + .collect(); + (events, Some(inp.modifiers)) + }); + } + Shown { close, activate, over_strip, dock, focused, body: Some(rect), fit } + }); + if !forwarded.0.is_empty() { + crate::panel_docking::forward_keys(app, ctx, forwarded.0, forwarded.1); + } + shown +} + +/// A drag of document window `uid`'s OS window by the `tab` at its top: the window follows the +/// pointer, and its document goes back under the tabs when the tab is released over the main +/// window's tab `strip` (on the screen). `origin` is the main window's top-left corner on the +/// screen. → whether the pointer is over the strip, and whether the tab was released there. +fn drag_tab( + app: &mut VectorcraftApp, + ui: &egui::Ui, + (uid, origin): (u64, egui::Pos2), + tab: &egui::Response, + strip: Option, +) -> (bool, bool) { + let Some(win) = app.ui.floating.iter_mut().find(|x| x.uid == uid) else { + return (false, false); + }; + if !tab.dragged() && !tab.drag_stopped() { + win.grab = None; + return (false, false); + } + let (inner, outer, pointer) = ui.input(|inp| (inp.viewport().inner_rect, inp.viewport().outer_rect, inp.pointer.latest_pos())); + let (Some(inner), Some(outer), Some(pointer)) = (inner, outer, pointer) else { + return (false, false); + }; + let at = inner.min + pointer.to_vec2(); + // The pointer stays where it pressed the tab, relative to the window. + let pressed = ui.input(|inp| inp.pointer.press_origin()).map_or(at, |p| inner.min + p.to_vec2()); + let grab = *win.grab.get_or_insert(pressed - outer.min); + let over = strip.is_some_and(|s| s.contains(at)); + if tab.drag_stopped() { + win.grab = None; + return (over, over); + } + let pos = at - grab; + if pos != outer.min { + win.screen = Some((pos, win.generation)); + win.place = egui::Rect::from_min_size(pos - origin.to_vec2(), win.place.size()); + } + (over, false) +} + +/// Document `i`'s window `w` as a window inside the main window, `blocked` by a modal or not; +/// `raise` brings it to the front. +fn app_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, blocked): (usize, bool), raise: bool) -> Shown { + let id = window_id(w); + if raise { + ctx.move_to_top(egui::LayerId::new(egui::Order::Middle, id)); + } + let title = crate::chrome::document_window_title(app, i).unwrap_or_default(); + let mut open = true; + let (mut activate, mut rect, mut fit) = (false, None, w.fit); + let frame = egui::Frame::window(&ctx.global_style()).inner_margin(0.0); + let shown = egui::Window::new(title) + .id(id) + .default_rect(w.place) + .min_size(MIN_SIZE) + .collapsible(false) + .resizable(true) + .constrain_to(ctx.content_rect()) + .frame(frame) + .open(&mut open) + .show(ctx, |ui| { + let (pressed, r, f) = body(app, ui, (i, blocked), fit); + (activate, rect, fit) = (pressed, Some(r), f); + }); + // A press on its title bar or edges, which brings the window to the front, also makes its + // document the current one. + activate |= shown.as_ref().is_some_and(|s| s.response.contains_pointer()) && ctx.input(|inp| inp.pointer.any_pressed()); + // Moved by its title bar onto the main window's tab strip, it goes back under the tabs. + // egui moves a window by the drag of its title bar's own widget, or, where it moves windows by + // a drag anywhere (after touch input), by the drag of the window itself. + let mover = ctx.read_response(id.with("__title_click")).or_else(|| shown.as_ref().map(|s| s.response.clone())); + let moved = mover.map_or((false, false), |r| (r.dragged(), r.drag_stopped())); + let pointer = ctx.input(|inp| inp.pointer.latest_pos()); + let over_strip = !blocked && (moved.0 || moved.1) && app.canvas.windows.strip.zip(pointer).is_some_and(|(strip, p)| strip.contains(p)); + Shown { close: !open, activate, over_strip, dock: over_strip && moved.1, focused: false, body: rect, fit } +} + +/// The host's rewrites of raw input ([`crate::services::Services::native_input_hook`]) for the +/// document windows' OS windows: eframe runs the host's hook for the main window only. +#[cfg(not(target_arch = "wasm32"))] +mod input { + use std::collections::HashSet; + + use crate::services::NativeInputHook; + + /// Runs the hook on the input of the document windows' OS windows. + #[derive(Default)] + struct DocumentWindowInput { + hook: Option, + windows: HashSet, + } + + impl egui::Plugin for DocumentWindowInput { + fn debug_name(&self) -> &'static str { + "vectorcraft document windows input" + } + + fn input_hook(&mut self, _: &egui::Context, input: &mut egui::RawInput) { + if let Some(hook) = self.hook.as_ref().filter(|_| self.windows.contains(&input.viewport_id)) { + hook(input); + } + } + } + + /// Run `hook` on the input of `windows` from their next frame on. + pub(super) fn register(ctx: &egui::Context, hook: Option, windows: HashSet) { + if hook.is_none() && ctx.with_plugin(|_: &mut DocumentWindowInput| ()).is_none() { + return; + } + ctx.add_plugin(DocumentWindowInput::default()); + ctx.with_plugin(|p: &mut DocumentWindowInput| { + p.hook = hook; + p.windows = windows; + }); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs new file mode 100644 index 0000000000..f32e0b2ab6 --- /dev/null +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -0,0 +1,727 @@ +use egui::{Pos2, Shape, pos2, vec2}; +use vectorcraft_engine::Session; + +use super::*; +use crate::menus::enabled; + +/// An app with `n` new 400 × 300 pt documents, the last one current. +fn app_with(n: usize) -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for _ in 0..n { + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + } + app +} + +/// One headless frame of the canvas panel's body (the tabs and the canvas or panes) on a +/// 1200 × 800 window, then the floating document windows, which egui draws inside the window → +/// the shapes it drew, `Shape::Vec`s flattened. +fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { + fn flat(s: Shape, out: &mut Vec) { + match s { + Shape::Vec(v) => v.into_iter().for_each(|s| flat(s, out)), + s => out.push(s), + } + } + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))), + max_texture_side: Some(8192), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| { + app.canvas_area(ui); + show(app, ui.ctx()); + }); + out.textures_delta.clear(); + let mut shapes = vec![]; + out.shapes.into_iter().for_each(|c| flat(c.shape, &mut shapes)); + shapes +} + +fn button(pos: Pos2, pressed: bool) -> egui::Event { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } +} + +/// A press and release at `pos`, then a frame to settle. +fn click(app: &mut VectorcraftApp, ctx: &egui::Context, pos: Pos2) { + frame(app, ctx, vec![egui::Event::PointerMoved(pos), button(pos, true)]); + frame(app, ctx, vec![button(pos, false)]); + frame(app, ctx, vec![]); +} + +/// Where the last frame drew document `i`'s window body. +fn body_of(app: &VectorcraftApp, i: usize) -> egui::Rect { + let uid = app.session.documents()[i].uid; + app.ui.floating.iter().find(|w| w.uid == uid).and_then(|w| w.body).unwrap() +} + +/// The whole of document `i`'s window inside the main window, title bar included. +fn window_of(app: &VectorcraftApp, ctx: &egui::Context, i: usize) -> egui::Rect { + let uid = app.session.documents()[i].uid; + let w = app.ui.floating.iter().find(|w| w.uid == uid).unwrap(); + ctx.memory(|m| m.area_rect(window_id(w))).unwrap() +} + +/// A drag with the primary button from `from` to `to`, then a frame to settle. +fn drag(app: &mut VectorcraftApp, ctx: &egui::Context, from: Pos2, to: Pos2) { + frame(app, ctx, vec![egui::Event::PointerMoved(from)]); + frame(app, ctx, vec![button(from, true)]); + for k in 1..=4 { + frame(app, ctx, vec![egui::Event::PointerMoved(from + (to - from) * (k as f32 / 4.0))]); + } + frame(app, ctx, vec![button(to, false)]); + frame(app, ctx, vec![]); +} + +/// Whether the last frame drew text holding `title` in the tab strip (the top 35 points). +fn tab_drawn(shapes: &[Shape], title: &str) -> bool { + shapes.iter().any(|s| matches!(s, Shape::Text(t) if t.pos.y < 35.0 && t.galley.text().contains(title))) +} + +#[test] +fn cascade_places_step_down_and_right_inside_the_area() { + let area = egui::Rect::from_min_size(pos2(10.0, 35.0), vec2(1190.0, 765.0)); + let places = cascade_places(area, 5); + assert_eq!(places.len(), 5); + for (k, p) in places.iter().enumerate() { + assert!(area.contains_rect(*p), "place {k} is inside the area: {p:?}"); + assert_eq!(p.size(), places[0].size(), "every window is the same size"); + let offset = CASCADE_MARGIN + k as f32 * CASCADE_STEP; + assert_eq!(p.min, area.min + vec2(offset, offset), "place {k} is {offset} pt down and right"); + } + // A small area holds fewer steps: the stack starts again at the corner and stays inside. + let small = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(500.0, 400.0)); + let places = cascade_places(small, 12); + assert!(places.iter().all(|p| small.contains_rect(*p)), "{places:?}"); + assert!(places.iter().skip(1).any(|p| p.min == places[0].min), "the stack starts again: {places:?}"); + // An area smaller than a window: the window fills it. + let tiny = egui::Rect::from_min_size(pos2(5.0, 5.0), vec2(100.0, 80.0)); + assert_eq!(cascade_places(tiny, 2), [tiny, tiny]); +} + +#[test] +fn a_control_channel_keeps_the_windows_inside_the_main_window() { + let ctx = egui::Context::default(); + ctx.set_embed_viewports(false); + let plain = app_with(0); + let wayland = ["WAYLAND_DISPLAY", "WAYLAND_SOCKET"].iter().any(|n| std::env::var_os(n).is_some_and(|v| !v.is_empty())); + if !wayland { + assert!(native(&plain, &ctx), "without a control channel the windows are OS windows"); + } + let (_tx, rx) = std::sync::mpsc::channel(); + let controlled = VectorcraftApp::new(Session::new(), Default::default()).with_control(rx); + assert!(!native(&controlled, &ctx), "with a control channel the windows stay inside the main window"); + ctx.set_embed_viewports(true); + assert!(!native(&plain, &ctx), "where egui draws every viewport inside the main window"); +} + +#[test] +fn float_in_window_moves_the_current_document_out_of_the_tabs() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + let shapes = frame(&mut app, &ctx, vec![]); + let title = app.session.documents()[2].title(); + assert!(tab_drawn(&shapes, &title), "the current document has a tab"); + let tabbed = app.canvas_rect.unwrap(); + assert_eq!(app.run("window.arrange.floatInWindow", json!({})).unwrap(), json!({"floating": [2]})); + frame(&mut app, &ctx, vec![]); + let shapes = frame(&mut app, &ctx, vec![]); + assert!(!tab_drawn(&shapes, &title), "a floating document has no tab"); + assert!(tab_drawn(&shapes, &app.session.documents()[0].title())); + assert_eq!(docked(&app), [0, 1]); + assert_eq!(app.session.active_index(), Some(2), "the floating document stays the current one"); + // Its window holds the canvas, fitted to the window; the main window shows a tabbed document. + let body = body_of(&app, 2); + let canvas = app.canvas_rect.unwrap(); + assert!(body.contains_rect(canvas) && canvas.width() < tabbed.width(), "the canvas is in the window: {canvas:?} in {body:?}"); + assert!(app.views[2].fitted); + assert_eq!(tab_document(&app), Some(0)); + assert_eq!(crate::control::inspect(&app, &ctx)["floating"], json!([2])); + // Floating it again leaves it where it is. + assert_eq!(app.run("window.arrange.floatInWindow", json!({})).unwrap(), json!({"floating": [2]})); + assert_eq!(app.ui.floating.len(), 1); +} + +#[test] +fn a_press_in_another_documents_window_or_the_main_window_makes_its_document_current() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.session.active_index(), Some(1)); + // The lower left of document 0's window, clear of document 1's window, which cascades below + // and to the right of it, and of the window's resize edges. + let body = body_of(&app, 0); + click(&mut app, &ctx, pos2(body.left() + 12.0, body.bottom() - 12.0)); + assert_eq!(app.session.active_index(), Some(0), "a press in its window makes document 0 current"); + assert!(body_of(&app, 0).contains_rect(app.canvas_rect.unwrap()), "its window holds the canvas now"); + // The main window shows the only tabbed document as a pane: a press there makes it current. + assert_eq!(tab_document(&app), Some(2)); + click(&mut app, &ctx, pos2(1100.0, 700.0)); + assert_eq!(app.session.active_index(), Some(2)); + // A press on the title bar of document 0's window, in front, makes document 0 current again. + let (window, body) = (window_of(&app, &ctx, 0), body_of(&app, 0)); + click(&mut app, &ctx, pos2(window.left() + 60.0, (window.top() + body.top()) / 2.0)); + assert_eq!(app.session.active_index(), Some(0), "a press on its title bar makes document 0 current"); +} + +#[test] +fn a_resized_window_fits_its_document_again_unless_it_was_zoomed() { + let mut app = app_with(2); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let (before, other) = (app.views[1].zoom, app.views[0].zoom); + // Document 1's window, in front and holding the canvas, grows from its lower-right corner. + let window = window_of(&app, &ctx, 1); + drag(&mut app, &ctx, window.right_bottom() - vec2(2.0, 2.0), window.right_bottom() + vec2(150.0, 100.0)); + assert!(window_of(&app, &ctx, 1).width() > window.width() + 100.0, "the window grew"); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.session.active_index(), Some(1)); + assert!(app.views[1].zoom > before, "the document fits its larger window: {before} → {}", app.views[1].zoom); + assert_eq!(app.views[0].zoom, other, "the other window keeps its size and its document's zoom"); + // A zoomed view keeps its zoom when its window changes size again. + app.run("view.zoomIn", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + let zoomed = app.views[1].zoom; + let window = window_of(&app, &ctx, 1); + drag(&mut app, &ctx, window.right_bottom() - vec2(2.0, 2.0), window.right_bottom() - vec2(100.0, 60.0)); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.views[1].zoom, zoomed, "a zoomed document keeps its zoom"); +} + +#[test] +fn cascade_floats_every_document_and_stacks_the_windows() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.tile", json!({})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + assert_eq!(app.run("window.arrange.cascade", json!({})).unwrap(), json!({"floating": [0, 1, 2]})); + assert!(!app.ui.tiled, "Cascade ends Tile"); + assert!(docked(&app).is_empty()); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let area = app.canvas.windows.area.unwrap(); + let places: Vec = app.ui.floating.iter().map(|w| w.place).collect(); + assert_eq!(places, cascade_places(area, 3), "the windows stack in tab order, document 1's moved from where it floated"); + for (i, place) in places.iter().copied().enumerate() { + let body = body_of(&app, i); + assert!((body.left() - place.left()).abs() < 4.0 && body.top() > place.top(), "document {i}'s window is at its place: {body:?} {place:?}"); + assert!(app.views[i].fitted, "document {i} fits its window"); + } + assert!(body_of(&app, 1).contains_rect(app.canvas_rect.unwrap()), "the current document's window holds the canvas"); +} + +#[test] +fn float_all_in_windows_floats_the_tabbed_documents_and_consolidate_brings_them_back() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let tabbed = app.canvas_rect.unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + let first = app.ui.floating[0].place; + assert_eq!(app.run("window.arrange.floatAllInWindows", json!({})).unwrap(), json!({"floating": [2, 0, 1]})); + assert_eq!(app.ui.floating[0].place, first, "a window already floating stays where it is"); + assert!(docked(&app).is_empty()); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(), json!({"tiled": false, "floating": []})); + frame(&mut app, &ctx, vec![]); + let shapes = frame(&mut app, &ctx, vec![]); + assert_eq!(docked(&app), [0, 1, 2]); + for d in app.session.documents() { + assert!(tab_drawn(&shapes, &d.title()), "{} has its tab again", d.title()); + } + assert_eq!(app.canvas_rect, Some(tabbed), "the canvas is under the tabs again"); + assert!(app.views[2].fitted); +} + +#[test] +fn tile_brings_floating_documents_back_into_the_grid() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.tile", json!({})).unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + let docs: Vec = app.canvas.panes.last.iter().map(|(i, _)| *i).collect(); + assert_eq!(docs, [0, 1], "a floating document leaves the grid; the tabbed ones share it"); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3})); + frame(&mut app, &ctx, vec![]); + let docs: Vec = app.canvas.panes.last.iter().map(|(i, _)| *i).collect(); + assert_eq!(docs, [0, 1, 2]); + assert!(app.ui.floating.is_empty()); +} + +#[test] +fn closing_a_floating_window_closes_its_document_and_asks_to_save_an_unsaved_one() { + let mut app = app_with(2); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + // Document 0's window is behind document 1's: its close button is at the top right of its + // title bar, clear of document 1's window to the right and below. + let close_button = |app: &VectorcraftApp, i: usize| { + let uid = app.session.documents()[i].uid; + let w = app.ui.floating.iter().find(|w| w.uid == uid).unwrap(); + let area = ctx.memory(|m| m.area_rect(window_id(w))).unwrap(); + let body = w.body.unwrap(); + (area, body) + }; + let (area0, body0) = close_button(&app, 0); + assert!(body0.top() > area0.top(), "the window has a title bar"); + // Close document 1 (in front): it is unsaved after an edit, so the app asks first. + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + assert!(app.session.documents()[1].is_dirty()); + frame(&mut app, &ctx, vec![]); + // The close button sits near the right end of the title bar. + let press_close = |app: &mut VectorcraftApp, i: usize| { + let (area, body) = close_button(app, i); + let bar = (area.top() + body.top()) / 2.0; + let n = app.session.documents().len(); + for dx in (4..40).step_by(3) { + click(app, &ctx, pos2(area.right() - dx as f32, bar)); + if app.ui.dialog.is_some() || app.session.documents().len() < n { + return true; + } + } + false + }; + assert!(press_close(&mut app, 1), "the close button of document 1's window acts"); + assert!(app.ui.dialog.is_some(), "an unsaved document asks to be saved"); + assert_eq!(app.session.documents().len(), 2); + // While the prompt is open the windows take no press. + let body = body_of(&app, 0); + click(&mut app, &ctx, pos2(body.left() + 12.0, body.bottom() - 12.0)); + assert_eq!(app.session.active_index(), Some(1), "a press in another window waits for the prompt"); + app.ui.dialog = None; + // Document 0 has no changes: its window closes with it. + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert!(press_close(&mut app, 0), "the close button of document 0's window acts"); + assert_eq!(app.session.documents().len(), 1); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.ui.floating.len(), 1, "its window has gone"); +} + +#[test] +fn presentation_mode_shows_the_floating_current_document_in_the_main_window() { + let mut app = app_with(2); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let body = body_of(&app, 1); + assert!(body.contains_rect(app.canvas_rect.unwrap()), "the current document's window holds the canvas"); + let windowed = (app.views[0].zoom, app.views[1].zoom); + app.run("view.presentation", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + let shown = app.canvas_rect.unwrap(); + assert!(shown.width() > body.width() + 100.0, "the main window shows the current document: {shown:?}, its window was {body:?}"); + // The presentation goes on to the other floating document, fitted to the main window, then + // ends on the first one. + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + app.run("document.activate", json!({"index": 1})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert!(app.views[0].zoom > windowed.0, "the presentation fitted document 0 to the main window"); + app.run("view.presentation", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert!(body_of(&app, 1).contains_rect(app.canvas_rect.unwrap()), "the window holds the canvas again"); + assert_eq!(app.ui.floating.len(), 2, "the windows come back"); + for (i, before) in [windowed.0, windowed.1].into_iter().enumerate() { + assert!((app.views[i].zoom - before).abs() < 1e-6, "document {i} fits its window again: {before} → {}", app.views[i].zoom); + } +} + +#[test] +fn a_document_made_current_in_presentation_mode_comes_to_the_front_after_it() { + let mut app = app_with(2); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let layer = |app: &VectorcraftApp, i: usize| { + let uid = app.session.documents()[i].uid; + let w = app.ui.floating.iter().find(|w| w.uid == uid).unwrap(); + egui::LayerId::new(egui::Order::Middle, window_id(w)) + }; + let top = |ctx: &egui::Context| ctx.memory(|m| m.areas().top_layer_id(egui::Order::Middle)); + assert_eq!(top(&ctx), Some(layer(&app, 1)), "the current document's window is in front"); + app.run("view.presentation", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.run("view.presentation", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert_eq!(top(&ctx), Some(layer(&app, 0)), "document 0's window comes to the front"); +} + +/// A stand-in for the window system of the documents' OS windows: it runs each one's frame, asks +/// each to close while `close` is set, and records the commands the windows were sent. Each +/// window is 500 × 400 points with its top-left corner at `origin` on the screen, and its next +/// frame takes `events`. +#[derive(Default)] +struct Host { + close: bool, + commands: Vec<(egui::ViewportId, egui::ViewportCommand)>, + origin: Pos2, + events: Vec, +} + +fn native_host() -> std::rc::Rc> { + let host = std::rc::Rc::new(std::cell::RefCell::new(Host::default())); + let shared = host.clone(); + egui::Context::set_immediate_viewport_renderer(move |ctx, mut viewport| { + let id = viewport.ids.this; + let close = if shared.borrow().close { vec![egui::ViewportEvent::Close] } else { vec![] }; + let size = vec2(500.0, 400.0); + let rect = egui::Rect::from_min_size(Pos2::ZERO, size); + let on_screen = egui::Rect::from_min_size(shared.borrow().origin, size); + let info = egui::ViewportInfo { + events: close, + inner_rect: Some(on_screen), + outer_rect: Some(on_screen), + focused: Some(false), + ..Default::default() + }; + let events = std::mem::take(&mut shared.borrow_mut().events); + let input = egui::RawInput { + viewport_id: id, + viewports: std::iter::once((id, info)).collect(), + screen_rect: Some(rect), + events, + ..Default::default() + }; + let mut full = ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui)); + full.textures_delta.clear(); + let mut host = shared.borrow_mut(); + for (vid, output) in full.viewport_output { + host.commands.extend(output.commands.into_iter().map(|c| (vid, c))); + } + }); + host +} + +#[test] +fn closing_an_os_window_keeps_it_while_its_unsaved_document_stays_open() { + let host = native_host(); + let ctx = egui::Context::default(); + ctx.set_embed_viewports(false); + let mut app = app_with(2); + if !native(&app, &ctx) { + // Wayland: the windows are inside the main window. + return; + } + frame(&mut app, &ctx, vec![]); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + let vid = viewport_id(app.session.documents()[1].uid); + host.borrow_mut().close = true; + frame(&mut app, &ctx, vec![]); + host.borrow_mut().close = false; + assert!(app.ui.dialog.is_some(), "the unsaved document asks to be saved"); + assert_eq!(app.session.documents().len(), 2); + assert!(is_floating(&app, 1), "the document still floats"); + assert!( + host.borrow().commands.iter().any(|(id, c)| *id == vid && *c == egui::ViewportCommand::CancelClose), + "its OS window is kept open: {:?}", + host.borrow().commands + ); +} + +/// Where the last frame drew the title of `title`'s tab in the tab strip. +fn tab_at(shapes: &[Shape], title: &str) -> Pos2 { + shapes + .iter() + .find_map(|s| match s { + Shape::Text(t) if t.pos.y < 35.0 && t.galley.text().contains(title) => Some(t.pos + vec2(4.0, 4.0)), + _ => None, + }) + .unwrap() +} + +#[test] +fn a_tab_is_torn_off_only_well_above_or_below_the_strip() { + let strip = egui::Rect::from_min_max(pos2(0.0, 40.0), pos2(1200.0, 75.0)); + assert!(!torn_off(strip, pos2(300.0, 60.0)), "along the strip"); + assert!(!torn_off(strip, pos2(300.0, 75.0 + TEAR_OFF - 1.0)), "a wobble below the strip"); + assert!(torn_off(strip, pos2(300.0, 75.0 + TEAR_OFF + 1.0))); + assert!(torn_off(strip, pos2(300.0, 40.0 - TEAR_OFF - 1.0)), "dragged up"); +} + +#[test] +fn dragging_a_tab_off_the_strip_floats_its_document_at_the_pointer() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let shapes = frame(&mut app, &ctx, vec![]); + let title = app.session.documents()[0].title(); + let tab = tab_at(&shapes, &title); + // A short drag, and a drag along the strip, leave the tabs as they are. + drag(&mut app, &ctx, tab, tab + vec2(0.0, 35.0 + TEAR_OFF - 10.0 - tab.y)); + drag(&mut app, &ctx, tab, tab + vec2(300.0, 0.0)); + assert!(app.ui.floating.is_empty(), "the document stays under its tab"); + assert_eq!(app.session.active_index(), Some(2), "a drag is not a click"); + // Dragged well below the strip, it floats in a window under the pointer and becomes current. + let to = pos2(300.0, 200.0); + drag(&mut app, &ctx, tab, to); + assert_eq!(docked(&app), [1, 2]); + assert_eq!(app.session.active_index(), Some(0), "the torn-off document is the current one"); + assert_eq!(app.ui.floating[0].place.min, to - GRAB, "its window opens under the pointer"); + frame(&mut app, &ctx, vec![]); + let shapes = frame(&mut app, &ctx, vec![]); + assert!(!tab_drawn(&shapes, &title), "it has left the strip"); + let window = window_of(&app, &ctx, 0); + assert!(window.contains(to) && (window.min - (to - GRAB)).length() < 1.0, "the pointer is over its window: {window:?}"); + assert!(body_of(&app, 0).contains_rect(app.canvas_rect.unwrap()), "its window holds the canvas"); +} + +#[test] +fn a_window_dragged_by_its_title_bar_onto_the_strip_goes_back_under_the_tabs() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let title_bar = |app: &VectorcraftApp, i: usize| { + let (window, body) = (window_of(app, &ctx, i), body_of(app, i)); + pos2(window.left() + 60.0, (window.top() + body.top()) / 2.0) + }; + // Moved elsewhere, document 2's window (in front) stays a window. + let from = title_bar(&app, 2); + drag(&mut app, &ctx, from, from + vec2(40.0, 30.0)); + assert_eq!(app.ui.floating.len(), 3, "a window moved off the strip still floats"); + // Dropped on the strip, it goes back under its tab, current; the other windows stay. + let from = title_bar(&app, 2); + drag(&mut app, &ctx, from, pos2(600.0, 15.0)); + assert_eq!(docked(&app), [2]); + assert_eq!(app.session.active_index(), Some(2)); + assert_eq!(app.ui.floating.len(), 2); + frame(&mut app, &ctx, vec![]); + let shapes = frame(&mut app, &ctx, vec![]); + assert!(tab_drawn(&shapes, &app.session.documents()[2].title()), "it has its tab again"); + assert!(app.views[2].fitted, "it fits the canvas under the tabs"); + let canvas = app.canvas_rect.unwrap(); + assert!(canvas.top() >= 35.0 && canvas.width() > 1000.0, "the canvas under the tabs shows it: {canvas:?}"); + // Torn off again, it opens where its tab is dropped, not where its last window was. + let to = pos2(200.0, 300.0); + let tab = tab_at(&shapes, &app.session.documents()[2].title()); + drag(&mut app, &ctx, tab, to); + frame(&mut app, &ctx, vec![]); + let window = window_of(&app, &ctx, 2); + assert!((window.min - (to - GRAB)).length() < 1.0, "its new window is under the pointer: {window:?}"); +} + +#[test] +fn after_touch_input_a_window_dragged_onto_the_strip_still_docks() { + let mut app = app_with(2); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + // A touch makes egui move windows by a drag anywhere on them. + let touch = egui::Event::Touch { + device_id: egui::TouchDeviceId(1), + id: egui::TouchId(1), + phase: egui::TouchPhase::Start, + pos: pos2(1100.0, 700.0), + force: None, + }; + frame(&mut app, &ctx, vec![touch]); + frame(&mut app, &ctx, vec![]); + let (window, body) = (window_of(&app, &ctx, 1), body_of(&app, 1)); + let from = pos2(window.left() + 60.0, (window.top() + body.top()) / 2.0); + drag(&mut app, &ctx, from, pos2(600.0, 15.0)); + assert_eq!(docked(&app), [1], "document 1 is back under the tabs"); +} + +#[test] +fn a_document_floated_again_after_cascade_opens_where_it_is_asked_to() { + let mut app = app_with(2); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.cascade", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.consolidateAllWindows", json!({"index": 1})).unwrap(); + frame(&mut app, &ctx, vec![]); + let at = pos2(200.0, 300.0); + app.run("window.arrange.floatInWindow", json!({"index": 1, "at": [at.x, at.y]})).unwrap(); + frame(&mut app, &ctx, vec![]); + let window = window_of(&app, &ctx, 1); + assert!((window.min - at).length() < 1.0, "its new window opens at {at:?}: {window:?}"); +} + +#[test] +fn float_in_window_and_consolidate_take_a_document() { + let mut app = app_with(3); + assert_eq!(app.run("window.arrange.floatInWindow", json!({"index": 0, "at": [100, 120]})).unwrap(), json!({"floating": [0]})); + assert_eq!(app.session.active_index(), Some(0), "document 0 becomes the current one"); + assert_eq!(app.ui.floating[0].place.min, pos2(100.0, 120.0)); + app.run("window.arrange.floatInWindow", json!({"index": 1})).unwrap(); + assert_eq!(app.run("window.arrange.floatInWindow", json!({"index": 3})), Err("no such document".to_string())); + app.run("window.arrange.tile", json!({})).unwrap(); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + assert_eq!(app.run("window.arrange.consolidateAllWindows", json!({"index": 1})).unwrap(), json!({"tiled": true, "floating": [0, 2]})); + assert_eq!(app.session.active_index(), Some(1)); + assert_eq!(docked(&app), [1], "only document 1 goes back under the tabs"); + assert_eq!(app.run("window.arrange.consolidateAllWindows", json!({"index": 7})), Err("no such document".to_string())); + assert_eq!(app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(), json!({"tiled": false, "floating": []})); +} + +#[test] +fn with_open_documents_as_tabs_cleared_new_documents_open_in_floating_windows() { + let mut app = app_with(1); + let ctx = egui::Context::default(); + app.run("prefs.set", json!({"key": "openDocumentsAsTabs", "value": false})).unwrap(); + assert_eq!(docked(&app), [0], "a document already open stays under its tab"); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + assert_eq!(docked(&app), [0]); + assert_eq!(floating_indices(&app), [1, 2], "each new document opens in a window of its own"); + assert_eq!(app.session.active_index(), Some(2), "the newest document is the current one"); + assert_ne!(app.ui.floating[0].place.min, app.ui.floating[1].place.min, "the windows open at cascade places"); + frame(&mut app, &ctx, vec![]); + let shapes = frame(&mut app, &ctx, vec![]); + assert!(!tab_drawn(&shapes, &app.session.documents()[2].title()), "a document in a window has no tab"); + assert!(tab_drawn(&shapes, &app.session.documents()[0].title())); + assert!(body_of(&app, 2).contains_rect(app.canvas_rect.unwrap()), "the new document's window holds the canvas"); +} + +#[test] +fn documents_open_when_the_app_starts_keep_their_tabs() { + let mut session = Session::new(); + session.prefs.open_documents_as_tabs = false; + session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let mut app = VectorcraftApp::new(session, Default::default()); + app.sync_views(); + assert_eq!(docked(&app), [0]); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + assert_eq!(floating_indices(&app), [1]); +} + +#[test] +fn a_document_created_in_a_batch_that_closes_another_still_floats() { + let mut app = app_with(2); + app.run("prefs.set", json!({"key": "openDocumentsAsTabs", "value": false})).unwrap(); + let steps = json!([ + {"command": "file.close", "params": {}}, + {"command": "file.new", "params": {"width": 400, "height": 300}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert_eq!(app.session.documents().len(), 2, "one document closed and one opened"); + assert_eq!(docked(&app), [0]); + assert_eq!(floating_indices(&app), [1], "the new document opens in a window of its own"); +} + +#[test] +fn each_document_in_a_batch_follows_the_preference_when_it_opened() { + let mut app = app_with(1); + let new = json!({"command": "file.new", "params": {"width": 400, "height": 300}}); + let tabs = |on: bool| json!({"command": "prefs.set", "params": {"key": "openDocumentsAsTabs", "value": on}}); + let steps = json!([tabs(false), new, tabs(true), new, tabs(false)]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert_eq!(floating_indices(&app), [1], "opened with the box cleared"); + assert_eq!(docked(&app), [0, 2], "opened with the box checked"); +} + +#[test] +fn checking_open_documents_as_tabs_again_leaves_floating_documents_where_they_are() { + let mut app = app_with(0); + app.run("prefs.set", json!({"key": "openDocumentsAsTabs", "value": false})).unwrap(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("prefs.set", json!({"key": "openDocumentsAsTabs", "value": true})).unwrap(); + assert_eq!(floating_indices(&app), [0], "the floating document stays in its window"); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + assert_eq!(docked(&app), [1], "a new document opens under a tab"); + assert_eq!(floating_indices(&app), [0]); +} + +#[test] +fn an_os_window_moves_by_its_tab_and_docks_on_the_strip() { + let host = native_host(); + let ctx = egui::Context::default(); + ctx.set_embed_viewports(false); + let mut app = app_with(2); + if !native(&app, &ctx) { + // Wayland: the windows are inside the main window. + return; + } + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + // The OS window's top-left corner is at (300, 300) on the screen; the main window's at (0, 0). + host.borrow_mut().origin = pos2(300.0, 300.0); + frame(&mut app, &ctx, vec![]); + let os_drag = |app: &mut VectorcraftApp, from: Pos2, to: Pos2| { + let steps = [vec![egui::Event::PointerMoved(from)], vec![button(from, true)]] + .into_iter() + .chain((1..=4).map(|k| vec![egui::Event::PointerMoved(from + (to - from) * (k as f32 / 4.0))])) + .chain([vec![button(to, false)], vec![]]); + for events in steps { + host.borrow_mut().events = events; + frame(app, &ctx, vec![]); + } + }; + // The tab at the top of the window: dragged down and right, the window follows the pointer. + let tab = pos2(20.0, 15.0); + os_drag(&mut app, tab, tab + vec2(100.0, 50.0)); + assert!(is_floating(&app, 1), "a window moved off the strip still floats"); + let w = &app.ui.floating[0]; + assert_eq!(w.screen.map(|s| s.0), Some(pos2(400.0, 350.0)), "the window moved with the pointer"); + assert_eq!(w.place.min, pos2(400.0, 350.0), "in the main window's points"); + // Released over the main window's tab strip (y 0 to 35 on the screen), it docks. + os_drag(&mut app, tab, pos2(20.0, -280.0)); + assert!(app.ui.floating.is_empty(), "the document is back under the tabs"); + assert_eq!(docked(&app), [0, 1]); + assert_eq!(app.session.active_index(), Some(1)); +} + +#[test] +fn the_arrange_items_are_enabled_as_the_documents_allow() { + let ids = [ + "window.arrange.cascade", + "window.arrange.tile", + "window.arrange.floatInWindow", + "window.arrange.floatAllInWindows", + "window.arrange.consolidateAllWindows", + ]; + let states = |app: &VectorcraftApp| ids.map(|id| enabled(app, id)); + let mut app = app_with(0); + assert_eq!(states(&app), [false; 5], "no document"); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + assert_eq!(states(&app), [false, false, true, true, false], "one tabbed document"); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + assert_eq!(states(&app), [true, true, true, true, false], "two tabbed documents"); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + assert_eq!(states(&app), [true, true, false, true, true], "the current document floats, one is tabbed"); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + assert_eq!(states(&app), [true, true, false, false, true], "every document floats"); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(); + assert_eq!(states(&app), [true, true, true, true, false], "consolidated"); +} diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index 93cdc8edaf..85309507f8 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -142,6 +142,19 @@ fn every_tool_is_listed_once_under_a_heading() { assert!(!heads.contains(&"More"), "every tool has a named heading: {heads:?}"); } +#[test] +fn enclosing_lasso_is_an_optional_addon_tool() { + let mut app = app(); + let id = vectorcraft_tools::addons::enclosing_lasso::ID; + assert_eq!(heading(id), "Enclosing Lasso"); + assert!(slot_of(&app, id).is_none()); + app.run("toolbar.addTool", json!({"tool": id})).unwrap(); + assert!(slot_of(&app, id).is_some()); + app.run("tool.select", json!({"tool": id})).unwrap(); + app.run("toolbar.reset", json!({})).unwrap(); + assert!(slot_of(&app, id).is_none()); +} + #[test] fn the_commands_add_move_remove_and_reset_tools() { let mut app = app(); @@ -515,10 +528,11 @@ fn drop_targets_follow_the_buttons_edges() { #[test] fn addon_tools_are_in_the_drawer_not_the_toolbars() { let mut app = app(); + let enclosing = vectorcraft_tools::addons::enclosing_lasso::ID; let addon: Vec<&str> = vectorcraft_tools::addons::GROUPS.iter().flat_map(|g| g.iter().map(|t| t.id)).collect(); assert_eq!( addon, - ["anchorEraserBrush", "extendPath", "measureInspect", "parametricShape", "cornerTool", "slideAnchor", "sharedEdge", "smartPen"] + ["anchorEraserBrush", "extendPath", "measureInspect", "parametricShape", "cornerTool", "slideAnchor", "sharedEdge", "smartPen", enclosing] ); for advanced in [false, true] { if advanced { @@ -531,7 +545,8 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { }; assert_eq!(listed("extendPath"), Some(("Path Precision Tools", addon[..7].to_vec()))); assert_eq!(listed("smartPen"), Some(("Smart Pen", vec!["smartPen"]))); - for tool in ["extendPath", "smartPen"] { + assert_eq!(listed(enclosing), Some(("Enclosing Lasso", vec![enclosing]))); + for tool in ["extendPath", "smartPen", enclosing] { app.run("toolbar.addTool", json!({"tool": tool})).unwrap(); assert!(slot_of(&app, tool).is_some(), "{tool}"); } diff --git a/crates/ui-egui/src/find_font.rs b/crates/ui-egui/src/find_font.rs index 5155542e01..af9a83af0b 100644 --- a/crates/ui-egui/src/find_font.rs +++ b/crates/ui-egui/src/find_font.rs @@ -1,6 +1,7 @@ //! Type → Find Font…: the fonts the document uses (missing ones marked), Find (select the text -//! using a font), Change / Change All to another installed font, and Find in Folder… (the missing -//! fonts' files, in the Missing Fonts dialog: `ui.findFontsInFolder`). +//! using a font), Change / Change All to another font from the list Replace With Font From shows +//! (the document's fonts, the recent fonts or every installed font), and Find in Folder… (the +//! missing fonts' files, in the Missing Fonts dialog: `ui.findFontsInFolder`). use egui::Ui; use serde_json::{Value, json}; @@ -22,9 +23,90 @@ pub fn open_on_missing(app: &mut VectorcraftApp) { open_at(app, first.unwrap_or(0)); } -/// Open the dialog with the document's font `selected` (an index into `text.fonts`) chosen. +/// Open the dialog with the document's font `selected` (an index into `text.fonts`) chosen, and +/// System's font ([`system_family`]) to change to. fn open_at(app: &mut VectorcraftApp, selected: usize) { - app.ui.dialog = Some(Dialog::new("findFont", json!({ "selected": selected, "family": "Source Sans 3", "style": "", "selectionOnly": false }))); + app.ui.dialog = Some(Dialog::new( + "findFont", + json!({ "selected": selected, "family": system_family(), "style": "", "selectionOnly": false, "replaceFrom": "system" }), + )); +} + +/// The font System chooses: Source Sans 3 when it is installed, otherwise the font menu's first +/// family (none when the menu is empty). +fn system_family() -> String { + system_family_in(installed, &vectorcraft_text::FontDb::global().menu_family_list()) +} + +/// [`system_family`] for the installed check `is_installed` and the font menu `menu`. +fn system_family_in(is_installed: impl Fn(&str) -> bool, menu: &[String]) -> String { + const PREFERRED: &str = "Source Sans 3"; + if is_installed(PREFERRED) { PREFERRED.to_string() } else { menu.first().cloned().unwrap_or_default() } +} + +/// Replace With Font From's lists (the `replaceFrom` field): the document's fonts, the recent +/// fonts and every installed font. +const SOURCES: [&str; 3] = ["document", "recent", "system"]; +const SOURCE_LABELS: [&str; 3] = ["Document", "Recent", "System"]; + +/// The families Replace With Font From lists. `None` is System: the font menu, every installed +/// family. Document lists the families `text.fonts` names, once each, in its order; Recent lists +/// the font menu's recent families (newest first, Number of Recent Fonts at most) that are +/// installed. +fn replacement_families(app: &VectorcraftApp, source: &str, used: &[Value]) -> Option> { + let names: Vec = match source { + "document" => used.iter().filter_map(|f| f["family"].as_str()).map(str::to_string).collect(), + "recent" => { + let installed = vectorcraft_text::FontDb::global().menu_family_list(); + app.recent_fonts().iter().filter_map(|r| installed.iter().find(|f| f.eq_ignore_ascii_case(r)).cloned()).collect() + } + _ => return None, + }; + let mut out: Vec = vec![]; + for n in names { + if !out.iter().any(|o| o.eq_ignore_ascii_case(&n)) { + out.push(n); + } + } + Some(out) +} + +/// Is `family` installed: it resolves to a face of its own, as `text.replaceFont` requires. +fn installed(family: &str) -> bool { + !family.is_empty() + && vectorcraft_text::FontDb::global().resolve(family, "Regular").is_some_and(|(_, m)| m != vectorcraft_text::FontMatch::Missing) +} + +/// Can Change and Change All replace with the dialog's font: a family is chosen, it is installed, +/// and it is one of the list Replace With Font From shows (System's list is the font menu). +fn can_replace(d: &Dialog, families: Option<&[String]>) -> bool { + let family = d.str("family"); + match families { + Some(list) => can_replace_in(&family, installed, list), + None => can_replace_in(&family, installed, &vectorcraft_text::FontDb::global().menu_family_list()), + } +} + +/// [`can_replace`] for the installed check `is_installed` and the shown list `list`. +fn can_replace_in(family: &str, is_installed: impl Fn(&str) -> bool, list: &[String]) -> bool { + is_installed(family) && list.iter().any(|f| f.eq_ignore_ascii_case(family)) +} + +/// Show list `source` ([`SOURCES`]): the chosen family stays when the list has it and it is +/// installed, otherwise the list's first installed family (none when there is none) is chosen in +/// its closest style. System chooses [`system_family`]. +fn set_source(app: &VectorcraftApp, d: &mut Dialog, source: &str, used: &[Value]) { + d.fields.insert("replaceFrom".into(), json!(source)); + let families = replacement_families(app, source, used); + if can_replace(d, families.as_deref()) { + return; + } + let family = match families { + Some(l) => l.into_iter().find(|f| installed(f)), + None => Some(system_family()), + }; + d.fields.insert("family".into(), json!(family.unwrap_or_default())); + d.fields.insert("style".into(), json!("")); } fn fonts(app: &mut VectorcraftApp) -> Vec { @@ -81,13 +163,31 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } ui.add_space(10.0); widgets::subheader(ui, tl!("Replace With Font")); + let source = d.str("replaceFrom"); + ui.horizontal(|ui| { + widgets::field_label(ui, tl!("Replace With Font From")); + let at = SOURCES.iter().position(|s| *s == source).unwrap_or(2); + if let Some(i) = widgets::dropdown_named(ui, "ff-from", Some(tl!("Replace With Font From")), SOURCE_LABELS[at], &SOURCE_LABELS, 120.0) { + set_source(app, &mut d, SOURCES[i], &list); + } + }); + let families = replacement_families(app, &d.str("replaceFrom"), &list); let fam = d.str("family"); ui.horizontal(|ui| { - // Picks the font only: nothing is previewed on the document. - let pick = font_menu::font_menu(ui, "ff-family", &fam, 220.0, sample.as_deref(), font_menu::MenuLook::of(app)); - if let Some((f, style)) = font_menu::picked(app, pick) { - d.fields.insert("family".into(), json!(f)); - d.fields.insert("style".into(), json!(style.unwrap_or_default())); + if let Some(families) = &families { + // Font names are shown as they are. + let names: Vec<&str> = families.iter().map(String::as_str).collect(); + if let Some(i) = widgets::dropdown_names_named(ui, "ff-family-list", Some(tl!("Replace With Font")), &fam, &names, 220.0) { + d.fields.insert("family".into(), json!(families[i])); + d.fields.insert("style".into(), json!("")); + } + } else { + // Picks the font only: nothing is previewed on the document. + let pick = font_menu::font_menu(ui, "ff-family", &fam, 220.0, sample.as_deref(), font_menu::MenuLook::of(app)); + if let Some((f, style)) = font_menu::picked(app, pick) { + d.fields.insert("family".into(), json!(f)); + d.fields.insert("style".into(), json!(style.unwrap_or_default())); + } } let styles = vectorcraft_text::FontDb::global().styles(&d.str("family")); // "(closest)" is ours; the font's style names are shown as they are. @@ -101,15 +201,17 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } }); ui.add_space(14.0); + // An empty list (Recent before any font was applied) leaves nothing to change to. + let replace = sel < list.len() && can_replace(&d, families.as_deref()); ui.horizontal(|ui| { let has = sel < list.len(); if ui.add_enabled(has, egui::Button::new(tl!("Find"))).clicked() { act = Some("find"); } - if ui.add_enabled(has, egui::Button::new(tl!("Change"))).on_hover_text(tl!("In the selected objects")).clicked() { + if ui.add_enabled(replace, egui::Button::new(tl!("Change"))).on_hover_text(tl!("In the selected objects")).clicked() { act = Some("change"); } - if ui.add_enabled(has, egui::Button::new(tl!("Change All"))).clicked() { + if ui.add_enabled(replace, egui::Button::new(tl!("Change All"))).clicked() { act = Some("changeAll"); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -225,6 +327,194 @@ mod tests { crate::dialogs::cancel(&mut app); } + /// A document set in Inter and Source Serif 4 (Inter twice), with Inter the one recent font. + fn two_font_document() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for (y, font) in [(20, "Inter"), (40, "Source Serif 4"), (60, "Inter")] { + app.session.execute("text.create", &json!({"x": 10, "y": y, "text": "Hi", "font": font})).unwrap(); + } + app.ui.recent_fonts = vec!["Inter".into()]; + app + } + + #[test] + fn replace_with_font_from_lists_the_document_s_recent_or_installed_fonts() { + let mut app = two_font_document(); + let used = fonts(&mut app); + let mut document = replacement_families(&app, "document", &used).unwrap(); + document.sort(); + assert_eq!(document, ["Inter", "Source Serif 4"]); + assert_eq!(replacement_families(&app, "recent", &used).unwrap(), ["Inter"]); + assert_eq!(replacement_families(&app, "system", &used), None, "System is the font menu of every installed family"); + open(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("replaceFrom"), "system"); + for source in SOURCES { + let mut d = app.ui.dialog.clone().unwrap(); + set_source(&app, &mut d, source, &used); + let listed = replacement_families(&app, source, &used); + assert!(can_replace(&d, listed.as_deref()), "{source}: {}", d.str("family")); + app.ui.dialog = Some(d); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert!(text.contains("Replace With Font From"), "{text}"); + } + } + + #[test] + fn change_all_replaces_with_a_font_from_the_document() { + let mut app = two_font_document(); + open(&mut app); + let used = fonts(&mut app); + let mut d = app.ui.dialog.clone().unwrap(); + set_source(&app, &mut d, "document", &used); + d.fields.insert("family".into(), json!("Inter")); + let from = used.iter().find(|f| f["family"] == "Source Serif 4").unwrap().clone(); + change(&mut app, &d, &from, true).unwrap(); + let families: Vec = fonts(&mut app).iter().map(|f| f["family"].clone()).collect(); + assert_eq!(families, [json!("Inter")]); + } + + /// A font applied with Change All becomes Recent's first family. + #[test] + fn change_all_adds_the_new_font_to_recent() { + let mut app = two_font_document(); + open(&mut app); + let used = fonts(&mut app); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("family".into(), json!("Source Serif 4")); + let from = used.iter().find(|f| f["family"] == "Inter").unwrap().clone(); + change(&mut app, &d, &from, true).unwrap(); + let used = fonts(&mut app); + assert_eq!(replacement_families(&app, "recent", &used).unwrap(), ["Source Serif 4", "Inter"]); + } + + /// A Change All that changes no text (the font's only text is locked) leaves Recent as it was. + #[test] + fn a_change_all_that_changes_nothing_leaves_recent_unchanged() { + let mut app = two_font_document(); + app.run("select.font", json!({"family": "Source Serif 4"})).unwrap(); + app.run("object.lock", json!({})).unwrap(); + open(&mut app); + let used = fonts(&mut app); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("family".into(), json!("Source Sans 3")); + let from = used.iter().find(|f| f["family"] == "Source Serif 4").unwrap().clone(); + assert_eq!(change(&mut app, &d, &from, true).unwrap()["runs"], 0); + assert_eq!(app.ui.recent_fonts, ["Inter"]); + } + + /// Change to another name of an installed family records the family's own name in Recent. + #[test] + fn change_records_the_family_s_own_name_in_recent() { + let mut app = two_font_document(); + open(&mut app); + let used = fonts(&mut app); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("family".into(), json!("SourceSerif4-Regular")); + let from = used.iter().find(|f| f["family"] == "Inter").unwrap().clone(); + assert_eq!(change(&mut app, &d, &from, true).unwrap()["runs"], 2); + assert_eq!(app.ui.recent_fonts, ["Source Serif 4", "Inter"]); + } + + #[test] + fn an_empty_recent_list_leaves_nothing_to_change_to() { + let mut app = two_font_document(); + app.ui.recent_fonts.clear(); + open(&mut app); + let used = fonts(&mut app); + let mut d = app.ui.dialog.clone().unwrap(); + set_source(&app, &mut d, "recent", &used); + assert_eq!(replacement_families(&app, "recent", &used).unwrap(), Vec::::new()); + assert_eq!(d.str("family"), ""); + assert!(!can_replace(&d, Some(&[]))); + app.ui.dialog = Some(d); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert!(text.contains("Recent"), "{text}"); + assert_eq!(app.ui.status, ""); + } + + /// Document lists a missing family, but Change and Change All stay off for it, in every list. + #[test] + fn a_missing_document_font_is_listed_but_not_offered_to_change_to() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for (y, font) in [(20, "Missing Family"), (40, "Inter")] { + app.session.execute("text.create", &json!({"x": 10, "y": y, "text": "Hi", "font": font})).unwrap(); + } + open(&mut app); + let used = fonts(&mut app); + let document = replacement_families(&app, "document", &used).unwrap(); + assert!(document.iter().any(|f| f == "Missing Family"), "{document:?}"); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("family".into(), json!("Missing Family")); + set_source(&app, &mut d, "document", &used); + assert_eq!(d.str("family"), "Inter", "the first installed family is chosen"); + assert!(can_replace(&d, Some(&document))); + d.fields.insert("family".into(), json!("Missing Family")); + assert!(!can_replace(&d, Some(&document))); + assert!(!can_replace(&d, None), "System"); + set_source(&app, &mut d, "system", &used); + assert!(can_replace(&d, None), "System chooses an installed family: {}", d.str("family")); + // A document set only in a missing family leaves nothing to change to. + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hi", "font": "Missing Family"})).unwrap(); + let used = fonts(&mut app); + set_source(&app, &mut d, "document", &used); + assert_eq!(d.str("family"), ""); + assert!(!can_replace(&d, replacement_families(&app, "document", &used).as_deref())); + } + + /// An empty Recent list clears the font; System then chooses an installed one again. + #[test] + fn system_after_an_empty_recent_list_chooses_an_installed_font() { + let mut app = two_font_document(); + app.ui.recent_fonts.clear(); + open(&mut app); + let used = fonts(&mut app); + let mut d = app.ui.dialog.clone().unwrap(); + set_source(&app, &mut d, "recent", &used); + assert_eq!(d.str("family"), ""); + set_source(&app, &mut d, "system", &used); + assert_eq!((d.str("family").as_str(), d.str("style").as_str()), ("Source Sans 3", "")); + assert!(can_replace(&d, None)); + } + + /// The dialog opens on System's font: Source Sans 3 when it is installed, otherwise the font + /// menu's first family. + #[test] + fn the_dialog_opens_on_an_installed_font() { + let menu = ["Inter".to_string(), "Source Serif 4".to_string()]; + assert_eq!(system_family_in(|_| true, &menu), "Source Sans 3"); + assert_eq!(system_family_in(|f| f != "Source Sans 3", &menu), "Inter"); + assert_eq!(system_family_in(|_| false, &[]), ""); + let mut app = two_font_document(); + open(&mut app); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!(d.str("family"), system_family()); + assert!(can_replace(&d, None), "{}", d.str("family")); + } + + /// A family that is installed but left out of the font menu (a hidden `.` family that + /// Document lists) cannot be changed to from System. + #[test] + fn system_offers_only_the_font_menu_s_families() { + let menu = ["Inter".to_string()]; + assert!(can_replace_in("inter", |_| true, &menu)); + assert!(!can_replace_in(".Hidden", |_| true, &menu)); + assert!(!can_replace_in("Inter", |_| false, &menu)); + let hidden = vectorcraft_text::FontDb::global().family_list().iter().find(|f| f.starts_with('.') && installed(f)).cloned(); + if let Some(hidden) = hidden { + let mut app = two_font_document(); + open(&mut app); + let used = fonts(&mut app); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("family".into(), json!(hidden)); + assert!(!can_replace(&d, None), "{hidden}"); + set_source(&app, &mut d, "system", &used); + assert_eq!(d.str("family"), system_family()); + } + } + #[test] fn rows_flag_missing_fonts_substituted_styles_and_lacking_characters() { let row = |status: &str, glyphs: u64| json!({"status": status, "resolved": {"style": "W4"}, "missingGlyphs": glyphs}); diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 93ae778e5f..e8fd10b4cc 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -8,7 +8,10 @@ //! Technology filter's Variable lists only variable font families. Preferences › Type › Enable //! in-menu font previews and Font Preview Size turn the samples off or size the rows. Recently //! used families appear first, in the order they were last applied, within the same search and -//! filters as the remaining families. +//! filters as the remaining families. In the Character and Properties panels and the Control bar, +//! the mouse wheel turned over the closed field applies the next family (or previous one) to the +//! selected text, one undo step per notch. The menu's order at the first turn stays fixed until the +//! pointer leaves the field or the text selection changes; steps stop at its first and last family. use std::collections::HashMap; use std::sync::Arc; @@ -33,9 +36,50 @@ pub enum FontPick { EndPreview, /// The star of a family was clicked: add it to the favourites, or take it out. Favorite(String), + /// The mouse wheel turned over the closed field: apply each of these families in turn, one + /// undo step each. + Wheel(Vec), } -/// How the menu looks: from the preferences and the favourites. +/// The UI that contains a font family field. +#[derive(Clone, Copy, Debug)] +pub enum WheelOwner { + Character, + Properties, + Control, + /// The Character popover attached to this Control bar link. + ControlPopover(egui::Id), +} + +impl WheelOwner { + fn visible(self, app: &VectorcraftApp, ctx: &egui::Context) -> bool { + if crate::panels::character::text_style(app).is_none() { + return false; + } + let panel = match self { + Self::Control | Self::ControlPopover(_) | Self::Properties if app.session.tool_id() == "artboard" => return false, + Self::Control => return app.ui.control_bar && app.ui.screen_mode < 2, + Self::ControlPopover(anchor) => { + return app.ui.control_bar && app.ui.screen_mode < 2 && widgets::popover_is_open(ctx, anchor); + } + Self::Character => "character", + Self::Properties => { + let selected = app.session.active().and_then(|document| document.selection.objects.first().and_then(|id| document.doc.node(*id))); + if !selected.is_some_and(|n| matches!(&n.kind, vectorcraft_doc::NodeKind::Text(_))) { + return false; + } + "properties" + } + }; + app.ui.dock + && app.ui.screen_mode < 3 + && (crate::panel_docking::showing(&app.ui, panel) + || (app.ui.transient_panel.as_deref() == Some(panel) && crate::panel_docking::showing(&app.ui, "appearance"))) + } +} + +/// How the menu looks (from the preferences and the favourites) and whether its closed field +/// takes the mouse wheel. #[derive(Clone, Copy, Debug)] pub struct MenuLook<'a> { /// Show each family's sample (Preferences › Type › Enable in-menu font previews). @@ -48,12 +92,17 @@ pub struct MenuLook<'a> { pub favorites: &'a [String], /// Recently applied families, newest first, limited by Number of Recent Fonts. pub recent: &'a [String], + /// The mouse wheel turned over the closed field steps through the families in the menu's + /// order ([`FontPick::Wheel`]): the Character and Properties panels and the Control bar. + pub wheel: bool, + /// Its owner, so a field hidden before the next layout cannot capture wheel input. + pub wheel_owner: Option, } impl Default for MenuLook<'static> { - /// Samples on, English names, medium rows, no favourites. + /// Samples on, English names, medium rows, no favourites, no wheel. fn default() -> Self { - Self { samples: true, english_names: true, row: ROW, favorites: &[], recent: &[] } + Self { samples: true, english_names: true, row: ROW, favorites: &[], recent: &[], wheel: false, wheel_owner: None } } } @@ -70,6 +119,8 @@ impl<'a> MenuLook<'a> { row, favorites: &app.ui.favorite_fonts, recent: app.recent_fonts(), + wheel: false, + wheel_owner: None, } } } @@ -235,6 +286,11 @@ struct MenuState { rows_key: Option, /// The height of the search field and filters last frame. header: f32, + /// The families the wheel steps through, listed at its first notch over the closed field and + /// kept for that text selection while the pointer stays on it: each step makes its family a recent one, which would + /// otherwise move it in the order. + wheel_order: Option>, + wheel_target: Option, } /// The font family menu showing `current`, `width` points wide, rows sampling `sample` (the @@ -249,12 +305,18 @@ pub fn font_menu( ) -> Option { let state_id = ui.scope_id().with(&id).with("font-menu"); let mut st: MenuState = ui.data(|d| d.get_temp(state_id)).unwrap_or_default(); + let target = ui.data(|d| d.get_temp(wheel_fields_id(ui.ctx().viewport_id()).with("target"))); + let target_changed = st.wheel_target != target; + if target_changed { + st.wheel_order = None; + st.wheel_target = target; + } let height = st.header + LIST_HEIGHT; let state = &mut st; // The search field and filters stay in place over the rows, which scroll. The rows are all // one height (a family's styles too), so only those in view are laid out: there are thousands // of families. - let shown = widgets::combo_menu(ui, &id, current, width, |menu| { + let (field, shown) = widgets::combo_menu_field(ui, &id, current, width, |menu| { menu.height(height).show_rows_with_header( |ui| header(ui, state_id, state, current, look), look.row, @@ -263,11 +325,54 @@ pub fn font_menu( ) }); let drawn = shown.is_some(); + if target_changed { + ui.data_mut(|d| d.remove::(field.id.with("wheel"))); + } let mut out = shown.flatten(); if !drawn && out.is_none() && st.previewed.take().is_some() { // Closed (Escape, a click outside) with a preview showing. out = Some(FontPick::EndPreview); } + let turns = remember_owned_wheel_field(ui, &field, look.wheel && !drawn && field.enabled(), state_id, look.wheel_owner); + if !look.wheel || !field.enabled() { + st.wheel_order = None; + ui.data_mut(|d| d.remove::(field.id.with("wheel"))); + } else if out.is_none() || drawn { + if !turns.is_empty() { + let mut own = vectorcraft_text::FontDb::global().canonical(current, "").0; + let mut steps = Vec::new(); + for turn in turns { + match turn { + WheelInput::Leave => st.wheel_order = None, + WheelInput::Notches(notches) => { + if st.wheel_order.is_none() { + st.wheel_order = Some(wheel_order(&st, look).into()); + } + if let Some(order) = st.wheel_order.as_deref() { + let next = wheel_steps(order, &own, notches); + if let Some(last) = next.last() { + own.clone_from(last); + } + steps.extend(next); + } + } + } + } + if !steps.is_empty() { + if drawn { + // These turns preceded the opener. The popup cancels back to the newly + // applied family, and any preview drawn this pass has not been applied. + st.current.clone_from(&own); + st.previewed = None; + } + out = Some(FontPick::Wheel(steps)); + } + } + if drawn || !field.contains_pointer() { + st.wheel_order = None; + ui.data_mut(|d| d.remove::(field.id.with("wheel"))); + } + } if matches!(out, Some(FontPick::Chosen(..))) { st.previewed = None; } @@ -275,6 +380,248 @@ pub fn font_menu( out } +/// Does the menu list family `f` for search `query` (lowercase) under the filters of `st`? +fn listed(db: &vectorcraft_text::FontDb, f: &str, query: &str, st: &MenuState, look: MenuLook) -> bool { + let label = db.family_display_name(f, look.english_names); + if !(query.is_empty() || f.to_lowercase().contains(query) || label.to_lowercase().contains(query)) { + return false; + } + if st.favorites_only && !look.favorites.iter().any(|x| x.eq_ignore_ascii_case(f)) { + return false; + } + if st.script == 0 && st.class.is_none() && !st.variable_only { + return true; + } + let traits = db.family_traits(f); + script_matches(st.script, traits) && st.class.is_none_or(|c| c == traits.class) && (!st.variable_only || traits.variable) +} + +/// The families the closed field's wheel steps through, in the open menu's order with no search: +/// the recent families first, then the others, under the menu's filters. +fn wheel_order(st: &MenuState, look: MenuLook) -> Vec { + let db = vectorcraft_text::FontDb::global(); + let families: Vec<_> = db.menu_family_list().iter().filter(|f| listed(db, f, "", st, look)).cloned().collect(); + grouped_rows(&families, look.recent, &[], |_| vec![]) + .into_iter() + .filter_map(|r| match r { + Row::Family(f) => Some(f), + Row::Heading(_) | Row::Style(..) => None, + }) + .collect() +} + +/// The families `notches` turns of the wheel step to from family `current` in `order`, one per +/// notch: forward (down the menu) when positive, back when negative. The steps stop at either end +/// of the order, and there are none when `current` is not in it. +fn wheel_steps(order: &[String], current: &str, notches: i32) -> Vec { + let Some(at) = order.iter().position(|f| f.eq_ignore_ascii_case(current)) else { return vec![] }; + let last = order.len().saturating_sub(1); + let n = notches.unsigned_abs() as usize; + let to = if notches >= 0 { at.saturating_add(n).min(last) } else { at.saturating_sub(n) }; + if to >= at { order.iter().skip(at + 1).take(to - at).cloned().collect() } else { order.iter().take(at).skip(to).rev().cloned().collect() } +} + +#[derive(Clone)] +enum WheelInput { + Leave, + Notches(i32), +} + +#[derive(Clone, Copy)] +struct WheelField { + id: egui::Id, + menu: egui::Id, + owner: Option, + rect: egui::Rect, + layer: egui::LayerId, +} + +#[derive(Clone, Default)] +struct WheelFields { + pass: u64, + pending_frame: u64, + activation_pass: u64, + activating: Vec, + pointer: Option, + fields: Vec, + pending: HashMap>, +} + +fn wheel_fields_id(viewport: egui::ViewportId) -> egui::Id { + egui::Id::unique("font-wheel-fields").with(viewport) +} + +#[derive(Clone, PartialEq)] +struct WheelTarget { + input: crate::state::InputGeneration, + workspace: u64, + selection: Vec, + range: Option<(vectorcraft_doc::NodeId, usize, usize)>, +} + +/// Pending turns and field rectangles belong to their input target and visible workspace. +pub(crate) fn sync_wheel_target(app: &VectorcraftApp, ctx: &egui::Context, viewport: egui::ViewportId) { + let target = WheelTarget { + input: app.input_generation(), + workspace: app.ui.docking_generation, + selection: app.session.active().map_or_else(Vec::new, |document| document.selection.objects.clone()), + range: crate::panels::character::text_editing(app), + }; + let key = wheel_fields_id(viewport); + let (previous, mut fields) = ctx.data(|d| (d.get_temp::(key.with("target")), d.get_temp::(key))); + if previous.is_some_and(|old| old != target) { + fields = None; + } + let mut hidden = Vec::new(); + if let Some(fields) = &mut fields { + fields.fields.retain(|field| { + if field.owner.is_none_or(|owner| owner.visible(app, ctx)) { + true + } else { + hidden.push(*field); + false + } + }); + for field in &hidden { + fields.pending.remove(&field.id); + } + } + ctx.data_mut(|d| { + if let Some(fields) = fields { + d.insert_temp(key, fields); + } else { + d.remove::(key); + } + for field in hidden { + d.remove::(field.id.with("wheel")); + if let Some(mut state) = d.get_temp::(field.menu) { + state.wheel_order = None; + d.insert_temp(field.menu, state); + } + } + d.insert_temp(key.with("target"), target); + }); +} + +/// Remember the visible closed fields for the next input batch and take this field's turns. +#[cfg(test)] +fn remember_wheel_field(ui: &Ui, resp: &egui::Response, enabled: bool) -> Vec { + remember_owned_wheel_field(ui, resp, enabled, resp.id, None) +} + +fn remember_owned_wheel_field(ui: &Ui, resp: &egui::Response, enabled: bool, menu: egui::Id, owner: Option) -> Vec { + let key = wheel_fields_id(ui.ctx().viewport_id()); + let pass = ui.ctx().cumulative_pass_nr(); + ui.data_mut(|d| { + let mut fields: WheelFields = d.get_temp(key).unwrap_or_default(); + if fields.pass != pass { + fields.pass = pass; + fields.fields.clear(); + } + fields.fields.retain(|f| f.id != resp.id); + if enabled { + fields.fields.push(WheelField { id: resp.id, menu, owner, rect: resp.interact_rect, layer: resp.layer_id }); + } + let turns = fields.pending.remove(&resp.id).unwrap_or_default(); + d.insert_temp(key, fields); + turns + }) +} + +/// Take the closed font fields' wheel events before egui smooths and combines them. Other +/// events stay in the input, so scrolling elsewhere keeps its own delta and event order. +pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { + let key = wheel_fields_id(raw.viewport_id); + let Some(mut fields) = ctx.data(|d| d.get_temp::(key)) else { return }; + if !ctx.input(|i| i.raw.viewports.contains_key(&raw.viewport_id)) { + ctx.data_mut(|d| d.remove::(key)); + return; + } + let frame = ctx.cumulative_frame_nr_for(raw.viewport_id); + let pass = ctx.cumulative_pass_nr_for(raw.viewport_id); + if pass < fields.pass || pass.saturating_sub(fields.pass) > 1 { + fields.fields.clear(); + fields.pointer = None; + } + if fields.pending_frame != frame { + fields.pending_frame = frame; + fields.pending.clear(); + } + let line = ctx.options(|o| o.input_options.line_scroll_speed).max(1.0); + let mut pointer = fields.pointer.or_else(|| ctx.input(|i| i.pointer.latest_pos())); + let over = + |field: &WheelField, point: Option| point.is_some_and(|p| field.rect.contains(p) && ctx.layer_id_at(p) == Some(field.layer)); + // An activation batch belongs to the popup, including a release after a prior press. + if fields.activation_pass != pass { + fields.activation_pass = pass; + fields.activating.clear(); + let pressed = ctx.input(|i| if i.pointer.button_down(egui::PointerButton::Primary) { i.pointer.press_origin() } else { None }); + if let Some(field) = fields.fields.iter().find(|f| over(f, pressed)) { + fields.activating.push(field.id); + } + } + let focused = ctx.memory(|m| m.focused()); + let mut captured = false; + raw.events.retain(|event| { + let opening = match event { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => { + fields.fields.iter().rev().find(|f| over(f, Some(*pos))).map(|f| f.id) + } + egui::Event::Key { key: egui::Key::Enter | egui::Key::Space, pressed: true, .. } if raw.focused => { + focused.filter(|id| fields.fields.iter().any(|f| f.id == *id)) + } + _ => None, + }; + if let Some(id) = opening + && !fields.activating.contains(&id) + { + fields.activating.push(id); + } + match event { + egui::Event::PointerMoved(p) | egui::Event::PointerButton { pos: p, .. } => { + for field in &fields.fields { + if over(field, pointer) && !over(field, Some(*p)) { + ctx.data_mut(|d| d.remove::(field.id.with("wheel"))); + fields.pending.entry(field.id).or_default().push(WheelInput::Leave); + } + } + pointer = Some(*p); + } + egui::Event::PointerGone => { + pointer = None; + for field in &fields.fields { + ctx.data_mut(|d| d.remove::(field.id.with("wheel"))); + fields.pending.entry(field.id).or_default().push(WheelInput::Leave); + } + } + egui::Event::MouseWheel { unit, delta, modifiers, .. } if modifiers.is_none() && delta.y != 0.0 => { + if let Some(field) = fields.fields.iter().rev().find(|f| !fields.activating.contains(&f.id) && over(f, pointer)).copied() { + let id = field.id.with("wheel"); + let mut notches: f32 = ctx.data(|d| d.get_temp(id)).unwrap_or(0.0); + notches -= match unit { + egui::MouseWheelUnit::Point => delta.y / line, + egui::MouseWheelUnit::Line | egui::MouseWheelUnit::Page => delta.y, + }; + let whole = notches.trunc(); + ctx.data_mut(|d| d.insert_temp(id, notches - whole)); + if whole != 0.0 { + fields.pending.entry(field.id).or_default().push(WheelInput::Notches(whole as i32)); + } + captured = true; + return false; + } + } + _ => {} + } + true + }); + fields.pointer = pointer; + ctx.data_mut(|d| d.insert_temp(key, fields)); + if captured { + ctx.request_repaint(); + } +} + /// What the menu's header hands its rows. struct Listed<'s> { st: &'s mut MenuState, @@ -372,7 +719,6 @@ fn header<'s>(ui: &mut Ui, state_id: egui::Id, st: &'s mut MenuState, current: & // as it was before any preview. let current = db.canonical(&st.current, "").0; let current = current.as_str(); - let favorite = |f: &str| look.favorites.iter().any(|x| x.eq_ignore_ascii_case(f)); // The generation is read first: fonts that load meanwhile make the next frame list them. let key: RowsKey = ( query.clone(), @@ -387,21 +733,7 @@ fn header<'s>(ui: &mut Ui, state_id: egui::Id, st: &'s mut MenuState, current: & db.generation(), ); if st.rows_key.as_ref() != Some(&key) { - let wanted = |f: &str| { - let label = db.family_display_name(f, look.english_names); - if !(query.is_empty() || f.to_lowercase().contains(&query) || label.to_lowercase().contains(&query)) { - return false; - } - if st.favorites_only && !favorite(f) { - return false; - } - if st.script == 0 && st.class.is_none() && !st.variable_only { - return true; - } - let traits = db.family_traits(f); - script_matches(st.script, traits) && st.class.is_none_or(|c| c == traits.class) && (!st.variable_only || traits.variable) - }; - let families: Vec<_> = db.menu_family_list().iter().filter(|f| wanted(f)).cloned().collect(); + let families: Vec<_> = db.menu_family_list().iter().filter(|f| listed(db, f, &query, st, look)).cloned().collect(); let rows = grouped_rows(&families, look.recent, &st.expanded, |f| db.styles(f)); // Filter changes (including un-starring a favourite) may remove rows; expanding // another family or a background font scan can insert rows before the highlight. @@ -823,6 +1155,21 @@ pub(crate) fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, pick: FontPic } } FontPick::Favorite(f) => toggle_favorite(app, f), + FontPick::Wheel(families) => { + if previewing { + app.session.cancel_interaction().ok(); + crate::panels::set_pstate(ctx, PREVIEWING, false); + } + crate::panels::character::end_typing(app); + // Each family is its own step, keeping the style when the family has it, else the + // closest it has. + for f in families { + let (cmd, params) = font_command(app, &f, None); + if app.run(cmd, params).is_err() { + break; + } + } + } FontPick::Chosen(f, style) => { if previewing { app.session.cancel_interaction().ok(); @@ -856,7 +1203,7 @@ pub(crate) fn picked(app: &mut VectorcraftApp, pick: Option) -> Option toggle_favorite(app, f); None } - FontPick::Preview(..) | FontPick::EndPreview => None, + FontPick::Preview(..) | FontPick::EndPreview | FontPick::Wheel(_) => None, } } diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index 4fdfc5733c..73db46de30 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -225,6 +225,136 @@ fn expanded_style_rows_do_not_retarget_the_highlight() { assert_eq!(remap_highlight(&after, Some(1), &before), None); } +/// #5253: each wheel notch over the closed field steps one family, down the menu or up it, and the +/// steps stop at its first and last family without going round. +#[test] +fn the_wheel_steps_one_family_per_notch_and_stops_at_the_ends() { + let order: Vec = ["Alpha", "Bravo", "Charlie", "Delta"].map(str::to_string).into(); + let steps = |current, notches| super::wheel_steps(&order, current, notches); + assert_eq!(steps("Bravo", 1), ["Charlie"]); + assert_eq!(steps("bravo", -1), ["Alpha"], "any case"); + assert_eq!(steps("Alpha", 2), ["Bravo", "Charlie"], "a step for each notch"); + assert_eq!(steps("Bravo", 5), ["Charlie", "Delta"], "stops at the last family"); + assert_eq!(steps("Charlie", -5), ["Bravo", "Alpha"], "stops at the first family"); + assert!(steps("Delta", 1).is_empty() && steps("Alpha", -1).is_empty(), "no wrapping"); + assert!(steps("Missing", 1).is_empty() && steps("Bravo", 0).is_empty()); +} + +/// #5253: the wheel follows the open menu's order and filters: the recent families first, then the +/// others in the database's order, under the favourites (and other) filters. +#[test] +fn the_wheel_follows_the_menus_order_and_filters() { + let names = vectorcraft_text::FontDb::global().menu_family_list(); + if names.len() < 3 { + return; + } + let recent = vec![names[2].clone()]; + let look = super::MenuLook { samples: false, recent: &recent, ..Default::default() }; + let order = super::wheel_order(&super::MenuState::default(), look); + assert_eq!(order.first(), Some(&names[2]), "the recent family first"); + // Other tests add fonts to the process-wide database meanwhile: compare places, not neighbours. + let at = |f: &String| order.iter().position(|x| x == f); + assert!(matches!((at(&names[0]), at(&names[1])), (Some(a), Some(b)) if 0 < a && a < b), "then the others in the menu's order"); + assert_eq!(order.iter().filter(|f| **f == names[2]).count(), 1, "once each"); + let favorites = vec![names[0].clone(), names[1].clone()]; + let st = super::MenuState { favorites_only: true, ..Default::default() }; + let order = super::wheel_order(&st, super::MenuLook { favorites: &favorites, ..look }); + assert_eq!(order, favorites, "the favourites filter"); +} + +/// A field removed by a later layout pass must not intercept the next wheel event. +#[test] +fn a_family_field_omitted_from_the_last_pass_leaves_the_wheel_to_its_owner() { + let ctx = egui::Context::default(); + let mut point = egui::Pos2::ZERO; + for _ in 0..3 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let resp = ui.button("Family"); + point = resp.rect.center(); + super::remember_wheel_field(ui, &resp, true); + }); + out.textures_delta.clear(); + } + let mut pass = 0; + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + if pass == 0 { + let resp = ui.button("Family"); + point = resp.rect.center(); + super::remember_wheel_field(ui, &resp, true); + ui.ctx().request_discard("the next pass removes the field"); + } + pass += 1; + }); + out.textures_delta.clear(); + assert!(pass > 1); + let mut raw = egui::RawInput { + events: vec![ + egui::Event::PointerMoved(point), + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ], + ..Default::default() + }; + super::take_raw_wheel(&ctx, &mut raw); + assert!(raw.events.iter().any(|e| matches!(e, egui::Event::MouseWheel { .. }))); +} + +/// Activation leaves later wheel input to the popup; an earlier turn still belongs to the field. +#[test] +fn activating_the_family_popup_leaves_its_wheel_input_available() { + let activations = [None, Some((egui::Key::Enter, egui::Modifiers::NONE)), Some((egui::Key::Space, egui::Modifiers::SHIFT))]; + for activation in activations { + let ctx = egui::Context::default(); + let frame = |events| { + let mut raw = egui::RawInput { events, ..Default::default() }; + super::take_raw_wheel(&ctx, &mut raw); + let mut point = egui::Pos2::ZERO; + let mut out = ctx.run_ui(raw, |ui| { + let resp = ui.button("Family"); + point = resp.rect.center(); + if activation.is_some() { + resp.request_focus(); + } + super::remember_wheel_field(ui, &resp, true); + }); + out.textures_delta.clear(); + point + }; + let mut point = egui::Pos2::ZERO; + for _ in 0..3 { + point = frame(vec![]); + } + let button = + |pressed| egui::Event::PointerButton { pos: point, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let opener = if let Some((key, modifiers)) = activation { + egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers } + } else { + frame(vec![egui::Event::PointerMoved(point), button(true)]); + button(false) + }; + let turn = || egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }; + let mut events = vec![egui::Event::PointerMoved(point)]; + if activation.is_some() { + events.push(turn()); + } + events.extend([opener, turn()]); + let mut raw = egui::RawInput { events, ..Default::default() }; + super::take_raw_wheel(&ctx, &mut raw); + assert_eq!(raw.events.iter().filter(|e| matches!(e, egui::Event::MouseWheel { .. })).count(), 1); + } +} + /// The Font Technology filter's Variable is the font adjective, not the Variables panel's noun. #[test] fn the_variable_filter_is_named_as_fonts_are() { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 073f577150..3bda3f6b84 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1177,6 +1177,7 @@ font-technology Variable Променливи Flip Row Order Обръщане реда на редовете Flip Vertical Вертикално обръщане Float in Window Плаващ прозорец + Float All in Windows Всички в плаващи прозорци Focal Fill Фокусно запълване Focal Stroke Фокусен щрих Folder Папка @@ -1340,6 +1341,10 @@ font-technology Variable Променливи Hard Light Твърда светлина Hard Mix Твърдо смесване Harmony Rules: Правила за хармония: + Segmented color wheel Сегментирано цветово колело + Show smooth color wheel Показване на плавно цветово колело + Show segmented color wheel Показване на сегментирано цветово колело + Show color bars Показване на цветни ленти Harmony Sets Набори от хармонии Height Височина Height: Височина: @@ -1657,6 +1662,8 @@ font-technology Variable Променливи Large Thumbnail View Изглед с големи миниатюри Large Thumbnails Големи миниатюри Lasso Tool Инструмент „Ласо“ + Enclosing Lasso Tool Инструмент „Обхващащо ласо“ + Enclosing Lasso Обхващащо ласо Last Effect: {name} Посл. ефект: {name} Last Effect: {} Посл. ефект: {} Last Effect… Посл. ефект… @@ -1794,6 +1801,7 @@ font-technology Variable Променливи Manually Ръчно Mark as trapped Маркиране като прехванато Mark Older Files as [Converted] When Opened Маркиране на по-стари файлове като [Конвертирани] при отваряне + Use System Defaults for Edit Original Системни настройки по подразбиране за „Редактиране на оригинал“ Marker… Маркер… Marks Маркери Marks and Bleed Маркери и изтичане @@ -1856,6 +1864,7 @@ font-technology Variable Променливи Modify Модифициране Mojikumi Моджикуми Insert Kashidas Вмъкване на кашиди + Kashidas Кашиди Long Дълго Stylistic Стилистично Mojikumi Set Набор Mojikumi @@ -2635,6 +2644,8 @@ digits Malayalam Малаялам Replace Spine Замяна на оста Replace Symbol Замяна на символ Replace With Font Замяна с шрифт + Replace With Font From Замяна с шрифт от + System Система Replaces the saved preset of that name. Заменя записаната предварителна настройка с това име. Replace… Замяна… Require a password to open the document Изискване на парола за отваряне на документа @@ -3306,6 +3317,7 @@ digits Malayalam Малаялам Templates… Шаблони… Text Displayed in Cell: Текст, показван в клетката: Text Export Options Опции за експортиране на текст + Text Fill & Stroke Color Цвят на запълване и щрих на текста Text Fill Color Цвят на запълване на текста Text Import Options Опции за импортиране на текст Text Stroke Color Цвят на щриха на текста @@ -5467,6 +5479,11 @@ theme Appearance Външен вид Export Type: Тип на експортиране: Movie Clip Филмов клип @msg name is empty името е празно +@msg an action is already recording вече се записва действие +@msg no such function key няма такъв функционален клавиш +@msg no such color няма такъв цвят +@msg {_1} cannot be used on Windows {_1} не може да се използва в Windows +@msg more than one action is named “{_1}” повече от едно действие се казва „{_1}“ @msg no symbol named `{n}` няма символ с име `{n}` Smudge Stick… Размазваща пръчка… Smudge Stick Размазваща пръчка @@ -5613,9 +5630,17 @@ axis Y Axis Y ос Action Options… Опции на действието… Action Options Опции на действието Rename Action Преименуване на действие + New Action… Ново действие… + New Action Ново действие + Create New Action Създаване на ново действие + Play Action Изпълнение на действие + Action Set: Набор от действия: + Function Key: Функционален клавиш: + Record Запис Create New Set Създаване на нов набор Stop Global Edit Край на глобалното редактиране Global Edit Options Опции за глобално редактиране + Leave Out of Global Edit Изключване от глобалното редактиране @msg Global Edit works on paths, compound paths, symbol instances and groups of them Глобалното редактиране работи с пътища, съставни пътища, екземпляри на символи и групи от тях Match Съвпадение On Artboards В работните области @@ -6102,3 +6127,14 @@ breakText Glyphs Глифи Create Swatch Legend Създаване на легенда на образците Create Swatch Legend… Създаване на легенда на образците… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Инструменти за текст + Text Tweaker… Настройка на текста… + Text Tweaker Настройка на текста + Attribute: Атрибут: + From: От: + To: До: + Bow Дъга + Spike Връх + Skip Spaces Пропускане на интервалите +@msg The art is too large to copy as a picture: other apps get no PNG of it Графиката е твърде голяма, за да се копира като изображение: другите приложения не получават PNG от нея diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 80e02fbe46..705c5d7e76 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -426,6 +426,7 @@ Variable Font Varijabilni font Text Fill Color Boja ispune teksta Text Stroke Color Boja poteza teksta + Text Fill & Stroke Color Boja ispune i poteza teksta All on Same Layers Sve na istim slojevima Direction Handles Ručke smjera Brush Strokes Potezi četkicom @@ -627,6 +628,7 @@ Cascade Kaskadno Tile Popločaj Float in Window Odvoji u prozor + Float All in Windows Odvoji sve u prozore Consolidate All Windows Objedini sve prozore Workspace Radni prostor Reset Essentials Vrati Osnove na početno @@ -1243,6 +1245,8 @@ lighting Light Svjetlo Hand Ruka Join Tool Alat za spajanje Lasso Tool Alat laso + Enclosing Lasso Tool Alat laso za obuhvatanje + Enclosing Lasso Laso za obuhvatanje Lasso Laso Line Cut Tool Alat za rez linijom Line Graph Tool Alat za linijski grafikon @@ -1826,6 +1830,7 @@ digits Malayalam Malajalam Left-to-Right Paragraph Direction Smjer pasusa s lijeva nadesno Line-end Punctuation Half Width Interpunkcija na kraju reda u pola širine Insert Kashidas Umetni kašide + Kashidas Kašide Long Dugo Stylistic Stilsko Mojikumi Set Mojikumi skup @@ -2625,6 +2630,10 @@ digits Malayalam Malajalam Current Colors Trenutne boje Current Colors (0) Trenutne boje (0) Harmony Rules: Pravila harmonije: + Segmented color wheel Segmentirani kotač boja + Show smooth color wheel Prikaži glatki kotač boja + Show segmented color wheel Prikaži segmentirani kotač boja + Show color bars Prikaži trake boja Harmony Rules Pravila harmonije Keep this row's colors (exclude) Zadrži boje ovog reda (isključi) Limit to Library: Ograniči na biblioteku: @@ -3554,6 +3563,7 @@ theme Appearance Izgled List Preferences Izlistaj postavke Manually Ručno Mark Older Files as [Converted] When Opened Označi starije datoteke kao [Pretvoreno] pri otvaranju + Use System Defaults for Edit Original Koristi sistemske zadane postavke za Uredi original Match User Interface Brightness Uskladi sa svjetlinom korisničkog interfejsa Light Gray Svijetlosiva Medium Gray Srednje siva @@ -3912,6 +3922,8 @@ effect Regular Obično In the selected objects U odabranim objektima Find in Folder… Pronađi u folderu… Replace With Font Zamijeni fontom + Replace With Font From Zamijeni fontom iz + System Sistem — substituted by {style} — zamijenjeno stilom {style} — {n} characters from another font — {n} znakova iz drugog fonta All Scripts Sve skripte @@ -5471,6 +5483,11 @@ mark-style Japanese Japanski Export Type: Vrsta izvoza: Movie Clip Filmski klip @msg name is empty naziv je prazan +@msg an action is already recording akcija se već snima +@msg no such function key nema takve funkcijske tipke +@msg no such color nema takve boje +@msg {_1} cannot be used on Windows {_1} se ne može koristiti na Windowsu +@msg more than one action is named “{_1}” više od jedne akcije ima naziv „{_1}” @msg no symbol named `{n}` nema simbola pod nazivom `{n}` Smudge Stick… Štapić za razmazivanje… Smudge Stick Štapić za razmazivanje @@ -5636,9 +5653,17 @@ axis Y Axis Y osa Action Options… Opcije akcije… Action Options Opcije akcije Rename Action Preimenuj akciju + New Action… Nova akcija… + New Action Nova akcija + Create New Action Napravi novu akciju + Play Action Reprodukuj akciju + Action Set: Skup akcija: + Function Key: Funkcijska tipka: + Record Snimi Create New Set Napravi novi skup Stop Global Edit Zaustavi globalno uređivanje Global Edit Options Opcije globalnog uređivanja + Leave Out of Global Edit Isključi iz globalnog uređivanja Match Podudaranje On Artboards Na radnim pločama All Artboards Sve radne ploče @@ -5647,6 +5672,8 @@ axis Y Axis Y osa @msg select one object odaberite jedan objekat @msg Global Edit works on paths, compound paths, symbol instances and groups of them Globalno uređivanje radi na putanjama, složenim putanjama, instancama simbola i njihovim grupama @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nisu pronađeni slični objekti (rotirane ili zrcaljene kopije se ne podudaraju); promijenite opcije globalnog uređivanja i pokušajte ponovo +@msg Global Edit is off Globalno uređivanje je isključeno +@msg only an object of the Global Edit other than the one it started from can be left out iz globalnog uređivanja može se isključiti samo objekt koji nije onaj od kojeg je počelo @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ili raspon poput 1, 3-5, a ne {v} Add to Symbols Dodaj u simbole Basic Shapes Osnovni oblici @@ -6134,3 +6161,14 @@ shape Open Otvoren Create Swatch Legend Kreiraj legendu uzoraka boja Create Swatch Legend… Kreiraj legendu uzoraka boja… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Alati za tekst + Text Tweaker… Podešavanje teksta… + Text Tweaker Podešavanje teksta + Attribute: Atribut: + From: Od: + To: Do: + Bow Luk + Spike Šiljak + Skip Spaces Preskoči razmake +@msg The art is too large to copy as a picture: other apps get no PNG of it Grafika je prevelika da bi se kopirala kao slika: druge aplikacije ne dobijaju njen PNG diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index b6985fb130..97d2024dde 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1610,6 +1610,7 @@ digits Malayalam Malaiàlam Flip Vertical Inverteix verticalment Flip: Inverteix: Float in Window Flota a la finestra + Float All in Windows Flota-ho tot en finestres Float Panel Flota el panell Float Tool Group Flota el grup d’eines Focal Fill Farciment focal @@ -1697,6 +1698,7 @@ digits Malayalam Malaiàlam Global Adjust Ajust global Global Brush Dimensions Dimensions globals del pinzell Global Edit Options Opcions globals d’edició + Leave Out of Global Edit Exclou de l’edició global Global Process Color Color de procés global Global Process Color, CMYK Color de procés global, CMYK Glow Amount Quantitat de resplendor @@ -1804,6 +1806,10 @@ digits Malayalam Malaiàlam Hard Mix Mescla dura Harmony Rules Regles d’harmonia Harmony Rules: Regles d’harmonia: + Segmented color wheel Roda de color segmentada + Show smooth color wheel Mostra la roda de color contínua + Show segmented color wheel Mostra la roda de color segmentada + Show color bars Mostra les barres de color Harmony Sets Conjunts d’harmonia HDTV 1080p HDTV 1080p HDTV 720p HDTV 720p @@ -1983,6 +1989,7 @@ digits Malayalam Malaiàlam Insert Character Insereix caràcter Insert Inline Symbol Insereix símbol en línia Insert Kashidas Insereix kashides + Kashidas Kashides Insert Special Character Insereix caràcter especial Insert Whitespace Character Insereix caràcter d’espai Inserting, deleting and rotating pages Inserir, suprimir i girar pàgines @@ -2094,6 +2101,8 @@ digits Malayalam Malaiàlam Largest: El més gran: Lasso Llaç Lasso Tool Eina de llaç + Enclosing Lasso Tool Eina de llaç envoltant + Enclosing Lasso Llaç envoltant Last Últim Last Artboard Últim tauler Last commit Últim commit @@ -2324,6 +2333,7 @@ digits Malayalam Malaiàlam Manually Manualment Mark as trapped Marca com a reventat Mark Older Files as [Converted] When Opened Marca els fitxers antics com a [Convertit] en obrir-los + Use System Defaults for Edit Original Utilitza els valors per defecte del sistema per a Edita l’original Marker… Marcador… Marks Marques Marks and Bleed Marques i sangrat @@ -3334,6 +3344,8 @@ digits Malayalam Malaiàlam Replace Spine Reemplaça l’espina Replace Symbol Reemplaça el símbol Replace With Font Reemplaça per un tipus de lletra + Replace With Font From Reemplaça per un tipus de lletra de + System Sistema Replace “{name}”, the file this document was opened from? Voleu reemplaçar “{name}”, el fitxer amb què es va obrir aquest document? Replaces the saved preset of that name. Reemplaça el preajust desat amb aquest nom. Replace… Reemplaça… @@ -3765,6 +3777,13 @@ digits Malayalam Malaiàlam Action Options… Opcions de l’acció… Action Options Opcions de l’acció Rename Action Canvia el nom de l’acció + New Action… Acció nova… + New Action Acció nova + Create New Action Crea una acció nova + Play Action Reprodueix l’acció + Action Set: Conjunt d’accions: + Function Key: Tecla de funció: + Record Enregistra Set Options… Defineix les opcions… Set Preference Defineix la preferència Set Slice Rectangle Defineix el rectangle del tall @@ -4225,6 +4244,7 @@ digits Malayalam Malaiàlam Text Displayed in Cell Text mostrat a la cel·la Text Displayed in Cell: Text mostrat a la cel·la: Text Export Options Opcions d’exportació de text + Text Fill & Stroke Color Color de farciment i traç del text Text Fill Color Color de farciment del text Text Import Options Opcions d’importació de text Text Orientation Orientació del text @@ -5150,6 +5170,11 @@ digits Malayalam Malaiàlam @msg move requires an existing destination panel per moure cal un panell de destinació existent @msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode Els fitxers PSD multicanal no es poden llegir: deseu-los en mode RGB, CMYK o escala de grisos @msg name is empty el nom és buit +@msg an action is already recording ja s’està enregistrant una acció +@msg no such function key no existeix aquesta tecla de funció +@msg no such color no existeix aquest color +@msg {_1} cannot be used on Windows {_1} no es pot fer servir al Windows +@msg more than one action is named “{_1}” més d’una acció es diu “{_1}” @msg name the file poseu un nom al fitxer @msg New Window isn't available yet: a document opens in one window Finestra nova encara no està disponible: un document s’obre en una sola finestra @msg no active document no hi ha cap document actiu @@ -5235,6 +5260,8 @@ digits Malayalam Malaiàlam @msg no selected slice in the image: select slices, or save all of them no hi ha cap tall seleccionat a la imatge: seleccioneu talls o deseu-los tots @msg no selection bounds no hi ha límits de selecció @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again no s’ha trobat cap objecte similar (les còpies girades o reflexades no coincideixen); canvieu les opcions d’edició global i torneu-ho a provar +@msg Global Edit is off L’edició global no està activa +@msg only an object of the Global Edit other than the one it started from can be left out només es pot excloure un objecte de l’edició global que no sigui aquell amb què va començar @msg no slice selected no hi ha cap tall seleccionat @msg no such action no existeix aquesta acció @msg no such action set no existeix aquest conjunt d’accions @@ -5978,6 +6005,11 @@ anchor Points: Punts: Horizontal Scale Escala horitzontal Vertical Scale Escala vertical @msg {label} must be a number from {min} to {max} {label} ha de ser un nombre de {min} a {max} + Character Color Color del caràcter + OpenType Features Funcions OpenType + Stylistic Sets Jocs estilístics +@msg features lists at most {max} tags features admet com a màxim {max} etiquetes +@msg unknown OpenType feature `{t}` funció OpenType desconeguda `{t}` @msg {label} must be a number above 0 and at most {max} {label} ha de ser un nombre superior a 0 i com a màxim {max} @msg no character style `{name}` No s'ha trobat l'estil de caràcter `{name}` @@ -6229,3 +6261,14 @@ breakText Glyphs Glifs Create Swatch Legend Crea una llegenda de mostres Create Swatch Legend… Crea una llegenda de mostres… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Eines de text + Text Tweaker… Ajustador de text… + Text Tweaker Ajustador de text + Attribute: Atribut: + From: De: + To: A: + Bow Arc + Spike Pic + Skip Spaces Omet els espais +@msg The art is too large to copy as a picture: other apps get no PNG of it La il·lustració és massa gran per copiar-la com a imatge: les altres aplicacions no en reben cap PNG diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 367be32b2c..56228845db 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -434,6 +434,7 @@ Variable Font Variabilní písmo Text Fill Color Barva výplně textu Text Stroke Color Barva tahu textu + Text Fill & Stroke Color Barva výplně a tahu textu All on Same Layers Vše ve stejných vrstvách Direction Handles Směrové úchyty Brush Strokes Tahy štětcem @@ -635,6 +636,7 @@ Cascade Do kaskády Tile Vedle sebe Float in Window Uvolnit do samostatného okna + Float All in Windows Uvolnit vše do samostatných oken Consolidate All Windows Sloučit všechna okna Workspace Pracovní prostor Reset Essentials Obnovit Essentials @@ -1264,6 +1266,8 @@ lighting Light Světlo Hand Ručička Join Tool Nástroj Spojení Lasso Tool Nástroj Laso + Enclosing Lasso Tool Nástroj obklopující laso + Enclosing Lasso Obklopující laso Lasso Laso Line Cut Tool Nástroj Řez čarou Line Graph Tool Nástroj Spojnicový graf @@ -1853,6 +1857,7 @@ digits Malayalam Malajálamské Left-to-Right Paragraph Direction Směr odstavce zleva doprava Line-end Punctuation Half Width Interpunkce na konci řádku poloviční šířky Insert Kashidas Vložit kašídy + Kashidas Kašídy Long Dlouhý Stylistic Stylistický Mojikumi Set Sada Mojikumi @@ -2656,6 +2661,10 @@ digits Malayalam Malajálamské Current Colors Aktuální barvy Current Colors (0) Aktuální barvy (0) Harmony Rules: Pravidla harmonie: + Segmented color wheel Segmentované barevné kolo + Show smooth color wheel Zobrazit plynulé barevné kolo + Show segmented color wheel Zobrazit segmentované barevné kolo + Show color bars Zobrazit barevné pruhy Harmony Rules Pravidla harmonie Keep this row's colors (exclude) Ponechat barvy tohoto řádku (vyloučit) Limit to Library: Omezit na knihovnu: @@ -3595,6 +3604,7 @@ theme Appearance Motiv List Preferences Vypsat předvolby Manually Ručně Mark Older Files as [Converted] When Opened Při otevření označit starší soubory jako [Converted] + Use System Defaults for Edit Original Pro Upravit originál použít výchozí aplikace systému Match User Interface Brightness Odpovídat jasu uživatelského rozhraní Light Gray Světle šedá Medium Gray Středně šedá @@ -3954,6 +3964,8 @@ effect Regular Pravidelný In the selected objects Ve vybraných objektech Find in Folder… Najít ve složce… Replace With Font Nahradit písmem + Replace With Font From Nahradit písmem z + System Systém — substituted by {style} — nahrazeno řezem {style} — {n} characters from another font — znaky z jiného písma: {n} All Scripts Všechny systémy písma @@ -5558,6 +5570,11 @@ mark-style Japanese Japonské Export Type: Typ exportu: Movie Clip Filmový klip @msg name is empty název je prázdný +@msg an action is already recording akce se už zaznamenává +@msg no such function key taková funkční klávesa neexistuje +@msg no such color taková barva neexistuje +@msg {_1} cannot be used on Windows Zkratku {_1} nelze ve Windows použít +@msg more than one action is named “{_1}” název „{_1}“ má více než jedna akce @msg no symbol named `{n}` žádný symbol s názvem `{n}` Smudge Stick… Rozmazávací tyčinka… Smudge Stick Rozmazávací tyčinka @@ -5728,9 +5745,17 @@ axis Y Axis osa Y Action Options… Možnosti akce… Action Options Možnosti akce Rename Action Přejmenovat akci + New Action… Nová akce… + New Action Nová akce + Create New Action Vytvořit novou akci + Play Action Přehrát akci + Action Set: Sada akcí: + Function Key: Funkční klávesa: + Record Zaznamenat Create New Set Vytvořit novou sadu Stop Global Edit Ukončit globální úpravy Global Edit Options Možnosti globálních úprav + Leave Out of Global Edit Vyřadit z globálních úprav Match Shoda On Artboards Na pracovních plochách All Artboards Všechny pracovní plochy @@ -5739,6 +5764,8 @@ axis Y Axis osa Y @msg select one object vyberte jeden objekt @msg Global Edit works on paths, compound paths, symbol instances and groups of them Globální úpravy pracují s cestami, složenými cestami, instancemi symbolů a jejich skupinami @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nebyly nalezeny žádné podobné objekty (otočené a zrcadlené kopie se nevyhledávají); změňte možnosti globálních úprav a zkuste to znovu +@msg Global Edit is off Globální úpravy nejsou zapnuté +@msg only an object of the Global Edit other than the one it started from can be left out z globálních úprav lze vyřadit jen jiný objekt než ten, od kterého začaly @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all nebo rozsah, například 1, 3-5, ne {v} Add to Symbols Přidat do symbolů Basic Shapes Základní tvary @@ -5994,6 +6021,11 @@ anchor Points: Body: Horizontal Scale Vodorovná změna velikosti Vertical Scale Svislá změna velikosti @msg {label} must be a number from {min} to {max} {label} musí být číslo od {min} do {max} + Character Color Barva znaků + OpenType Features Funkce OpenType + Stylistic Sets Stylistické sady +@msg features lists at most {max} tags features obsahuje nejvýše {max} značek +@msg unknown OpenType feature `{t}` neznámá funkce OpenType `{t}` @msg {label} must be a number above 0 and at most {max} {label} musí být číslo větší než 0 a nejvýše {max} @msg no character style `{name}` styl znaků `{name}` neexistuje @@ -6243,3 +6275,14 @@ breakText Glyphs Glyfy Create Swatch Legend Vytvořit legendu vzorníku Create Swatch Legend… Vytvořit legendu vzorníku… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Nástroje textu + Text Tweaker… Ladění textu… + Text Tweaker Ladění textu + Attribute: Atribut: + From: Od: + To: Do: + Bow Oblouk + Spike Špička + Skip Spaces Přeskočit mezery +@msg The art is too large to copy as a picture: other apps get no PNG of it Kresba je příliš velká na zkopírování jako obrázek: ostatní aplikace z ní nedostanou PNG diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 7b077a50ad..8556ae44ec 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -393,6 +393,7 @@ Variable Font Variabel skrifttype Text Fill Color Tekstfyldfarve Text Stroke Color Tekststregfarve + Text Fill & Stroke Color Tekstfyld- og stregfarve All on Same Layers Alt på samme lag Direction Handles Retningshåndtag Brush Strokes Penselstrøg @@ -585,6 +586,7 @@ Cascade Kaskade Tile Fliselæg Float in Window Flyd i vindue + Float All in Windows Flyd alle i vinduer Consolidate All Windows Saml alle vinduer Workspace Arbejdsområde Reset Essentials Nulstil Essentials @@ -1177,6 +1179,8 @@ lighting Light Lys Hand Hånd Join Tool Sammenføjningsværktøj Lasso Tool Lassoværktøj + Enclosing Lasso Tool Omsluttende lassoværktøj + Enclosing Lasso Omsluttende lasso Lasso Lasso Line Cut Tool Linjeskæringsværktøj Line Graph Tool Linjediagramværktøj @@ -1658,6 +1662,7 @@ digits Malayalam Malayalam Left-to-Right Paragraph Direction Afsnitsretning fra venstre mod højre Line-end Punctuation Half Width Skilletegn i halv bredde ved linjeslut Insert Kashidas Indsæt kashidaer + Kashidas Kashidaer Long Lang Stylistic Stilistisk Mojikumi Set Mojikumi-sæt @@ -2443,6 +2448,10 @@ digits Malayalam Malayalam Current Colors Aktuelle farver Current Colors (0) Aktuelle farver (0) Harmony Rules: Harmoniregler: + Segmented color wheel Segmenteret farvehjul + Show smooth color wheel Vis glat farvehjul + Show segmented color wheel Vis segmenteret farvehjul + Show color bars Vis farvebjælker Harmony Rules Harmoniregler Keep this row's colors (exclude) Behold farverne i denne række (ekskludér) Limit to Library: Begræns til bibliotek: @@ -3322,6 +3331,7 @@ theme Appearance Udseende List Preferences Oplist indstillinger Manually Manuelt Mark Older Files as [Converted] When Opened Markér ældre filer som [konverteret] ved åbning + Use System Defaults for Edit Original Anvend systemets standarder til Redigér original Match User Interface Brightness Match lysstyrken i brugergrænsefladen Light Gray Lysegrå Medium Gray Mellemgrå @@ -3674,6 +3684,8 @@ effect Regular Regular In the selected objects I de markerede objekter Find in Folder… Find i mappe… Replace With Font Erstat med skrifttype + Replace With Font From Erstat med skrifttype fra + System System — substituted by {style} — erstattet af {style} — {n} characters from another font — {n} tegn fra en anden skrifttype All Scripts Alle scripts @@ -5351,6 +5363,11 @@ swatch Bright Violet Kraftig violet Export Type: Eksporttype: Movie Clip Filmklip @msg name is empty navnet er tomt +@msg an action is already recording en handling optages allerede +@msg no such function key ingen sådan funktionstast +@msg no such color ingen sådan farve +@msg {_1} cannot be used on Windows {_1} kan ikke bruges i Windows +@msg more than one action is named “{_1}” mere end én handling hedder »{_1}« @msg no symbol named `{n}` intet symbol med navnet `{n}` Remove Color Profile… Fjern farveprofil… Color wheel Farvehjul @@ -5630,9 +5647,17 @@ axis Y Axis Y-akse Action Options… Indstillinger for handling… Action Options Indstillinger for handling Rename Action Omdøb handling + New Action… Ny handling… + New Action Ny handling + Create New Action Opret ny handling + Play Action Afspil handling + Action Set: Handlingssæt: + Function Key: Funktionstast: + Record Optag Create New Set Opret nyt sæt Stop Global Edit Stop global redigering Global Edit Options Indstillinger for global redigering + Leave Out of Global Edit Udelad fra global redigering @msg Global Edit works on paths, compound paths, symbol instances and groups of them Global redigering virker på stier, sammensatte stier, symbolforekomster og grupper af dem Match Match On Artboards På tegneflader @@ -6118,3 +6143,14 @@ breakText Glyphs Glyffer Create Swatch Legend Opret farveprøveforklaring Create Swatch Legend… Opret farveprøveforklaring… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Tekstværktøjer + Text Tweaker… Tekstjustering… + Text Tweaker Tekstjustering + Attribute: Attribut: + From: Fra: + To: Til: + Bow Bue + Spike Spids + Skip Spaces Spring mellemrum over +@msg The art is too large to copy as a picture: other apps get no PNG of it Grafikken er for stor til at blive kopieret som et billede: andre programmer får ingen PNG af den diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c87b45d229..11793dc22b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1208,6 +1208,7 @@ file-filter Templates Vorlagen Flip Row Order Zeilenreihenfolge umkehren Flip Vertical Vertikal spiegeln Float in Window In eigenem Fenster anzeigen + Float All in Windows Alle in eigenen Fenstern anzeigen Focal Fill Fläche im Fokus Focal Stroke Kontur im Fokus Folder Ordner @@ -1371,6 +1372,10 @@ file-filter Templates Vorlagen Hard Light Hartes Licht Hard Mix Hart mischen Harmony Rules: Harmonieregeln: + Segmented color wheel Segmentierter Farbkreis + Show smooth color wheel Stufenlosen Farbkreis anzeigen + Show segmented color wheel Segmentierten Farbkreis anzeigen + Show color bars Farbbalken anzeigen Harmony Sets Harmoniesätze Height Höhe Height: Höhe: @@ -1705,6 +1710,8 @@ file-filter Templates Vorlagen Large Thumbnail View Große Miniaturansicht Large Thumbnails Große Miniaturen Lasso Tool Lasso-Werkzeug + Enclosing Lasso Tool Umschließendes Lasso-Werkzeug + Enclosing Lasso Umschließendes Lasso Last Effect: {name} Letzter Effekt: {name} Last Effect: {} Letzter Effekt: {} Last Effect… Letzter Effekt… @@ -1856,6 +1863,7 @@ file-filter Templates Vorlagen Manually Manuell Mark as trapped Als überfüllt kennzeichnen Mark Older Files as [Converted] When Opened Ältere Dateien beim Öffnen als [Konvertiert] kennzeichnen + Use System Defaults for Edit Original Systemstandards für „Original bearbeiten“ verwenden Marker… Markierung… Marks Marken Marks and Bleed Marken und Anschnitt @@ -1918,6 +1926,7 @@ file-filter Templates Vorlagen Modify Ändern Mojikumi Mojikumi Insert Kashidas Kashidas einfügen + Kashidas Kashidas Long Lang Stylistic Stilistisch Mojikumi Set Mojikumi-Satz @@ -2662,6 +2671,8 @@ digits Malayalam Malayalam Replace Spine Achse ersetzen Replace Symbol Symbol ersetzen Replace With Font Durch Schrift ersetzen + Replace With Font From Ersetzende Schrift aus + System System Replaces the saved preset of that name. Ersetzt die gespeicherte Vorgabe dieses Namens. Replace… Ersetzen… Require a password to open the document Kennwort zum Öffnen des Dokuments verlangen @@ -3334,6 +3345,7 @@ effect Points Punkte Templates… Vorlagen… Text Displayed in Cell: In der Zelle angezeigter Text: Text Export Options Textexportoptionen + Text Fill & Stroke Color Flächen- und Konturfarbe des Texts Text Fill Color Flächenfarbe des Texts Text Import Options Textimportoptionen Text Stroke Color Konturfarbe des Texts @@ -5136,6 +5148,11 @@ effect Soft Weich Export Type: Exporttyp: Movie Clip Movieclip @msg name is empty Name ist leer +@msg an action is already recording eine Aktion wird bereits aufgezeichnet +@msg no such function key keine solche Funktionstaste +@msg no such color keine solche Farbe +@msg {_1} cannot be used on Windows {_1} kann unter Windows nicht verwendet werden +@msg more than one action is named “{_1}” mehr als eine Aktion heißt „{_1}“ @msg no symbol named `{n}` kein Symbol namens `{n}` Smudge Stick… Wischstift… Smudge Stick Wischstift @@ -5310,9 +5327,17 @@ axis Y Axis Y-Achse Action Options… Aktionsoptionen… Action Options Aktionsoptionen Rename Action Aktion umbenennen + New Action… Neue Aktion… + New Action Neue Aktion + Create New Action Neue Aktion erstellen + Play Action Aktion abspielen + Action Set: Aktionssatz: + Function Key: Funktionstaste: + Record Aufzeichnen Create New Set Neuen Satz erstellen Stop Global Edit Globale Bearbeitung beenden Global Edit Options Optionen für globale Bearbeitung + Leave Out of Global Edit Von globaler Bearbeitung ausschließen Match Übereinstimmung On Artboards Auf Zeichenflächen All Artboards Alle Zeichenflächen @@ -5321,6 +5346,8 @@ axis Y Axis Y-Achse @msg select one object wählen Sie ein Objekt aus @msg Global Edit works on paths, compound paths, symbol instances and groups of them Globale Bearbeitung funktioniert mit Pfaden, zusammengesetzten Pfaden, Symbolinstanzen und Gruppen daraus @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again keine ähnlichen Objekte gefunden (gedrehte oder gespiegelte Kopien werden nicht erkannt); ändern Sie die Optionen für globale Bearbeitung und versuchen Sie es erneut +@msg Global Edit is off Globale Bearbeitung ist nicht aktiv +@msg only an object of the Global Edit other than the one it started from can be left out nur ein Objekt der globalen Bearbeitung außer dem, mit dem sie begonnen hat, kann ausgeschlossen werden @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all oder ein Bereich wie 1, 3-5, nicht {v} Add to Symbols Zu Symbolen hinzufügen Basic Shapes Grundformen @@ -5579,6 +5606,11 @@ anchor Points: Punkte: Horizontal Scale Horizontale Skalierung Vertical Scale Vertikale Skalierung @msg {label} must be a number from {min} to {max} {label} muss eine Zahl von {min} bis {max} sein + Character Color Zeichenfarbe + OpenType Features OpenType-Funktionen + Stylistic Sets Stilsätze +@msg features lists at most {max} tags features enthält höchstens {max} Tags +@msg unknown OpenType feature `{t}` unbekannte OpenType-Funktion `{t}` @msg {label} must be a number above 0 and at most {max} {label} muss eine Zahl über 0 und höchstens {max} sein @msg no character style `{name}` Zeichenformat `{name}` nicht gefunden @@ -5829,3 +5861,14 @@ breakText Glyphs Glyphen Create Swatch Legend Farbfeldlegende erstellen Create Swatch Legend… Farbfeldlegende erstellen… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Textwerkzeuge + Text Tweaker… Text-Tweaker… + Text Tweaker Text-Tweaker + Attribute: Attribut: + From: Von: + To: Bis: + Bow Bogen + Spike Spitze + Skip Spaces Leerzeichen überspringen +@msg The art is too large to copy as a picture: other apps get no PNG of it Das Bildmaterial ist zu groß, um es als Bild zu kopieren: Andere Apps erhalten kein PNG davon diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 615e0e6ee0..687a4a8e88 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1150,6 +1150,7 @@ font-technology Variable Μεταβλητές Flip Row Order Αντιστροφή σειράς γραμμών Flip Vertical Κατακόρυφη αναστροφή Float in Window Μετατροπή σε ανεξάρτητο παράθυρο + Float All in Windows Μετατροπή όλων σε ανεξάρτητα παράθυρα Focal Fill Εστιακό γέμισμα Focal Stroke Εστιακό περίγραμμα Folder Φάκελος @@ -1310,6 +1311,10 @@ font-technology Variable Μεταβλητές Hard Light Έντονο φως Hard Mix Έντονη ανάμειξη Harmony Rules: Κανόνες χρωματικής αρμονίας: + Segmented color wheel Τμηματοποιημένος χρωματικός τροχός + Show smooth color wheel Εμφάνιση ομαλού χρωματικού τροχού + Show segmented color wheel Εμφάνιση τμηματοποιημένου χρωματικού τροχού + Show color bars Εμφάνιση χρωματικών ράβδων Harmony Sets Σύνολα χρωματικής αρμονίας Height Ύψος Height: Ύψος: @@ -1615,6 +1620,8 @@ font-technology Variable Μεταβλητές Large Thumbnail View Προβολή μεγάλων μικρογραφιών Large Thumbnails Μεγάλες μικρογραφίες Lasso Tool Λάσο (Lasso Tool) + Enclosing Lasso Tool Εργαλείο περικλείοντος λάσου + Enclosing Lasso Περικλείον λάσο Last Effect: {name} Τελευταίο εφέ: {name} Last Effect: {} Τελευταίο εφέ: {} Last Effect… Τελευταίο εφέ… @@ -2646,6 +2653,7 @@ theme Appearance Εμφάνιση Manually Χειροκίνητα Mark as trapped Σήμανση ως επικαλυπτόμενου Mark Older Files as [Converted] When Opened Σήμανση παλαιότερων αρχείων ως [Μετατράπηκε] κατά το άνοιγμα + Use System Defaults for Edit Original Χρήση προεπιλογών συστήματος για την Επεξεργασία πρωτοτύπου Marker… Δείκτης… Marks Σημάδια Marks and Bleed Σημάδια και ξάκρισμα @@ -2692,6 +2700,7 @@ theme Appearance Εμφάνιση Modified: Τροποποιήθηκε: Mojikumi Mojikumi Insert Kashidas Εισαγωγή κασίντα + Kashidas Κασίντα Long Μακρύ Stylistic Στιλιστικό Mojikumi Set Σύνολο Mojikumi @@ -3258,6 +3267,8 @@ digits Malayalam Μαλαγιάλαμ Replace Spine Αντικατάσταση κεντρικής καμπύλης Replace Symbol Αντικατάσταση συμβόλου Replace With Font Αντικατάσταση με γραμματοσειρά + Replace With Font From Αντικατάσταση με γραμματοσειρά από + System Σύστημα Replaces the saved preset of that name. Αντικαθιστά την αποθηκευμένη προεπιλογή με αυτό το όνομα. Require a password to open the document Απαίτηση κωδικού για το άνοιγμα εγγράφου Reset Bounding Box Επαναφορά πλαισίου οριοθέτησης @@ -3727,6 +3738,7 @@ digits Malayalam Μαλαγιάλαμ Templates Folder Φάκελος προτύπων Text Displayed in Cell: Κείμενο που εμφανίζεται στο κελί: Text Export Options Επιλογές εξαγωγής κειμένου + Text Fill & Stroke Color Χρώμα γεμίσματος και περιγράμματος κειμένου Text Fill Color Χρώμα γεμίσματος κειμένου Text Import Options Επιλογές εισαγωγής κειμένου Text Stroke Color Χρώμα περιγράμματος κειμένου @@ -5509,6 +5521,11 @@ effect Points Σημεία Export Type: Τύπος εξαγωγής: Movie Clip Κλιπ ταινίας @msg name is empty το όνομα είναι κενό +@msg an action is already recording μια ενέργεια καταγράφεται ήδη +@msg no such function key δεν υπάρχει τέτοιο πλήκτρο λειτουργίας +@msg no such color δεν υπάρχει τέτοιο χρώμα +@msg {_1} cannot be used on Windows Το {_1} δεν μπορεί να χρησιμοποιηθεί στα Windows +@msg more than one action is named “{_1}” περισσότερες από μία ενέργειες ονομάζονται «{_1}» @msg no symbol named `{n}` κανένα σύμβολο με όνομα `{n}` Smudge Stick… Μουτζούρα… Smudge Stick Μουτζούρα @@ -5679,9 +5696,17 @@ axis Y Axis Άξονας Y Action Options… Επιλογές ενέργειας… Action Options Επιλογές ενέργειας Rename Action Μετονομασία ενέργειας + New Action… Νέα ενέργεια… + New Action Νέα ενέργεια + Create New Action Δημιουργία νέας ενέργειας + Play Action Αναπαραγωγή ενέργειας + Action Set: Σύνολο ενεργειών: + Function Key: Πλήκτρο λειτουργίας: + Record Καταγραφή Create New Set Δημιουργία νέου συνόλου Stop Global Edit Τερματισμός καθολικής επεξεργασίας Global Edit Options Επιλογές καθολικής επεξεργασίας + Leave Out of Global Edit Εξαίρεση από την καθολική επεξεργασία Match Αντιστοίχιση On Artboards Σε πίνακες σχεδίασης All Artboards Όλοι οι πίνακες σχεδίασης @@ -5690,6 +5715,8 @@ axis Y Axis Άξονας Y @msg select one object επιλέξτε ένα αντικείμενο @msg Global Edit works on paths, compound paths, symbol instances and groups of them Η καθολική επεξεργασία λειτουργεί σε διαδρομές, σύνθετες διαδρομές, παρουσίες συμβόλων και ομάδες τους @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again δεν βρέθηκαν παρόμοια αντικείμενα (τα περιστραμμένα ή κατοπτρισμένα αντίγραφα δεν εντοπίζονται)· αλλάξτε τις επιλογές καθολικής επεξεργασίας και δοκιμάστε ξανά +@msg Global Edit is off Η καθολική επεξεργασία δεν είναι ενεργή +@msg only an object of the Global Edit other than the one it started from can be left out μπορεί να εξαιρεθεί μόνο ένα αντικείμενο της καθολικής επεξεργασίας εκτός από εκείνο με το οποίο ξεκίνησε @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ή ένα εύρος όπως 1, 3-5, όχι {v} Add to Symbols Προσθήκη στα σύμβολα Basic Shapes Βασικά σχήματα @@ -5945,6 +5972,11 @@ anchor Points: Σημεία: Horizontal Scale Οριζόντια κλίμακα Vertical Scale Κατακόρυφη κλίμακα @msg {label} must be a number from {min} to {max} Το {label} πρέπει να είναι αριθμός από {min} έως {max} + Character Color Χρώμα χαρακτήρων + OpenType Features Χαρακτηριστικά OpenType + Stylistic Sets Στιλιστικά σύνολα +@msg features lists at most {max} tags Το features περιέχει έως {max} ετικέτες +@msg unknown OpenType feature `{t}` άγνωστο χαρακτηριστικό OpenType `{t}` @msg {label} must be a number above 0 and at most {max} Το {label} πρέπει να είναι αριθμός μεγαλύτερος από 0 και έως {max} @msg no character style `{name}` Δεν βρέθηκε το στυλ χαρακτήρων `{name}` @@ -6195,3 +6227,14 @@ breakText Glyphs Γλύφοι Create Swatch Legend Δημιουργία υπομνήματος δειγμάτων χρωμάτων Create Swatch Legend… Δημιουργία υπομνήματος δειγμάτων χρωμάτων… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Εργαλεία κειμένου + Text Tweaker… Ρύθμιση κειμένου… + Text Tweaker Ρύθμιση κειμένου + Attribute: Ιδιότητα: + From: Από: + To: Έως: + Bow Τόξο + Spike Αιχμή + Skip Spaces Παράλειψη κενών +@msg The art is too large to copy as a picture: other apps get no PNG of it Το γραφικό είναι πολύ μεγάλο για αντιγραφή ως εικόνα: οι άλλες εφαρμογές δεν λαμβάνουν PNG του diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c4d4a196b6..eb0aeaeaba 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1226,6 +1226,7 @@ font-technology Variable Variables Flip Row Order Invertir orden de filas Flip Vertical Voltear verticalmente Float in Window Flotar en ventana + Float All in Windows Flotar todo en ventanas Focal Fill Relleno focal Focal Stroke Trazo focal Folder Carpeta @@ -1389,6 +1390,10 @@ font-technology Variable Variables Hard Light Luz fuerte Hard Mix Mezcla definida Harmony Rules: Reglas de armonía: + Segmented color wheel Rueda de color segmentada + Show smooth color wheel Mostrar rueda de color continua + Show segmented color wheel Mostrar rueda de color segmentada + Show color bars Mostrar barras de color Harmony Sets Conjuntos de armonía Height Altura Height: Altura: @@ -1708,6 +1713,8 @@ font-technology Variable Variables Large Thumbnail View Vista de miniaturas grandes Large Thumbnails Miniaturas grandes Lasso Tool Herramienta Lazo + Enclosing Lasso Tool Herramienta Lazo envolvente + Enclosing Lasso Lazo envolvente Last Effect: {name} Último efecto: {name} Last Effect: {} Último efecto: {} Last Effect… Último efecto… @@ -1859,6 +1866,7 @@ font-technology Variable Variables Manually Manualmente Mark as trapped Marcar como reventado Mark Older Files as [Converted] When Opened Marcar archivos antiguos como [Convertido] al abrirlos + Use System Defaults for Edit Original Usar valores predeterminados del sistema para Editar original Marker… Marcador… Marks Marcas Marks and Bleed Marcas y sangrado @@ -1921,6 +1929,7 @@ font-technology Variable Variables Modify Modificar Mojikumi Mojikumi Insert Kashidas Insertar kashidas + Kashidas Kashidas Long Larga Stylistic Estilística Mojikumi Set Conjunto de mojikumi @@ -2705,6 +2714,8 @@ digits Malayalam Malayálam Replace Spine Reemplazar eje Replace Symbol Reemplazar símbolo Replace With Font Reemplazar con fuente + Replace With Font From Reemplazar con fuente de + System Sistema Replaces the saved preset of that name. Reemplaza el preajuste guardado con ese nombre. Replace… Reemplazar… Require a password to open the document Solicitar una contraseña para abrir el documento @@ -3390,6 +3401,7 @@ digits Malayalam Malayálam Templates… Plantillas… Text Displayed in Cell: Texto mostrado en la celda: Text Export Options Opciones de exportación de texto + Text Fill & Stroke Color Color de relleno y trazo del texto Text Fill Color Color de relleno del texto Text Import Options Opciones de importación de texto Text Stroke Color Color de trazo del texto @@ -5499,6 +5511,11 @@ mark-style Japanese Japonesas Export Type: Tipo de exportación: Movie Clip Clip de película @msg name is empty el nombre está vacío +@msg an action is already recording ya se está grabando una acción +@msg no such function key no existe esa tecla de función +@msg no such color no existe ese color +@msg {_1} cannot be used on Windows {_1} no se puede usar en Windows +@msg more than one action is named “{_1}” más de una acción se llama “{_1}” @msg no symbol named `{n}` no hay ningún símbolo llamado `{n}` Smudge Stick… Difuminar con barra… Smudge Stick Difuminar con barra @@ -5669,9 +5686,17 @@ axis Y Axis Eje Y Action Options… Opciones de acción… Action Options Opciones de acción Rename Action Cambiar nombre de acción + New Action… Nueva acción… + New Action Nueva acción + Create New Action Crear nueva acción + Play Action Reproducir acción + Action Set: Conjunto de acciones: + Function Key: Tecla de función: + Record Grabar Create New Set Crear nuevo conjunto Stop Global Edit Detener edición global Global Edit Options Opciones de edición global + Leave Out of Global Edit Excluir de la edición global Match Coincidir On Artboards En mesas de trabajo All Artboards Todas las mesas de trabajo @@ -5680,6 +5705,8 @@ axis Y Axis Eje Y @msg select one object seleccione un objeto @msg Global Edit works on paths, compound paths, symbol instances and groups of them La edición global funciona con trazados, trazados compuestos, instancias de símbolos y grupos de ellos @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again no se encontraron objetos similares (las copias giradas o reflejadas no coinciden); cambie las opciones de edición global e inténtelo de nuevo +@msg Global Edit is off La edición global no está activa +@msg only an object of the Global Edit other than the one it started from can be left out solo se puede excluir un objeto de la edición global distinto de aquel con el que empezó @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all o un intervalo como 1, 3-5, no {v} Add to Symbols Agregar a símbolos Basic Shapes Formas básicas @@ -5936,6 +5963,11 @@ anchor Points: Puntos: Horizontal Scale Escala horizontal Vertical Scale Escala vertical @msg {label} must be a number from {min} to {max} {label} debe ser un número de {min} a {max} + Character Color Color de los caracteres + OpenType Features Funciones OpenType + Stylistic Sets Conjuntos estilísticos +@msg features lists at most {max} tags features admite como máximo {max} etiquetas +@msg unknown OpenType feature `{t}` función OpenType desconocida `{t}` @msg {label} must be a number above 0 and at most {max} {label} debe ser un número mayor que 0 y como máximo {max} @msg no character style `{name}` No existe el estilo de carácter `{name}` @@ -6185,3 +6217,14 @@ breakText Glyphs Glifos Create Swatch Legend Crear leyenda de muestras Create Swatch Legend… Crear leyenda de muestras… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Herramientas de texto + Text Tweaker… Ajustador de texto… + Text Tweaker Ajustador de texto + Attribute: Atributo: + From: Desde: + To: Hasta: + Bow Arco + Spike Pico + Skip Spaces Omitir espacios +@msg The art is too large to copy as a picture: other apps get no PNG of it La ilustración es demasiado grande para copiarla como imagen: las demás aplicaciones no reciben un PNG de ella diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 7d571168f5..806ad1dbd7 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -431,6 +431,7 @@ Variable Font Muuttuva fontti Text Fill Color Tekstin täyttöväri Text Stroke Color Tekstin viivan väri + Text Fill & Stroke Color Tekstin täytön ja viivan väri All on Same Layers Kaikki samoilla tasoilla Direction Handles Suuntakahvat Brush Strokes Sivellinviivat @@ -626,6 +627,7 @@ Cascade Porrasta Tile Vierekkäin Float in Window Kelluta ikkunassa + Float All in Windows Kelluta kaikki ikkunoissa Consolidate All Windows Yhdistä kaikki ikkunat Workspace Työtila Reset Essentials Palauta Essentials @@ -1240,6 +1242,8 @@ lighting Light Valo Hand Käsi Join Tool Liitostyökalu Lasso Tool Lassotyökalu + Enclosing Lasso Tool Sulkeva lassotyökalu + Enclosing Lasso Sulkeva lasso Lasso Lasso Line Cut Tool Viivaleikkaustyökalu Line Graph Tool Viivakaaviotyökalu @@ -1814,6 +1818,7 @@ digits Malayalam Malajalam Left-to-Right Paragraph Direction Kappaleen suunta vasemmalta oikealle Line-end Punctuation Half Width Rivinlopun välimerkit puolileveinä Insert Kashidas Lisää kashidat + Kashidas Kashidat Long Pitkä Stylistic Tyylitelty Mojikumi Set Mojikumi-joukko @@ -2600,6 +2605,10 @@ digits Malayalam Malajalam Current Colors Nykyiset värit Current Colors (0) Nykyiset värit (0) Harmony Rules: Harmoniasäännöt: + Segmented color wheel Segmentoitu väriympyrä + Show smooth color wheel Näytä liukuva väriympyrä + Show segmented color wheel Näytä segmentoitu väriympyrä + Show color bars Näytä väripalkit Harmony Rules Harmoniasäännöt Keep this row's colors (exclude) Säilytä tämän rivin värit (jätä pois) Limit to Library: Rajoita kirjastoon: @@ -3519,6 +3528,7 @@ theme Appearance Ulkoasu List Preferences Luettele asetukset Manually Manuaalisesti Mark Older Files as [Converted] When Opened Merkitse vanhemmat tiedostot [Muunnettu] avattaessa + Use System Defaults for Edit Original Käytä järjestelmän oletuksia toiminnossa Muokkaa alkuperäistä Match User Interface Brightness Sovita käyttöliittymän kirkkauteen Light Gray Vaaleanharmaa Medium Gray Keskiharmaa @@ -3873,6 +3883,8 @@ effect Regular Normaali In the selected objects Valituissa objekteissa Find in Folder… Etsi kansiosta… Replace With Font Korvaa fontilla + Replace With Font From Korvaavan fontin lähde + System Järjestelmä — substituted by {style} — korvattu tyylillä {style} — {n} characters from another font — {n} merkkiä toisesta fontista All Scripts Kaikki kirjoitusjärjestelmät @@ -5521,6 +5533,11 @@ mark-style Japanese Japanilainen Export Type: Vientityyppi: Movie Clip Elokuvaleike @msg name is empty nimi on tyhjä +@msg an action is already recording toimintoa nauhoitetaan jo +@msg no such function key toimintonäppäintä ei ole +@msg no such color väriä ei ole +@msg {_1} cannot be used on Windows {_1} ei ole käytettävissä Windowsissa +@msg more than one action is named “{_1}” useamman kuin yhden toiminnon nimi on ”{_1}” @msg no symbol named `{n}` symbolia nimeltä `{n}` ei ole Smudge Stick… Sumennuskynä… Smudge Stick Sumennuskynä @@ -5758,9 +5775,17 @@ axis Y Axis Y-akseli Action Options… Toiminnon asetukset… Action Options Toiminnon asetukset Rename Action Nimeä toiminto uudelleen + New Action… Uusi toiminto… + New Action Uusi toiminto + Create New Action Luo uusi toiminto + Play Action Toista toiminto + Action Set: Toimintosarja: + Function Key: Toimintonäppäin: + Record Nauhoita Create New Set Luo uusi sarja Stop Global Edit Lopeta yleismuokkaus Global Edit Options Yleismuokkauksen asetukset + Leave Out of Global Edit Jätä pois yleismuokkauksesta Match Vastaavuus On Artboards Piirtoalustoilla All Artboards Kaikki piirtoalustat @@ -5769,6 +5794,8 @@ axis Y Axis Y-akseli @msg select one object valitse yksi objekti @msg Global Edit works on paths, compound paths, symbol instances and groups of them Yleismuokkaus toimii poluille, yhdistelmäpoluille, symbolien esiintymille ja niiden ryhmille @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again samankaltaisia objekteja ei löytynyt (kierrettyjä tai peilattuja kopioita ei tunnisteta); muuta yleismuokkauksen asetuksia ja yritä uudelleen +@msg Global Edit is off Yleismuokkaus ei ole käynnissä +@msg only an object of the Global Edit other than the one it started from can be left out yleismuokkauksesta voi jättää pois vain muun objektin kuin sen, josta se alkoi @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all tai alue, kuten 1, 3-5, ei {v} Add to Symbols Lisää symboleihin Basic Shapes Perusmuodot @@ -6024,6 +6051,11 @@ anchor Points: Pisteet: Horizontal Scale Vaakaskaalaus Vertical Scale Pystyskaalaus @msg {label} must be a number from {min} to {max} {label} on oltava luku {min} ja {max} väliltä + Character Color Merkin väri + OpenType Features OpenType-ominaisuudet + Stylistic Sets Tyylisarjat +@msg features lists at most {max} tags features sisältää enintään {max} tunnistetta +@msg unknown OpenType feature `{t}` tuntematon OpenType-ominaisuus `{t}` @msg {label} must be a number above 0 and at most {max} {label} on oltava luku, joka on yli 0 ja enintään {max} @msg no character style `{name}` Merkkityyliä `{name}` ei löytynyt @@ -6273,3 +6305,14 @@ breakText Glyphs Merkit Create Swatch Legend Luo värimallien selite Create Swatch Legend… Luo värimallien selite… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Tekstityökalut + Text Tweaker… Tekstin säätö… + Text Tweaker Tekstin säätö + Attribute: Määrite: + From: Alku: + To: Loppu: + Bow Kaari + Spike Piikki + Skip Spaces Ohita välilyönnit +@msg The art is too large to copy as a picture: other apps get no PNG of it Grafiikka on liian suuri kopioitavaksi kuvana: muut sovellukset eivät saa siitä PNG-kuvaa diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4372280dbd..f646102576 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1220,6 +1220,7 @@ font-technology Variable Variables Flip Row Order Inverser l’ordre des lignes Flip Vertical Retourner verticalement Float in Window Flottant dans une fenêtre + Float All in Windows Tout flottant dans des fenêtres Focal Fill Fond actif Focal Stroke Contour actif Folder Dossier @@ -1382,6 +1383,10 @@ font-technology Variable Variables Handles Poignées Hard Light Lumière crue Hard Mix Mélange maximal + Segmented color wheel Roue chromatique segmentée + Show smooth color wheel Afficher la roue chromatique continue + Show segmented color wheel Afficher la roue chromatique segmentée + Show color bars Afficher les barres de couleur Harmony Rules: Règles d’harmonie : Harmony Sets Ensembles d’harmonies Height Hauteur @@ -1702,6 +1707,8 @@ font-technology Variable Variables Large Thumbnail View Grandes vignettes Large Thumbnails Grandes vignettes Lasso Tool Outil Lasso + Enclosing Lasso Tool Outil Lasso englobant + Enclosing Lasso Lasso englobant Last Effect: {name} Dernier effet : {name} Last Effect: {} Dernier effet : {} Last Effect… Dernier effet… @@ -1853,6 +1860,7 @@ font-technology Variable Variables Manually Manuellement Mark as trapped Marquer comme grossi-maigri Mark Older Files as [Converted] When Opened Marquer les anciens fichiers comme [Converti] à l’ouverture + Use System Defaults for Edit Original Utiliser les applications par défaut du système pour Modifier l’original Marker… Marqueur… Marks Repères Marks and Bleed Repères et fond perdu @@ -1915,6 +1923,7 @@ font-technology Variable Variables Modify Modifier Mojikumi Mojikumi Insert Kashidas Insérer des kashidas + Kashidas Kashidas Long Longue Stylistic Stylistique Mojikumi Set Jeu de mojikumi @@ -2697,6 +2706,8 @@ digits Malayalam Malayalam Replace Spine Remplacer la dorsale Replace Symbol Remplacer le symbole Replace With Font Remplacer par la police + Replace With Font From Remplacer par une police de + System Système Replaces the saved preset of that name. Remplace le paramètre prédéfini enregistré sous ce nom. Replace… Remplacer… Require a password to open the document Exiger un mot de passe pour ouvrir le document @@ -3382,6 +3393,7 @@ digits Malayalam Malayalam Templates… Modèles… Text Displayed in Cell: Texte affiché dans la cellule : Text Export Options Options d’exportation du texte + Text Fill & Stroke Color Couleur de fond et de contour du texte Text Fill Color Couleur de fond du texte Text Import Options Options d’importation du texte Text Stroke Color Couleur de contour du texte @@ -5553,6 +5565,11 @@ theme Appearance Apparence Export Type: Type d'exportation : Movie Clip Clip @msg name is empty le nom est vide +@msg an action is already recording un script est déjà en cours d’enregistrement +@msg no such function key touche de fonction inexistante +@msg no such color couleur inexistante +@msg {_1} cannot be used on Windows {_1} ne peut pas être utilisé sous Windows +@msg more than one action is named “{_1}” plusieurs scripts s’appellent « {_1} » @msg no symbol named `{n}` aucun symbole nommé `{n}` Smudge Stick… Estompe… Smudge Stick Estompe @@ -5723,9 +5740,17 @@ axis Y Axis Axe Y Action Options… Options de script… Action Options Options de script Rename Action Renommer le script + New Action… Nouveau script… + New Action Nouveau script + Create New Action Créer un script + Play Action Exécuter le script + Action Set: Jeu de scripts : + Function Key: Touche de fonction : + Record Enregistrer Create New Set Créer un jeu Stop Global Edit Arrêter la modification globale Global Edit Options Options de modification globale + Leave Out of Global Edit Exclure de la modification globale Match Correspondance On Artboards Sur les plans de travail All Artboards Tous les plans de travail @@ -5734,6 +5759,8 @@ axis Y Axis Axe Y @msg select one object sélectionnez un seul objet @msg Global Edit works on paths, compound paths, symbol instances and groups of them La modification globale s’applique aux tracés, aux tracés transparents, aux occurrences de symboles et aux groupes de ces objets @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again aucun objet similaire trouvé (les copies pivotées ou symétriques ne sont pas reconnues) ; modifiez les options de modification globale et réessayez +@msg Global Edit is off La modification globale n’est pas active +@msg only an object of the Global Edit other than the one it started from can be left out seul un objet de la modification globale autre que celui à partir duquel elle a commencé peut être exclu @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards` : all ou une plage telle que 1, 3-5, et non {v} Add to Symbols Ajouter aux symboles Basic Shapes Formes de base @@ -5989,6 +6016,11 @@ anchor Points: Points : Horizontal Scale Mise à l’échelle horizontale Vertical Scale Échelle verticale @msg {label} must be a number from {min} to {max} {label} doit être un nombre compris entre {min} et {max} + Character Color Couleur des caractères + OpenType Features Fonctions OpenType + Stylistic Sets Jeux stylistiques +@msg features lists at most {max} tags features contient au plus {max} balises +@msg unknown OpenType feature `{t}` fonction OpenType inconnue `{t}` @msg {label} must be a number above 0 and at most {max} {label} doit être un nombre supérieur à 0 et au plus égal à {max} @msg no character style `{name}` Style de caractère `{name}` introuvable @@ -6238,3 +6270,14 @@ breakText Glyphs Glyphes Create Swatch Legend Créer une légende des nuances Create Swatch Legend… Créer une légende des nuances… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Outils de texte + Text Tweaker… Ajusteur de texte… + Text Tweaker Ajusteur de texte + Attribute: Attribut : + From: De : + To: À : + Bow Arc + Spike Pointe + Skip Spaces Ignorer les espaces +@msg The art is too large to copy as a picture: other apps get no PNG of it L’illustration est trop grande pour être copiée en tant qu’image : les autres applications n’en reçoivent pas de PNG diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9890ecf5a9..d5c9f279ad 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1528,6 +1528,7 @@ file-filter Templates Sablonok Flip Vertical Függőleges tükrözés Flip: Tükrözés: Float in Window Lebegtetés ablakban + Float All in Windows Összes lebegtetése ablakokban Float Panel Panel lebegtetése Float Tool Group Eszközcsoport lebegtetése Focal Fill Aktív kitöltés @@ -1771,6 +1772,10 @@ file-filter Templates Sablonok Hard Mix Kemény keverés Harmony Rules Harmóniaszabályok Harmony Rules: Harmóniaszabályok: + Segmented color wheel Szegmentált színkör + Show smooth color wheel Folytonos színkör megjelenítése + Show segmented color wheel Szegmentált színkör megjelenítése + Show color bars Színsávok megjelenítése Harmony Sets Harmóniakészletek HDTV 1080p HDTV 1080p HDTV 720p HDTV 720p @@ -2151,6 +2156,8 @@ file-filter Templates Sablonok Largest: Legnagyobb: Lasso Lasszó Lasso Tool Lasszó + Enclosing Lasso Tool Körülzáró lasszó + Enclosing Lasso Körülzáró lasszó Last Utolsó Last commit Utolsó commit Last Effect: {name} Legutóbbi effektus: {name} @@ -2346,6 +2353,7 @@ file-filter Templates Sablonok Manually Kézzel Mark as trapped Megjelölés csapdázottként Mark Older Files as [Converted] When Opened Régebbi fájlok megjelölése [Átalakítva] címkével megnyitáskor + Use System Defaults for Edit Original Rendszer alapértelmezéseinek használata az Eredeti szerkesztéséhez Marker… Jelölő… Marks Jelek Marks and Bleed Jelek és kifutó @@ -2432,6 +2440,7 @@ file-filter Templates Sablonok Modify Módosítás Mojikumi Mojikumi Insert Kashidas Kasidák beszúrása + Kashidas Kasidák Long Hosszú Stylistic Stilisztikai Mojikumi Set Mojikumi-készlet @@ -3231,6 +3240,8 @@ mark-style Japanese Japán Replace Spine Gerinc cseréje Replace Symbol Szimbólum cseréje Replace With Font Helyettesítő betűtípus + Replace With Font From Helyettesítő betűtípus forrása + System Rendszer Replace “{name}”, the file this document was opened from? Felülírod ezt a fájlt, amelyből a dokumentumot megnyitottad: „{name}”? Replaces the saved preset of that name. Felülírja az azonos nevű mentett előbeállítást. Replace… Csere… @@ -4043,6 +4054,7 @@ mark-style Japanese Japán Text Displayed in Cell A cellában megjelenő szöveg Text Displayed in Cell: A cellában megjelenő szöveg: Text Export Options Szövegexportálási beállítások + Text Fill & Stroke Color Szöveg kitöltő- és körvonalszíne Text Fill Color Szöveg kitöltőszíne Text Import Options Szövegimportálási beállítások Text Stroke Color Szöveg körvonalszíne @@ -5541,6 +5553,11 @@ imageTrace Outline Körvonal Export Type: Exportálás típusa: Movie Clip Mozgóklip @msg name is empty a név üres +@msg an action is already recording már folyik egy művelet felvétele +@msg no such function key nincs ilyen funkcióbillentyű +@msg no such color nincs ilyen szín +@msg {_1} cannot be used on Windows A(z) {_1} nem használható Windows rendszeren +@msg more than one action is named “{_1}” több művelet neve is „{_1}” @msg no symbol named `{n}` nincs `{n}` nevű szimbólum Smudge Stick… Elmosó rúd… Smudge Stick Elmosó rúd @@ -5711,9 +5728,17 @@ axis Y Axis Y tengely Action Options… Művelet beállításai… Action Options Művelet beállításai Rename Action Művelet átnevezése + New Action… Új művelet… + New Action Új művelet + Create New Action Új művelet létrehozása + Play Action Művelet lejátszása + Action Set: Műveletkészlet: + Function Key: Funkcióbillentyű: + Record Felvétel Create New Set Új készlet létrehozása Stop Global Edit Globális szerkesztés befejezése Global Edit Options Globális szerkesztés beállításai + Leave Out of Global Edit Kizárás a globális szerkesztésből Match Egyezés On Artboards Rajztáblákon All Artboards Minden rajztábla @@ -5722,6 +5747,8 @@ axis Y Axis Y tengely @msg select one object jelöljön ki egy objektumot @msg Global Edit works on paths, compound paths, symbol instances and groups of them A globális szerkesztés útvonalakon, összetett útvonalakon, szimbólumpéldányokon és ezek csoportjain működik @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nem található hasonló objektum (az elforgatott vagy tükrözött másolatok nem számítanak egyezésnek); módosítsa a globális szerkesztés beállításait, és próbálja újra +@msg Global Edit is off A globális szerkesztés nincs bekapcsolva +@msg only an object of the Global Edit other than the one it started from can be left out a globális szerkesztésből csak a kiindulási objektumtól eltérő objektum zárható ki @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all vagy egy tartomány, például 1, 3-5, nem {v} Add to Symbols Hozzáadás a szimbólumokhoz Basic Shapes Alapalakzatok @@ -5978,6 +6005,11 @@ anchor Points: Pontok: Horizontal Scale Vízszintes méretezés Vertical Scale Függőleges méretezés @msg {label} must be a number from {min} to {max} {label} {min} és {max} közötti szám kell legyen + Character Color Karakterszín + OpenType Features OpenType-funkciók + Stylistic Sets Stíluskészletek +@msg features lists at most {max} tags a features legfeljebb {max} címkét tartalmazhat +@msg unknown OpenType feature `{t}` ismeretlen OpenType-funkció: `{t}` @msg {label} must be a number above 0 and at most {max} {label} 0-nál nagyobb és legfeljebb {max} értékű szám kell legyen @msg no character style `{name}` A(z) `{name}` karakterstílus nem található @@ -6227,3 +6259,14 @@ breakText Glyphs Glifák Create Swatch Legend Színmintajelmagyarázat létrehozása Create Swatch Legend… Színmintajelmagyarázat létrehozása… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Szövegeszközök + Text Tweaker… Szöveghangoló… + Text Tweaker Szöveghangoló + Attribute: Jellemző: + From: Ettől: + To: Eddig: + Bow Ív + Spike Csúcs + Skip Spaces Szóközök kihagyása +@msg The art is too large to copy as a picture: other apps get no PNG of it A grafika túl nagy ahhoz, hogy képként másolható legyen: más alkalmazások nem kapnak róla PNG-t diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index d8ceeacad7..3e784fe339 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -393,6 +393,7 @@ Variable Font Font variabel Text Fill Color Warna isian teks Text Stroke Color Warna stroke teks + Text Fill & Stroke Color Warna isian & stroke teks All on Same Layers Semua di lapisan yang sama Direction Handles Gagang arah Brush Strokes Sapuan kuas @@ -585,6 +586,7 @@ Cascade Bertingkat Tile Ubin Float in Window Mengambang di jendela + Float All in Windows Mengambangkan semua di jendela Consolidate All Windows Konsolidasikan semua jendela Workspace Ruang kerja Reset Essentials Atur ulang Essentials @@ -1177,6 +1179,8 @@ lighting Light Cahaya Hand Tangan Join Tool Alat sambung Lasso Tool Alat lasso + Enclosing Lasso Tool Alat laso pengeliling + Enclosing Lasso Laso pengeliling Lasso Lasso Line Cut Tool Alat potong garis Line Graph Tool Alat grafik garis @@ -1658,6 +1662,7 @@ digits Malayalam Malayalam Left-to-Right Paragraph Direction Arah paragraf kiri ke kanan Line-end Punctuation Half Width Tanda baca akhir baris lebar setengah Insert Kashidas Sisipkan kashida + Kashidas Kashida Long Panjang Stylistic Stilistik Mojikumi Set Set Mojikumi @@ -2443,6 +2448,10 @@ digits Malayalam Malayalam Current Colors Warna saat ini Current Colors (0) Warna saat ini (0) Harmony Rules: Aturan harmoni: + Segmented color wheel Roda warna bersegmen + Show smooth color wheel Tampilkan roda warna halus + Show segmented color wheel Tampilkan roda warna bersegmen + Show color bars Tampilkan bilah warna Harmony Rules Aturan harmoni Keep this row's colors (exclude) Pertahankan warna baris ini (kecualikan) Limit to Library: Batasi ke pustaka: @@ -3322,6 +3331,7 @@ theme Appearance Tampilan List Preferences Daftarkan preferensi Manually Secara manual Mark Older Files as [Converted] When Opened Tandai file lama sebagai [Converted] saat dibuka + Use System Defaults for Edit Original Gunakan default sistem untuk Edit asli Match User Interface Brightness Sesuaikan dengan kecerahan antarmuka pengguna Light Gray Abu-abu terang Medium Gray Abu-abu sedang @@ -3674,6 +3684,8 @@ effect Regular Reguler In the selected objects Di objek yang dipilih Find in Folder… Temukan di folder… Replace With Font Ganti dengan font + Replace With Font From Ganti dengan font dari + System Sistem — substituted by {style} — digantikan oleh {style} — {n} characters from another font — {n} karakter dari font lain All Scripts Semua skrip @@ -5351,6 +5363,11 @@ swatch Bright Violet Violet cerah Export Type: Jenis ekspor: Movie Clip Klip film @msg name is empty nama kosong +@msg an action is already recording sebuah tindakan sedang direkam +@msg no such function key tidak ada tombol fungsi seperti itu +@msg no such color tidak ada warna seperti itu +@msg {_1} cannot be used on Windows {_1} tidak dapat digunakan di Windows +@msg more than one action is named “{_1}” lebih dari satu tindakan bernama “{_1}” @msg no symbol named `{n}` tidak ada simbol bernama `{n}` Remove Color Profile… Hapus profil warna… Color wheel Roda warna @@ -5630,9 +5647,17 @@ axis Y Axis Sumbu Y Action Options… Opsi tindakan… Action Options Opsi tindakan Rename Action Ganti nama tindakan + New Action… Tindakan baru… + New Action Tindakan baru + Create New Action Buat tindakan baru + Play Action Putar tindakan + Action Set: Set tindakan: + Function Key: Tombol fungsi: + Record Rekam Create New Set Buat set baru Stop Global Edit Hentikan edit global Global Edit Options Opsi edit global + Leave Out of Global Edit Keluarkan dari edit global @msg Global Edit works on paths, compound paths, symbol instances and groups of them Edit global berfungsi pada jalur, jalur gabungan, instans simbol, dan grupnya Match Cocokkan On Artboards Di artboard @@ -6118,3 +6143,14 @@ breakText Glyphs Glif Create Swatch Legend Buat Legenda Swatch Create Swatch Legend… Buat Legenda Swatch… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Alat Teks + Text Tweaker… Penyetel Teks… + Text Tweaker Penyetel Teks + Attribute: Atribut: + From: Dari: + To: Ke: + Bow Busur + Spike Puncak + Skip Spaces Lewati Spasi +@msg The art is too large to copy as a picture: other apps get no PNG of it Gambar terlalu besar untuk disalin sebagai gambar: aplikasi lain tidak mendapatkan PNG darinya diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 1f6ffb4cf5..c95b9d71d5 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1238,6 +1238,7 @@ file-filter Templates Modelli Flip Row Order Inverti ordine delle righe Flip Vertical Capovolgi verticalmente Float in Window Rendi mobile nella finestra + Float All in Windows Rendi tutto mobile nelle finestre Focal Fill Riempimento attivo Focal Stroke Traccia attiva Folder Cartella @@ -1401,6 +1402,10 @@ file-filter Templates Modelli Hard Light Luce intensa Hard Mix Miscela intensa Harmony Rules: Regole di armonia: + Segmented color wheel Ruota dei colori segmentata + Show smooth color wheel Mostra ruota dei colori continua + Show segmented color wheel Mostra ruota dei colori segmentata + Show color bars Mostra barre di colore Harmony Sets Gruppi di armonia Height Altezza Height: Altezza: @@ -1737,6 +1742,8 @@ file-filter Templates Modelli Large Thumbnail View Vista miniature grandi Large Thumbnails Miniature grandi Lasso Tool Strumento Lazo + Enclosing Lasso Tool Strumento Lazo di inclusione + Enclosing Lasso Lazo di inclusione Last Effect: {name} Ultimo effetto: {name} Last Effect: {} Ultimo effetto: {} Last Effect… Ultimo effetto… @@ -1888,6 +1895,7 @@ file-filter Templates Modelli Manually Manualmente Mark as trapped Contrassegna come sottoposto a trapping Mark Older Files as [Converted] When Opened Contrassegna i file meno recenti come [Convertito] all'apertura + Use System Defaults for Edit Original Usa le impostazioni predefinite di sistema per Modifica originale Marker… Indicatore… Marks Segni Marks and Bleed Segni e abbondanza @@ -1950,6 +1958,7 @@ file-filter Templates Modelli Modify Modifica Mojikumi Mojikumi Insert Kashidas Inserisci kashida + Kashidas Kashida Long Lunga Stylistic Stilistica Mojikumi Set Set mojikumi @@ -2738,6 +2747,8 @@ digits Malayalam Malayalam Replace Spine Sostituisci dorsale Replace Symbol Sostituisci simbolo Replace With Font Sostituisci con font + Replace With Font From Sostituisci con font da + System Sistema Replaces the saved preset of that name. Sostituisce il preset salvato con quel nome. Replace… Sostituisci… Require a password to open the document Richiedi una password per aprire il documento @@ -3426,6 +3437,7 @@ digits Malayalam Malayalam Templates… Modelli… Text Displayed in Cell: Testo visualizzato nella cella: Text Export Options Opzioni di esportazione testo + Text Fill & Stroke Color Colore riempimento e traccia testo Text Fill Color Colore riempimento testo Text Import Options Opzioni di importazione testo Text Stroke Color Colore traccia testo @@ -5171,6 +5183,11 @@ lighting Light Luce Export Type: Tipo di esportazione: Movie Clip Clip filmato @msg name is empty il nome è vuoto +@msg an action is already recording è già in corso la registrazione di un’azione +@msg no such function key tasto funzione inesistente +@msg no such color colore inesistente +@msg {_1} cannot be used on Windows {_1} non può essere usato su Windows +@msg more than one action is named “{_1}” più di un’azione si chiama “{_1}” @msg no symbol named `{n}` nessun simbolo denominato `{n}` Smudge Stick… Sfumino… Smudge Stick Sfumino @@ -5344,9 +5361,17 @@ axis Y Axis Asse Y Action Options… Opzioni azione… Action Options Opzioni azione Rename Action Rinomina azione + New Action… Nuova azione… + New Action Nuova azione + Create New Action Crea nuova azione + Play Action Esegui azione + Action Set: Set di azioni: + Function Key: Tasto funzione: + Record Registra Create New Set Crea nuovo set Stop Global Edit Interrompi modifica globale Global Edit Options Opzioni modifica globale + Leave Out of Global Edit Escludi dalla modifica globale Match Corrispondenza On Artboards Sulle tavole da disegno All Artboards Tutte le tavole da disegno @@ -5355,6 +5380,8 @@ axis Y Axis Asse Y @msg select one object selezionate un oggetto @msg Global Edit works on paths, compound paths, symbol instances and groups of them La modifica globale funziona su tracciati, tracciati composti, istanze di simboli e gruppi di essi @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nessun oggetto simile trovato (le copie ruotate o riflesse non vengono riconosciute); cambiate le opzioni di modifica globale e riprovate +@msg Global Edit is off La modifica globale non è attiva +@msg only an object of the Global Edit other than the one it started from can be left out si può escludere solo un oggetto della modifica globale diverso da quello da cui è partita @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all o un intervallo come 1, 3-5, non {v} Add to Symbols Aggiungi ai simboli Basic Shapes Forme di base @@ -5613,6 +5640,11 @@ anchor Points: Punti: Horizontal Scale Scala orizzontale Vertical Scale Scala verticale @msg {label} must be a number from {min} to {max} {label} deve essere un numero da {min} a {max} + Character Color Colore carattere + OpenType Features Funzioni OpenType + Stylistic Sets Set stilistici +@msg features lists at most {max} tags features contiene al massimo {max} tag +@msg unknown OpenType feature `{t}` funzione OpenType sconosciuta `{t}` @msg {label} must be a number above 0 and at most {max} {label} deve essere un numero maggiore di 0 e al massimo {max} @msg no character style `{name}` Stile di carattere `{name}` non trovato @@ -5863,3 +5895,14 @@ breakText Glyphs Glifi Create Swatch Legend Crea legenda campioni Create Swatch Legend… Crea legenda campioni… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Strumenti testo + Text Tweaker… Regolatore testo… + Text Tweaker Regolatore testo + Attribute: Attributo: + From: Da: + To: A: + Bow Arco + Spike Picco + Skip Spaces Salta gli spazi +@msg The art is too large to copy as a picture: other apps get no PNG of it La grafica è troppo grande per essere copiata come immagine: le altre app non ne ricevono un PNG diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 3d6849e46c..eb3d1fc5e9 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -71,6 +71,7 @@ digits Malayalam マラヤーラム数字 Join Our Discord Discord に参加 Line-end Punctuation Half Width 行末約物半角 Insert Kashidas カシーダを挿入 + Kashidas カシーダ Long 長い Stylistic スタイリスティック Mojikumi Set 文字組み @@ -463,6 +464,7 @@ digits Malayalam マラヤーラム数字 Variable Font バリアブルフォント Text Fill Color テキストカラー (塗り) Text Stroke Color テキストカラー (線) + Text Fill & Stroke Color テキストカラー (塗りと線) All on Same Layers 同じレイヤー上のすべて Direction Handles 方向線ハンドル Brush Strokes ブラシストローク @@ -647,6 +649,7 @@ digits Malayalam マラヤーラム数字 Cascade 重ねて表示 Tile 並べて表示 Float in Window ウィンドウを分離 + Float All in Windows すべてをウィンドウに分離 Consolidate All Windows すべてのウィンドウを統合 Workspace ワークスペース Reset Essentials 初期設定をリセット @@ -1725,6 +1728,10 @@ digits Malayalam マラヤーラム数字 Hard Light ハードライト Hard Mix ハードミックス Harmony Rules: ハーモニールール: + Segmented color wheel 分割カラーホイール + Show smooth color wheel 滑らかなカラーホイールを表示 + Show segmented color wheel 分割カラーホイールを表示 + Show color bars カラーバーを表示 Height 高さ Height: 高さ: Help › Search Commands… ヘルプ › コマンドを検索… @@ -1985,6 +1992,8 @@ digits Malayalam マラヤーラム数字 Large 大 Large Tabs 大きいタブ Lasso Tool なげなわツール + Enclosing Lasso Tool 囲みなげなわツール + Enclosing Lasso 囲みなげなわ Last Effect: {name} 最後の効果:{name} Last Page 最後のページ Layer Options… レイヤーオプション… @@ -2088,6 +2097,7 @@ digits Malayalam マラヤーラム数字 Manage Workspaces ワークスペースを管理 Manually 手動 Mark Older Files as [Converted] When Opened 古いファイルを開くときに[変換]と表示 + Use System Defaults for Edit Original 「オリジナルを編集」にシステムのデフォルトを使用 Mark as trapped トラップ済みとしてマーク Marks トンボ Match User Interface Brightness ユーザーインターフェイスの明るさに合わせる @@ -2722,6 +2732,8 @@ mark-style Japanese 日本式 Replace Font フォントを置換 Replace Symbol シンボルを置き換え Replace With Font 置換するフォント + Replace With Font From 置換するフォントの一覧 + System システム Replace it with another file, or ignore it: its images keep showing the preview saved with the document. 別のファイルに置き換えるか、無視してください。無視した場合、画像にはドキュメントに保存されたプレビューが表示され続けます。 Replaces the saved preset of that name. 同じ名前の保存済みプリセットを置き換えます。 Replace… 置換… @@ -5214,6 +5226,11 @@ lighting Light ライト Export Type: 書き出しタイプ: Movie Clip ムービークリップ @msg name is empty 名前が空です +@msg an action is already recording すでにアクションを記録中です +@msg no such function key 指定されたファンクションキーが見つかりません +@msg no such color 指定されたカラーが見つかりません +@msg {_1} cannot be used on Windows {_1} は Windows では使用できません +@msg more than one action is named “{_1}” 「{_1}」という名前のアクションが複数あります @msg no symbol named `{n}` `{n}` という名前のシンボルはありません Smudge Stick… スマッジスティック… Smudge Stick スマッジスティック @@ -5409,9 +5426,17 @@ axis Y Axis Y 軸 Action Options… アクションオプション… Action Options アクションオプション Rename Action アクション名を変更 + New Action… 新規アクション… + New Action 新規アクション + Create New Action 新規アクションを作成 + Play Action アクションを再生 + Action Set: アクションセット: + Function Key: ファンクションキー: + Record 記録 Create New Set 新規セットを作成 Stop Global Edit グローバル編集を終了 Global Edit Options グローバル編集オプション + Leave Out of Global Edit グローバル編集から除外 Match 一致 On Artboards アートボード上 All Artboards すべてのアートボード @@ -5420,6 +5445,8 @@ axis Y Axis Y 軸 @msg select one object オブジェクトを 1 つ選択してください @msg Global Edit works on paths, compound paths, symbol instances and groups of them グローバル編集はパス、複合パス、シンボルインスタンスとそれらのグループに使用できます @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again 類似するオブジェクトが見つかりません(回転または反転したコピーは一致しません)。グローバル編集オプションを変更してもう一度試してください +@msg Global Edit is off グローバル編集はオフです +@msg only an object of the Global Edit other than the one it started from can be left out 除外できるのは、グローバル編集を開始したオブジェクト以外のオブジェクトだけです @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all または 1, 3-5 のような範囲を指定してください ({v} ではなく) Add to Symbols シンボルに追加 Basic Shapes 基本シェイプ @@ -5678,6 +5705,11 @@ anchor Points: ポイント: Horizontal Scale 水平比率 Vertical Scale 垂直比率 @msg {label} must be a number from {min} to {max} {label} には {min} から {max} までの数値を指定してください + Character Color 文字カラー + OpenType Features OpenType 機能 + Stylistic Sets スタイルセット +@msg features lists at most {max} tags features に指定できるタグは {max} 個までです +@msg unknown OpenType feature `{t}` 不明な OpenType 機能 `{t}` @msg {label} must be a number above 0 and at most {max} {label} には 0 より大きく {max} 以下の数値を指定してください @msg no character style `{name}` 文字スタイル `{name}` が見つかりません @@ -5928,3 +5960,14 @@ breakText Glyphs 字形 Create Swatch Legend スウォッチの凡例を作成 Create Swatch Legend… スウォッチの凡例を作成… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools テキストツール + Text Tweaker… テキストの調整… + Text Tweaker テキストの調整 + Attribute: 属性: + From: 開始: + To: 終了: + Bow 弓形 + Spike 山形 + Skip Spaces スペースをスキップ +@msg The art is too large to copy as a picture: other apps get no PNG of it アートワークが大きすぎるため画像としてコピーできません:他のアプリには PNG が渡されません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 1a01580e2e..a504987b65 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -350,6 +350,7 @@ Font Size შრიფტის ზომა Text Fill Color ტექსტის შევსების ფერი Text Stroke Color ტექსტის კონტურის ფერი + Text Fill & Stroke Color ტექსტის შევსებისა და კონტურის ფერი All on Same Layers ყველა იმავე შრეებზე Direction Handles მიმართულების სახელურები Brush Strokes ფუნჯის შტრიხები @@ -537,6 +538,7 @@ Cascade კასკადად Tile ფილებად Float in Window ცალკე ფანჯარაში გამოტანა + Float All in Windows ყველას ცალკე ფანჯრებში გამოტანა Consolidate All Windows ყველა ფანჯრის გაერთიანება Workspace სამუშაო სივრცე Reset Essentials Essentials-ის ჩამოყრა @@ -1106,6 +1108,8 @@ lighting Light სინათლე Hand Tool ხელის ხელსაწყო Join Tool შეერთების ხელსაწყო Lasso Tool ლასოს ხელსაწყო + Enclosing Lasso Tool შემომსაზღვრელი ლასოს ხელსაწყო + Enclosing Lasso შემომსაზღვრელი ლასო Line Cut Tool ხაზით ჭრის ხელსაწყო Line Graph Tool ხაზოვანი დიაგრამის ხელსაწყო Line Segment Tool ხაზის სეგმენტის ხელსაწყო @@ -1560,6 +1564,7 @@ digits Malayalam მალაიალამური Left-to-Right Paragraph Direction აბზაცის მიმართულება მარცხნიდან მარჯვნივ Line-end Punctuation Half Width სტრიქონის ბოლოს პუნქტუაცია ნახევარი სიგანით Insert Kashidas ქაშიდების ჩასმა + Kashidas ქაშიდები Long გრძელი Stylistic სტილისტური Mojikumi Set Mojikumi-ის ნაკრები @@ -2334,6 +2339,10 @@ digits Malayalam მალაიალამური Colors: ფერები: Current Colors ({total}) მიმდინარე ფერები ({total}) Harmony Rules: ჰარმონიის წესები: + Segmented color wheel სეგმენტირებული ფერთა წრე + Show smooth color wheel გლუვი ფერთა წრის ჩვენება + Show segmented color wheel სეგმენტირებული ფერთა წრის ჩვენება + Show color bars ფერთა ზოლების ჩვენება Keep this row's colors (exclude) ამ სტრიქონის ფერების შენარჩუნება (გამორიცხვა) Limit to Library: ბიბლიოთეკით შეზღუდვა: Link harmony colors ჰარმონიის ფერების დაკავშირება @@ -3132,6 +3141,7 @@ theme Appearance იერსახე List Preferences პარამეტრების სია Manually ხელით Mark Older Files as [Converted] When Opened ძველი ფაილების მარკირება როგორც [გარდაქმნილი] გახსნისას + Use System Defaults for Edit Original სისტემის ნაგულისხმევის გამოყენება ორიგინალის რედაქტირებისთვის Match User Interface Brightness ინტერფეისის სიკაშკაშესთან შესაბამისობა Light Gray ღია ნაცრისფერი Medium Gray საშუალო ნაცრისფერი @@ -3457,6 +3467,8 @@ effect Regular ჩვეულებრივი In the selected objects მონიშნულ ობიექტებში Find in Folder… საქაღალდეში ძებნა… Replace With Font ჩანაცვლება შრიფტით + Replace With Font From ჩანაცვლების შრიფტის წყარო + System სისტემა — substituted by {style} — ჩანაცვლებულია: {style} — {n} characters from another font — სხვა შრიფტის სიმბოლოები: {n} All Scripts ყველა დამწერლობა @@ -5258,6 +5270,11 @@ imageTrace Outline კონტური Export Type: ექსპორტის ტიპი: Movie Clip ანიმაციური კლიპი @msg name is empty სახელი ცარიელია +@msg an action is already recording მოქმედება უკვე იწერება +@msg no such function key ასეთი ფუნქციური კლავიში არ არის +@msg no such color ასეთი ფერი არ არის +@msg {_1} cannot be used on Windows {_1} ვერ გამოიყენება Windows-ში +@msg more than one action is named “{_1}” „{_1}“ ერთზე მეტი მოქმედების სახელია @msg no symbol named `{n}` სიმბოლო სახელით `{n}` არ არის @msg no saved selection recalled შენახული მონიშვნა გამოძახებული არ არის @msg The last start of VectorCraft ended on {name} before its window appeared, so it started on {summary}. To try that graphics processor again, change Preferences › Performance › Graphics Processor or start with WGPU_BACKEND set VectorCraft-ის ბოლო გაშვება ფანჯრის გამოჩენამდე შეწყდა (გრაფიკული პროცესორი: {name}), ამიტომ VectorCraft გაეშვა: {summary}. ამ გრაფიკული პროცესორის ხელახლა საცდელად შეცვალეთ პარამეტრები › წარმადობა › გრაფიკული პროცესორი ან გაუშვით WGPU_BACKEND ცვლადის მითითებით @@ -5642,9 +5659,17 @@ axis Y Axis Y ღერძი Action Options… მოქმედების პარამეტრები… Action Options მოქმედების პარამეტრები Rename Action მოქმედების სახელის შეცვლა + New Action… ახალი მოქმედება… + New Action ახალი მოქმედება + Create New Action ახალი მოქმედების შექმნა + Play Action მოქმედების შესრულება + Action Set: მოქმედებების ნაკრები: + Function Key: ფუნქციური კლავიში: + Record ჩაწერა Create New Set ახალი ნაკრების შექმნა Stop Global Edit გლობალური რედაქტირების დასრულება Global Edit Options გლობალური რედაქტირების პარამეტრები + Leave Out of Global Edit გლობალური რედაქტირებიდან გამორიცხვა Match დამთხვევა On Artboards სამუშაო დაფებზე All Artboards ყველა სამუშაო დაფა @@ -5653,6 +5678,8 @@ axis Y Axis Y ღერძი @msg select one object მონიშნეთ ერთი ობიექტი @msg Global Edit works on paths, compound paths, symbol instances and groups of them გლობალური რედაქტირება მუშაობს ტრაექტორიებზე, შედგენილ ტრაექტორიებზე, სიმბოლოს ეგზემპლარებსა და მათ ჯგუფებზე @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again მსგავსი ობიექტები ვერ მოიძებნა (შემობრუნებული ან არეკლილი ასლები არ ემთხვევა); შეცვალეთ გლობალური რედაქტირების პარამეტრები და სცადეთ ხელახლა +@msg Global Edit is off გლობალური რედაქტირება გამორთულია +@msg only an object of the Global Edit other than the one it started from can be left out გლობალური რედაქტირებიდან შეიძლება გამოირიცხოს მხოლოდ ობიექტი, რომლითაც ის არ დაწყებულა @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ან დიაპაზონი, მაგალითად 1, 3-5, და არა {v} Add to Symbols სიმბოლოებში დამატება Basic Shapes ძირითადი ფიგურები @@ -5982,6 +6009,11 @@ anchor Points: წერტილები: Horizontal Scale ჰორიზონტალური მასშტაბი Vertical Scale ვერტიკალური მასშტაბი @msg {label} must be a number from {min} to {max} {label} უნდა იყოს რიცხვი {min}-დან {max}-მდე + Character Color სიმბოლოს ფერი + OpenType Features OpenType შესაძლებლობები + Stylistic Sets სტილისტური ნაკრებები +@msg features lists at most {max} tags features შეიძლება შეიცავდეს არაუმეტეს {max} ტეგს +@msg unknown OpenType feature `{t}` უცნობი OpenType შესაძლებლობა `{t}` @msg {label} must be a number above 0 and at most {max} {label} უნდა იყოს 0-ზე მეტი და არაუმეტეს {max}-ისა რიცხვი @msg no character style `{name}` სიმბოლოს სტილი `{name}` ვერ მოიძებნა @@ -6231,3 +6263,14 @@ breakText Glyphs გლიფები Create Swatch Legend ფერის ნიმუშების ლეგენდის შექმნა Create Swatch Legend… ფერის ნიმუშების ლეგენდის შექმნა… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools ტექსტის ხელსაწყოები + Text Tweaker… ტექსტის მორგება… + Text Tweaker ტექსტის მორგება + Attribute: ატრიბუტი: + From: საწყისი: + To: საბოლოო: + Bow რკალი + Spike პიკი + Skip Spaces ჰარების გამოტოვება +@msg The art is too large to copy as a picture: other apps get no PNG of it ნახატი ზედმეტად დიდია სურათად დასაკოპირებლად: სხვა აპები მის PNG-ს ვერ მიიღებენ diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 5f24419728..1702c2d15d 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -64,6 +64,7 @@ digits Malayalam 말라얄람어 Join Our Discord Discord 참여하기 Line-end Punctuation Half Width 줄 끝 문장 부호 반각 Insert Kashidas 카시다 삽입 + Kashidas 카시다 Long 길게 Stylistic 스타일 Mojikumi Set 모지쿠미 세트 @@ -456,6 +457,7 @@ digits Malayalam 말라얄람어 Variable Font 가변 글꼴 Text Fill Color 문자 칠 색상 Text Stroke Color 문자 선 색상 + Text Fill & Stroke Color 문자 칠 및 선 색상 All on Same Layers 같은 레이어의 모두 Direction Handles 방향 핸들 Brush Strokes 브러시 선 @@ -640,6 +642,7 @@ digits Malayalam 말라얄람어 Cascade 계단식 배열 Tile 바둑판식 배열 Float in Window 창에 플로팅 + Float All in Windows 모두 창에 플로팅 Consolidate All Windows 모든 창 통합 Workspace 작업 영역 Reset Essentials Essentials 재설정 @@ -1715,6 +1718,10 @@ digits Malayalam 말라얄람어 Hard Light 하드 라이트 Hard Mix 하드 믹스 Harmony Rules: 하모니 규칙: + Segmented color wheel 분할 색상환 + Show smooth color wheel 부드러운 색상환 표시 + Show segmented color wheel 분할 색상환 표시 + Show color bars 색상 막대 표시 Height 높이 Height: 높이: Help › Search Commands… 도움말 › 명령 검색… @@ -1975,6 +1982,8 @@ digits Malayalam 말라얄람어 Large 크게 Large Tabs 큰 탭 Lasso Tool 올가미 도구 + Enclosing Lasso Tool 둘러싸기 올가미 도구 + Enclosing Lasso 둘러싸기 올가미 Last Effect: {name} 마지막 효과: {name} Last Page 마지막 페이지 Layer Options… 레이어 옵션… @@ -2078,6 +2087,7 @@ digits Malayalam 말라얄람어 Manage Workspaces 작업 영역 관리 Manually 수동 Mark Older Files as [Converted] When Opened 열 때 이전 파일을 [Converted]로 표시 + Use System Defaults for Edit Original 원본 편집에 시스템 기본값 사용 Mark as trapped 트래핑됨으로 표시 Marks 표시 Match User Interface Brightness 사용자 인터페이스 밝기에 맞춤 @@ -2711,6 +2721,8 @@ mark-style Japanese 일본식 Replace Font 글꼴 바꾸기 Replace Symbol 심볼 바꾸기 Replace With Font 바꿀 글꼴 + Replace With Font From 바꿀 글꼴 목록 + System 시스템 Replace it with another file, or ignore it: its images keep showing the preview saved with the document. 다른 파일로 바꾸거나 무시하세요. 무시하면 해당 이미지는 문서에 저장된 미리 보기로 계속 표시됩니다. Replaces the saved preset of that name. 같은 이름으로 저장된 사전 설정을 대체합니다. Replace… 바꾸기… @@ -5132,6 +5144,11 @@ lighting Light 광원 Export Type: 내보내기 유형: Movie Clip 무비 클립 @msg name is empty 이름이 비어 있습니다 +@msg an action is already recording 이미 액션을 기록하고 있습니다 +@msg no such function key 해당 기능 키가 없습니다 +@msg no such color 해당 색상이 없습니다 +@msg {_1} cannot be used on Windows {_1}은(는) Windows에서 사용할 수 없습니다 +@msg more than one action is named “{_1}” “{_1}”(이)라는 이름의 액션이 둘 이상 있습니다 @msg no symbol named `{n}` 이름이 `{n}`인 심볼이 없습니다 Smudge Stick… 문지르기 막대… Smudge Stick 문지르기 막대 @@ -5305,9 +5322,17 @@ axis Y Axis Y축 Action Options… 액션 옵션… Action Options 액션 옵션 Rename Action 액션 이름 바꾸기 + New Action… 새 액션… + New Action 새 액션 + Create New Action 새 액션 만들기 + Play Action 액션 재생 + Action Set: 액션 세트: + Function Key: 기능 키: + Record 기록 Create New Set 새 세트 만들기 Stop Global Edit 전체 편집 중지 Global Edit Options 전체 편집 옵션 + Leave Out of Global Edit 전체 편집에서 제외 Match 일치 On Artboards 아트보드에서 All Artboards 모든 아트보드 @@ -5316,6 +5341,8 @@ axis Y Axis Y축 @msg select one object 개체 하나를 선택하십시오 @msg Global Edit works on paths, compound paths, symbol instances and groups of them 전체 편집은 패스, 컴파운드 패스, 심볼 인스턴스 및 이들의 그룹에서 작동합니다 @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again 유사한 개체를 찾을 수 없습니다(회전하거나 반사한 복사본은 일치하지 않습니다). 전체 편집 옵션을 변경한 후 다시 시도하십시오 +@msg Global Edit is off 전체 편집이 꺼져 있습니다 +@msg only an object of the Global Edit other than the one it started from can be left out 전체 편집을 시작한 개체가 아닌 전체 편집의 개체만 제외할 수 있습니다 @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all 또는 1, 3-5 같은 범위여야 합니다({v}이(가) 아님) Add to Symbols 심볼에 추가 Basic Shapes 기본 모양 @@ -5574,6 +5601,11 @@ anchor Points: 포인트: Horizontal Scale 가로 비율 Vertical Scale 세로 비율 @msg {label} must be a number from {min} to {max} {label}은(는) {min}에서 {max} 사이의 숫자여야 합니다 + Character Color 문자 색상 + OpenType Features OpenType 기능 + Stylistic Sets 스타일 세트 +@msg features lists at most {max} tags features에는 태그를 최대 {max}개까지 지정할 수 있습니다 +@msg unknown OpenType feature `{t}` 알 수 없는 OpenType 기능 `{t}` @msg {label} must be a number above 0 and at most {max} {label}은(는) 0 초과 {max} 이하의 숫자여야 합니다 @msg no character style `{name}` 문자 스타일 `{name}`을 찾을 수 없습니다 @@ -5824,3 +5856,14 @@ breakText Glyphs 글리프 Create Swatch Legend 견본 범례 만들기 Create Swatch Legend… 견본 범례 만들기… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools 텍스트 도구 + Text Tweaker… 텍스트 조정… + Text Tweaker 텍스트 조정 + Attribute: 속성: + From: 시작: + To: 끝: + Bow 활 모양 + Spike 뾰족한 모양 + Skip Spaces 공백 건너뛰기 +@msg The art is too large to copy as a picture: other apps get no PNG of it 아트워크가 너무 커서 이미지로 복사할 수 없습니다: 다른 앱에는 PNG가 전달되지 않습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d7ccca2114..263545d27c 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -407,6 +407,7 @@ Variable Font Variabel lettertype Text Fill Color Tekstvulkleur Text Stroke Color Tekstcontourkleur + Text Fill & Stroke Color Tekstvul- en contourkleur All on Same Layers Alles op dezelfde lagen Direction Handles Richtingsgrepen Brush Strokes Penseelstreken @@ -599,6 +600,7 @@ Cascade Trapsgewijs schikken Tile Naast elkaar schikken Float in Window In venster zweven + Float All in Windows Alles in vensters zweven Consolidate All Windows Alle vensters samenvoegen Workspace Werkruimte Reset Essentials Essentials herstellen @@ -1191,6 +1193,8 @@ lighting Light Licht Hand Hand Join Tool Samenvoegen-gereedschap Lasso Tool Lasso-gereedschap + Enclosing Lasso Tool Omsluitend lassogereedschap + Enclosing Lasso Omsluitende lasso Lasso Lasso Line Cut Tool Lijnknip-gereedschap Line Graph Tool Lijndiagram-gereedschap @@ -1672,6 +1676,7 @@ digits Malayalam Malayalam Left-to-Right Paragraph Direction Alinearichting van links naar rechts Line-end Punctuation Half Width Leestekens op regeleinde op halve breedte Insert Kashidas Kashida's invoegen + Kashidas Kashida's Long Lang Stylistic Stilistisch Mojikumi Set Mojikumi-set @@ -2457,6 +2462,10 @@ digits Malayalam Malayalam Current Colors Huidige kleuren Current Colors (0) Huidige kleuren (0) Harmony Rules: Harmonieregels: + Segmented color wheel Gesegmenteerd kleurenwiel + Show smooth color wheel Vloeiend kleurenwiel tonen + Show segmented color wheel Gesegmenteerd kleurenwiel tonen + Show color bars Kleurbalken tonen Harmony Rules Harmonieregels Keep this row's colors (exclude) De kleuren van deze rij behouden (uitsluiten) Limit to Library: Beperken tot bibliotheek: @@ -3336,6 +3345,7 @@ theme Appearance Vormgeving List Preferences Voorkeuren weergeven Manually Handmatig Mark Older Files as [Converted] When Opened Oudere bestanden bij het openen markeren als [geconverteerd] + Use System Defaults for Edit Original Systeemstandaarden gebruiken voor Origineel bewerken Match User Interface Brightness Aanpassen aan helderheid van gebruikersinterface Light Gray Lichtgrijs Medium Gray Middelgrijs @@ -3688,6 +3698,8 @@ effect Regular Regelmatig In the selected objects In de geselecteerde objecten Find in Folder… Zoeken in map… Replace With Font Vervangen door lettertype + Replace With Font From Vervangen door lettertype uit + System Systeem — substituted by {style} — vervangen door {style} — {n} characters from another font — {n} tekens van een ander lettertype All Scripts Alle scripts @@ -5359,6 +5371,11 @@ swatch Bright Violet Felviolet Export Type: Exporttype: Movie Clip Filmclip @msg name is empty naam is leeg +@msg an action is already recording er wordt al een actie opgenomen +@msg no such function key functietoets bestaat niet +@msg no such color kleur bestaat niet +@msg {_1} cannot be used on Windows {_1} kan niet worden gebruikt in Windows +@msg more than one action is named “{_1}” meer dan één actie heet „{_1}” @msg no symbol named `{n}` geen symbool met de naam `{n}` Remove Color Profile… Kleurprofiel verwijderen… Color wheel Kleurenwiel @@ -5674,9 +5691,17 @@ axis Y Axis Y-as Action Options… Actieopties… Action Options Actieopties Rename Action Actie hernoemen + New Action… Nieuwe actie… + New Action Nieuwe actie + Create New Action Nieuwe actie maken + Play Action Actie afspelen + Action Set: Actieset: + Function Key: Functietoets: + Record Opnemen Create New Set Nieuwe set maken Stop Global Edit Globale bewerking stoppen Global Edit Options Opties voor globale bewerking + Leave Out of Global Edit Uitsluiten van globale bewerking @msg Global Edit works on paths, compound paths, symbol instances and groups of them Globale bewerking werkt op paden, samengestelde paden, symboolinstanties en groepen daarvan Match Overeenkomst On Artboards Op tekengebieden @@ -6162,3 +6187,14 @@ breakText Glyphs Glyphs Create Swatch Legend Stalenlegenda maken Create Swatch Legend… Stalenlegenda maken… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Teksthulpmiddelen + Text Tweaker… Tekst bijstellen… + Text Tweaker Tekst bijstellen + Attribute: Kenmerk: + From: Van: + To: Tot: + Bow Boog + Spike Piek + Skip Spaces Spaties overslaan +@msg The art is too large to copy as a picture: other apps get no PNG of it Het illustratiewerk is te groot om als afbeelding te kopiëren: andere apps krijgen er geen PNG van diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index be0a2a24b4..a2bce6ac59 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -394,6 +394,7 @@ Variable Font Czcionka zmienna Text Fill Color Kolor wypełnienia tekstu Text Stroke Color Kolor obrysu tekstu + Text Fill & Stroke Color Kolor wypełnienia i obrysu tekstu All on Same Layers Wszystko na tych samych warstwach Direction Handles Uchwyty kierunkowe Brush Strokes Pociągnięcia pędzla @@ -593,6 +594,7 @@ Cascade Kaskadowo Tile Sąsiadująco Float in Window Pływające w oknie + Float All in Windows Wszystkie pływające w oknach Consolidate All Windows Scal wszystkie okna Workspace Obszar roboczy Reset Essentials Resetuj Essentials @@ -1188,6 +1190,8 @@ lighting Light Światło Hand Tool Narzędzie Rączka Join Tool Narzędzie Łączenie Lasso Tool Narzędzie Lasso + Enclosing Lasso Tool Narzędzie lassa obejmującego + Enclosing Lasso Lasso obejmujące Line Cut Tool Narzędzie Cięcie linią Line Graph Tool Narzędzie Wykres liniowy Line Segment Tool Narzędzie Odcinek @@ -1772,6 +1776,7 @@ digits Malayalam Malajalam Left-to-Right Paragraph Direction Kierunek akapitu od lewej do prawej Line-end Punctuation Half Width Interpunkcja na końcu wiersza o połowie szerokości Insert Kashidas Wstaw kaszidy + Kashidas Kaszidy Long Długi Stylistic Stylistyczny Mojikumi Set Zestaw mojikumi @@ -2566,6 +2571,10 @@ digits Malayalam Malajalam Colors: Kolory: Current Colors ({total}) Bieżące kolory ({total}) Harmony Rules: Reguły harmonii: + Segmented color wheel Segmentowe koło kolorów + Show smooth color wheel Pokaż płynne koło kolorów + Show segmented color wheel Pokaż segmentowe koło kolorów + Show color bars Pokaż paski kolorów Keep this row's colors (exclude) Zachowaj kolory tego wiersza (wyklucz) Limit to Library: Ogranicz do biblioteki: Link harmony colors Połącz kolory harmonii @@ -3458,6 +3467,7 @@ theme Appearance Wygląd List Preferences Wyświetl preferencje Manually Ręcznie Mark Older Files as [Converted] When Opened Oznaczaj starsze pliki jako [Przekonwertowane] przy otwieraniu + Use System Defaults for Edit Original Używaj ustawień domyślnych systemu dla polecenia Edytuj oryginał Match User Interface Brightness Dopasuj do jasności interfejsu Light Gray Jasnoszary Medium Gray Średnio szary @@ -3794,6 +3804,8 @@ effect Regular Normalny In the selected objects W zaznaczonych obiektach Find in Folder… Znajdź w folderze… Replace With Font Zastąp czcionką + Replace With Font From Zastąp czcionką z + System System — substituted by {style} — zastąpiona przez {style} — {n} characters from another font — znaki z innej czcionki: {n} All Scripts Wszystkie skrypty @@ -5411,6 +5423,11 @@ mark-style Japanese Japońskie Export Type: Typ eksportu: Movie Clip Klip filmowy @msg name is empty nazwa jest pusta +@msg an action is already recording operacja jest już nagrywana +@msg no such function key brak takiego klawisza funkcyjnego +@msg no such color brak takiego koloru +@msg {_1} cannot be used on Windows Skrótu {_1} nie można używać w systemie Windows +@msg more than one action is named “{_1}” więcej niż jedna operacja nazywa się „{_1}” @msg no symbol named `{n}` brak symbolu o nazwie `{n}` Smudge Stick… Rozmazywacz… Smudge Stick Rozmazywacz @@ -5581,9 +5598,17 @@ axis Y Axis Oś Y Action Options… Opcje operacji… Action Options Opcje operacji Rename Action Zmień nazwę operacji + New Action… Nowa operacja… + New Action Nowa operacja + Create New Action Utwórz nową operację + Play Action Odtwórz operację + Action Set: Zestaw operacji: + Function Key: Klawisz funkcyjny: + Record Nagraj Create New Set Utwórz nowy zestaw Stop Global Edit Zakończ edycję globalną Global Edit Options Opcje edycji globalnej + Leave Out of Global Edit Wyklucz z edycji globalnej Match Dopasowanie On Artboards Na obszarach kompozycji All Artboards Wszystkie obszary kompozycji @@ -5592,6 +5617,8 @@ axis Y Axis Oś Y @msg select one object zaznacz jeden obiekt @msg Global Edit works on paths, compound paths, symbol instances and groups of them Edycja globalna działa na ścieżkach, ścieżkach złożonych, wystąpieniach symboli i ich grupach @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nie znaleziono podobnych obiektów (obrócone i odbite kopie nie są dopasowywane); zmień opcje edycji globalnej i spróbuj ponownie +@msg Global Edit is off Edycja globalna jest wyłączona +@msg only an object of the Global Edit other than the one it started from can be left out z edycji globalnej można wykluczyć tylko obiekt inny niż ten, od którego się zaczęła @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all lub zakres, np. 1, 3-5, a nie {v} Add to Symbols Dodaj do symboli Basic Shapes Kształty podstawowe @@ -5848,6 +5875,11 @@ anchor Points: Punkty: Horizontal Scale Skala pozioma Vertical Scale Skala pionowa @msg {label} must be a number from {min} to {max} {label} musi być liczbą od {min} do {max} + Character Color Kolor znaków + OpenType Features Funkcje OpenType + Stylistic Sets Zestawy stylistyczne +@msg features lists at most {max} tags features może zawierać najwyżej {max} znaczników +@msg unknown OpenType feature `{t}` nieznana funkcja OpenType `{t}` @msg {label} must be a number above 0 and at most {max} {label} musi być liczbą większą od 0 i nie większą niż {max} @msg no character style `{name}` Nie znaleziono stylu znakowego `{name}` @@ -6098,3 +6130,14 @@ breakText Glyphs Glify Create Swatch Legend Utwórz legendę próbek Create Swatch Legend… Utwórz legendę próbek… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Narzędzia tekstu + Text Tweaker… Strojenie tekstu… + Text Tweaker Strojenie tekstu + Attribute: Atrybut: + From: Od: + To: Do: + Bow Łuk + Spike Szpic + Skip Spaces Pomiń spacje +@msg The art is too large to copy as a picture: other apps get no PNG of it Grafika jest zbyt duża, aby skopiować ją jako obraz: inne aplikacje nie otrzymają jej w formacie PNG diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 2f07e53096..b6efe4bf7b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1091,6 +1091,7 @@ Flip Row Order Inverter Ordem das Linhas Flip Vertical Espelhar Verticalmente Float in Window Flutuar na Janela + Float All in Windows Flutuar Tudo em Janelas Folder Pasta Folder Name: Nome da Pasta: Font Fonte @@ -1215,6 +1216,10 @@ Hard Light Luz Forte Hard Mix Mistura definida Harmony Rules: Regras de Harmonia: + Segmented color wheel Roda de cores segmentada + Show smooth color wheel Mostrar roda de cores contínua + Show segmented color wheel Mostrar roda de cores segmentada + Show color bars Mostrar barras de cores Harmony Sets Conjuntos de Harmonia Height Altura Height: Altura: @@ -1455,6 +1460,8 @@ Large Grande Large Tabs Guias Grandes Lasso Tool Ferramenta Laço + Enclosing Lasso Tool Ferramenta Laço envolvente + Enclosing Lasso Laço envolvente Last Effect: {name} Último Efeito: {name} Last Effect… Último Efeito… Last Page Última Página @@ -1580,6 +1587,7 @@ Manage Workspaces… Gerenciar Espaços de Trabalho… Manually Manualmente Mark Older Files as [Converted] When Opened Marcar Arquivos Antigos como [Convertido] Ao Abrir + Use System Defaults for Edit Original Usar Padrões do Sistema para Editar Original Mark as trapped Marcar como sobreimpresso Marker… Marcador… Marks Marcas @@ -2253,6 +2261,8 @@ digits Malayalam Malaiala Replace Spine Substituir Coluna Replace Symbol Substituir Símbolo Replace With Font Substituir Com Fonte + Replace With Font From Substituir Com Fonte De + System Sistema Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Substitua por outro arquivo, ou ignore-o: suas imagens continuam mostrando a pré-visualização salva com o documento. Replaces the saved preset of that name. Substitui o predefinido salvo com esse nome. Replace… Substituir… @@ -2781,6 +2791,7 @@ digits Malayalam Malaiala Templates… Modelos… Text Displayed in Cell: Texto Exibido na Célula: Text Export Options Opções de Exportação de Texto + Text Fill & Stroke Color Cor de Preenchimento e Traçado do Texto Text Fill Color Cor de Preenchimento do Texto Text Import Options Opções de Importação de Texto Text Stroke Color Cor do Traçado do Texto @@ -3317,6 +3328,7 @@ font-technology Variable Variáveis Merge Selected Mesclar selecionados Model Modelo Insert Kashidas Inserir Kashidas + Kashidas Kashidas Long Longo Stylistic Estilístico Mojikumi Set Conjunto Mojikumi @@ -5473,6 +5485,11 @@ mark-style Japanese Japonesas # Symbol Options › Export Type @msg name is empty o nome está vazio +@msg an action is already recording uma ação já está sendo gravada +@msg no such function key tecla de função inexistente +@msg no such color cor inexistente +@msg {_1} cannot be used on Windows {_1} não pode ser usado no Windows +@msg more than one action is named “{_1}” mais de uma ação se chama “{_1}” @msg no symbol named `{n}` nenhum símbolo chamado `{n}` Smudge Stick… Esfuminho… Smudge Stick Esfuminho @@ -5643,9 +5660,17 @@ axis Y Axis Eixo Y Action Options… Opções da Ação… Action Options Opções da Ação Rename Action Renomear Ação + New Action… Nova Ação… + New Action Nova Ação + Create New Action Criar Nova Ação + Play Action Reproduzir Ação + Action Set: Conjunto de Ações: + Function Key: Tecla de Função: + Record Gravar Create New Set Criar Novo Conjunto Stop Global Edit Parar Edição Global Global Edit Options Opções de Edição Global + Leave Out of Global Edit Deixar Fora da Edição Global Match Corresponder On Artboards Nas Mesas de Trabalho All Artboards Todas as Mesas de Trabalho @@ -5654,6 +5679,8 @@ axis Y Axis Eixo Y @msg select one object selecione um objeto @msg Global Edit works on paths, compound paths, symbol instances and groups of them A edição global funciona com demarcadores, demarcadores compostos, instâncias de símbolos e grupos deles @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nenhum objeto semelhante encontrado (cópias giradas ou refletidas não são correspondidas); altere as opções de edição global e tente novamente +@msg Global Edit is off A edição global está desativada +@msg only an object of the Global Edit other than the one it started from can be left out só é possível deixar fora da edição global um objeto diferente daquele com que ela começou @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ou um intervalo como 1, 3-5, não {v} Add to Symbols Adicionar aos Símbolos Basic Shapes Formas Básicas @@ -5910,6 +5937,11 @@ anchor Points: Pontos: Horizontal Scale Escala Horizontal Vertical Scale Escala Vertical @msg {label} must be a number from {min} to {max} {label} deve ser um número de {min} a {max} + Character Color Cor do Caractere + OpenType Features Recursos OpenType + Stylistic Sets Conjuntos Estilísticos +@msg features lists at most {max} tags features aceita no máximo {max} marcas +@msg unknown OpenType feature `{t}` recurso OpenType desconhecido `{t}` @msg {label} must be a number above 0 and at most {max} {label} deve ser um número maior que 0 e no máximo {max} @msg no character style `{name}` Estilo de caractere `{name}` não encontrado @@ -6316,3 +6348,14 @@ swatch Yellow Green Verde-amarelado Create Swatch Legend Criar Legenda de Amostras Create Swatch Legend… Criar Legenda de Amostras… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Ferramentas de texto + Text Tweaker… Ajustador de texto… + Text Tweaker Ajustador de texto + Attribute: Atributo: + From: De: + To: Até: + Bow Arco + Spike Pico + Skip Spaces Ignorar espaços +@msg The art is too large to copy as a picture: other apps get no PNG of it A arte é grande demais para ser copiada como imagem: outros aplicativos não recebem um PNG dela diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index cb6cbd10b9..999b1f1553 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1235,6 +1235,7 @@ file-filter Templates Шаблоны Flip Row Order Изменить порядок строк Flip Vertical Отразить по вертикали Float in Window Плавать в окне + Float All in Windows Все плавающие в окнах Focal Fill Фокусная заливка Focal Stroke Фокусная обводка Folder Папка @@ -1398,6 +1399,10 @@ file-filter Templates Шаблоны Hard Light Жёсткий свет Hard Mix Жёсткое наложение Harmony Rules: Правила гармонии: + Segmented color wheel Сегментированный цветовой круг + Show smooth color wheel Показать плавный цветовой круг + Show segmented color wheel Показать сегментированный цветовой круг + Show color bars Показать цветовые полосы Harmony Sets Наборы гармонии Height Высота Height: Высота: @@ -1734,6 +1739,8 @@ file-filter Templates Шаблоны Large Thumbnail View Крупные миниатюры Large Thumbnails Крупные миниатюры Lasso Tool Инструмент «Лассо» + Enclosing Lasso Tool Инструмент «Охватывающее лассо» + Enclosing Lasso Охватывающее лассо Last Effect: {name} Последний эффект: {name} Last Effect: {} Последний эффект: {} Last Effect… Последний эффект… @@ -1885,6 +1892,7 @@ file-filter Templates Шаблоны Manually Вручную Mark as trapped Пометить как треппинг Mark Older Files as [Converted] When Opened Помечать старые файлы как [Преобразованные] при открытии + Use System Defaults for Edit Original Использовать системные значения по умолчанию для «Редактировать оригинал» Marker… Маркер… Marks Метки Marks and Bleed Метки и вылет @@ -1947,6 +1955,7 @@ file-filter Templates Шаблоны Modify Изменить Mojikumi Mojikumi Insert Kashidas Вставлять кашиды + Kashidas Кашиды Long Длинные Stylistic Стилистические Mojikumi Set Набор mojikumi @@ -2733,6 +2742,8 @@ digits Malayalam Малаялам Replace Spine Заменить остов Replace Symbol Заменить символ Replace With Font Заменить шрифтом + Replace With Font From Заменить шрифтом из + System Система Replaces the saved preset of that name. Заменяет сохранённый набор с таким именем. Replace… Заменить… Require a password to open the document Требовать пароль для открытия документа @@ -3421,6 +3432,7 @@ digits Malayalam Малаялам Templates… Шаблоны… Text Displayed in Cell: Текст, отображаемый в ячейке: Text Export Options Параметры экспорта текста + Text Fill & Stroke Color Цвет заливки и обводки текста Text Fill Color Цвет заливки текста Text Import Options Параметры импорта текста Text Stroke Color Цвет обводки текста @@ -5166,6 +5178,11 @@ lighting Light Свет Export Type: Тип экспорта: Movie Clip Видеоклип @msg name is empty имя пустое +@msg an action is already recording действие уже записывается +@msg no such function key такой функциональной клавиши нет +@msg no such color такого цвета нет +@msg {_1} cannot be used on Windows Сочетание {_1} нельзя использовать в Windows +@msg more than one action is named “{_1}” несколько действий называются «{_1}» @msg no symbol named `{n}` нет символа с именем `{n}` Smudge Stick… Растушёвка… Smudge Stick Растушёвка @@ -5339,9 +5356,17 @@ axis Y Axis Ось Y Action Options… Параметры действия… Action Options Параметры действия Rename Action Переименовать действие + New Action… Новое действие… + New Action Новое действие + Create New Action Создать новое действие + Play Action Воспроизвести действие + Action Set: Набор действий: + Function Key: Функциональная клавиша: + Record Записать Create New Set Создать новый набор Stop Global Edit Завершить глобальное редактирование Global Edit Options Параметры глобального редактирования + Leave Out of Global Edit Исключить из глобального редактирования Match Совпадение On Artboards На монтажных областях All Artboards Все монтажные области @@ -5350,6 +5375,8 @@ axis Y Axis Ось Y @msg select one object выберите один объект @msg Global Edit works on paths, compound paths, symbol instances and groups of them Глобальное редактирование работает с контурами, составными контурами, экземплярами символов и их группами @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again похожие объекты не найдены (повёрнутые или отражённые копии не учитываются); измените параметры глобального редактирования и повторите попытку +@msg Global Edit is off Глобальное редактирование выключено +@msg only an object of the Global Edit other than the one it started from can be left out исключить из глобального редактирования можно только объект, отличный от того, с которого оно началось @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all или диапазон, например 1, 3-5, а не {v} Add to Symbols Добавить в символы Basic Shapes Базовые фигуры @@ -5971,6 +5998,11 @@ anchor Points: Точки: Horizontal Scale Масштаб по горизонтали Vertical Scale Масштаб по вертикали @msg {label} must be a number from {min} to {max} {label} должно быть числом от {min} до {max} + Character Color Цвет символов + OpenType Features Функции OpenType + Stylistic Sets Стилистические наборы +@msg features lists at most {max} tags features содержит не более {max} тегов +@msg unknown OpenType feature `{t}` неизвестная функция OpenType `{t}` @msg {label} must be a number above 0 and at most {max} {label} должно быть числом больше 0 и не более {max} @msg no character style `{name}` Стиль символов `{name}` не найден @@ -6220,3 +6252,126 @@ breakText Glyphs Глифы Create Swatch Legend Создать легенду образцов Create Swatch Legend… Создать легенду образцов… HEX HEX + +# The strings the report listed as missing for ru. + 1 Layer 1 слой + 4K UHD 4K UHD + 8K UHD 8K UHD + A3 A3 + A4 A4 + A5 A5 + A6 A6 + Arrow Scale: Масштаб стрелок: + Arrow Style: Стиль стрелок: + Art and Bright Colors Художественные и яркие цвета + Artboard Options: edit with the Artboard tool Параметры монтажной области: измените их инструментом «Монтажная область» + Automate Автоматизация + B4 B4 + B5 B5 + CRLF (Windows) CRLF (Windows) + Check for Updates… Проверить обновления… + Color Table (4 colors) Таблица цветов (4 цвета) + Create PDF layers from top-level layers Создавать PDF-слои из слоёв верхнего уровня + Current Colors (0) Текущие цвета (0) + Differences from VectorCraft Default: Отличия от значений VectorCraft по умолчанию: + Differences from [Default]: Отличия от [По умолчанию]: + Dimension Lines Размерные линии + Dimension Text Размерный текст + Dot Gain 15% Растискивание 15 % + Drag art, colors and text styles here to reuse them across documents. Libraries are stored on this machine — no account required. Перетащите сюда объекты, цвета и стили текста, чтобы использовать их в разных документах. Библиотеки хранятся на этом компьютере — учётная запись не нужна. + Expand 1 Selected Разбить 1 объект + Extension Lines Выносные линии + Extension: Выносная линия: + Font Size: Размер шрифта: + Graphic Styles (4) Стили графики (4) + Gray Gamma 2.2 Gray Gamma 2.2 + HDTV 1080p HDTV 1080p + HDTV 720p HDTV 720p + Hide Extension Lines Скрыть выносные линии + Hide Units Скрыть единицы + Invalid panel layout; restored the default dock Недопустимая раскладка панелей; восстановлена стыковка по умолчанию + Japanese Double Postcard Японская двойная открытка + Japanese Envelope #3 Японский конверт №3 + Japanese Envelope #4 Японский конверт №4 + Japanese Postcard Японская открытка + Kaku #2 Каку №2 + Kaku #3 Каку №3 + LF (macOS, Linux) LF (macOS, Linux) + Legal Legal + Line Type: Тип линии: + Line Weight: Толщина линии: + Load Variable Library Загрузить библиотеку переменных + PDF 1.7 PDF 1.7 + PDF/X-1a:2001 PDF/X-1a:2001 + PDF/X-3:2002 PDF/X-3:2002 + PDF/X-4:2010 PDF/X-4:2010 + Part of ArtCraft. MIT OR Apache-2.0. Fonts: Source Sans 3, Inter, JetBrains Mono, Noto Sans SC (OFL). Icons: Lucide (ISC) + VectorCraft. Часть ArtCraft. MIT OR Apache-2.0. Шрифты: Source Sans 3, Inter, JetBrains Mono, Noto Sans SC (OFL). Значки: Lucide (ISC) + VectorCraft. + Phone 375×812 Телефон 375×812 + Photo Low Fidelity Фото (низкое качество) + Preparing the image… Подготовка изображения… + Print & Proof Печать и цветопроба + Printing & Proofing Печать и цветопроба + RECENT (1) НЕДАВНИЕ (1) + RGB RGB + Reset Automation Сбросить «Автоматизация» + Reset Essentials Classic Сбросить «Основные (классические)» + Reset Layout Сбросить «Макет» + Reset Painting Сбросить «Рисование» + Reset Printing and Proofing Сбросить «Печать и цветопроба» + Reset Tracing Сбросить «Трассировка» + Reset Typography Сбросить «Типографика» + Reset Web Сбросить «Веб» + Restricted Colors Ограниченные цвета + Right-click an item to move it into this group. Щёлкните объект правой кнопкой мыши, чтобы переместить его в эту группу. + SVG 1.1 SVG 1.1 + Scale X Масштаб X + Scale X: Масштаб X: + Scale Y Масштаб Y + Scale Y: Масштаб Y: + Selected Styles Only (0) Только выбранные стили (0) + Selected Swatches Only (0) Только выбранные образцы (0) + Shear: Наклон: + Simplified Chinese Упрощённый китайский + Spot Colors (0) Плашечные цвета (0) + Tablet 1024×768 Планшет 1024×768 + Tabloid Tabloid + Tracing the colors… Трассировка цветов… + UTF-16 (Unicode) UTF-16 (Unicode) + Units & Scale Единицы и масштаб + VectorCraft Updates Обновления VectorCraft + Video 1920×1080 Видео 1920×1080 + Video 3840×2160 Видео 3840×2160 + Web 1280×720 Веб 1280×720 + WebP WebP + Yonroku-ban Ёнроку-бан + [High Quality Print] [Высококачественная печать] + [High Resolution] [Высокое разрешение] + [Low Resolution] [Низкое разрешение] + [Medium Resolution] [Среднее разрешение] + [PDF/X-1a:2001] [PDF/X-1a:2001] + [PDF/X-3:2002] [PDF/X-3:2002] + [PDF/X-4:2010] [PDF/X-4:2010] + [Smallest File Size] [Минимальный размер файла] + [VectorCraft Default] [Значения VectorCraft по умолчанию] + sRGB IEC61966-2.1 sRGB IEC61966-2.1 +@id file.close Закрыть файл +@id pathfinder.add Объединить +@msg give corners of the path: anchors between two straight sides укажите углы контура: опорные точки между двумя прямыми сторонами +@msg image '{key}' has no pixels and was left out изображение '{key}' не содержит пикселов и было пропущено +@msg not an RTF file: it doesn't start with {\\rtf это не файл RTF: он не начинается с {\\rtf +@msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), which can't be opened yet: save it as PDF, PDF-compatible .ai or SVG это файл PostScript (.ai, сохранённый в старом формате или без совместимости с PDF, либо EPS-файл), который пока нельзя открыть: сохраните его как PDF, .ai с совместимостью с PDF или SVG +@msg this kind of brush has no options dialog yet у кистей этого типа пока нет диалога параметров +digits Hindi Хинди +font-script Japanese Японский +shape Open Открытый +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Инструменты текста + Text Tweaker… Настройка текста… + Text Tweaker Настройка текста + Attribute: Атрибут: + From: От: + To: До: + Bow Дуга + Spike Пик + Skip Spaces Пропускать пробелы +@msg The art is too large to copy as a picture: other apps get no PNG of it Графика слишком велика для копирования в виде изображения: другие приложения не получат её PNG diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index b8cc549339..7f815addf6 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1185,6 +1185,7 @@ font-technology Variable Variabla Flip Row Order Vänd radordning Flip Vertical Vänd lodrätt Float in Window Gör flytande i fönster + Float All in Windows Gör alla flytande i fönster Focal Fill Fokal fyllning Focal Stroke Fokal kontur Folder Mapp @@ -1348,6 +1349,10 @@ font-technology Variable Variabla Hard Light Hårt ljus Hard Mix Hård blandning Harmony Rules: Harmoniregler: + Segmented color wheel Segmenterat färghjul + Show smooth color wheel Visa steglöst färghjul + Show segmented color wheel Visa segmenterat färghjul + Show color bars Visa färgstaplar Harmony Sets Harmoniuppsättningar Height Höjd Height: Höjd: @@ -1663,6 +1668,8 @@ font-technology Variable Variabla Large Thumbnail View Stor miniatyrvy Large Thumbnails Stora miniatyrer Lasso Tool Lassoverktyg + Enclosing Lasso Tool Omslutande lassoverktyg + Enclosing Lasso Omslutande lasso Last Effect: {name} Senaste effekten: {name} Last Effect: {} Senaste effekten: {} Last Effect… Senaste effekten… @@ -1800,6 +1807,7 @@ font-technology Variable Variabla Manually Manuellt Mark as trapped Märk som överfyllt Mark Older Files as [Converted] When Opened Märk äldre filer som [Konverterad] när de öppnas + Use System Defaults for Edit Original Använd systemets standardinställningar för Redigera original Marker… Markör… Marks Märken Marks and Bleed Märken och utfall @@ -1862,6 +1870,7 @@ font-technology Variable Variabla Modify Ändra Mojikumi Mojikumi Insert Kashidas Infoga kashidor + Kashidas Kashidor Long Lång Stylistic Stilistisk Mojikumi Set Mojikumi-uppsättning @@ -2641,6 +2650,8 @@ digits Malayalam Malayalam Replace Spine Ersätt ryggrad Replace Symbol Ersätt symbol Replace With Font Ersätt med typsnitt + Replace With Font From Ersätt med typsnitt från + System System Replaces the saved preset of that name. Ersätter den sparade förinställningen med samma namn. Replace… Ersätt… Require a password to open the document Kräv lösenord för att öppna dokumentet @@ -3312,6 +3323,7 @@ digits Malayalam Malayalam Templates… Mallar… Text Displayed in Cell: Text som visas i cellen: Text Export Options Alternativ för textexport + Text Fill & Stroke Color Textens fyllnads- och konturfärg Text Fill Color Textens fyllnadsfärg Text Import Options Alternativ för textimport Text Stroke Color Textens konturfärg @@ -5513,6 +5525,11 @@ theme Appearance Utseende Export Type: Exporttyp: Movie Clip Filmklipp @msg name is empty namnet är tomt +@msg an action is already recording en åtgärd spelas redan in +@msg no such function key funktionstangenten finns inte +@msg no such color färgen finns inte +@msg {_1} cannot be used on Windows {_1} kan inte användas i Windows +@msg more than one action is named “{_1}” fler än en åtgärd heter ”{_1}” @msg no symbol named `{n}` ingen symbol med namnet `{n}` Angular Vinkelmått Away from the Line Bort från linjen @@ -5751,9 +5768,17 @@ axis Y Axis Y-axel Action Options… Alternativ för åtgärd… Action Options Alternativ för åtgärd Rename Action Byt namn på åtgärd + New Action… Ny åtgärd… + New Action Ny åtgärd + Create New Action Skapa ny åtgärd + Play Action Spela upp åtgärd + Action Set: Åtgärdsuppsättning: + Function Key: Funktionstangent: + Record Spela in Create New Set Skapa ny uppsättning Stop Global Edit Avsluta global redigering Global Edit Options Alternativ för global redigering + Leave Out of Global Edit Uteslut från global redigering Match Matcha On Artboards På ritytor All Artboards Alla ritytor @@ -5762,6 +5787,8 @@ axis Y Axis Y-axel @msg select one object markera ett objekt @msg Global Edit works on paths, compound paths, symbol instances and groups of them Global redigering fungerar på banor, sammansatta banor, symbolinstanser och grupper av dem @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again inga liknande objekt hittades (roterade eller speglade kopior matchas inte); ändra alternativen för global redigering och försök igen +@msg Global Edit is off Global redigering är inte aktiv +@msg only an object of the Global Edit other than the one it started from can be left out bara ett annat objekt än det som den globala redigeringen började med kan uteslutas @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all eller ett intervall som 1, 3-5, inte {v} Add to Symbols Lägg till i symboler Basic Shapes Grundformer @@ -6046,6 +6073,11 @@ shape Open Öppen Horizontal Scale Horisontell skala Vertical Scale Vertikal skala @msg {label} must be a number from {min} to {max} {label} måste vara ett tal från {min} till {max} + Character Color Teckenfärg + OpenType Features OpenType-funktioner + Stylistic Sets Stilistiska uppsättningar +@msg features lists at most {max} tags features får innehålla högst {max} taggar +@msg unknown OpenType feature `{t}` okänd OpenType-funktion `{t}` @msg {label} must be a number above 0 and at most {max} {label} måste vara ett tal över 0 och högst {max} @msg no character style `{name}` Teckenformatet `{name}` hittades inte @@ -6295,3 +6327,18 @@ breakText Glyphs Glyfer Create Swatch Legend Skapa färgrutelegend Create Swatch Legend… Skapa färgrutelegend… HEX HEX + +# The strings the report listed as missing for sv. + Font Size: Teckenstorlek: +digits Hindi Hindi +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Textverktyg + Text Tweaker… Textjustering… + Text Tweaker Textjustering + Attribute: Attribut: + From: Från: + To: Till: + Bow Båge + Spike Spets + Skip Spaces Hoppa över mellanslag +@msg The art is too large to copy as a picture: other apps get no PNG of it Teckningen är för stor för att kopieras som en bild: andra appar får ingen PNG av den diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index ae1a4f708e..bb2de38d61 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1792,8 +1792,8 @@ fn dataset_import_repeated_column_error_is_translated() { use vectorcraft_engine::{EngineError, Session}; let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); - let e = s.execute("dataset.import", &json!({"csv": "name,City,City\nR,Paris,Rome"})).unwrap_err(); - let want = "columns 2 and 3 both name the variable `City`"; + let e = s.execute("dataset.import", &json!({"csv": "City,City\nParis,Rome"})).unwrap_err(); + let want = "columns 1 and 2 both name the variable `City`"; assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{e}"); let e = e.to_string(); for code in COMPLETE_MESSAGES { @@ -1842,8 +1842,8 @@ fn dataset_export_limit_errors_are_translated() { use vectorcraft_engine::{EngineError, Session}; let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); - let rows: String = (1..=1000).map(|i| format!("Set {i},x\n")).collect(); - s.execute("dataset.import", &json!({"csv": format!("name,V1\n{rows}")})).unwrap(); + let rows = "x\n".repeat(1000); + s.execute("dataset.import", &json!({"csv": format!("V1\n{rows}")})).unwrap(); s.execute("dataset.new", &json!({"name": "Set 1001"})).unwrap(); let mut errors = vec![]; let e = s.execute("dataset.export", &json!({})).unwrap_err(); @@ -1906,8 +1906,8 @@ fn dataset_import_cell_errors_are_translated() { s.execute("variable.define", &json!({"name": "Sales", "kind": "graph"})).unwrap(); let mut errors = vec![]; for (csv, want) in [ - ("name,Show\nX,maybe".to_string(), "line 2: value for `Show` must be true or false"), - (format!("name,Sales\nX,\"{}\"", "1,".repeat(140_000)), "line 2: value for `Sales` is longer than 262144 bytes"), + ("Show\nmaybe".to_string(), "line 2: value for `Show` must be true or false"), + (format!("Sales\n\"{}\"", "1,".repeat(140_000)), "line 2: value for `Sales` is longer than 262144 bytes"), ] { let e = s.execute("dataset.import", &json!({"csv": csv})).unwrap_err(); assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{e}"); diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9009af8ae1..0517c552a8 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1179,6 +1179,7 @@ font-technology Variable Değişken Flip Row Order Satır Sırasını Çevir Flip Vertical Dikey Çevir Float in Window Pencerede Yüzer Yap + Float All in Windows Tümünü Pencerelerde Yüzer Yap Focal Fill Odak Dolgusu Focal Stroke Odak Konturu Folder Klasör @@ -1311,6 +1312,10 @@ font-technology Variable Değişken Handles Kollar Hard Light Sert Işık Harmony Rules: Uyum Kuralları: + Segmented color wheel Bölümlü renk tekerleği + Show smooth color wheel Kesintisiz renk tekerleğini göster + Show segmented color wheel Bölümlü renk tekerleğini göster + Show color bars Renk çubuklarını göster Harmony Sets Armoni Setleri Height Yükseklik Height: Yükseklik: @@ -1545,6 +1550,8 @@ font-technology Variable Değişken Large Thumbnail View Büyük Küçük Resim Görünümü Large Thumbnails Büyük Küçük Resimler Lasso Tool Kement Aracı + Enclosing Lasso Tool Çevreleyen Kement Aracı + Enclosing Lasso Çevreleyen Kement Last Effect: {name} Son Etki: {name} Last Effect: {} Son Etki: {} Last Effect… Son Etki… @@ -1694,6 +1701,7 @@ font-technology Variable Değişken Manually Manuel olarak Mark as trapped Sıkışmış olarak işaretle Mark Older Files as [Converted] When Opened Eski Dosyaları Açıldığında [Dönüştürülmüş] Olarak İşaretle + Use System Defaults for Edit Original Orijinali Düzenle için Sistem Varsayılanlarını Kullan Marker… işaretleyici… Marks İşaretler Marks and Bleed İşaretler ve Taşma Payı @@ -2512,6 +2520,8 @@ digits Malayalam Malayalam Replace Spine Omurgayı Değiştir Replace Symbol Sembolü Değiştir Replace With Font Yazı Tipiyle Değiştir + Replace With Font From Değiştirilecek Yazı Tipi Kaynağı + System Sistem Replaces the saved preset of that name. Bu adın kayıtlı ön ayarını değiştirir. Replace… Değiştir… Require a password to open the document Belgeyi açmak için parola gerektir @@ -3205,6 +3215,7 @@ digits Malayalam Malayalam Templates… Şablonlar… Text Displayed in Cell: Hücrede Görüntülenen Metin: Text Export Options Metin Dışa Aktarma Seçenekleri + Text Fill & Stroke Color Metin Dolgu ve Kontur Rengi Text Fill Color Metin Dolgu Rengi Text Import Options Metin İçe Aktarma Seçenekleri Text Stroke Color Metin Kontur Rengi @@ -5223,6 +5234,11 @@ theme Appearance Görünüm Export Type: İhracat Türü: Movie Clip Film Klibi @msg name is empty isim boş +@msg an action is already recording zaten bir eylem kaydediliyor +@msg no such function key öyle bir işlev tuşu yok +@msg no such color öyle bir renk yok +@msg {_1} cannot be used on Windows {_1} Windows'ta kullanılamaz +@msg more than one action is named “{_1}” birden fazla eylemin adı “{_1}” @msg no symbol named `{n}` `{n}` adında bir sembol yok Artboard Options: edit with the Artboard tool Çalışma Yüzeyi Seçenekleri: Çalışma Yüzeyi aracıyla düzenleme @msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), which can't be opened yet: save it as PDF, PDF-compatible .ai or SVG bu henüz açılamayan bir PostScript dosyasıdır (eski bir formatta kaydedilmiş veya PDF uyumluluğu olmayan bir .ai veya bir EPS dosyası): PDF, PDF uyumlu .ai veya SVG olarak kaydedin @@ -5509,6 +5525,7 @@ theme Appearance Görünüm Highlight: Vurgu: In Merge Mode, Clicking Stroke Splits the Path Birleştirme modunda kontura tıklamak yolu böler Insert Kashidas Keşide Ekle + Kashidas Keşide Load Variable Library… Değişken Kitaplığı Yükle… Save Variable Library… Değişken Kitaplığını Kaydet… @msg a variable library holds text variables, and the document has none değişken kitaplığı metin değişkenleri içerir ve belgede hiç metin değişkeni yok @@ -5685,9 +5702,17 @@ axis Y Axis Y ekseni Action Options… Eylem Seçenekleri… Action Options Eylem Seçenekleri Rename Action Eylemi Yeniden Adlandır + New Action… Yeni Eylem… + New Action Yeni Eylem + Create New Action Yeni Eylem Oluştur + Play Action Eylemi Oynat + Action Set: Eylem Seti: + Function Key: İşlev Tuşu: + Record Kayıt Create New Set Yeni Set Oluştur Stop Global Edit Genel Düzenlemeyi Durdur Global Edit Options Genel Düzenleme Seçenekleri + Leave Out of Global Edit Genel Düzenlemenin Dışında Bırak Match Eşleştir On Artboards Çalışma Yüzeylerinde All Artboards Tüm Çalışma Yüzeyleri @@ -5696,6 +5721,8 @@ axis Y Axis Y ekseni @msg select one object bir nesne seçin @msg Global Edit works on paths, compound paths, symbol instances and groups of them Genel düzenleme yollar, bileşik yollar, sembol örnekleri ve bunların grupları üzerinde çalışır @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again benzer nesne bulunamadı (döndürülmüş veya yansıtılmış kopyalar eşleşmez); Genel Düzenleme Seçeneklerini değiştirip yeniden deneyin +@msg Global Edit is off Genel düzenleme kapalı +@msg only an object of the Global Edit other than the one it started from can be left out yalnızca genel düzenlemenin başladığı nesne dışındaki bir nesne düzenlemenin dışında bırakılabilir @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ya da 1, 3-5 gibi bir aralık olmalı, {v} değil Add to Symbols Sembollere Ekle Basic Shapes Temel Şekiller @@ -5951,6 +5978,11 @@ anchor Points: Noktalar: Horizontal Scale Yatay Ölçek Vertical Scale Dikey Ölçek @msg {label} must be a number from {min} to {max} {label} {min} ile {max} arasında bir sayı olmalıdır + Character Color Karakter Rengi + OpenType Features OpenType Özellikleri + Stylistic Sets Stilistik Setler +@msg features lists at most {max} tags features en fazla {max} etiket içerebilir +@msg unknown OpenType feature `{t}` bilinmeyen OpenType özelliği `{t}` @msg {label} must be a number above 0 and at most {max} {label} 0'ın üzerinde ve en fazla {max} olan bir sayı olmalıdır @msg no character style `{name}` `{name}` karakter stili bulunamadı @@ -6200,3 +6232,14 @@ breakText Glyphs Glifler Create Swatch Legend Renk Örneği Açıklaması Oluştur Create Swatch Legend… Renk Örneği Açıklaması Oluştur… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Metin Araçları + Text Tweaker… Metin Ayarlayıcı… + Text Tweaker Metin Ayarlayıcı + Attribute: Öznitelik: + From: Başlangıç: + To: Bitiş: + Bow Yay + Spike Sivri Uç + Skip Spaces Boşlukları Atla +@msg The art is too large to copy as a picture: other apps get no PNG of it Çizim, resim olarak kopyalanamayacak kadar büyük: diğer uygulamalar bunun PNG'sini almaz diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 7535b5357c..71d3310321 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1232,6 +1232,7 @@ file-filter Templates Шаблони Flip Row Order Змінити порядок рядків Flip Vertical Відобразити по вертикалі Float in Window Відкріпити у вікні + Float All in Windows Відкріпити все у вікна Focal Fill Фокусна заливка Focal Stroke Фокусне обведення Folder Папка @@ -1395,6 +1396,10 @@ file-filter Templates Шаблони Hard Light Жорстке світло Hard Mix Жорстке накладання Harmony Rules: Правила гармонії: + Segmented color wheel Сегментоване колірне коло + Show smooth color wheel Показати плавне колірне коло + Show segmented color wheel Показати сегментоване колірне коло + Show color bars Показати колірні смуги Harmony Sets Набори гармонії Height Висота Height: Висота: @@ -1731,6 +1736,8 @@ file-filter Templates Шаблони Large Thumbnail View Великі мініатюри Large Thumbnails Великі мініатюри Lasso Tool Інструмент «Ласо» + Enclosing Lasso Tool Інструмент «Охоплювальне ласо» + Enclosing Lasso Охоплювальне ласо Last Effect: {name} Останній ефект: {name} Last Effect: {} Останній ефект: {} Last Effect… Останній ефект… @@ -1882,6 +1889,7 @@ file-filter Templates Шаблони Manually Вручну Mark as trapped Позначити як трепінг Mark Older Files as [Converted] When Opened Помічати старі файли як [Перетворені] при відкритті + Use System Defaults for Edit Original Використовувати системні типові програми для «Редагувати оригінал» Marker… Маркер… Marks Мітки Marks and Bleed Мітки та виліт @@ -1944,6 +1952,7 @@ file-filter Templates Шаблони Modify Змінити Mojikumi Mojikumi Insert Kashidas Вставляти кашиди + Kashidas Кашиди Long Довгі Stylistic Стилістичні Mojikumi Set Набір mojikumi @@ -2730,6 +2739,8 @@ digits Malayalam Малаялам Replace Spine Замінити вісь Replace Symbol Замінити символ Replace With Font Замінити шрифтом + Replace With Font From Замінити шрифтом з + System Система Replaces the saved preset of that name. Замінює збережений набір із таким ім’ям. Replace… Замінити… Require a password to open the document Вимагати пароль для відкриття документа @@ -3419,6 +3430,7 @@ effect Points Точки Templates… Шаблони… Text Displayed in Cell: Текст, що відображається в комірці: Text Export Options Параметри експорту тексту + Text Fill & Stroke Color Колір заливки та обведення тексту Text Fill Color Колір заливки тексту Text Import Options Параметри імпорту тексту Text Stroke Color Колір обведення тексту @@ -5151,6 +5163,11 @@ lighting Light Світло Export Type: Тип експорту: Movie Clip Кліп @msg name is empty ім’я порожнє +@msg an action is already recording дія вже записується +@msg no such function key такої функціональної клавіші немає +@msg no such color такого кольору немає +@msg {_1} cannot be used on Windows Сполучення {_1} не можна використовувати у Windows +@msg more than one action is named “{_1}” кілька дій мають назву «{_1}» @msg no symbol named `{n}` немає символу з назвою `{n}` Smudge Stick… Розтушовування… Smudge Stick Розтушовування @@ -5324,9 +5341,17 @@ axis Y Axis Вісь Y Action Options… Параметри дії… Action Options Параметри дії Rename Action Перейменувати дію + New Action… Нова дія… + New Action Нова дія + Create New Action Створити нову дію + Play Action Відтворити дію + Action Set: Набір дій: + Function Key: Функціональна клавіша: + Record Записати Create New Set Створити новий набір Stop Global Edit Завершити глобальне редагування Global Edit Options Параметри глобального редагування + Leave Out of Global Edit Виключити з глобального редагування Match Збіг On Artboards На монтажних областях All Artboards Усі монтажні області @@ -5335,6 +5360,8 @@ axis Y Axis Вісь Y @msg select one object виберіть один об’єкт @msg Global Edit works on paths, compound paths, symbol instances and groups of them Глобальне редагування працює з контурами, складеними контурами, екземплярами символів та їхніми групами @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again схожих об’єктів не знайдено (повернуті чи віддзеркалені копії не враховуються); змініть параметри глобального редагування та спробуйте ще раз +@msg Global Edit is off Глобальне редагування вимкнено +@msg only an object of the Global Edit other than the one it started from can be left out виключити з глобального редагування можна лише об’єкт, відмінний від того, з якого воно почалося @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all або діапазон, наприклад 1, 3-5, а не {v} Add to Symbols Додати до символів Basic Shapes Базові фігури @@ -5593,6 +5620,11 @@ anchor Points: Точки: Horizontal Scale Масштаб по горизонталі Vertical Scale Масштаб за вертикаллю @msg {label} must be a number from {min} to {max} {label} має бути числом від {min} до {max} + Character Color Колір символів + OpenType Features Функції OpenType + Stylistic Sets Стилістичні набори +@msg features lists at most {max} tags features містить не більше {max} тегів +@msg unknown OpenType feature `{t}` невідома функція OpenType `{t}` @msg {label} must be a number above 0 and at most {max} {label} має бути числом більше 0 і не більше {max} @msg no character style `{name}` Стиль символів `{name}` не знайдено @@ -5843,3 +5875,14 @@ breakText Glyphs Гліфи Create Swatch Legend Створити легенду зразків Create Swatch Legend… Створити легенду зразків… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Інструменти тексту + Text Tweaker… Налаштування тексту… + Text Tweaker Налаштування тексту + Attribute: Атрибут: + From: Від: + To: До: + Bow Дуга + Spike Пік + Skip Spaces Пропускати пробіли +@msg The art is too large to copy as a picture: other apps get no PNG of it Графіка завелика, щоб скопіювати її як зображення: інші програми не отримають її PNG diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 07852ac9fd..8110a2d206 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1431,6 +1431,7 @@ file-filter Templates Mẫu Flip Vertical Lật dọc Flip: Lật: Float in Window Nổi trong cửa sổ + Float All in Windows Nổi tất cả trong cửa sổ Float Panel Thả nổi bảng Float Tool Group Thả nổi nhóm công cụ Focal Fill Tô tiêu điểm @@ -1610,6 +1611,10 @@ file-filter Templates Mẫu Hard Light Ánh sáng mạnh Hard Mix Trộn cứng Harmony Rules: Quy tắc hài hòa màu: + Segmented color wheel Bánh xe màu phân đoạn + Show smooth color wheel Hiện bánh xe màu liền mạch + Show segmented color wheel Hiện bánh xe màu phân đoạn + Show color bars Hiện các thanh màu Harmony Sets Bộ hài hòa màu Height Chiều cao Height: Chiều cao: @@ -1985,6 +1990,8 @@ digits Hindi Hindi Large Thumbnails Hình thu nhỏ lớn Largest: Lớn nhất: Lasso Tool Công cụ Lasso + Enclosing Lasso Tool Công cụ Lasso bao quanh + Enclosing Lasso Lasso bao quanh Last Cuối cùng Last commit Commit cuối cùng Last Effect: {name} Hiệu ứng vừa dùng: {name} @@ -2167,6 +2174,7 @@ digits Hindi Hindi Manually Thủ công Mark as trapped Đánh dấu đã chồng màu Mark Older Files as [Converted] When Opened Đánh dấu tệp cũ là [Đã chuyển đổi] khi mở + Use System Defaults for Edit Original Dùng mặc định hệ thống cho Chỉnh sửa bản gốc Marker… Ký hiệu đánh dấu… Marks Dấu in Marks and Bleed Dấu in và chảy tràn @@ -2245,6 +2253,7 @@ digits Hindi Hindi Modify Sửa đổi Mojikumi Mojikumi Insert Kashidas Chèn kashida + Kashidas Kashida Long Dài Stylistic Kiểu cách Mojikumi Set Bộ Mojikumi @@ -2999,6 +3008,8 @@ mark-style Japanese Kiểu Nhật Replace Spine Thay thế trục Replace Symbol Thay thế ký hiệu Replace With Font Thay thế bằng phông chữ + Replace With Font From Thay thế bằng phông chữ từ + System Hệ thống Replace “{name}”, the file this document was opened from? Thay thế “{name}”, tệp mà tài liệu này được mở từ đó? Replaces the saved preset of that name. Thay thế thiết lập sẵn đã lưu có tên đó. Replace… Thay thế… @@ -3748,6 +3759,7 @@ mark-style Japanese Kiểu Nhật Text Văn bản Text Displayed in Cell: Văn bản hiển thị trong ô: Text Export Options Tùy chọn xuất văn bản + Text Fill & Stroke Color Màu tô & nét văn bản Text Fill Color Màu tô văn bản Text Import Options Tùy chọn nhập văn bản Text Stroke Color Màu nét văn bản @@ -5152,6 +5164,11 @@ theme Appearance Giao diện Export Type: Kiểu xuất: Movie Clip Clip phim @msg name is empty tên trống +@msg an action is already recording đang ghi một hành động +@msg no such function key không có phím chức năng như vậy +@msg no such color không có màu như vậy +@msg {_1} cannot be used on Windows không thể dùng {_1} trên Windows +@msg more than one action is named “{_1}” có nhiều hành động tên là “{_1}” @msg no symbol named `{n}` không có biểu tượng nào tên `{n}` Smudge Stick… Bút chì xóa mờ… Smudge Stick Bút chì xóa mờ @@ -5325,9 +5342,17 @@ axis Y Axis Trục Y Action Options… Tùy chọn hành động… Action Options Tùy chọn hành động Rename Action Đổi tên hành động + New Action… Hành động mới… + New Action Hành động mới + Create New Action Tạo hành động mới + Play Action Phát hành động + Action Set: Bộ hành động: + Function Key: Phím chức năng: + Record Ghi Create New Set Tạo bộ mới Stop Global Edit Dừng chỉnh sửa toàn cục Global Edit Options Tùy chọn chỉnh sửa toàn cục + Leave Out of Global Edit Loại khỏi chỉnh sửa toàn cục Match Khớp On Artboards Trên các bảng vẽ All Artboards Tất cả bảng vẽ @@ -5336,6 +5361,8 @@ axis Y Axis Trục Y @msg select one object hãy chọn một đối tượng @msg Global Edit works on paths, compound paths, symbol instances and groups of them Chỉnh sửa toàn cục hoạt động trên đường dẫn, đường dẫn phức hợp, phiên bản biểu tượng và nhóm của chúng @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again không tìm thấy đối tượng tương tự (các bản sao đã xoay hoặc lật không được tính); hãy thay đổi tùy chọn chỉnh sửa toàn cục rồi thử lại +@msg Global Edit is off Chỉnh sửa toàn cục đang tắt +@msg only an object of the Global Edit other than the one it started from can be left out chỉ có thể loại khỏi chỉnh sửa toàn cục một đối tượng khác với đối tượng mà nó bắt đầu @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all hoặc một phạm vi như 1, 3-5, không phải {v} Add to Symbols Thêm vào ký hiệu Basic Shapes Hình cơ bản @@ -5594,6 +5621,11 @@ anchor Points: Điểm: Horizontal Scale Tỷ lệ ngang Vertical Scale Tỷ lệ dọc @msg {label} must be a number from {min} to {max} {label} phải là một số từ {min} đến {max} + Character Color Màu ký tự + OpenType Features Tính năng OpenType + Stylistic Sets Bộ phong cách +@msg features lists at most {max} tags features chứa tối đa {max} thẻ +@msg unknown OpenType feature `{t}` tính năng OpenType không xác định `{t}` @msg {label} must be a number above 0 and at most {max} {label} phải là một số lớn hơn 0 và tối đa {max} @msg no character style `{name}` Không tìm thấy kiểu ký tự `{name}` @@ -5844,3 +5876,14 @@ breakText Glyphs Glyph Create Swatch Legend Tạo chú giải mẫu màu Create Swatch Legend… Tạo chú giải mẫu màu… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Công cụ văn bản + Text Tweaker… Tinh chỉnh văn bản… + Text Tweaker Tinh chỉnh văn bản + Attribute: Thuộc tính: + From: Từ: + To: Đến: + Bow Cung + Spike Đỉnh nhọn + Skip Spaces Bỏ qua khoảng trắng +@msg The art is too large to copy as a picture: other apps get no PNG of it Hình vẽ quá lớn để sao chép dưới dạng ảnh: các ứng dụng khác không nhận được PNG của nó diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d609725c4e..aaf791fea2 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1176,6 +1176,7 @@ file-filter Templates 模板 Flip Row Order 反转行顺序 Flip Vertical 垂直翻转 Float in Window 在窗口中浮动 + Float All in Windows 全部在窗口中浮动 Focal Fill 焦点填色 Focal Stroke 焦点描边 Folder 文件夹 @@ -1338,6 +1339,10 @@ file-filter Templates 模板 Hard Light 强光 Hard Mix 实色混合 Harmony Rules: 协调规则: + Segmented color wheel 分段色轮 + Show smooth color wheel 显示平滑色轮 + Show segmented color wheel 显示分段色轮 + Show color bars 显示颜色条 Harmony Sets 色彩调和组 Height 高度 Height: 高度: @@ -1624,6 +1629,8 @@ file-filter Templates 模板 Large Thumbnail View 大缩略图视图 Large Thumbnails 大缩略图 Lasso Tool 套索工具 + Enclosing Lasso Tool 包围套索工具 + Enclosing Lasso 包围套索 Last Effect: {name} 最后一次效果:{name} Last Effect: {} 上次效果:{} Last Effect… 上次效果… @@ -1739,7 +1746,7 @@ file-filter Templates 模板 Lossy: 有损: Low 低 lowercase 小写 - Luminosity 亮度 + Luminosity 明度 LZW Compression LZW 压缩 Mac Mac Magenta 洋红 @@ -1769,6 +1776,7 @@ file-filter Templates 模板 Manually 手动 Mark as trapped 标示为已陷印 Mark Older Files as [Converted] When Opened 打开旧文件时标记为 [已转换] + Use System Defaults for Edit Original “编辑原稿”使用系统默认设置 Marker… 标记… Marks 标记 Marks and Bleed 标记和出血 @@ -2608,6 +2616,8 @@ digits Malayalam 马拉雅拉姆数字 Replace Spine 替换脊线 Replace Symbol 替换符号 Replace With Font 替换为字体 + Replace With Font From 替换字体来源 + System 系统 Replaces the saved preset of that name. 替换同名已存预设。 Replace… 替换… Require a password to open the document 打开文档时需要密码 @@ -3258,6 +3268,7 @@ digits Malayalam 马拉雅拉姆数字 Templates… 模板… Text Displayed in Cell: 单元格中显示的文字: Text Export Options 文本导出选项 + Text Fill & Stroke Color 文字填色和描边颜色 Text Fill Color 文字填色 Text Import Options 文本导入选项 Text Stroke Color 文字描边颜色 @@ -4896,6 +4907,7 @@ font-technology Variable 可变 Right-to-Left Paragraph Direction 从右到左段落方向 Line-end Punctuation Half Width 行尾标点半角 Insert Kashidas 插入卡希达 + Kashidas 卡希达 Long 长 Stylistic 风格化 Mojikumi Set 标点挤压集 @@ -5391,6 +5403,11 @@ lighting Light 光源 Export Type: 导出类型: Movie Clip 影片剪辑 @msg name is empty 名称为空 +@msg an action is already recording 已在记录动作 +@msg no such function key 没有此功能键 +@msg no such color 没有此颜色 +@msg {_1} cannot be used on Windows {_1} 在 Windows 上不能使用 +@msg more than one action is named “{_1}” 有多个动作名为“{_1}” @msg no symbol named `{n}` 没有名为 `{n}` 的符号 Smudge Stick… 涂抹棒… Smudge Stick 涂抹棒 @@ -5566,9 +5583,17 @@ axis Y Axis Y 轴 Action Options… 动作选项… Action Options 动作选项 Rename Action 重命名动作 + New Action… 新建动作… + New Action 新建动作 + Create New Action 创建新动作 + Play Action 播放动作 + Action Set: 动作组: + Function Key: 功能键: + Record 记录 Create New Set 创建新组 Stop Global Edit 停止全局编辑 Global Edit Options 全局编辑选项 + Leave Out of Global Edit 从全局编辑中排除 Match 匹配 On Artboards 在画板上 All Artboards 所有画板 @@ -5577,6 +5602,8 @@ axis Y Axis Y 轴 @msg select one object 请选择一个对象 @msg Global Edit works on paths, compound paths, symbol instances and groups of them 全局编辑适用于路径、复合路径、符号实例及其编组 @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again 未找到相似对象(旋转或镜像的副本不会匹配);请更改全局编辑选项后重试 +@msg Global Edit is off 全局编辑未开启 +@msg only an object of the Global Edit other than the one it started from can be left out 只能从全局编辑中排除起始对象以外的对象 @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`:应为 all 或 1, 3-5 这样的范围,而不是 {v} Add to Symbols 添加到符号 Basic Shapes 基本形状 @@ -5835,6 +5862,11 @@ anchor Points: 点: Horizontal Scale 水平缩放 Vertical Scale 垂直缩放 @msg {label} must be a number from {min} to {max} {label} 必须是 {min} 到 {max} 之间的数字 + Character Color 字符颜色 + OpenType Features OpenType 特性 + Stylistic Sets 风格集 +@msg features lists at most {max} tags features 最多包含 {max} 个标签 +@msg unknown OpenType feature `{t}` 未知的 OpenType 特性 `{t}` @msg {label} must be a number above 0 and at most {max} {label} 必须是大于 0 且不超过 {max} 的数字 @msg no character style `{name}` 找不到字符样式 `{name}` @@ -6084,3 +6116,14 @@ breakText Glyphs 字形 Create Swatch Legend 创建色板图例 Create Swatch Legend… 创建色板图例… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools 文字工具 + Text Tweaker… 文字微调… + Text Tweaker 文字微调 + Attribute: 属性: + From: 起始: + To: 结束: + Bow 弓形 + Spike 尖峰 + Skip Spaces 跳过空格 +@msg The art is too large to copy as a picture: other apps get no PNG of it 图稿太大,无法作为图片复制:其他应用不会获得它的 PNG diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 32dbb3ba2b..a0bf8bf80b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1202,6 +1202,7 @@ file-filter Templates 範本 Flip Row Order 反轉列順序 Flip Vertical 垂直翻轉 Float in Window 在視窗中浮動 + Float All in Windows 全部在視窗中浮動 Focal Fill 焦點填色 Focal Stroke 焦點筆畫 Folder 資料夾 @@ -1366,6 +1367,10 @@ file-filter Templates 範本 Hard Light 實光 Hard Mix 實色混合 Harmony Rules: 色彩調和規則: + Segmented color wheel 分段色輪 + Show smooth color wheel 顯示平滑色輪 + Show segmented color wheel 顯示分段色輪 + Show color bars 顯示顏色條 Harmony Sets 色彩調和組 Height 高度 Height: 高度: @@ -2571,6 +2576,8 @@ file-filter Templates 範本 Large Thumbnail View 大縮圖檢視 Large Thumbnails 大縮圖 Lasso Tool 套索工具 + Enclosing Lasso Tool 包圍套索工具 + Enclosing Lasso 包圍套索 Last Effect: {name} 最後一次效果:{name} Last Effect: {} 上次效果:{} Last Effect… 最後一次效果… @@ -2723,6 +2730,7 @@ file-filter Templates 範本 Manually 手動 Mark as trapped 標示為已陷印 Mark Older Files as [Converted] When Opened 開啟舊檔時標示為 [已轉換] + Use System Defaults for Edit Original 「編輯原稿」使用系統預設值 Marker… 標記… Marks 標記 Marks and Bleed 標記與出血 @@ -2784,6 +2792,7 @@ file-filter Templates 範本 Modified: 修改時間: Modify 修改 Insert Kashidas 插入卡希達 + Kashidas 卡希達 Long 長 Stylistic 風格化 Mojikumi Set 標點間距 @@ -3590,6 +3599,8 @@ digits Malayalam 馬來亞拉姆數字 Replace Spine 取代脊線 Replace Symbol 取代符號 Replace With Font 取代為字體 + Replace With Font From 取代字體來源 + System 系統 Replaces the saved preset of that name. 取代同名的已儲存預設集。 Replace… 取代… Require a password to open the document 開啟文件時需要密碼 @@ -4276,6 +4287,7 @@ digits Malayalam 馬來亞拉姆數字 Templates… 範本… Text Displayed in Cell: 儲存格中顯示的文字: Text Export Options 文字匯出選項 + Text Fill & Stroke Color 文字填色與筆畫顏色 Text Fill Color 文字填色 Text Import Options 文字匯入選項 Text Stroke Color 文字筆畫顏色 @@ -5208,6 +5220,11 @@ lighting Light 光源 Export Type: 轉存類型: Movie Clip 影片片段 @msg name is empty 名稱為空 +@msg an action is already recording 已在錄製動作 +@msg no such function key 沒有這個功能鍵 +@msg no such color 沒有這個顏色 +@msg {_1} cannot be used on Windows {_1} 無法在 Windows 上使用 +@msg more than one action is named “{_1}” 有多個動作名為「{_1}」 @msg no symbol named `{n}` 沒有名為 `{n}` 的符號 Smudge Stick… 塗抹棒… Smudge Stick 塗抹棒 @@ -5362,9 +5379,17 @@ axis Y Axis Y 軸 Action Options… 動作選項… Action Options 動作選項 Rename Action 重新命名動作 + New Action… 新增動作… + New Action 新增動作 + Create New Action 建立新動作 + Play Action 播放動作 + Action Set: 動作組: + Function Key: 功能鍵: + Record 錄製 Create New Set 建立新組 Stop Global Edit 停止整體編輯 Global Edit Options 整體編輯選項 + Leave Out of Global Edit 從整體編輯中排除 Match 符合 On Artboards 在工作區域上 All Artboards 所有工作區域 @@ -5373,6 +5398,8 @@ axis Y Axis Y 軸 @msg select one object 請選取一個物件 @msg Global Edit works on paths, compound paths, symbol instances and groups of them 整體編輯適用於路徑、複合路徑、符號實體及其群組 @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again 找不到相似的物件(旋轉或鏡像的副本不會相符);請變更整體編輯選項後再試一次 +@msg Global Edit is off 整體編輯未開啟 +@msg only an object of the Global Edit other than the one it started from can be left out 只能從整體編輯中排除起始物件以外的物件 @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`:應為 all 或 1, 3-5 這類範圍,而不是 {v} Add to Symbols 新增至符號 Basic Shapes 基本形狀 @@ -5631,6 +5658,11 @@ anchor Points: 點: Horizontal Scale 水平縮放 Vertical Scale 垂直縮放 @msg {label} must be a number from {min} to {max} {label} 必須是 {min} 到 {max} 之間的數字 + Character Color 字元顏色 + OpenType Features OpenType 功能 + Stylistic Sets 風格集 +@msg features lists at most {max} tags features 最多包含 {max} 個標籤 +@msg unknown OpenType feature `{t}` 未知的 OpenType 功能 `{t}` @msg {label} must be a number above 0 and at most {max} {label} 必須是大於 0 且不超過 {max} 的數字 @msg no character style `{name}` 找不到字元樣式 `{name}` @@ -5881,3 +5913,14 @@ breakText Glyphs 字符 Create Swatch Legend 建立色票圖例 Create Swatch Legend… 建立色票圖例… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools 文字工具 + Text Tweaker… 文字微調… + Text Tweaker 文字微調 + Attribute: 屬性: + From: 起始: + To: 結束: + Bow 弓形 + Spike 尖峰 + Skip Spaces 略過空格 +@msg The art is too large to copy as a picture: other apps get no PNG of it 圖稿太大,無法作為圖片複製:其他應用程式不會取得它的 PNG diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs index 89c102f358..4818a0c159 100644 --- a/crates/ui-egui/src/io.rs +++ b/crates/ui-egui/src/io.rs @@ -18,11 +18,13 @@ mod open; mod save; pub use export::{EXPORT_CANCELLED, cancel_exports, export, export_for_screens, export_pdf, hide_exports, reveal, save_command_output}; -pub(crate) use export::{export_files, exported_with_notes, file_url, open_in_app, reveal_path, run_to_file, save_command_output_named}; +pub(crate) use export::{ + export_files, exported_with_notes, file_url, open_in_app, open_original, reveal_path, run_to_file, save_command_output_named, +}; pub(crate) use open::{EXPORT_PRESETS, import_presets, opened}; pub use open::{ MAX_RECENT_FILES, OpensAs, ask_revert, install_module, install_plugin, new_from_template, note_recent, open_bytes, open_dialog, open_document, - open_path, open_recent_reporting, open_reporting, opens_as, place_bytes, recent_files, report_open_error, + open_path, open_reporting, opens_as, place_bytes, recent_files, report_open_error, }; #[cfg(test)] pub(crate) use open::{open_file, opened_with_notes}; diff --git a/crates/ui-egui/src/io/export.rs b/crates/ui-egui/src/io/export.rs index 60c7656dda..f323231511 100644 --- a/crates/ui-egui/src/io/export.rs +++ b/crates/ui-egui/src/io/export.rs @@ -217,6 +217,22 @@ pub(crate) fn open_in_app(app: &mut VectorcraftApp, path: &str) -> Result<(), St app.services.open_file.as_mut().ok_or("no app to open files here")?(path) } +/// Edit Original: open `path` in the system's default app for it, or with Preferences › File +/// Handling › Use System Defaults for Edit Original off, in the app that made it (#5236): PhotoCraft +/// for a raster image where it is installed. Any other file, or no PhotoCraft, uses the system's app. +pub(crate) fn open_original(app: &mut VectorcraftApp, path: &str) -> Result<(), String> { + let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().into_owned()).unwrap_or_default(); + let raster = vectorcraft_engine::cmd::fileio::readable_format(&ext).is_some_and(|f| f.raster); + if !app.session.prefs.edit_original_system_defaults + && raster + && let Some(open) = app.services.open_in_photocraft.as_mut() + && open(path)? + { + return Ok(()); + } + open_in_app(app, path) +} + /// File → Export for Screens with `document.exportForScreens` params: the files go into `folder`; /// without one the web downloads them (the ZIP, or each file) and the other frontends get them /// back as base64. With `openLocation`, the file manager shows the first file written. When an diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 9ea56a0a62..ace4f2694e 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -229,15 +229,9 @@ pub fn open_reporting(app: &mut VectorcraftApp, path: &str) -> Result Result { - if let Some(r) = try_activate_open_document(app, path)? { - return Ok(r); - } - open_reporting(app, path) -} - +/// A file already open in a tab is not opened again: its tab comes to the front, unsaved edits +/// and all (#3455), without the questions asked after an open (missing links and fonts). +/// → `{activated: true, …}` as `document.open`'s result, or None. fn try_activate_open_document(app: &mut VectorcraftApp, path: &str) -> Result, String> { let Some(index) = document_index_for_path(app, path) else { return Ok(None); @@ -252,7 +246,7 @@ fn try_activate_open_document(app: &mut VectorcraftApp, path: &str) -> Result Result /// [`open_path`]; with `background`, a document (not a file that installs, imports or asks /// first) is decoded off the UI thread ([`crate::opening::start`]). pub(crate) fn open_file(app: &mut VectorcraftApp, path: &str, background: bool) -> Result { + // File › Open, Open Recent, the Home screen, a drop and the Finder all focus a document that + // is already open, or still being read, instead of opening a second copy. + if let Some(r) = try_activate_open_document(app, path)? { + return Ok(r); + } + if app.opening.pending.iter().any(|p| same_open_path(&p.path, path)) { + return Ok(Value::Null); + } // A shortcut set is read by Import Shortcut Set, up to its reader's cap. if dialogs::shortcut_import::is_kys(path) { dialogs::shortcut_import::command(app, &json!({ "path": path }))?; diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index d1c15369fb..3392e7e431 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -370,7 +370,8 @@ pub fn save_pdf(app: &mut VectorcraftApp, mode: SaveMode, mut params: Value) -> /// Open a written file in the system viewer (not on the web, which downloads it). pub(super) fn view_file(app: &mut VectorcraftApp, path: &str) { - if !is_web(app) { + // The viewer is another app: an export automation asked for is written but not opened. + if !is_web(app) && app.refuse_automation("viewAfterSaving").is_ok() { app.open_url(&file_url(path)); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index de33cfcce6..bdfcaffffa 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -34,6 +34,7 @@ pub mod credits; pub mod cursors; mod custom_toolbars; pub mod dialogs; +pub mod doc_windows; pub mod dock; mod edit_toolbar; pub mod export_progress; diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 7a3213f78a..0b30e0dc63 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -71,6 +71,7 @@ pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static st crate::addons::pathtools::dashes::COMMAND => (crate::addons::pathtools::dashes::KIND, crate::addons::pathtools::dashes::fields()), crate::addons::color::nearest::COMMAND => (crate::addons::color::nearest::KIND, crate::addons::color::nearest::fields()), crate::addons::color::legend::COMMAND => (crate::addons::color::legend::KIND, crate::addons::color::legend::fields()), + crate::addons::typetools::COMMAND => (crate::addons::typetools::KIND, crate::addons::typetools::fields(app)), "artboard.rearrange" => (crate::dialogs::rearrange_artboards::KIND, crate::dialogs::rearrange_artboards::open_fields(app)), _ => return None, }) diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 5ba39f237d..5661450266 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -126,7 +126,7 @@ fn run_ui_part1(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Ok(io::cancel_exports(app)), "file.exportInBackground" => Ok(io::hide_exports(app)), id if id.starts_with("file.openRecent") => match recent_slot(app, id).cloned() { - Some(path) => io::open_recent_reporting(app, &path), + Some(path) => io::open_reporting(app, &path), None => Err("no such recent file".into()), }, "type.findFont" => { @@ -545,7 +545,11 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Err("brightness must be dark|mediumDark|mediumLight|light".into()), }, "window.newWindow" => Err("New Window isn't available yet: a document opens in one window".into()), + "window.arrange.cascade" => crate::doc_windows::cascade(app), "window.arrange.tile" => crate::canvas::tile(app), + "window.arrange.floatInWindow" => crate::doc_windows::float_in_window(app, p), + "window.arrange.floatAllInWindows" => crate::doc_windows::float_all(app), + "window.arrange.consolidateAllWindows" if p.get("index").is_some_and(|i| !i.is_null()) => crate::doc_windows::dock(app, p), "window.arrange.consolidateAllWindows" => crate::canvas::consolidate(app), "window.nextDocument" => crate::chrome::step_document(app, true), "window.previousDocument" => crate::chrome::step_document(app, false), @@ -811,6 +815,10 @@ fn run_ui_part11(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::package::open(app), crate::panels::actions::RENAME_ACTION => crate::panels::actions::rename_action(app, p), + crate::panels::actions::NEW_ACTION => crate::panels::actions::new_action(app, p), + crate::panels::actions::ACTION_OPTIONS => crate::panels::actions::action_options(app, p), + crate::panels::actions::PLAY_ACTION => crate::panels::actions::play_action(app, p), + crate::panels::actions::STOP_RECORDING => crate::panels::actions::stop(app, p), "ui.batchDialog" => { let set = p.get("set").and_then(Value::as_u64).unwrap_or(0) as usize; let action = p.get("action").and_then(Value::as_u64).unwrap_or(0) as usize; diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 26904fcae6..523d930e0d 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -283,11 +283,18 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { app.session.active().is_some() && crate::dialogs::perspective_presets::slot_preset(app, id).is_some() } "ui.perspectivePlane" => app.session.active().is_some(), - // Only one window per document so far: greyed out, as Cascade and Float in Window are (#3724). + // Only one window per document so far: grayed out (#3724). "window.newWindow" => false, - // Tile with two documents or more; Consolidate All Windows while they are tiled. - "window.arrange.tile" => app.session.documents().len() > 1, - "window.arrange.consolidateAllWindows" => app.ui.tiled && !app.session.documents().is_empty(), + // Tile and Cascade with two documents or more; Float in Window for a current document under + // the tabs; Float All in Windows while a document is under the tabs; Consolidate All + // Windows while documents are tiled or floating. + "window.arrange.tile" | "window.arrange.cascade" => app.session.documents().len() > 1, + "window.arrange.floatInWindow" => app.session.active_index().is_some_and(|i| !crate::doc_windows::is_floating(app, i)), + "window.arrange.floatAllInWindows" => !crate::doc_windows::docked(app).is_empty(), + "window.arrange.consolidateAllWindows" => { + let n = app.session.documents().len(); + n > 0 && (app.ui.tiled || crate::doc_windows::docked(app).len() < n) + } "window.nextDocument" | "window.previousDocument" => !app.session.documents().is_empty(), _ => true, } diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 04769b2c60..4b46453ca7 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -527,6 +527,28 @@ fn select_same_link_block_series_selects_a_thread_from_the_menu() { assert_eq!(json!(ids), json!([a, b])); } +#[test] +fn select_same_text_fill_and_stroke_color_follows_text_stroke_color_in_the_menu() { + let mut app = app_with_a_rectangle(); + let entries = menu_entries(&app); + let at = |id: &str| entries.iter().position(|e| e.command.as_deref() == Some(id)); + let entry = at("select.same.textFillAndStrokeColor").map(|i| &entries[i]).expect("menu entry"); + assert_eq!((entry.path.clone(), entry.label.as_str()), (vec!["Select".to_string(), "Same".to_string()], "Text Fill & Stroke Color")); + assert_eq!(at("select.same.textStrokeColor").map(|i| i + 1), at("select.same.textFillAndStrokeColor")); + let text = |app: &mut VectorcraftApp, y: i32, fill: &str, stroke: &str| { + let id = app.run("text.create", json!({"x": 0, "y": y, "text": "type"})).unwrap()["id"].clone(); + app.run("text.setRangeStyle", json!({"id": id.clone(), "start": 0, "end": 4, "fill": fill, "stroke": stroke})).unwrap(); + id + }; + let a = text(&mut app, 40, "#ff0000", "#0000ff"); + let b = text(&mut app, 80, "#ff0000", "#0000ff"); + let _ = text(&mut app, 120, "#ff0000", "#00ff00"); + app.run("select.set", json!({"ids": [a.clone()]})).unwrap(); + invoke(&mut app, "select.same.textFillAndStrokeColor", json!({})); + let ids: Vec = app.session.active().unwrap().selection.objects.iter().map(|i| i.0).collect(); + assert_eq!(json!(ids), json!([a, b])); +} + #[test] fn edit_selection_opens_its_dialog_on_the_saved_selections() { let mut app = app_with_a_rectangle(); diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 9eabfc6814..3a55ab37c0 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -470,6 +470,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Font Size", "select.same.fontSize"), c("Text Fill Color", "select.same.textFillColor"), c("Text Stroke Color", "select.same.textStrokeColor"), + c("Text Fill & Stroke Color", "select.same.textFillAndStrokeColor"), ], ), sub( @@ -611,9 +612,10 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { sub( "Arrange", vec![ - todo("Cascade"), + c("Cascade", "window.arrange.cascade"), c("Tile", "window.arrange.tile"), - todo("Float in Window"), + c("Float in Window", "window.arrange.floatInWindow"), + c("Float All in Windows", "window.arrange.floatAllInWindows"), c("Consolidate All Windows", "window.arrange.consolidateAllWindows"), ], ), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 5f7dc201e8..9e887870a1 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -581,17 +581,35 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("window.workspace.rename", "Rename Workspace", "", "{name, to}"), ("window.workspace.list", "List Workspaces", "", "{}"), ("window.newWindow", "New Window", "", "{}"), + ( + "window.arrange.cascade", + "Cascade", + "", + "{} put every open document in a floating window of its own and stack the windows from the upper left of the document area to its lower right, 30 pt apart, in tab order, each fitted to its window, the current document's in front; on the desktop each is an OS window, on the web and Wayland a window inside the app's window; returns {floating} (document indices)", + ), ( "window.arrange.tile", "Tile", "", - "{} show every open document at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of documents, rounded up), each fitted to its pane; the current document's pane takes the tools, a click in another pane makes its document the current one; the tabs stay; returns {tiled: true, panes}", + "{} show every open document at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of documents, rounded up), each fitted to its pane; the current document's pane takes the tools, a click in another pane makes its document the current one; the tabs stay; documents in floating windows come back under the tabs first; with fewer than two documents open the view stays as it is; returns {tiled, panes}", + ), + ( + "window.arrange.floatInWindow", + "Float in Window", + "", + "{index?, at?: [x, y]} move the current document, or document `index` (which becomes the current one), out of the tab strip into a floating window of its own, fitted to it, with the window's top-left corner at `at` (main window points) or else at the next place of a cascade; dragging a document tab more than 24 pt above or below the tab strip does this at the pointer; the window holding the current document takes the tools, a click in another document's window makes its document the current one; a document already floating stays where it is; returns {floating} (document indices)", + ), + ( + "window.arrange.floatAllInWindows", + "Float All in Windows", + "", + "{} move every document under the tab strip into a floating window of its own, at the next places of a cascade; returns {floating} (document indices)", ), ( "window.arrange.consolidateAllWindows", "Consolidate All Windows", "", - "{} show one document at a time again, under its tab, after Tile; returns {tiled: false}", + "{index?} show one document at a time again, under its tab, after Tile, Float in Window, Float All in Windows or Cascade; returns {tiled: false, floating: []}; with `index`, only document `index` goes back under its tab and becomes the current one, the other windows and Tile staying as they are, as when a document window is dragged by its title bar (an OS window by the tab at its top) onto the tab strip; returns {tiled, floating} (document indices)", ), ( "window.nextDocument", @@ -706,7 +724,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.charStyleOptions.resetPanel", "Reset Panel", "", - "{} clear the settings of the section shown, Basic Character Formats or Advanced Character Formats, in the open Character Style Options or New Character Style dialog; available only on those sections", + "{} clear the settings of the section shown, Basic Character Formats, Advanced Character Formats, Character Color or OpenType Features, in the open Character Style Options or New Character Style dialog; available only on those sections", ), ( "ui.newCharStyle", @@ -1162,7 +1180,31 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ crate::panels::actions::RENAME_ACTION, "Rename Action", "", - "{set: index, action: index, name} rename the Actions panel's action at action in set (0 is the top set) to name, with spaces trimmed from both ends; its steps stay. The panel menu's Action Options… (dialog `actionSetOptions` with set, action and name) runs this for the selected action. An index past the last set or action, or an empty name, is an error and renames nothing → {name}", + "{set: index, action: index, name} rename the Actions panel's action at action in set (0 is the top set) to name, with spaces trimmed from both ends; its steps, function key and color stay. An index past the last set or action, or an empty name, is an error and renames nothing → {name}", + ), + ( + crate::panels::actions::NEW_ACTION, + "New Action", + "", + "{set: index, name, key?: 0-15, cmd?, shift?, color?: red|yellow|green|blue|violet} add an action named name (spaces trimmed from both ends) after the last action of the Actions panel's set at set (0 is the top set) and start recording into it; Stop Playing/Recording (ui.action.stop) ends the recording. key 1 to 15 is the function key F1 to F15 that plays the action (0 or null: none), with cmd (Ctrl, Command on macOS) and shift; color is its Button Mode color (null or \"\": none), which the panel does not show. Action function keys take priority over command shortcuts and preserve the command's binding. On Windows F1, Ctrl+F4 and Ctrl+F6 cannot be used. The set becomes current and the new action is selected. The panel's Create New Action button and menu's New Action… (dialog `actionNew` with set, name, key, cmd, shift and color) run this on Record. While an action is recording, and for an index past the last set, an empty name, or a key or color that is not one of these, it is an error and nothing is added → {set, action}", + ), + ( + crate::panels::actions::ACTION_OPTIONS, + "Action Options", + "", + "{set: index, action: index, name?, key?: 0-15, cmd?, shift?, color?: red|yellow|green|blue|violet} change the Actions panel's action at action in set (0 is the top set); its steps stay. name renames it (spaces trimmed from both ends), key 1 to 15 with cmd (Ctrl, Command on macOS) and shift sets the function key F1 to F15 that plays it (0 or null: none), and color sets its Button Mode color (null or \"\": none); a param left out keeps what the action has, and cmd or shift alone changes that modifier of its key. Action function keys take priority over command shortcuts and preserve the command's binding. The panel menu's Action Options… (dialog `actionSetOptions` with set, action, name, key, cmd, shift and color) runs this for the selected action. An index past the last set or action, an empty name, or a key or color that is not one of these is an error and changes nothing → {name, key, color}", + ), + ( + crate::panels::actions::PLAY_ACTION, + "Play Action", + "", + "{action: name, set?: name} play the Actions panel's action named action as one undoable batch; set names the set to look in (default: every set). A name no action has, or one that more than one action in the sets looked in has, is an error and nothing plays → what command.batch returns", + ), + ( + crate::panels::actions::STOP_RECORDING, + "Stop Playing/Recording", + "", + "{} end the Actions panel's recording and keep its steps, in the action ui.action.new made for it, else in a new action after the last action of its set, as the panel's Stop Playing/Recording button does. With nothing recording it changes nothing → {stopped}", ), ( "ui.batchDialog", diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index e1949573dd..6de2fe0f74 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -20,6 +20,9 @@ pub struct Pending { /// What the status bar shows ("Opening Poster.vectorcraft"). pub label: String, done: Receiver>, + /// The automation roots in force where the open started: the document is installed under + /// them too (its links are read as it opens). + scope: ScopeHandle, } /// The files being read. @@ -57,6 +60,7 @@ pub fn start(app: &mut VectorcraftApp, path: &str, bytes: Vec) -> Result) -> Result std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("vectorcraft-opening-scope-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A file asked for again while it is still being read is not read a second time (#3455). +#[test] +fn a_file_asked_for_again_while_it_is_read_opens_once() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + let bytes = vectorcraft_format::save(&vectorcraft_doc::Document::new(120.0, 80.0), false); + start(&mut app, "/art/Poster.vectorcraft", bytes).unwrap(); + assert_eq!(crate::io::open_file(&mut app, "/art/Poster.vectorcraft", true).unwrap(), Value::Null); + assert_eq!(app.opening.pending.len(), 1); + let t0 = std::time::Instant::now(); + while !app.opening.pending.is_empty() && t0.elapsed().as_secs() < 30 { + poll(&mut app); + std::thread::yield_now(); + } + assert_eq!(app.session.documents().len(), 1); +} diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 0375ed76f6..9d8c71538c 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1177,8 +1177,9 @@ pub(crate) fn modal_open(app: &VectorcraftApp, ctx: &egui::Context) -> bool { /// Keys, text and clipboard events that a floating panel's own OS window left over run the main /// window's shortcuts, tool keys and clipboard on its next frame ([`VectorcraftApp::raw_input_hook`]). /// craft-ui forwards nothing while a field in that window has the keyboard. A field of the main -/// window loses it, as a click elsewhere in one window would take it. -fn forward_keys(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, modifiers: Option) { +/// window loses it, as a click elsewhere in one window would take it. A floating document's OS +/// window forwards its keys here too ([`crate::doc_windows`]). +pub(crate) fn forward_keys(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, modifiers: Option) { if events.is_empty() { return; } diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 30a95705ce..174fab9bc3 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -16,8 +16,116 @@ pub use files::{ACTIONS_EXT, LOAD_SET, SAVE_SET, load_set, save_set}; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Action { + /// Tells the action apart from every other action in this run, also one with the same name: + /// the recording New Action starts fills the action with this id wherever it is. It is not + /// saved: each action gets a new id when it is made, copied or loaded. + #[serde(skip, default = "next_action_id")] + pub id: u64, pub name: String, pub steps: Vec<(String, Value)>, + /// The function key that plays the action when shortcuts are read, if one is assigned. A + /// saved value that is not a function key loads as none. + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_key")] + pub key: Option, + /// The action's Button Mode color, one of [`COLORS`], if one is assigned. The panel does not + /// show it. A saved value that is not one of them loads as none. + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_color")] + pub color: Option, +} + +impl Action { + /// An action with a new [`Action::id`], no function key and no color. + pub fn new(name: impl Into, steps: Vec<(String, Value)>) -> Self { + Self { id: next_action_id(), name: name.into(), steps, key: None, color: None } + } + + /// A copy of the action with a new [`Action::id`] and no function key, so the key still plays + /// only the original. + pub fn copy(&self) -> Self { + Self { id: next_action_id(), key: None, ..self.clone() } + } +} + +/// An action id no other action in this run has. +fn next_action_id() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} + +/// The highest function key an action can play with: F1 to F15. +pub const FUNCTION_KEYS: u8 = 15; + +/// A function key that plays an action: F1 to F15, alone or with Ctrl (Command on macOS), Shift, +/// or both. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionKey { + /// 1 to [`FUNCTION_KEYS`]: F1 to F15. + pub key: u8, + /// Held with Ctrl, Command on macOS. + #[serde(default)] + pub cmd: bool, + #[serde(default)] + pub shift: bool, +} + +impl FunctionKey { + /// The key as shortcut text (`Cmd+Shift+F5`). + fn shortcut(self) -> String { + format!("{}{}F{}", if self.cmd { "Cmd+" } else { "" }, if self.shift { "Shift+" } else { "" }, self.key) + } + + /// The chord the key is pressed as; none when `key` is not 1 to [`FUNCTION_KEYS`]. + pub fn chord(self) -> Option { + (1..=FUNCTION_KEYS).contains(&self.key).then(|| crate::keymap::vc_chord(&self.shortcut())).flatten() + } + + /// The key as the menus show shortcuts on this platform (`Ctrl+Shift+F5`, `⇧⌘F5`). + pub fn text(self) -> String { + crate::menus::pretty_shortcut(&self.shortcut()) + } + + /// The function key that params `p` give: `key` (1 to 15, F1 to F15; 0 or null for none), `cmd` + /// and `shift`. `Ok(None)` for no key; an error for a `key` that is not one of them. + pub fn from_params(p: &Value) -> Result, String> { + match p.get("key") { + None | Some(Value::Null) => Ok(None), + Some(v) => match v.as_u64() { + Some(0) => Ok(None), + Some(n) if n <= u64::from(FUNCTION_KEYS) => { + let flag = |k: &str| p.get(k).and_then(Value::as_bool).unwrap_or(false); + Ok(Some(Self { key: n as u8, cmd: flag("cmd"), shift: flag("shift") })) + } + _ => Err("no such function key".into()), + }, + } + } +} + +/// The Button Mode colors an action can have, as (value, label). +pub const COLORS: [(&str, &str); 5] = [("red", "Red"), ("yellow", "Yellow"), ("green", "Green"), ("blue", "Blue"), ("violet", "Violet")]; + +/// Serde reader for [`Action::key`]: a value that is not a function key is none. +fn deserialize_key<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + let v = ::deserialize(d)?; + Ok(serde_json::from_value::(v).ok().filter(|k| k.chord().is_some())) +} + +/// Serde reader for [`Action::color`]: a value that is not one of [`COLORS`] is none. +fn deserialize_color<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + let v = ::deserialize(d)?; + Ok(v.as_str().filter(|c| COLORS.iter().any(|(id, _)| id == c)).map(str::to_string)) +} + +/// The color that params `p` give: `color`, one of [`COLORS`], or null or `""` for none. +fn color_param(p: &Value) -> Result, String> { + match p.get("color") { + None | Some(Value::Null) => Ok(None), + Some(v) => match v.as_str() { + Some("") => Ok(None), + Some(c) if COLORS.iter().any(|(id, _)| *id == c) => Ok(Some(c.to_string())), + _ => Err("no such color".into()), + }, + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -57,18 +165,15 @@ pub fn default_sets() -> Vec { vec![ActionSet::new( "Default Actions", vec![ - Action { name: "Duplicate and Offset 10 pt".into(), steps: vec![step("object.move", json!({"dx": 10, "dy": 10, "copy": true}))] }, - Action { - name: "Unite and Simplify".into(), - steps: vec![step("object.pathfinder.unite", json!({})), step("object.path.simplify", json!({"tolerance": 0.5}))], - }, - Action { - name: "Center on Artboard".into(), - steps: vec![step("object.align", json!({"horizontal": "center", "vertical": "center", "to": "artboard"}))], - }, - Action { name: "Outline Text".into(), steps: vec![step("type.createOutlines", json!({}))] }, - Action { name: "Rotate 90° CW".into(), steps: vec![step("object.rotate", json!({"angle": -90}))] }, - Action { name: "Reflect Horizontal".into(), steps: vec![step("object.reflect", json!({"axis": "vertical"}))] }, + Action::new("Duplicate and Offset 10 pt", vec![step("object.move", json!({"dx": 10, "dy": 10, "copy": true}))]), + Action::new( + "Unite and Simplify", + vec![step("object.pathfinder.unite", json!({})), step("object.path.simplify", json!({"tolerance": 0.5}))], + ), + Action::new("Center on Artboard", vec![step("object.align", json!({"horizontal": "center", "vertical": "center", "to": "artboard"}))]), + Action::new("Outline Text", vec![step("type.createOutlines", json!({}))]), + Action::new("Rotate 90° CW", vec![step("object.rotate", json!({"angle": -90}))]), + Action::new("Reflect Horizontal", vec![step("object.reflect", json!({"axis": "vertical"}))]), ], )] } @@ -84,9 +189,9 @@ pub fn play(app: &mut VectorcraftApp, set: usize, idx: usize) -> Result Result { let index = |k: &str| p.get(k).and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); let name = p.get("name").and_then(Value::as_str).map(str::trim).unwrap_or_default(); @@ -98,6 +203,255 @@ pub fn rename_action(app: &mut VectorcraftApp, p: &Value) -> Result Result { + if app.ui.recording.is_some() { + return Err("an action is already recording".into()); + } + let len = app.ui.action_sets.len(); + let set = p.get("set").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).filter(|&s| s < len).ok_or("no such action set")?; + let name = p.get("name").and_then(Value::as_str).map(str::trim).unwrap_or_default().to_string(); + if name.is_empty() { + return Err("name is empty".into()); + } + let key = FunctionKey::from_params(p)?; + let color = color_param(p)?; + if let Some(message) = key.and_then(key_error) { + return Err(message); + } + let action = Action { key, color, ..Action::new(name.clone(), vec![]) }; + let id = action.id; + let Some(s) = app.ui.action_sets.get_mut(set) else { return Err("no such action set".into()) }; + s.actions.push(action); + let index = s.actions.len() - 1; + start_recording(app, set, name, Some(id)); + app.ui.action_set = Some(set); + app.ui.action_sets_selected = vec![set]; + if let Some(ctx) = app.ui_ctx.clone() { + set_pstate::>(&ctx, "actions-selected", Some((set, index))); + } + Ok(json!({ "set": set, "action": index })) +} + +/// The command that changes an action's name, function key and color ([`action_options`]). +pub const ACTION_OPTIONS: &str = "ui.action.options"; + +/// `ui.action.options {set, action, name?, key?, cmd?, shift?, color?}`: changes the +/// action at index `action` of set `set` (0 is the top set) and keeps its steps. `name` renames it +/// (spaces trimmed from both ends), `key` (1 to 15, F1 to F15; 0 or null for none) with `cmd` +/// (Ctrl, Command on macOS) and `shift` sets the function key that plays it, and `color` (one of +/// [`COLORS`]; null or `""` for none) its Button Mode color; a param left out keeps what the action +/// has, and `cmd` or `shift` alone changes that modifier of the action's key. The action's function +/// key takes priority over command shortcuts. An index past the last set or action, an empty name, +/// or a key or color that is not one of them is an error, and then nothing changes. The panel +/// menu's Action Options… runs this for the selected action. → {name, key, color} +pub fn action_options(app: &mut VectorcraftApp, p: &Value) -> Result { + let index = |k: &str| p.get(k).and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); + let (set, at) = index("set").zip(index("action")).ok_or("no such action")?; + let had = app.ui.action_sets.get(set).and_then(|s| s.actions.get(at)).map(|a| a.key).ok_or("no such action")?; + let name = match p.get("name") { + None | Some(Value::Null) => None, + Some(v) => match v.as_str().map(str::trim).unwrap_or_default() { + "" => return Err("name is empty".into()), + n => Some(n.to_string()), + }, + }; + // `cmd` and `shift` left out keep the modifiers of the action's key. + let flag = |k: &str, kept: bool| p.get(k).and_then(Value::as_bool).unwrap_or(kept); + let with_mods = + |k: FunctionKey| FunctionKey { cmd: flag("cmd", had.is_some_and(|h| h.cmd)), shift: flag("shift", had.is_some_and(|h| h.shift)), ..k }; + let key = if p.get("key").is_some() { + Some(FunctionKey::from_params(p)?.map(with_mods)) + } else if p.get("cmd").is_some() || p.get("shift").is_some() { + had.map(|h| Some(with_mods(h))) + } else { + None + }; + let color = if p.get("color").is_some() { Some(color_param(p)?) } else { None }; + if let Some(Some(k)) = key + && had != Some(k) + && let Some(message) = key_error(k) + { + return Err(message); + } + let Some(action) = app.ui.action_sets.get_mut(set).and_then(|s| s.actions.get_mut(at)) else { return Err("no such action".into()) }; + if let Some(name) = name { + action.name = name; + } + if let Some(key) = key { + action.key = key; + } + if let Some(color) = color { + action.color = color; + } + Ok(json!({ "name": action.name, "key": action.key, "color": action.color })) +} + +/// The command that plays an action by its name ([`play_action`]). +pub const PLAY_ACTION: &str = "ui.action.play"; + +/// `ui.action.play {action, set?}`: plays the action named `action` as one undoable batch, as +/// Play Current Selection does. `set` names the set to look in (default: every set); a `set` that +/// is not a string is an error. A name that no action has is an error, and so is a name that more +/// than one action in the sets looked in has: then nothing plays. → what `command.batch` returns +pub fn play_action(app: &mut VectorcraftApp, p: &Value) -> Result { + let name = p.get("action").and_then(Value::as_str).ok_or("no such action")?; + let in_set = match p.get("set") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_str().ok_or("no such action set")?), + }; + let found: Vec<(usize, usize)> = app + .ui + .action_sets + .iter() + .enumerate() + .filter(|(_, s)| in_set.is_none_or(|n| s.name == n)) + .flat_map(|(si, s)| s.actions.iter().enumerate().filter(|(_, a)| a.name == name).map(move |(ai, _)| (si, ai))) + .collect(); + match found[..] { + [] => Err("no such action".into()), + [(s, a)] => play(app, s, a), + _ => Err(format!("more than one action is named “{}”", name)), + } +} + +/// The command that ends a recording ([`stop`]). +pub const STOP_RECORDING: &str = "ui.action.stop"; + +/// `ui.action.stop {}`: ends the recording in progress and keeps its steps, in the action New +/// Action made for it, else in a new action after the last action of its set, as the bottom bar's +/// Stop Playing/Recording does. With nothing recording it changes nothing. → {stopped} +pub fn stop(app: &mut VectorcraftApp, _: &Value) -> Result { + let stopped = app.ui.recording.is_some(); + stop_recording(app); + Ok(json!({ "stopped": stopped })) +} + +/// The command that `chord` runs under `km`, pressed once or pressed twice. +#[cfg(test)] +fn command_on(km: &craft_keymap::Keymap, chord: &craft_keymap::Chord) -> Option { + crate::keymap::lookup(km, chord).or_else(|| match km.lookup(chord, true, &craft_keymap::Active::NONE) { + craft_keymap::Lookup::Run(c) => Some(c), + craft_keymap::Lookup::Cycle(v) => v.into_iter().next(), + _ => None, + }) +} + +/// The function returns an error message if the function key is invalid or reserved on this platform. +pub fn key_error(key: FunctionKey) -> Option { + let Some(chord) = key.chord() else { return Some("no such function key".into()) }; + if crate::keymap::platform() == craft_keymap::Platform::Windows && (key.key == 1 || key.cmd && !key.shift && matches!(key.key, 4 | 6)) { + return Some(format!("{} cannot be used on Windows", key.text())); + } + if crate::keymap::template().is_reserved(&chord) { + return Some(format!("{} is reserved by the system", key.text())); + } + None +} + +fn playable_chord(key: FunctionKey) -> Option { + key_error(key).is_none().then(|| key.chord()).flatten() +} + +/// Starts recording into set `set`: Stop Playing/Recording adds an action named `name` with the +/// steps, or, with `into`, gives them to the action with that id. +fn start_recording(app: &mut VectorcraftApp, set: usize, name: String, into: Option) { + let start = app.session.journal.len(); + // Keep every step from here on until recording stops, however long it runs. + app.session.journal.hold(Some(start)); + app.ui.recording = Some((set, name, start)); + app.ui.recording_into = into; +} + +/// Stop Playing/Recording: ends the recording and keeps its steps (see [`start_recording`]). An +/// action New Action made that was deleted while it recorded keeps nothing. +fn stop_recording(app: &mut VectorcraftApp) { + let Some((set, name, start)) = app.ui.recording.take() else { return }; + // A canceled undo group numbers the steps down when it drops entries made before them. + let start = app.session.journal.held().unwrap_or(start); + let steps = app.session.journal_for_action(start); + app.session.journal.hold(None); + match app.ui.recording_into.take() { + Some(id) => { + if let Some(a) = app.ui.action_sets.iter_mut().flat_map(|s| s.actions.iter_mut()).find(|a| a.id == id) { + a.steps.extend(steps); + } + } + None => { + if let Some(s) = app.ui.action_sets.get_mut(set) { + s.actions.push(Action::new(name, steps)); + } + } + } +} + +crate::shortcut_editor::ui_mirror!(fn function_key_chords() -> Vec); + +/// Mirrors the actions' function keys for code without app access (cheap when unchanged). +pub fn sync_function_keys(ui: &crate::UiState) { + let chords: Vec = ui.action_sets.iter().flat_map(|s| s.actions.iter().filter_map(|a| playable_chord(a.key?))).collect(); + if function_key_chords().read().is_ok_and(|v| *v != chords) + && let Ok(mut v) = function_key_chords().write() + { + *v = chords; + } +} + +/// Whether `chord` plays an action, by the function keys [`sync_function_keys`] last mirrored. +pub(crate) fn plays_an_action(chord: &craft_keymap::Chord) -> bool { + let platform = crate::keymap::platform(); + let chord = chord.effective(platform); + function_key_chords().read().is_ok_and(|v| v.iter().any(|c| c.effective(platform) == chord)) +} + +/// Plays each action whose function key was pressed this frame, in the order of the presses and +/// before any command with the same shortcut, and takes those key presses. The frame's other +/// events stay for the command, panel and tool shortcuts. +pub fn play_function_key(app: &mut VectorcraftApp, ctx: &egui::Context) { + let keys: Vec<(craft_keymap::Chord, (usize, usize))> = app + .ui + .action_sets + .iter() + .enumerate() + .flat_map(|(si, s)| s.actions.iter().enumerate().filter_map(move |(ai, a)| Some((playable_chord(a.key?)?, (si, ai))))) + .collect(); + if keys.is_empty() { + return; + } + let platform = crate::keymap::platform(); + let hits: Vec<(usize, usize)> = ctx.input_mut(|i| { + let mut hits = Vec::new(); + i.events.retain(|e| { + let hit = match e { + egui::Event::Key { key, pressed: true, modifiers, .. } => craft_keymap::Key::from_egui(*key) + .map(|k| craft_keymap::Chord::new(craft_keymap::Mods::from_egui(modifiers, platform), k)) + .and_then(|c| keys.iter().find(|(k, _)| *k == c).map(|(_, at)| *at)), + _ => None, + }; + if !matches!(e, egui::Event::Key { repeat: true, .. }) { + hits.extend(hit); + } + hit.is_none() + }); + hits + }); + for (set, action) in hits { + if let Err(e) = play(app, set, action) { + app.status(e); + } + } +} + /// The command that deletes action sets ([`delete_sets`]). pub const DELETE_SETS: &str = "ui.actionSet.delete"; @@ -143,8 +497,8 @@ fn delete_selection(app: &mut VectorcraftApp, ctx: &egui::Context) { /// ([`ActionSet::id`]), which Delete Selection's question passes: the sets with these ids are /// deleted wherever they are now, `sets` is not read, and when one of them no longer exists /// nothing is deleted. A recording into a deleted set stops, and its steps are dropped; a -/// recording into another set goes on. An open Set Options or Batch dialog for a deleted set -/// closes. When the current set is deleted, no set is current afterwards. +/// recording into another set goes on. An open Set Options, New Action or Batch dialog for a +/// deleted set closes. When the current set is deleted, no set is current afterwards. pub fn delete_sets(app: &mut VectorcraftApp, p: &Value) -> Result { let len = app.ui.action_sets.len(); let mut sets: Vec = match (p.get("ids"), p.get("sets")) { @@ -169,13 +523,14 @@ pub fn delete_sets(app: &mut VectorcraftApp, p: &Value) -> Result if let Some((rec, ..)) = app.ui.recording.as_mut() { if sets.contains(rec) { app.ui.recording = None; + app.ui.recording_into = None; app.session.journal.hold(None); } else { *rec -= sets.iter().filter(|&&s| s < *rec).count(); } } - // An open Set Options or Batch dialog holds a set index: it closes when its set is deleted, - // and otherwise follows its set down. + // An open Set Options, New Action or Batch dialog holds a set index: it closes when its set is + // deleted, and otherwise follows its set down. if let Some(d) = app.ui.dialog.as_mut().filter(|d| holds_set(d)) && let Some(set) = d.fields.get("set").and_then(Value::as_u64).and_then(|s| usize::try_from(s).ok()) { @@ -203,9 +558,12 @@ pub fn delete_sets(app: &mut VectorcraftApp, p: &Value) -> Result Ok(json!({ "deleted": sets.len() })) } -/// Whether dialog `d` is a Set Options or Batch dialog that holds a set index in its `set` field. +/// Whether dialog `d` is a Set Options, New Action or Batch dialog that holds a set index in its +/// `set` field. fn holds_set(d: &crate::state::Dialog) -> bool { - d.kind == crate::dialogs::action_batch::KIND || (d.kind == crate::dialogs::action_set_options::KIND && d.fields.contains_key("set")) + d.kind == crate::dialogs::action_batch::KIND + || d.kind == crate::dialogs::action_new::KIND + || (d.kind == crate::dialogs::action_set_options::KIND && d.fields.contains_key("set")) } /// The command that duplicates an action or an action set ([`duplicate`]). @@ -234,8 +592,9 @@ fn duplicate_selection(app: &mut VectorcraftApp, ctx: &egui::Context) { /// of set `set` into the same set, right after the original; without `action`, copies set `set` /// with all its actions to right after the original set (default: the current set). The copy is /// named after the original with " copy" added, and a copied set gets an id of its own -/// ([`ActionSet::id`]). The copy is selected and its set is the current one. A recording and an -/// open Set Options or Batch dialog keep to their own set and action. → {set, action?} +/// ([`ActionSet::id`]). Copied actions have no function key, so a key plays only the original. +/// The copy is selected and its set is the current one. A recording and an open Set Options or +/// Batch dialog keep to their own set and action. → {set, action?} pub fn duplicate(app: &mut VectorcraftApp, p: &Value) -> Result { const SELECTED: &str = "actions-selected"; let len = app.ui.action_sets.len(); @@ -250,7 +609,7 @@ pub fn duplicate(app: &mut VectorcraftApp, p: &Value) -> Result { Some(v) => Some(index(v).filter(|&a| a < src.actions.len()).ok_or("no such action")?), }; let (copy, result) = if let Some(a) = action { - let Some(mut copy) = src.actions.get(a).cloned() else { return Err("no such action".into()) }; + let Some(mut copy) = src.actions.get(a).map(Action::copy) else { return Err("no such action".into()) }; copy.name = format!("{} copy", copy.name); src.actions.insert(a + 1, copy); // A Batch dialog open on a later action of the set follows it down. @@ -262,7 +621,7 @@ pub fn duplicate(app: &mut VectorcraftApp, p: &Value) -> Result { } (Some((set, a + 1)), json!({ "set": set, "action": a + 1 })) } else { - let copy = ActionSet::new(format!("{} copy", src.name), src.actions.clone()); + let copy = ActionSet::new(format!("{} copy", src.name), src.actions.iter().map(Action::copy).collect()); app.ui.action_sets.insert(set + 1, copy); if let Some((rec, ..)) = app.ui.recording.as_mut() && *rec > set @@ -291,6 +650,11 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut egui::Ui) { // deleted since leaves the stored pair pointing at another set's action. let selected = pstate::>(ui.ctx(), "actions-selected").filter(|&(s, _)| app.ui.action_set == Some(s)); let has = selected.and_then(|(s, a)| app.ui.action_sets.get(s).and_then(|set| set.actions.get(a))).is_some(); + if widgets::menu_item(ui, tl!("New Action…"), crate::dialogs::action_new::can_open(app), false) + && let Err(e) = crate::dialogs::action_new::open(app) + { + app.status(e); + } if widgets::menu_item(ui, tl!("New Set…"), true, false) { crate::dialogs::action_set_options::open_new(app); } @@ -412,19 +776,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { app.ui.action_set = current; app.ui.action_sets_selected = sets_selected; widgets::divider(ui); - // Bottom bar: stop, record, play, new set, delete. + // Bottom bar: stop, record, play, new set, new action, delete. ui.horizontal(|ui| { let recording = app.ui.recording.is_some(); if widgets::icon_button(ui, "square", tl!("Stop Playing/Recording"), false, 24.0).clicked() - && let Some((set, name, start)) = app.ui.recording.take() + && let Err(e) = app.run(STOP_RECORDING, json!({})) { - // A canceled undo group numbers the steps down when it drops entries made before them. - let start = app.session.journal.held().unwrap_or(start); - let steps = app.session.journal_for_action(start); - app.session.journal.hold(None); - if let Some(s) = app.ui.action_sets.get_mut(set) { - s.actions.push(Action { name, steps }); - } + app.status(e); } let (r, resp) = ui.allocate_exact_size(egui::vec2(24.0, 24.0), egui::Sense::click()); ui.painter().circle_filled(r.center(), 6.0, if recording { egui::Color32::from_rgb(0xe0, 0x30, 0x30) } else { t.icon }); @@ -440,10 +798,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { app.ui.action_sets_selected = vec![set]; } let n = app.ui.action_sets.get(set).map_or(0, |s| s.actions.len()) + 1; - let start = app.session.journal.len(); - // Keep every step from here on until recording stops, however long it runs. - app.session.journal.hold(Some(start)); - app.ui.recording = Some((set, format!("Action {n}"), start)); + start_recording(app, set, format!("Action {n}"), None); } if widgets::icon_button(ui, "dc-actions", tl!("Play Current Selection"), false, 24.0).clicked() && let Some(s) = selected @@ -453,6 +808,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { if widgets::icon_button(ui, "dc-folder", tl!("Create New Set"), false, 24.0).clicked() { crate::dialogs::action_set_options::open_new(app); } + if widgets::icon_button(ui, "dc-new-item", tl!("Create New Action"), false, 24.0).clicked() + && let Err(e) = crate::dialogs::action_new::open(app) + { + app.status(e); + } if widgets::icon_button(ui, "trash-2", tl!("Delete Selection"), false, 24.0).clicked() { delete_selection(app, ui.ctx()); } @@ -501,10 +861,11 @@ mod tests { click(&ctx, &mut app, text_rect(&texts, "Reflect Horizontal").center(), show); frame_events(&ctx, &mut app, vec![], show); assert_eq!(pstate::>(&ctx, "actions-selected"), Some((0, 5)), "selected on the frames after the click"); - // The bottom bar's 24-point buttons, left to right: stop, record, play, new set, delete. + // The bottom bar's 24-point buttons, left to right: stop, record, play, new set, new action, + // delete. let mut bar = crate::toolbar::tests::widget_rects(&ctx, egui::vec2(24.0, 24.0)); bar.sort_by(|a, b| a.left().total_cmp(&b.left())); - let [_, _, play, _, delete] = bar[..] else { panic!("the bottom bar: {bar:?}") }; + let [_, _, play, _, _, delete] = bar[..] else { panic!("the bottom bar: {bar:?}") }; click(&ctx, &mut app, text_rect(&texts, "Duplicate and Offset 10 pt").center(), show); click(&ctx, &mut app, play.center(), show); assert_eq!(app.session.active().unwrap().selection.len(), 1); @@ -526,13 +887,13 @@ mod tests { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); let ctx = egui::Context::default(); - // The bottom bar's 24-point buttons, left to right: stop, record, play, new set, delete. A new - // set or action moves the bar down. + // The bottom bar's 24-point buttons, left to right: stop, record, play, new set, new action, + // delete. A new set or action moves the bar down. let bar = |ctx: &egui::Context, app: &mut VectorcraftApp| { frame_events(ctx, app, vec![], show); let mut bar = crate::toolbar::tests::widget_rects(ctx, egui::vec2(24.0, 24.0)); bar.sort_by(|a, b| a.left().total_cmp(&b.left())); - let [stop, record, _, new_set, _] = bar[..] else { panic!("the bottom bar: {bar:?}") }; + let [stop, record, _, new_set, _, _] = bar[..] else { panic!("the bottom bar: {bar:?}") }; (stop, record, new_set) }; let (_, _, new_set) = bar(&ctx, &mut app); @@ -667,7 +1028,7 @@ mod tests { fn action_options_is_off_after_a_set_above_the_selection_is_deleted() { use super::super::tests_appearance::{click, frame_events}; let mut app = app_with_sets(); - let action = |name: &str| Action { name: name.into(), steps: vec![] }; + let action = |name: &str| Action::new(name, vec![]); app.ui.action_sets[2].actions.push(action("Spin")); app.ui.action_sets.push(ActionSet::new("Last", vec![action("Wrong")])); let ctx = egui::Context::default(); @@ -698,13 +1059,13 @@ mod tests { app.ui.action_sets.push(ActionSet::new("Last", vec![])); app.ui.action_set = Some(2); set_pstate::>(&ctx, "actions-selected", Some((2, 0))); - app.ui.action_sets[2].actions.push(Action { name: "Spin".into(), steps: vec![] }); + app.ui.action_sets[2].actions.push(Action::new("Spin", vec![])); app.run(DELETE_SETS, json!({"sets": [2]})).unwrap(); assert_eq!(selected(&ctx), None, "the deleted set's action is no longer selected"); crate::dialogs::action_set_options::open_new(&mut app); crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(app.ui.action_set, Some(2), "the new set is current, at the deleted set's index"); - app.ui.action_sets[2].actions.push(Action { name: "Recorded".into(), steps: vec![] }); + app.ui.action_sets[2].actions.push(Action::new("Recorded", vec![])); let texts = frame_events(&ctx, &mut app, vec![], menu); let item = texts.iter().find(|(s, _)| s.trim() == "Action Options…").map(|(_, r)| *r).expect("Action Options… in the menu"); click(&ctx, &mut app, item.center(), menu); @@ -714,7 +1075,7 @@ mod tests { /// An app with the default set and the sets Mine (two actions) and Other. fn app_with_sets() -> VectorcraftApp { let mut app = VectorcraftApp::new(Session::new(), Default::default()); - let action = |name: &str| Action { name: name.into(), steps: vec![("object.move".into(), json!({"dx": 1, "dy": 0}))] }; + let action = |name: &str| Action::new(name, vec![("object.move".into(), json!({"dx": 1, "dy": 0}))]); app.ui.action_sets.push(ActionSet::new("Mine", vec![action("Nudge"), action("Nudge Again")])); app.ui.action_sets.push(ActionSet::new("Other", vec![])); app @@ -724,12 +1085,12 @@ mod tests { app.ui.action_sets.iter().map(|s| s.name.clone()).collect() } - /// The bottom bar's Delete Selection button (stop, record, play, new set, delete). + /// The bottom bar's Delete Selection button (stop, record, play, new set, new action, delete). fn trash(ctx: &egui::Context, app: &mut VectorcraftApp) -> egui::Pos2 { super::super::tests_appearance::frame_events(ctx, app, vec![], show); let mut bar = crate::toolbar::tests::widget_rects(ctx, egui::vec2(24.0, 24.0)); bar.sort_by(|a, b| a.left().total_cmp(&b.left())); - let [_, _, _, _, delete] = bar[..] else { panic!("the bottom bar: {bar:?}") }; + let [_, _, _, _, _, delete] = bar[..] else { panic!("the bottom bar: {bar:?}") }; delete.center() } @@ -871,7 +1232,7 @@ mod tests { fn ok_deletes_only_the_asked_one_of_two_sets_with_the_same_name() { use super::super::tests_appearance::click; let mut app = VectorcraftApp::new(Session::new(), Default::default()); - let x = |n: &str| ActionSet::new("X", vec![Action { name: n.into(), steps: vec![] }]); + let x = |n: &str| ActionSet::new("X", vec![Action::new(n, vec![])]); app.ui.action_sets = vec![x("first"), x("second")]; let ctx = egui::Context::default(); click_set(&ctx, &mut app, "X", egui::Modifiers::NONE); @@ -943,7 +1304,7 @@ mod tests { frame_events(&ctx, &mut app, vec![], show); let mut bar = crate::toolbar::tests::widget_rects(&ctx, egui::vec2(24.0, 24.0)); bar.sort_by(|a, b| a.left().total_cmp(&b.left())); - let [stop, record, _, _, _] = bar[..] else { panic!("the bottom bar: {bar:?}") }; + let [stop, record, _, _, _, _] = bar[..] else { panic!("the bottom bar: {bar:?}") }; click(&ctx, &mut app, record.center(), show); app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); click(&ctx, &mut app, stop.center(), show); @@ -970,7 +1331,7 @@ mod tests { frame_events(&ctx, &mut app, vec![], show); let mut bar = crate::toolbar::tests::widget_rects(&ctx, egui::vec2(24.0, 24.0)); bar.sort_by(|a, b| a.left().total_cmp(&b.left())); - let [stop, record, _, _, _] = bar[..] else { panic!("the bottom bar: {bar:?}") }; + let [stop, record, _, _, _, _] = bar[..] else { panic!("the bottom bar: {bar:?}") }; click(&ctx, &mut app, record.center(), show); assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(0), vec![0]), "the set recorded into is current"); app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); @@ -1171,10 +1532,11 @@ mod tests { } let ctx = egui::Context::default(); frame_events(&ctx, &mut app, vec![], show); - // The bottom bar's 24-point buttons, left to right: stop, record, play, new set, delete. + // The bottom bar's 24-point buttons, left to right: stop, record, play, new set, new action, + // delete. let mut bar = crate::toolbar::tests::widget_rects(&ctx, egui::vec2(24.0, 24.0)); bar.sort_by(|a, b| a.left().total_cmp(&b.left())); - let [stop, record, _, _, _] = bar[..] else { panic!("the bottom bar: {bar:?}") }; + let [stop, record, _, _, _, _] = bar[..] else { panic!("the bottom bar: {bar:?}") }; click(&ctx, &mut app, record.center(), show); for (id, p) in [("document.activate", json!({"index": 1})), ("shape.rectangle", rect(50)), ("edit.undoGroup.end", json!({"cancel": true}))] { app.run(id, p).unwrap(); @@ -1200,7 +1562,7 @@ mod tests { let start = app.session.journal.len(); app.run(id, params).unwrap(); let steps = app.session.journal_for_action(start); - app.ui.action_sets[0].actions.push(Action { name: name.into(), steps }); + app.ui.action_sets[0].actions.push(Action::new(name, steps)); app.ui.action_sets[0].actions.len() - 1 }; app.run("edit.copy", json!({})).unwrap(); @@ -1249,7 +1611,7 @@ mod tests { let start = app.session.journal.len(); app.run(id, params).unwrap(); let steps = app.session.journal_for_action(start); - app.ui.action_sets[0].actions.push(Action { name: name.into(), steps }); + app.ui.action_sets[0].actions.push(Action::new(name, steps)); app.ui.action_sets[0].actions.len() - 1 }; let (x0, x1) = (boards[0].x0, boards[0].x1); @@ -1374,7 +1736,7 @@ mod tests { fn save_actions_does_not_write_a_set_load_actions_refuses() { let mut app = app_with_sets(); let files = with_files(&mut app, "/sets/none.vcactions"); - app.ui.action_sets[2].actions = vec![Action { name: "A".into(), steps: vec![] }; 1001]; + app.ui.action_sets[2].actions = vec![Action::new("A", vec![]); 1001]; let r = app.run(SAVE_SET, json!({"set": 2, "path": "/sets/big.vcactions"})); assert_eq!(r.unwrap_err(), "the action set file holds more than 1,000 actions"); assert!(files.borrow().is_empty(), "nothing written"); @@ -1396,4 +1758,559 @@ mod tests { assert_eq!(v["name"], json!("Other"), "the set chosen, not the current one"); assert_eq!(app.run(SAVE_SET, json!({"id": 0, "set": 0, "path": "/sets/y.vcactions"})).unwrap_err(), "no such action set"); } + + /// The bottom bar's stop and Create New Action buttons (stop, record, play, new set, new + /// action, delete). + fn stop_and_new_action(ctx: &egui::Context, app: &mut VectorcraftApp) -> (egui::Pos2, egui::Pos2) { + super::super::tests_appearance::frame_events(ctx, app, vec![], show); + let mut bar = crate::toolbar::tests::widget_rects(ctx, egui::vec2(24.0, 24.0)); + bar.sort_by(|a, b| a.left().total_cmp(&b.left())); + let [stop, _, _, _, new_action, _] = bar[..] else { panic!("the bottom bar: {bar:?}") }; + (stop.center(), new_action.center()) + } + + /// The texts the dialog layer draws once the open dialog has settled. + fn dialog_texts(app: &mut VectorcraftApp) -> Vec { + let ctx = egui::Context::default(); + let mut texts = vec![]; + for _ in 0..3 { + texts = super::super::tests_appearance::frame_events(&ctx, app, vec![], |app, ui| crate::dialogs::show(app, ui.ctx())); + } + texts.into_iter().map(|(t, _)| t).collect() + } + + /// The Create New Action button and the panel menu's New Action… both open New Action with a + /// suggested name in the current set, no function key and no color; Cancel adds nothing and + /// starts no recording. Record with another set chosen adds the action there, selects it and + /// records into it, and Stop keeps exactly the steps recorded in that action; Record and Stop + /// with nothing done in between keep an empty action. + #[test] + fn new_action_asks_for_a_name_and_set_and_records_into_the_new_action() { + use super::super::tests_appearance::{click, frame_events}; + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + click_set(&ctx, &mut app, "Mine", egui::Modifiers::NONE); + let (_, new_action) = stop_and_new_action(&ctx, &mut app); + click(&ctx, &mut app, new_action, show); + let d = app.ui.dialog.as_ref().expect("Create New Action opens New Action"); + assert_eq!(d.kind, crate::dialogs::action_new::KIND); + let fields = (d.fields["set"].clone(), d.str("name"), d.fields["key"].clone(), d.str("color")); + assert_eq!(fields, (json!(1), "Action 3".to_string(), json!(0), String::new()), "the current set, a free name, no key or color"); + crate::dialogs::cancel(&mut app); + let counts = |app: &VectorcraftApp| app.ui.action_sets.iter().map(|s| s.actions.len()).collect::>(); + assert_eq!(counts(&app), [6, 2, 0], "Cancel adds nothing"); + assert!(app.ui.recording.is_none(), "and records nothing"); + let texts = frame_events(&ctx, &mut app, vec![], menu); + let item = texts.iter().find(|(s, _)| s.trim() == "New Action…").map(|(_, r)| *r).expect("New Action… in the menu"); + click(&ctx, &mut app, item.center(), menu); + let d = app.ui.dialog.as_mut().expect("New Action… opens New Action"); + assert_eq!(d.kind, crate::dialogs::action_new::KIND); + d.fields.insert("set".into(), json!(2)); + d.fields.insert("name".into(), json!(" Box ")); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(action_names(&app, 2), ["Box"], "added to the set chosen, with the name trimmed"); + let selected = pstate::>(&ctx, "actions-selected"); + assert_eq!((app.ui.action_set, selected), (Some(2), Some((2, 0))), "its set is current and it is selected"); + assert!(app.ui.recording.is_some(), "Record starts recording"); + assert!(frame_events(&ctx, &mut app, vec![], show).iter().any(|(t, _)| t == "● Recording"), "the panel shows the recording"); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let (stop, _) = stop_and_new_action(&ctx, &mut app); + click(&ctx, &mut app, stop, show); + assert!(app.ui.recording.is_none()); + let steps: Vec = app.ui.action_sets[2].actions[0].steps.iter().map(|(c, _)| c.clone()).collect(); + assert_eq!(steps, ["shape.rectangle"], "the recorded steps, in the new action"); + assert_eq!(counts(&app), [6, 2, 1], "Stop adds no other action"); + app.run(NEW_ACTION, json!({"set": 2, "name": "Empty"})).unwrap(); + let (stop, _) = stop_and_new_action(&ctx, &mut app); + click(&ctx, &mut app, stop, show); + assert_eq!(action_names(&app, 2), ["Box", "Empty"]); + assert!(app.ui.action_sets[2].actions[1].steps.is_empty(), "nothing recorded: an empty action"); + } + + /// New Action shows Name, Action Set, Function Key with Ctrl (Command on macOS) and Shift, Color and Record. + #[test] + fn new_action_shows_its_fields() { + let mut app = app_with_sets(); + crate::dialogs::action_new::open(&mut app).unwrap(); + let texts = dialog_texts(&mut app); + for label in ["New Action", "Name:", "Action Set:", "Default Actions", "Function Key:", "Shift", "Color:", "None", "Record", "Cancel"] { + assert!(texts.iter().any(|t| t == label), "{label}: {texts:?}"); + } + assert!(!texts.iter().any(|t| t == "Replace")); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.duplicate", "Shift+F14"); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("key".into(), json!(14)); + d.fields.insert("shift".into(), json!(true)); + let texts = dialog_texts(&mut app); + assert!(!texts.iter().any(|s| s == "Replace" || s.contains("already used")), "{texts:?}"); + } + + /// `ui.action.new` refuses an index past the last set, an empty name, a key or color that is + /// not one, and a second recording, and then adds nothing. New Action does not open without a + /// set or while recording, follows its set when an earlier set is deleted, and closes when its + /// set is deleted. On Windows F1, Ctrl+F4 and Ctrl+F6 are refused. + #[test] + fn new_action_refuses_bad_params_and_adds_nothing() { + let mut app = app_with_sets(); + let counts = |app: &VectorcraftApp| app.ui.action_sets.iter().map(|s| s.actions.len()).collect::>(); + for (p, want) in [ + (json!({"set": 3, "name": "A"}), "no such action set"), + (json!({"name": "A"}), "no such action set"), + (json!({"set": 1, "name": " "}), "name is empty"), + (json!({"set": 1}), "name is empty"), + (json!({"set": 1, "name": "A", "key": 16}), "no such function key"), + (json!({"set": 1, "name": "A", "key": "F5"}), "no such function key"), + (json!({"set": 1, "name": "A", "color": "pink"}), "no such color"), + ] { + assert_eq!(app.run(NEW_ACTION, p.clone()).unwrap_err(), want, "{p}"); + } + if crate::keymap::platform() == craft_keymap::Platform::Windows { + for (key, cmd) in [(1, false), (1, true), (4, true), (6, true)] { + let want = format!("{} cannot be used on Windows", FunctionKey { key, cmd, shift: false }.text()); + assert_eq!(app.run(NEW_ACTION, json!({"set": 1, "name": "A", "key": key, "cmd": cmd})).unwrap_err(), want); + } + } + assert_eq!(counts(&app), [6, 2, 0], "nothing added"); + assert!(app.ui.recording.is_none(), "nothing recording"); + // The dialog follows its set down, and closes with it. + crate::dialogs::action_new::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("set".into(), json!(2)); + app.run(DELETE_SETS, json!({"sets": [1]})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.fields["set"].clone()), Some(json!(1)), "New Action follows Other"); + app.run(DELETE_SETS, json!({"sets": [1]})).unwrap(); + assert!(app.ui.dialog.is_none(), "New Action closes with its set"); + crate::dialogs::action_new::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("set".into(), json!(9)); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert!(app.ui.dialog.is_some(), "a set that is gone: the dialog stays open"); + app.ui.dialog = None; + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run(NEW_ACTION, json!({"set": 0, "name": "A"})).unwrap(); + assert_eq!(app.run(NEW_ACTION, json!({"set": 0, "name": "B"})).unwrap_err(), "an action is already recording"); + assert_eq!(crate::dialogs::action_new::open(&mut app).unwrap_err(), "an action is already recording"); + assert!(!crate::dialogs::action_new::can_open(&app)); + assert_eq!(counts(&app), [7], "one action added"); + app.ui.action_sets.clear(); + app.ui.recording = None; + assert_eq!(crate::dialogs::action_new::open(&mut app).unwrap_err(), "no such action set"); + assert!(app.ui.dialog.is_none()); + } + + /// A recording that New Action started goes into its action wherever the action is when Stop + /// is pressed, and is dropped when the action was deleted meanwhile. + #[test] + fn a_new_actions_recording_follows_its_action() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let ctx = egui::Context::default(); + app.run(NEW_ACTION, json!({"set": 2, "name": "Box"})).unwrap(); + app.run(DELETE_SETS, json!({"sets": [1]})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let (stop, _) = stop_and_new_action(&ctx, &mut app); + super::super::tests_appearance::click(&ctx, &mut app, stop, show); + assert_eq!((action_names(&app, 1), app.ui.action_sets[1].actions[0].steps.len()), (vec!["Box".to_string()], 1)); + app.run(NEW_ACTION, json!({"set": 1, "name": "Gone"})).unwrap(); + app.ui.action_sets[1].actions.pop(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let (stop, _) = stop_and_new_action(&ctx, &mut app); + super::super::tests_appearance::click(&ctx, &mut app, stop, show); + assert_eq!(action_names(&app, 1), ["Box"], "the deleted action is not made again"); + assert!(app.ui.recording.is_none() && app.ui.recording_into.is_none()); + // `ui.action.stop` ends a recording as the button does. + assert_eq!(app.run(STOP_RECORDING, json!({})).unwrap(), json!({"stopped": false}), "nothing recording"); + app.run(NEW_ACTION, json!({"set": 1, "name": "Remote"})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + assert_eq!(app.run(STOP_RECORDING, json!({})).unwrap(), json!({"stopped": true})); + assert_eq!((action_names(&app, 1), app.ui.action_sets[1].actions[1].steps.len()), (vec!["Box".to_string(), "Remote".into()], 1)); + assert!(app.ui.recording.is_none()); + } + + #[test] + fn shortcut_precedence_assignment_preserves_command_bindings() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.duplicate", "Shift+F14"); + let before = app.ui.shortcut_overrides.clone(); + let set = app.ui.shortcut_set.clone(); + app.run(ACTION_OPTIONS, json!({"set": 1, "action": 0, "key": 14, "shift": true})).unwrap(); + assert_eq!(app.ui.shortcut_overrides, before); + assert_eq!(app.ui.shortcut_set, set); + let ctx = egui::Context::default(); + let event = egui::Event::Key { key: egui::Key::F14, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::SHIFT }; + let mut output = ctx.run_ui(egui::RawInput { events: vec![event], ..Default::default() }, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + output.textures_delta.clear(); + assert_eq!(app.session.active().unwrap().history.undo.last().unwrap().label, "Nudge"); + assert_eq!(app.ui.shortcut_overrides, before); + let undo = app.session.active().unwrap().history.undo.len(); + let repeated = egui::Event::Key { key: egui::Key::F14, physical_key: None, pressed: true, repeat: true, modifiers: egui::Modifiers::SHIFT }; + let mut output = + ctx.run_ui(egui::RawInput { events: vec![repeated], ..Default::default() }, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + output.textures_delta.clear(); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + app.run(NEW_ACTION, json!({"set": 2, "name": "Another", "key": 14, "shift": true})).unwrap(); + assert_eq!(app.ui.shortcut_overrides, before); + assert_eq!(app.ui.shortcut_set, set); + } + + #[test] + fn shortcut_precedence_action_options_does_not_offer_replacement() { + let mut app = app_with_sets(); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.duplicate", "Shift+F14"); + crate::dialogs::action_set_options::open_action(&mut app, 1, 0); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("key".into(), json!(14)); + d.fields.insert("shift".into(), json!(true)); + let texts = dialog_texts(&mut app); + assert!(!texts.iter().any(|s| s == "Replace" || s.contains("already used")), "{texts:?}"); + } + + #[test] + fn shortcut_precedence_duplicate_keys_play_the_first_action_once() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let key = Some(FunctionKey { key: 15, cmd: false, shift: false }); + app.ui.action_sets[1].actions[0].key = key; + app.ui.action_sets[1].actions[1].key = key; + let before = app.session.active().unwrap().history.undo.len(); + let ctx = egui::Context::default(); + let event = egui::Event::Key { key: egui::Key::F15, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let mut output = ctx.run_ui(egui::RawInput { events: vec![event], ..Default::default() }, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + output.textures_delta.clear(); + let history = &app.session.active().unwrap().history.undo; + assert_eq!(history.len(), before + 1); + assert_eq!(history.last().unwrap().label, "Nudge"); + } + + #[test] + fn shortcut_precedence_preferences_and_files_retain_action_keys() { + let mut app = app_with_sets(); + let key = FunctionKey { key: 14, cmd: false, shift: true }; + app.ui.action_sets[1].actions[0].key = Some(key); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.duplicate", "Shift+F14"); + let saved = serde_json::to_value(&app.ui).unwrap(); + let restored = serde_json::from_value::(saved).unwrap().sanitized(); + assert_eq!(restored.action_sets[1].actions[0].key, Some(key)); + let _files = with_files(&mut app, "/sets/Mine.vcactions"); + app.run(SAVE_SET, json!({"set": 1, "path": "/sets/Mine.vcactions"})).unwrap(); + app.run(LOAD_SET, json!({"path": "/sets/Mine.vcactions"})).unwrap(); + assert_eq!(app.ui.action_sets.last().unwrap().actions[0].key, Some(key)); + } + + #[test] + fn shortcut_precedence_applies_while_the_type_tool_edits() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("text.create", json!({"x": 20, "y": 50, "text": "Hi"})).unwrap(); + app.select_tool("type"); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + assert!(app.session.tool_wants_text()); + let key = FunctionKey { key: 15, cmd: true, shift: false }; + app.ui.action_sets[1].actions[0].key = Some(key); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.duplicate", "Cmd+F15"); + let before = app.session.active().unwrap().history.undo.len(); + let ctx = egui::Context::default(); + let event = egui::Event::Key { key: egui::Key::F15, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }; + let mut output = ctx.run_ui(egui::RawInput { events: vec![event], ..Default::default() }, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + output.textures_delta.clear(); + let history = &app.session.active().unwrap().history.undo; + assert_eq!(history.len(), before + 1); + assert_eq!(history.last().unwrap().label, "Nudge"); + } + + #[test] + fn shortcut_precedence_command_edits_retain_action_keys() { + let mut app = app_with_sets(); + let key = FunctionKey { key: 15, cmd: false, shift: false }; + app.ui.action_sets[1].actions[0].key = Some(key); + app.run("shortcuts.set", json!({"id": "edit.duplicate", "shortcut": "F15"})).unwrap(); + assert_eq!(app.ui.action_sets[1].actions[0].key, Some(key)); + crate::shortcut_editor::open(&mut app); + let mut overrides = app.ui.shortcut_overrides.clone(); + crate::keymap::set_override(&mut overrides, "edit.duplicate", "Shift+F14"); + app.ui.dialog.as_mut().unwrap().fields.insert("overrides".into(), crate::keymap::stored::to_value(&overrides)); + crate::shortcut_editor::confirm(&mut app).unwrap(); + assert_eq!(app.ui.action_sets[1].actions[0].key, Some(key)); + } + + /// Action function keys take priority over command shortcuts and keep both assignments. + #[test] + fn function_keys_play_their_action_and_preserve_other_assignments() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let p = |set: usize, action: usize, k: FunctionKey| json!({"set": set, "action": action, "key": k.key, "cmd": k.cmd, "shift": k.shift}); + let keys = |app: &VectorcraftApp| app.ui.action_sets[1].actions.iter().map(|a| a.key).collect::>(); + let f15 = FunctionKey { key: 15, cmd: false, shift: false }; + app.run(ACTION_OPTIONS, p(1, 0, f15)).unwrap(); + assert_eq!(keys(&app), [Some(f15), None]); + app.run(ACTION_OPTIONS, p(1, 1, f15)).unwrap(); + app.run(NEW_ACTION, json!({"set": 2, "name": "New", "key": 15})).unwrap(); + stop_recording(&mut app); + assert_eq!(keys(&app), [Some(f15), Some(f15)]); + assert_eq!(app.ui.action_sets[2].actions[0].key, Some(f15)); + let shift_f14 = FunctionKey { key: 14, cmd: false, shift: true }; + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.duplicate", "Shift+F14"); + app.run(ACTION_OPTIONS, p(1, 0, shift_f14)).unwrap(); + let km = |app: &VectorcraftApp| crate::keymap::keymap_with(&app.ui.shortcut_overrides); + assert!(crate::keymap::lookup(&km(&app), &shift_f14.chord().unwrap()).is_some(), "the command keeps its shortcut"); + assert_eq!(keys(&app), [Some(shift_f14), Some(f15)]); + // The keys play their actions. + app.ui.action_sets[1].actions[1].steps = vec![("shape.rectangle".into(), json!({"x": 10, "y": 10, "width": 20, "height": 20}))]; + let ctx = egui::Context::default(); + let press = |app: &mut VectorcraftApp, key, modifiers| { + let ev = egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + let mut out = ctx.run_ui(egui::RawInput { events: vec![ev], ..Default::default() }, |ui| crate::shortcuts::handle(app, ui.ctx())); + out.textures_delta.clear(); + }; + let last = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.last().map(|s| s.label.clone()); + let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let before = undo(&app); + press(&mut app, egui::Key::F15, egui::Modifiers::NONE); + assert_eq!((last(&app), undo(&app)), (Some("Nudge Again".to_string()), before + 1), "F15 plays Nudge Again"); + let id = app.session.active().unwrap().selection.objects.clone(); + let x = |app: &VectorcraftApp| app.session.active().unwrap().doc.bounds_of(&id, false).unwrap().x0; + let before = x(&app); + press(&mut app, egui::Key::F14, egui::Modifiers::SHIFT); + assert_eq!((last(&app), x(&app)), (Some("Nudge".to_string()), before + 1.0), "Shift+F14 plays Nudge"); + let before = undo(&app); + press(&mut app, egui::Key::F14, egui::Modifiers::NONE); + assert_eq!(undo(&app), before, "F14 without Shift plays nothing"); + app.run("shortcuts.set", json!({"id": "edit.duplicate", "shortcut": "F15"})).unwrap(); + assert_eq!(keys(&app), [Some(shift_f14), Some(f15)]); + crate::shortcut_editor::open(&mut app); + let mut ov = app.ui.shortcut_overrides.clone(); + crate::keymap::set_override(&mut ov, "edit.duplicate", "Shift+F14"); + app.ui.dialog.as_mut().unwrap().fields.insert("overrides".into(), crate::keymap::stored::to_value(&ov)); + crate::shortcut_editor::confirm(&mut app).unwrap(); + assert_eq!(keys(&app), [Some(shift_f14), Some(f15)]); + } + + /// Off macOS, an action's Cmd function key and a command's Ctrl shortcut share the chord. + #[test] + fn an_action_keeps_a_commands_ctrl_shortcut_for_a_cmd_function_key() { + if crate::keymap::platform().is_mac() { + return; + } + let mut app = app_with_sets(); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.duplicate", "Ctrl+F13"); + let cmd_f13 = FunctionKey { key: 13, cmd: true, shift: false }; + let km = |app: &VectorcraftApp| crate::keymap::keymap_with(&app.ui.shortcut_overrides); + assert!(crate::keymap::lookup(&km(&app), &cmd_f13.chord().unwrap()).is_some(), "Ctrl+F13 runs Duplicate"); + app.run(ACTION_OPTIONS, json!({"set": 1, "action": 0, "key": 13, "cmd": true, "shift": false})).unwrap(); + assert!(crate::keymap::lookup(&km(&app), &cmd_f13.chord().unwrap()).is_some(), "the command keeps its shortcut"); + assert_eq!(app.ui.action_sets[1].actions[0].key, Some(cmd_f13)); + } + + /// An action's function key leaves a command's double-press shortcut assigned. + #[test] + fn a_double_press_shortcut_keeps_the_function_key() { + let mut app = app_with_sets(); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.duplicate", "F15 F15"); + let f15 = FunctionKey { key: 15, cmd: false, shift: false }; + let km = |app: &VectorcraftApp| crate::keymap::keymap_with(&app.ui.shortcut_overrides); + assert!(command_on(&km(&app), &f15.chord().unwrap()).is_some(), "F15 pressed twice runs Duplicate"); + app.run(ACTION_OPTIONS, json!({"set": 1, "action": 0, "key": 15})).unwrap(); + assert!(command_on(&km(&app), &f15.chord().unwrap()).is_some(), "the command keeps its shortcut"); + assert_eq!(app.ui.action_sets[1].actions[0].key, Some(f15)); + } + + /// The web build keeps an action's Ctrl or Cmd function key from the browser. + #[test] + fn an_action_key_runs_a_shortcut_for_the_web_build() { + let mut app = app_with_sets(); + let press = || crate::shortcuts::runs_a_shortcut("F13", "F13", egui::Modifiers::COMMAND); + sync_function_keys(&app.ui); + assert!(!press(), "Ctrl+F13 runs nothing"); + app.ui.action_sets[1].actions[0].key = Some(FunctionKey { key: 13, cmd: true, shift: false }); + sync_function_keys(&app.ui); + assert!(press(), "Ctrl+F13 plays Nudge"); + } + + /// Every action key pressed in one frame plays its action, and a command shortcut pressed in + /// the same frame still runs. + #[test] + fn action_keys_and_a_command_shortcut_in_one_frame_all_run() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.ui.action_sets[1].actions[0].key = Some(FunctionKey { key: 15, cmd: false, shift: false }); + app.ui.action_sets[1].actions[1].key = Some(FunctionKey { key: 14, cmd: false, shift: false }); + app.run("shortcuts.set", json!({"id": "edit.duplicate", "shortcut": "F13"})).unwrap(); + let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.iter().map(|s| s.label.clone()).collect::>(); + let before = undo(&app).len(); + let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let events = vec![key(egui::Key::F15), key(egui::Key::F14), key(egui::Key::F13)]; + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert_eq!(undo(&app)[before..], ["Nudge", "Nudge Again", "Duplicate"], "both actions played, then Duplicate ran"); + } + + /// `ui.action.play` plays an action by its name, in the set named when one is, and refuses a + /// name that more than one action has, or that none has. + #[test] + fn play_action_by_name_refuses_a_name_more_than_one_action_has() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.ui.action_sets[2].actions.push(Action::new("Nudge", vec![("object.move".into(), json!({"dx": 5, "dy": 0}))])); + let id = app.session.active().unwrap().selection.objects.clone(); + let x = |app: &VectorcraftApp| app.session.active().unwrap().doc.bounds_of(&id, false).unwrap().x0; + let before = x(&app); + assert_eq!(app.run(PLAY_ACTION, json!({"action": "Nudge"})).unwrap_err(), "more than one action is named “Nudge”"); + assert_eq!(app.run(PLAY_ACTION, json!({"action": "Nope"})).unwrap_err(), "no such action"); + assert_eq!(app.run(PLAY_ACTION, json!({"action": "Nudge", "set": "Missing"})).unwrap_err(), "no such action"); + assert_eq!(app.run(PLAY_ACTION, json!({})).unwrap_err(), "no such action"); + assert_eq!(app.run(PLAY_ACTION, json!({"action": "Nudge Again", "set": 0})).unwrap_err(), "no such action set"); + assert_eq!(x(&app), before, "nothing played"); + app.run(PLAY_ACTION, json!({"action": "Nudge", "set": "Other"})).unwrap(); + assert_eq!(x(&app), before + 5.0, "Other's Nudge played"); + app.run(PLAY_ACTION, json!({"action": "Nudge Again"})).unwrap(); + assert_eq!(x(&app), before + 6.0, "a name one action has plays without a set"); + } + + /// Action Options shows the action's function key and color; OK sets them and keeps the name's + /// steps, Cancel keeps them as they were. A rename keeps them, and a copy has no key. + #[test] + fn action_options_sets_the_function_key_and_color_and_keeps_the_steps() { + use crate::dialogs::action_set_options::open_action; + let mut app = app_with_sets(); + open_action(&mut app, 1, 1); + let texts = dialog_texts(&mut app); + for label in ["Action Options", "Name:", "Function Key:", "Shift", "Color:"] { + assert!(texts.iter().any(|t| t == label), "{label}: {texts:?}"); + } + let set = |app: &mut VectorcraftApp| { + let d = app.ui.dialog.as_mut().expect("Action Options is open"); + assert_eq!((d.fields["key"].clone(), d.bool("shift"), d.str("color")), (json!(0), false, String::new())); + d.fields.insert("key".into(), json!(15)); + d.fields.insert("shift".into(), json!(true)); + d.fields.insert("color".into(), json!("green")); + }; + set(&mut app); + crate::dialogs::cancel(&mut app); + let a = |app: &VectorcraftApp, i: usize| app.ui.action_sets[1].actions[i].clone(); + assert_eq!((a(&app, 1).key, a(&app, 1).color), (None, None), "Cancel keeps them"); + open_action(&mut app, 1, 1); + set(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + let shift_f15 = FunctionKey { key: 15, cmd: false, shift: true }; + assert_eq!((a(&app, 1).name, a(&app, 1).key, a(&app, 1).color), ("Nudge Again".to_string(), Some(shift_f15), Some("green".to_string()))); + assert_eq!(a(&app, 1).steps, [("object.move".to_string(), json!({"dx": 1, "dy": 0}))], "the steps stay"); + open_action(&mut app, 1, 1); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["key"].clone(), d.bool("shift"), d.str("color")), (json!(15), true, "green".to_string()), "shown when it opens again"); + assert!(dialog_texts(&mut app).iter().any(|t| t == "Green")); + app.ui.dialog = None; + app.run(RENAME_ACTION, json!({"set": 1, "action": 1, "name": "Push"})).unwrap(); + assert_eq!((a(&app, 1).key, a(&app, 1).color.as_deref()), (Some(shift_f15), Some("green")), "a rename keeps them"); + app.run(DUPLICATE, json!({"set": 1, "action": 1})).unwrap(); + assert_eq!( + (a(&app, 2).name.as_str(), a(&app, 2).key, a(&app, 2).color.as_deref()), + ("Push copy", None, Some("green")), + "the copy has no key" + ); + assert_ne!(a(&app, 2).id, a(&app, 1).id); + assert_eq!(a(&app, 1).key, Some(shift_f15), "the original keeps it"); + app.run(ACTION_OPTIONS, json!({"set": 1, "action": 1, "key": 0, "color": null})).unwrap(); + assert_eq!((a(&app, 1).name.as_str(), a(&app, 1).key, a(&app, 1).color.clone()), ("Push", None, None), "cleared; the name stays"); + app.run(ACTION_OPTIONS, json!({"set": 1, "action": 1, "key": 15, "cmd": true, "shift": true})).unwrap(); + app.run(ACTION_OPTIONS, json!({"set": 1, "action": 1, "key": 14})).unwrap(); + assert_eq!(a(&app, 1).key, Some(FunctionKey { key: 14, cmd: true, shift: true }), "a new key keeps the modifiers left out"); + app.run(ACTION_OPTIONS, json!({"set": 1, "action": 1, "shift": false})).unwrap(); + assert_eq!(a(&app, 1).key, Some(FunctionKey { key: 14, cmd: true, shift: false }), "shift alone changes Shift"); + app.run(ACTION_OPTIONS, json!({"set": 1, "action": 2, "shift": true})).unwrap(); + assert_eq!(a(&app, 2).key, None, "a modifier alone gives no key"); + for (p, want) in [ + (json!({"set": 1, "action": 9}), "no such action"), + (json!({"set": 1, "action": 1, "name": " "}), "name is empty"), + (json!({"set": 1, "action": 1, "color": "pink"}), "no such color"), + (json!({"set": 1, "action": 1, "key": 99}), "no such function key"), + ] { + assert_eq!(app.run(ACTION_OPTIONS, p.clone()).unwrap_err(), want, "{p}"); + } + } + + /// Function keys and colors are saved with the UI preferences and in action set files; older + /// preferences and files without them, or with values that are not one, load none. + #[test] + fn function_keys_and_colors_are_kept_with_the_preferences_and_in_set_files() { + let mut app = app_with_sets(); + let k = FunctionKey { key: 13, cmd: true, shift: true }; + app.run(ACTION_OPTIONS, json!({"set": 1, "action": 0, "key": 13, "cmd": true, "shift": true, "color": "violet"})).unwrap(); + let saved = serde_json::to_value(&app.ui).unwrap(); + let first = &saved["action_sets"][1]["actions"][0]; + assert_eq!((first["key"].clone(), first["color"].clone()), (json!({"key": 13, "cmd": true, "shift": true}), json!("violet"))); + assert!(saved["action_sets"][1]["actions"][1].get("key").is_none(), "no key: nothing written"); + let restored = serde_json::from_value::(saved.clone()).unwrap(); + let a = &restored.action_sets[1].actions[0]; + assert_eq!((a.key, a.color.as_deref()), (Some(k), Some("violet"))); + let mut odd = saved.clone(); + odd["action_sets"][1]["actions"][0]["key"] = json!("F13"); + odd["action_sets"][1]["actions"][0]["color"] = json!("pink"); + let restored = serde_json::from_value::(odd).unwrap(); + let a = &restored.action_sets[1].actions[0]; + assert_eq!((a.name.as_str(), a.key, a.color.clone()), ("Nudge", None, None), "values that are not one load as none"); + let files = with_files(&mut app, "/sets/Mine.vcactions"); + app.run(SAVE_SET, json!({"set": 1, "path": "/sets/Mine.vcactions"})).unwrap(); + let v: Value = serde_json::from_slice(&files.borrow()["/sets/Mine.vcactions"]).unwrap(); + assert_eq!( + (v["version"].clone(), v["actions"][0]["key"].clone(), v["actions"][0]["color"].clone()), + (json!(1), first["key"].clone(), json!("violet")) + ); + app.run(LOAD_SET, json!({"path": "/sets/Mine.vcactions"})).unwrap(); + let loaded = &app.ui.action_sets[3].actions[0]; + assert_eq!((loaded.key, loaded.color.as_deref()), (Some(k), Some("violet"))); + app.run(DELETE_SETS, json!({"sets": [1, 3]})).unwrap(); + app.run(LOAD_SET, json!({"path": "/sets/Mine.vcactions"})).unwrap(); + assert_eq!(app.ui.action_sets[2].actions[0].key, Some(k), "a free key loads with its action"); + let plain = json!({"format": "vcactions", "version": 1, "name": "P", "actions": [{"name": "A", "steps": []}]}); + app.run(LOAD_SET, json!({"data": plain.to_string()})).unwrap(); + let a = &app.ui.action_sets[3].actions[0]; + assert_eq!((a.key, a.color.clone()), (None, None), "a file without them loads none"); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.duplicate", "Cmd+Shift+F13"); + app.run(DELETE_SETS, json!({"sets": [2]})).unwrap(); + app.run(LOAD_SET, json!({"path": "/sets/Mine.vcactions"})).unwrap(); + let a = &app.ui.action_sets.last().unwrap().actions[0]; + assert_eq!((a.key, a.color.as_deref()), (Some(k), Some("violet"))); + } + + /// Saved function keys survive loading; reserved keys cannot play actions on this platform. + #[test] + fn loaded_preferences_keep_function_keys_and_skip_reserved_keys_at_playback() { + let app = app_with_sets(); + let mut saved = serde_json::to_value(&app.ui).unwrap(); + let key = |k: u8, cmd: bool, shift: bool| json!({"key": k, "cmd": cmd, "shift": shift}); + for (set, action, k) in [ + (1, 0, key(13, false, false)), + (1, 1, key(13, false, false)), + (0, 0, key(1, false, false)), + (0, 1, key(12, false, true)), + (0, 2, key(4, true, false)), + ] { + saved["action_sets"][set]["actions"][action]["key"] = k; + } + let mut overrides = app.ui.shortcut_overrides.clone(); + crate::keymap::set_override(&mut overrides, "edit.duplicate", "Shift+F12"); + saved["shortcut_overrides"] = crate::keymap::stored::to_value(&overrides); + let ui = serde_json::from_value::(saved).unwrap().sanitized(); + let keys = |set: usize| ui.action_sets[set].actions.iter().map(|a| a.key).collect::>(); + let f13 = FunctionKey { key: 13, cmd: false, shift: false }; + assert_eq!(keys(1), [Some(f13), Some(f13)]); + let windows = crate::keymap::platform() == craft_keymap::Platform::Windows; + let f1 = FunctionKey { key: 1, cmd: false, shift: false }; + let ctrl_f4 = FunctionKey { key: 4, cmd: true, shift: false }; + let shift_f12 = FunctionKey { key: 12, cmd: false, shift: true }; + assert_eq!(keys(0)[..3], [Some(f1), Some(shift_f12), Some(ctrl_f4)]); + assert_eq!(playable_chord(f1).is_some(), !windows); + assert_eq!(playable_chord(ctrl_f4).is_some(), !windows); + assert!( + crate::keymap::lookup(&crate::keymap::keymap_with(&ui.shortcut_overrides), &shift_f12.chord().unwrap()).is_some(), + "the command keeps its shortcut" + ); + } } diff --git a/crates/ui-egui/src/panels/actions/files.rs b/crates/ui-egui/src/panels/actions/files.rs index df5ffe8523..252d4c8e7d 100644 --- a/crates/ui-egui/src/panels/actions/files.rs +++ b/crates/ui-egui/src/panels/actions/files.rs @@ -1,8 +1,10 @@ //! Action set files: the Actions panel menu's Save Actions… and Load Actions…. //! //! An action set file (`.vcactions`) is JSON: `{"format": "vcactions", "version": 1, "name", -//! "actions": [{"name", "steps": [{"command", "params"}]}]}`. Each step is a command id and its -//! params, as `command.batch` takes them. +//! "actions": [{"name", "steps": [{"command", "params"}], "key"?, "color"?}]}`. Each step is a +//! command id and its params, as `command.batch` takes them. `key` is the action's function key +//! (`{"key": 1 to 15, "cmd", "shift"}`) and `color` its Button Mode color; an action without them, +//! or with a value that is not one, has none. use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -42,6 +44,10 @@ struct SetFile { struct FileAction { name: String, steps: Vec, + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "super::deserialize_key")] + key: Option, + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "super::deserialize_color")] + color: Option, } /// A step of an action in an action set file: a command id and its params, as `command.batch` @@ -61,6 +67,8 @@ pub fn write_set(set: &ActionSet) -> String { .map(|a| FileAction { name: a.name.clone(), steps: a.steps.iter().map(|(command, params)| FileStep { command: command.clone(), params: params.clone() }).collect(), + key: a.key, + color: a.color.clone(), }) .collect(); let file = SetFile { format: ACTIONS_EXT.into(), version: 1, name: set.name.clone(), actions }; @@ -85,8 +93,11 @@ pub fn read_set(text: &str, name: &str) -> Result { if f.actions.iter().any(|a| a.steps.len() > MAX_ACTION_STEPS) { return Err("an action in the action set file has more than 10,000 steps".into()); } - let actions = - f.actions.into_iter().map(|a| Action { name: a.name, steps: a.steps.into_iter().map(|s| (s.command, s.params)).collect() }).collect(); + let actions = f + .actions + .into_iter() + .map(|a| Action { key: a.key, color: a.color, ..Action::new(a.name, a.steps.into_iter().map(|s| (s.command, s.params)).collect()) }) + .collect(); let set_name = if f.name.trim().is_empty() { name.to_string() } else { f.name }; Ok(ActionSet::new(set_name, actions)) } @@ -151,8 +162,9 @@ pub(crate) fn can_load(app: &VectorcraftApp) -> bool { /// `ui.actionSet.load {path? | data?}`: reads the action set file at `path` (else a picked one), or /// the file's text `data`, and adds its set after the others, with its actions. A set with the -/// same name as one in the panel gets the next free number (`Print 2`). The current set and the -/// other sets stay as they are → `{set: index, name, actions: n}`. +/// same name as one in the panel gets the next free number (`Print 2`). Loaded actions keep their +/// function keys. The current set and the other sets stay as they are → +/// `{set: index, name, actions: n}`. pub fn load_set(app: &mut VectorcraftApp, p: &Value) -> Result { let (text, stem) = match p.get("data") { Some(Value::String(data)) => { diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index f1f0707f69..b9e289a494 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -801,10 +801,30 @@ fn font_height_reference(app: &mut VectorcraftApp, ui: &mut Ui, width: f32) { } /// The font family menu and the font style dropdown of style `s` (Character and Properties panels, -/// Control bar), with their `ids` and `widths`. +/// Control bar), with their `ids` and `widths`. The mouse wheel over the closed family field steps +/// the text through the families. pub(crate) fn font_pickers(app: &mut VectorcraftApp, ui: &mut Ui, s: &CharStyle, ids: (&str, &str), widths: (f32, f32)) { + let wheel_owner = match ids.0 { + "ch-font" => Some(crate::font_menu::WheelOwner::Character), + "font" => Some(crate::font_menu::WheelOwner::Properties), + "cb-font" => Some(crate::font_menu::WheelOwner::Control), + _ => None, + }; + font_pickers_owned(app, ui, s, ids, widths, wheel_owner); +} + +fn font_pickers_owned( + app: &mut VectorcraftApp, + ui: &mut Ui, + s: &CharStyle, + ids: (&str, &str), + widths: (f32, f32), + wheel_owner: Option, +) { + crate::font_menu::sync_wheel_target(app, ui.ctx(), ui.ctx().viewport_id()); let sample = crate::font_menu::sample_text(app); - if let Some(pick) = crate::font_menu::font_menu(ui, ids.0, &s.font_family, widths.0, sample.as_deref(), crate::font_menu::MenuLook::of(app)) { + let look = crate::font_menu::MenuLook { wheel: true, wheel_owner, ..crate::font_menu::MenuLook::of(app) }; + if let Some(pick) = crate::font_menu::font_menu(ui, ids.0, &s.font_family, widths.0, sample.as_deref(), look) { crate::font_menu::apply(app, ui.ctx(), pick); } let styles = vectorcraft_text::FontDb::global().styles(&s.font_family); @@ -892,7 +912,7 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { .on_hover_text(tl!("Character options")); widgets::popover(&link, link.clicked(), |ui| { ui.set_width(260.0); - show(app, ui); + show_owned(app, ui, crate::font_menu::WheelOwner::ControlPopover(link.id)); }); font_pickers(app, ui, &s, ("cb-font", "cb-font-style"), (150.0, 96.0)); size_field(app, ui, "cb-font-size", 96.0); @@ -904,7 +924,11 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { const SNAP_TO_GLYPH_OPTIONS: &str = "ch-snap-to-glyph-options"; pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { - attributes(app, ui); + show_owned(app, ui, crate::font_menu::WheelOwner::Character); +} + +fn show_owned(app: &mut VectorcraftApp, ui: &mut Ui, owner: crate::font_menu::WheelOwner) { + attributes(app, ui, owner); // Drawing over type needs no type selected, so the options show without one too. if pstate::(ui.ctx(), SNAP_TO_GLYPH_OPTIONS) { snap_to_glyph_options(app, ui); @@ -942,7 +966,7 @@ fn snap_to_glyph_options(app: &mut VectorcraftApp, ui: &mut Ui) { } /// The character attributes of the type selected (an empty state without any). -fn attributes(app: &mut VectorcraftApp, ui: &mut Ui) { +fn attributes(app: &mut VectorcraftApp, ui: &mut Ui, owner: crate::font_menu::WheelOwner) { let Some((s, _)) = text_style(app) else { app.character_focus = None; super::empty_state(ui, "type", tl!("No text selected"), tl!("Select a text object to edit its character attributes.")); @@ -954,7 +978,7 @@ fn attributes(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(f) = app.character_focus { widgets::arm_field_focus(ui.ctx(), f.salt()); } - font_pickers(app, ui, &s, ("ch-font", "ch-style"), (w - 4.0, w - 4.0)); + font_pickers_owned(app, ui, &s, ("ch-font", "ch-style"), (w - 4.0, w - 4.0), Some(owner)); variable_font(app, ui, &s, w - 4.0); ui.add_space(2.0); let hidden = pstate::(ui.ctx(), "ch-hide-options"); @@ -1213,6 +1237,12 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { ui.add_enabled_ui(has, |ui| { ui.menu_button(format!(" {}", tl!("Character Direction")), |ui| char_direction_items(app, ui)); }); + // A mixed selection is unchecked; choosing it enables kashidas for the whole range. + let kashidas = shared(app, |s| s.kashidas) == Some(true); + let selected_characters = text_editing(app).is_none_or(|(_, start, end)| end > start); + if menu_item(ui, tl!("Kashidas"), has && selected_characters, kashidas) { + format(app, json!({"kashidas": !kashidas})); + } ui.separator(); } // No Break: the selected characters stay on one line. @@ -1266,7 +1296,7 @@ fn fractional_widths_on(app: &VectorcraftApp) -> bool { /// and Small Caps off, the normal position (neither superscript nor subscript), Roman Baseline /// character alignment, Proportional Metrics, Tate-chu-yoko, Standard Vertical Roman Alignment and /// No Break off, Tate-chu-yoko Settings Up/Down and Left/Right 0, the Default character direction, -/// the Default digits and the Em Box font height reference, whether or not Show East Asian +/// Kashidas on, the Default digits and the Em Box font height reference, whether or not Show East Asian /// Options, Show Indic Options and Show Font Height Options are on. fn reset_panel(app: &mut VectorcraftApp) { let d = CharStyle::default(); @@ -1278,7 +1308,7 @@ fn reset_panel(app: &mut VectorcraftApp) { "allCaps": false, "smallCaps": d.small_caps.is_some(), "position": d.position.id(), "charAlign": d.char_align, "proportionalMetrics": d.proportional_metrics, "tateChuYoko": d.tate_chu_yoko, "tcyUpDown": d.tcy_up_down, "tcyLeftRight": d.tcy_left_right, - "standardVerticalRoman": d.standard_vertical_roman, "noBreak": d.no_break, "charDirection": "default", + "standardVerticalRoman": d.standard_vertical_roman, "noBreak": d.no_break, "charDirection": "default", "kashidas": d.kashidas, "digits": d.digits, "fontHeightReference": d.font_height_reference }), ); diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 5775fbdc58..9f28427c16 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -1028,6 +1028,45 @@ fn no_break_menu_item_toggles_the_selected_characters() { assert!(!on(&app)); } +/// Kashidas appears with Middle Eastern options, starts checked, and a mixed selection is +/// unchecked until the user enables all of its characters. +#[test] +fn kashidas_menu_item_handles_default_and_mixed_ranges() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.show_indic_options = true; + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "AB"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let ctx = egui::Context::default(); + let row = |app: &mut VectorcraftApp| { + super::super::tests_appearance::frame_events(&ctx, app, vec![], menu) + .into_iter() + .find(|(text, _)| text.trim_start_matches(['✓', ' ']) == "Kashidas") + .expect("Kashidas menu item") + }; + assert!(row(&mut app).0.starts_with('✓')); + app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 1, "kashidas": false})).unwrap(); + assert!(!row(&mut app).0.starts_with('✓')); + let at = row(&mut app).1.center(); + super::super::tests_appearance::click(&ctx, &mut app, at, menu); + assert!(row(&mut app).0.starts_with('✓')); + let states = match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| r.style.kashidas).collect::>(), + _ => panic!("text"), + }; + assert!(states.iter().all(|v| *v)); + app.select_tool("type"); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + app.session.set_tool_option("select", &json!({"start": 1, "end": 1})); + let at = row(&mut app).1.center(); + super::super::tests_appearance::click(&ctx, &mut app, at, menu); + let after = match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| r.style.kashidas).collect::>(), + _ => panic!("text"), + }; + assert!(after.iter().all(|v| *v), "an empty caret leaves all characters unchanged"); +} + /// Reset Panel sets every character attribute the panel shows, except the font family, style /// and size, back to its default (Small Caps, the position, Character Alignment, Proportional /// Metrics, Tate-chu-yoko and its settings, No Break, Character Direction, Digits and the font height reference diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 9e751cf1f5..9fc91f5068 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -227,7 +227,7 @@ pub(crate) fn open_file(app: &mut VectorcraftApp, p: &Value, reveal: bool) -> Re } else { app.refuse_automation("links.editOriginal")?; openable_original(&path)?; - crate::io::open_in_app(app, &path)?; + crate::io::open_original(app, &path)?; } Ok(json!({ "path": path })) } diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 1a7dad123c..d6c62a13d1 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -20,12 +20,12 @@ enum Flag { /// A checkbox row: label and the feature it toggles. type Toggle = (&'static str, Flag); -const FIGURES: [&str; 5] = ["Default Figure", "Tabular Lining", "Proportional Lining", "Proportional Oldstyle", "Tabular Oldstyle"]; +pub(crate) const FIGURES: [&str; 5] = ["Default Figure", "Tabular Lining", "Proportional Lining", "Proportional Oldstyle", "Tabular Oldstyle"]; -const POSITIONS: [&str; 5] = ["Default Position", "Superscript", "Subscript", "Numerator", "Denominator"]; +pub(crate) const POSITIONS: [&str; 5] = ["Default Position", "Superscript", "Subscript", "Numerator", "Denominator"]; /// The features the Position menu's entries after Default Position turn on, in menu order. -const POSITION_TAGS: [&str; 4] = ["sups", "subs", "numr", "dnom"]; +pub(crate) const POSITION_TAGS: [&str; 4] = ["sups", "subs", "numr", "dnom"]; /// The bit of [`OtFeatures::extra`] that turns `tag` on (0 for a tag outside [`EXTRA_FEATURES`]). fn extra_bit(tag: &str) -> u32 { @@ -51,7 +51,7 @@ impl Flag { /// The Figure menu entry `f` shows: Default Figure, Tabular Lining, Proportional Lining /// (`pnum` and `lnum`), Proportional Oldstyle or Tabular Oldstyle. -fn figure(f: &OtFeatures) -> usize { +pub(crate) fn figure(f: &OtFeatures) -> usize { let proportional_lining = extra_bit("pnum") | extra_bit("lnum"); match (f.tabular_figures, f.oldstyle_figures) { (false, false) if f.extra & proportional_lining == proportional_lining => 2, @@ -81,7 +81,7 @@ fn set_figure(f: &mut OtFeatures, i: usize) { /// The Position menu entry `f` shows: Superscript (`sups`), Subscript (`subs`), Numerator /// (`numr`) or Denominator (`dnom`) when `f` turns that one on, Default Position when it turns /// none of them on, and `None` when it turns on more than one. -fn position(f: &OtFeatures) -> Option { +pub(crate) fn position(f: &OtFeatures) -> Option { let mut on = POSITION_TAGS.iter().enumerate().filter(|(_, t)| f.extra & extra_bit(t) != 0).map(|(i, _)| i + 1); match (on.next(), on.next()) { (None, _) => Some(0), diff --git a/crates/ui-egui/src/panels/pathfinder.rs b/crates/ui-egui/src/panels/pathfinder.rs index 34f2b58f3a..4d08938c53 100644 --- a/crates/ui-egui/src/panels/pathfinder.rs +++ b/crates/ui-egui/src/panels/pathfinder.rs @@ -522,9 +522,7 @@ mod tests { fn actions_panel_play_records_pathfinder_step() { let mut app = two_squares(); click_button(&mut app, "Intersect"); - app.ui.action_sets[0] - .actions - .push(crate::panels::actions::Action { name: "Unite".into(), steps: vec![("object.pathfinder.unite".into(), json!({}))] }); + app.ui.action_sets[0].actions.push(crate::panels::actions::Action::new("Unite", vec![("object.pathfinder.unite".into(), json!({}))])); let idx = app.ui.action_sets[0].actions.len() - 1; select_two_squares(&mut app, 110.0); crate::panels::actions::play(&mut app, 0, idx).unwrap(); diff --git a/crates/ui-egui/src/panels/tests_appearance.rs b/crates/ui-egui/src/panels/tests_appearance.rs index 1fee26cc68..dc56d99e8a 100644 --- a/crates/ui-egui/src/panels/tests_appearance.rs +++ b/crates/ui-egui/src/panels/tests_appearance.rs @@ -835,6 +835,316 @@ fn an_effects_name_edits_it_and_its_empty_space_highlights_it() { assert!(app.ui.dialog.is_some(), "a double-click on the empty space opens the dialog"); } +#[test] +fn transform_effect_name_edits_the_displayed_appearance_target() { + for target_kind in ["object", "group", "layer"] { + let mut app = app_with_rect(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + if target_kind == "group" { + let group = app.run("object.group", json!({})).unwrap()["id"].clone(); + app.run("layer.target", json!({"id": group})).unwrap(); + } else if target_kind == "layer" { + let layer = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.target", json!({"id": layer.0})).unwrap(); + } + let target = app.session.doc().unwrap().selection.subjects()[0]; + app.run("effect.apply", json!({"effect": "distort.transform", "item": null, "params": {"moveH": 12}})).unwrap(); + let ctx = drop_ctx(); + let texts = frame_events(&ctx, &mut app, vec![], appearance::show); + click_mod(&ctx, &mut app, text_rect(&texts, "Transform").center(), egui::Modifiers::NONE); + let dialog = app.ui.dialog.as_mut().unwrap_or_else(|| panic!("Transform did not open for {target_kind}")); + assert_eq!(dialog.f64("moveH", 0.0), 12.0); + dialog.fields.insert("moveH".into(), json!(35)); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(text.lines().any(|s| s == "Transform"), "{text}"); + assert!(app.session.in_interaction()); + let rendered = vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc); + assert_eq!(rendered.over_white(30, 50), [255, 255, 255], "{target_kind}: original position"); + assert_eq!(rendered.over_white(130, 50), [255, 0, 0], "{target_kind}: transformed position"); + crate::dialogs::confirm(&mut app).unwrap(); + let node = app.session.doc().unwrap().doc.node(target).unwrap(); + assert_eq!(node.appearance.effects.len(), 1); + assert_eq!(node.appearance.effects[0].params["moveH"].as_f64(), Some(35.0)); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.node(target).unwrap().appearance.effects[0].params["moveH"].as_f64(), Some(12.0)); + } +} + +#[test] +fn transform_effect_typed_scale_changes_the_painted_object() { + for layer_target in [false, true] { + let mut app = app_with_rect(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + if layer_target { + app.run("effect.apply", json!({"effect": "distort.transform", "item": null, "params": {"objects": false}})).unwrap(); + let layer = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.target", json!({"id": layer.0})).unwrap(); + } + app.run("effect.apply", json!({"effect": "distort.transform", "item": null})).unwrap(); + let target = app.session.doc().unwrap().selection.subjects()[0]; + let ctx = drop_ctx(); + crate::theme::install_fonts(&ctx); + let texts = frame_events(&ctx, &mut app, vec![], appearance::show); + click_mod(&ctx, &mut app, text_rect(&texts, "Transform").center(), egui::Modifiers::NONE); + for _ in 0..2 { + frame_events(&ctx, &mut app, vec![], |app, ui| crate::dialogs::show(app, ui.ctx())); + } + frame_events(&ctx, &mut app, vec![egui::Event::Text("50".into())], |app, ui| crate::dialogs::show(app, ui.ctx())); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + frame_events(&ctx, &mut app, vec![enter], |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(app.ui.dialog.is_none()); + let doc = &app.session.doc().unwrap().doc; + assert_eq!(doc.node(target).unwrap().appearance.effects[0].params["scaleH"].as_f64(), Some(50.0)); + let rendered = vectorcraft_testkit::raster::render_artboard(doc); + assert_eq!(rendered.over_white(20, 50), [255, 255, 255], "layer target: {layer_target}"); + assert_eq!(rendered.over_white(50, 50), [255, 0, 0], "layer target: {layer_target}"); + } +} + +#[test] +fn transform_effect_preview_commit_cancel_and_undo_cover_artwork_targets() { + use vectorcraft_testkit::raster::{Image, render_artboard}; + let rightmost = + |image: &Image| (0..image.width).rev().find(|&x| (0..image.height).any(|y| image.over_white(x, y).iter().any(|&c| c < 245))).unwrap(); + for kind in ["object", "fill", "stroke", "group", "layer", "text", "image"] { + for preview in [true, false] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + match kind { + "text" => { + app.run("text.create", json!({"x": 20, "y": 80, "size": 20, "text": "HI"})).unwrap(); + } + "image" => { + let mut png = Vec::new(); + image::RgbaImage::from_pixel(20, 20, image::Rgba([255, 0, 0, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + app.run( + "file.place", + json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "link": false, "at": [30, 70]}), + ) + .unwrap(); + } + _ => { + app.run("shape.rectangle", json!({"x": 20, "y": 60, "width": 20, "height": 20})).unwrap(); + } + } + if kind != "image" { + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + } + if kind == "stroke" { + app.run("paint.setFill", json!({"none": true})).unwrap(); + app.run("stroke.set", json!({"weight": 4})).unwrap(); + } + if kind == "group" { + app.run("object.group", json!({})).unwrap(); + } else if kind == "layer" { + let layer = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.target", json!({"id": layer.0})).unwrap(); + } + let item = match kind { + "fill" => Some(0), + "stroke" => Some(1), + _ => None, + }; + app.run("effect.apply", json!({"effect": "distort.transform", "item": item})).unwrap(); + let baseline = render_artboard(&app.session.doc().unwrap().doc); + let ctx = drop_ctx(); + crate::theme::install_fonts(&ctx); + let mut texts = frame_events(&ctx, &mut app, vec![], appearance::show); + if let Some(i) = item { + let label = text_rect(&texts, if i == 0 { "Fill:" } else { "Stroke:" }); + click_mod(&ctx, &mut app, egui::pos2(label.left() - 12.0, label.center().y), egui::Modifiers::NONE); + texts = frame_events(&ctx, &mut app, vec![], appearance::show); + } + click_mod(&ctx, &mut app, text_rect(&texts, "Transform").center(), egui::Modifiers::NONE); + let d = app.ui.dialog.as_mut().unwrap_or_else(|| panic!("{kind}: dialog did not open")); + d.fields.insert("moveH".into(), json!(40)); + d.fields.insert("copies".into(), json!(2)); + d.fields.insert("preview".into(), json!(preview)); + crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + let painted = render_artboard(&app.session.doc().unwrap().doc); + if preview { + assert!(rightmost(&painted) >= rightmost(&baseline) + 75, "{kind}: preview must draw both copies"); + } else { + assert_eq!(painted.rgba, baseline.rgba, "{kind}: Preview off"); + } + crate::dialogs::confirm(&mut app).unwrap(); + let committed = render_artboard(&app.session.doc().unwrap().doc); + assert!(rightmost(&committed) >= rightmost(&baseline) + 75, "{kind}: OK must draw both copies"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(render_artboard(&app.session.doc().unwrap().doc).rgba, baseline.rgba, "{kind}: undo"); + let undo = app.session.active().unwrap().history.undo.len(); + app.run("effect.dialog", json!({"effect": "distort.transform", "item": item, "index": 0})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("moveH".into(), json!(40)); + d.fields.insert("copies".into(), json!(2)); + crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + crate::dialogs::cancel(&mut app); + assert_eq!(render_artboard(&app.session.doc().unwrap().doc).rgba, baseline.rgba, "{kind}: Cancel"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "{kind}: Cancel must preserve undo history"); + } + } +} + +#[test] +fn transform_effect_copies_preview_while_the_field_is_still_focused() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.units_general = "cm".into(); + app.run("file.new", json!({"width": 400, "height": 1200})).unwrap(); + assert_eq!(app.session.general_unit(), Unit::named("cm").unwrap()); + app.run("shape.rectangle", json!({"x": 20, "y": 60, "width": 20, "height": 20})).unwrap(); + app.run("object.group", json!({})).unwrap(); + app.run("appearance.addFill", json!({})).unwrap(); + app.run("paint.setFill", json!({"item": 0, "color": "#000000"})).unwrap(); + app.run("appearance.addFill", json!({})).unwrap(); + app.run("paint.setFill", json!({"item": 1, "color": "#ffffff"})).unwrap(); + app.run("effect.apply", json!({"effect": "path.offsetPath", "item": 0, "params": {"offset": 10}})).unwrap(); + app.run("effect.apply", json!({"effect": "distort.transform", "item": 0, "params": {"scaleH": 99.5, "moveV": 72.0 / 2.54}})).unwrap(); + let target = app.session.doc().unwrap().selection.subjects()[0]; + let ctx = drop_ctx(); + crate::theme::install_fonts(&ctx); + let texts = frame_events(&ctx, &mut app, vec![], appearance::show); + let fill = texts.iter().filter(|(s, _)| s == "Fill:").max_by(|(_, a), (_, b)| a.top().total_cmp(&b.top())).unwrap().1; + click_mod(&ctx, &mut app, egui::pos2(fill.left() - 12.0, fill.center().y), egui::Modifiers::NONE); + let texts = frame_events(&ctx, &mut app, vec![], appearance::show); + click_mod(&ctx, &mut app, text_rect(&texts, "Transform").center(), egui::Modifiers::NONE); + for _ in 0..2 { + frame_events(&ctx, &mut app, vec![], |app, ui| crate::dialogs::show(app, ui.ctx())); + } + let texts = frame_events(&ctx, &mut app, vec![], |app, ui| crate::dialogs::show(app, ui.ctx())); + let copies = text_rect(&texts, "0").center(); + click(&ctx, &mut app, copies, |app, ui| crate::dialogs::show(app, ui.ctx())); + frame_events(&ctx, &mut app, vec![egui::Event::Text("30".into())], |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(app.ui.dialog.is_some()); + assert!(ctx.memory(|m| m.focused().is_some())); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("copies", 0.0), 30.0); + let effect = &app.session.doc().unwrap().doc.node(target).unwrap().appearance.items[0].effects()[1]; + assert_eq!(effect.params["copies"].as_f64(), Some(30.0)); + let rendered = vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc); + assert!(rendered.over_white(30, 600).iter().any(|&c| c < 245), "the focused field must update the visible copy stack"); + crate::dialogs::cancel(&mut app); + let restored = vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc); + assert_eq!(restored.over_white(30, 600), [255, 255, 255]); +} + +#[test] +fn transform_effect_live_fields_keep_partial_text_and_honor_preview() { + let cm = 72.0 / 2.54; + let cases: [(&str, &str, usize, &[&str], f64); 6] = [ + ("scaleH", "100%", 0, &["5", "0", ".", "1", "2", "5", "6"], 50.13), + ("scaleV", "100%", 1, &["7", "5"], 75.0), + ("moveH", "0cm", 0, &["1", ".", "5"], 1.5 * cm), + ("moveV", "0cm", 1, &["-", "1", ",", "5"], -1.5 * cm), + ("rotate", "0°", 0, &["4", "5", ".", "1", "2", "3"], 45.123), + ("copies", "0", 0, &["2", ".", "5", "6"], 3.0), + ]; + for (key, shown, index, chunks, expected) in cases { + for preview in [true, false] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.units_general = "cm".into(); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 60, "height": 30})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + let params = if key == "copies" { json!({"moveH": 20}) } else { json!({}) }; + app.run("effect.apply", json!({"effect": "distort.transform", "item": null, "params": params})).unwrap(); + let target = app.session.doc().unwrap().selection.subjects()[0]; + let baseline = vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc); + app.run("effect.dialog", json!({"effect": "distort.transform", "item": null, "index": 0})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(preview)); + let ctx = drop_ctx(); + crate::theme::install_fonts(&ctx); + for _ in 0..2 { + frame_events(&ctx, &mut app, vec![], |app, ui| crate::dialogs::show(app, ui.ctx())); + } + let texts = frame_events(&ctx, &mut app, vec![], |app, ui| crate::dialogs::show(app, ui.ctx())); + let at = texts + .iter() + .filter(|(s, _)| s.replace(' ', "") == shown) + .nth(index) + .unwrap_or_else(|| panic!("{key}: missing field {shown}: {texts:?}")) + .1 + .center(); + click(&ctx, &mut app, at, |app, ui| crate::dialogs::show(app, ui.ctx())); + let select_all = + egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }; + frame_events(&ctx, &mut app, vec![select_all], |app, ui| crate::dialogs::show(app, ui.ctx())); + for chunk in chunks { + frame_events(&ctx, &mut app, vec![egui::Event::Text((*chunk).into())], |app, ui| crate::dialogs::show(app, ui.ctx())); + } + let held = app.ui.dialog.as_ref().unwrap().f64(key, f64::NAN); + assert!((held - expected).abs() < 1e-8, "{key}, Preview {preview}: {held} != {expected}"); + let rendered = vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc); + if preview { + let applied = app.session.doc().unwrap().doc.node(target).unwrap().appearance.effects[0].params[key].as_f64().unwrap(); + assert!((applied - expected).abs() < 1e-8, "{key}: preview parameters"); + assert_ne!(rendered.rgba, baseline.rgba, "{key}: visible preview"); + } else { + assert_eq!(rendered.rgba, baseline.rgba, "{key}: Preview off"); + } + let texts = frame_events(&ctx, &mut app, vec![], |app, ui| crate::dialogs::show(app, ui.ctx())); + click(&ctx, &mut app, text_rect(&texts, "OK").center(), |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(app.ui.dialog.is_none()); + let applied = app.session.doc().unwrap().doc.node(target).unwrap().appearance.effects[0].params[key].as_f64().unwrap(); + assert!((applied - expected).abs() < 1e-8, "{key}: confirmed parameters"); + if preview { + assert_eq!( + vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc).rgba, + rendered.rgba, + "{key}: OK matches preview" + ); + } + assert_ne!(vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc).rgba, baseline.rgba, "{key}: OK"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc).rgba, baseline.rgba, "{key}: undo"); + } + } +} + +#[test] +fn transform_effect_sliders_update_the_painted_preview_and_cancel() { + for (key, label, index, fraction, expected, tolerance) in [ + ("scaleH", "Horizontal:", 0, 0.25, 50.0, 4.0), + ("scaleV", "Vertical:", 0, 0.25, 50.0, 4.0), + ("moveH", "Horizontal:", 1, 0.55, 100.0, 20.0), + ("moveV", "Vertical:", 1, 0.55, 100.0, 20.0), + ] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 60, "height": 30})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + app.run("effect.apply", json!({"effect": "distort.transform", "item": null})).unwrap(); + let baseline = vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc); + app.run("effect.dialog", json!({"effect": "distort.transform", "item": null, "index": 0})).unwrap(); + let ctx = drop_ctx(); + crate::theme::install_fonts(&ctx); + for _ in 0..2 { + frame_events(&ctx, &mut app, vec![], |app, ui| crate::dialogs::show(app, ui.ctx())); + } + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(&mut app, ui.ctx())); + output.textures_delta.clear(); + let mut rails: Vec<_> = output + .platform_output + .accesskit_update + .as_ref() + .unwrap() + .nodes + .iter() + .filter(|(_, n)| n.role() == egui::accesskit::Role::Slider && n.label() == Some(label)) + .filter_map(|(_, n)| n.bounds()) + .collect(); + rails.sort_by(|a, b| a.y0.total_cmp(&b.y0)); + let bounds = rails.get(index).unwrap_or_else(|| panic!("{key}: slider not found")); + let at = egui::pos2((bounds.x0 + (bounds.x1 - bounds.x0) * fraction) as f32, ((bounds.y0 + bounds.y1) / 2.0) as f32); + click(&ctx, &mut app, at, |app, ui| crate::dialogs::show(app, ui.ctx())); + let value = app.ui.dialog.as_ref().unwrap().f64(key, f64::NAN); + assert!((value - expected).abs() <= tolerance, "{key}: {value}"); + assert_ne!(vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc).rgba, baseline.rgba, "{key}: slider preview"); + crate::dialogs::cancel(&mut app); + assert_eq!(vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc).rgba, baseline.rgba, "{key}: Cancel"); + } +} + /// A fill or stroke row's label ("Fill:", "Stroke:") is a link: a click opens the Color or Stroke /// panel with or without modifiers, with the tooltip "Click to edit". Its empty space only takes the /// click rules: no tooltip, and neither a Ctrl-click nor a double-click there opens a panel. diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 98e1dd250e..215cf7148a 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -1,7 +1,7 @@ //! The Links panel, its flyout, Link Info, Edit Original / Show in Folder, the Placement Options //! dialog and the Properties panel's image section, drawn headless. -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; use serde_json::json; @@ -168,6 +168,44 @@ fn edit_original_and_show_in_folder_hand_the_file_to_the_system() { assert!(app.run("links.editOriginal", json!({"id": linked})).is_err()); } +/// #5236: with Preferences › File Handling › Use System Defaults for Edit Original off, Edit +/// Original opens a raster image in the app that made it, PhotoCraft, and falls back to the +/// system's default app when PhotoCraft isn't installed or the file isn't a raster image. +#[test] +fn edit_original_opens_raster_images_in_photocraft_without_system_defaults() { + /// What each open asked for: (`true` for PhotoCraft, the path). + type Opened = Rc>>; + let dir = Folder::new("with"); + let (mut app, linked, _) = app(&dir); + let opened: Opened = Rc::default(); + let installed = Rc::new(Cell::new(true)); + let (o, w, i) = (opened.clone(), opened.clone(), installed.clone()); + app.services.open_file = Some(Box::new(move |p: &str| { + o.borrow_mut().push((false, p.to_string())); + Ok(()) + })); + app.services.open_in_photocraft = Some(Box::new(move |p: &str| { + if i.get() { + w.borrow_mut().push((true, p.to_string())); + } + Ok(i.get()) + })); + // On (the default): the system's app. + let path = app.run("links.editOriginal", json!({"id": linked})).unwrap()["path"].as_str().unwrap().to_string(); + app.run("prefs.set", json!({"key": "editOriginalSystemDefaults", "value": false})).unwrap(); + app.run("links.editOriginal", json!({"id": linked})).unwrap(); + installed.set(false); + app.run("links.editOriginal", json!({"id": linked})).unwrap(); + installed.set(true); + // A file that isn't a raster image goes to the system's app. + crate::io::open_original(&mut app, "/Art/plan.emf").unwrap(); + assert_eq!(*opened.borrow(), [(false, path.clone()), (true, path.clone()), (false, path), (false, "/Art/plan.emf".to_string())]); + // PhotoCraft failing to open it is said, not hidden behind the system's app. + app.services.open_in_photocraft = Some(Box::new(|_: &str| Err("PhotoCraft didn't start".to_string()))); + assert!(app.run("links.editOriginal", json!({"id": linked})).is_err()); + assert_eq!(opened.borrow().len(), 4); +} + /// Edit Original hands only regular image and document files to the system's default app. #[test] fn edit_original_opens_image_and_document_files_only() { diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index ab89d2faf8..87aa5cd13f 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -429,23 +429,24 @@ mod tests { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); let t = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "x"})).unwrap()["id"].as_u64().unwrap(); - app.run("dataset.import", json!({"csv": "name,Name\nA,Ann\nB,Bob\n"})).unwrap(); + app.run("dataset.import", json!({"csv": "Name\nAnn\nBob\n"})).unwrap(); + let (a, b) = ("Data Set 1", "Data Set 2"); let message = |row: &str| format!("nothing in data set {row} was applied: no object is bound to a variable it has a value for"); - app.run("dataset.select", json!({"name": "A"})).unwrap(); - assert_eq!(app.ui.status, message("A")); + app.run("dataset.select", json!({"name": a})).unwrap(); + assert_eq!(app.ui.status, message(a)); app.run("dataset.next", json!({})).unwrap(); - assert_eq!(app.ui.status, message("B")); + assert_eq!(app.ui.status, message(b)); app.run("dataset.prev", json!({})).unwrap(); - assert_eq!(app.ui.status, message("A")); + assert_eq!(app.ui.status, message(a)); app.run("variable.bind", json!({"variable": "Name", "ids": [t]})).unwrap(); - app.run("dataset.select", json!({"name": "B"})).unwrap(); + app.run("dataset.select", json!({"name": b})).unwrap(); assert_eq!(app.ui.status, ""); // Stepping to a data set that applies clears the message as well. for step in ["dataset.next", "dataset.prev"] { app.run("variable.unbind", json!({"variable": "Name", "ids": [t]})).unwrap(); - app.run("dataset.select", json!({"name": "A"})).unwrap(); - assert_eq!(app.ui.status, message("A")); + app.run("dataset.select", json!({"name": a})).unwrap(); + assert_eq!(app.ui.status, message(a)); app.run("variable.bind", json!({"variable": "Name", "ids": [t]})).unwrap(); app.run(step, json!({})).unwrap(); assert_eq!(app.ui.status, "", "{step}"); diff --git a/crates/ui-egui/src/picks.rs b/crates/ui-egui/src/picks.rs index 362108a46f..fd5c4d61ce 100644 --- a/crates/ui-egui/src/picks.rs +++ b/crates/ui-egui/src/picks.rs @@ -20,6 +20,7 @@ use std::rc::Rc; use std::sync::mpsc::{Receiver, TryRecvError}; use serde_json::Value; +use vectorcraft_engine::file_access::ScopeHandle; use crate::state::Dialog; use crate::{FilePick, VectorcraftApp}; @@ -91,6 +92,9 @@ struct Waiting { entry: Entry, /// The active document when it was asked for ([`vectorcraft_engine::DocState::uid`]). doc: Option, + /// The automation roots in force when it was asked for: the entry runs again under them, not + /// with the desktop's access of the frame the answer comes in. + scope: ScopeHandle, } /// The app's file dialogs ([`VectorcraftApp`]'s `picks`). @@ -286,7 +290,7 @@ fn ask(app: &mut VectorcraftApp, request: PickRequest) -> Option { (Some(entry), Some(start)) => { if let Some(answer) = start(request.clone()) { let doc = entry.document(app); - app.picks.waiting = Some(Waiting { request, answer, entry, doc }); + app.picks.waiting = Some(Waiting { request, answer, entry, doc, scope: ScopeHandle::capture() }); return None; } } @@ -333,20 +337,22 @@ pub(crate) fn poll(app: &mut VectorcraftApp, ctx: &egui::Context) { // The dialog's thread is gone: as cancelled. Err(TryRecvError::Disconnected) => vec![], }; - let Some(Waiting { request, entry, doc, .. }) = app.picks.waiting.take() else { return }; + let Some(Waiting { request, entry, doc, scope, .. }) = app.picks.waiting.take() else { return }; app.picks.refused = false; // Once more: what waited for the dialog (files from the Finder, the menu bar) goes on. ctx.request_repaint(); if answer.is_empty() { return; } - if !on_document(app, doc) { - return; - } - app.picks.answer = Some((request, answer)); - rerun(app, entry); - // An entry that took another way this time leaves the answer unused. - app.picks.answer = None; + scope.run(|| { + if !on_document(app, doc) { + return; + } + app.picks.answer = Some((request, answer)); + rerun(app, entry); + // An entry that took another way this time leaves the answer unused. + app.picks.answer = None; + }); } /// Make the document an entry asked for (`doc`, by its uid) active again before it runs again: diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index c2b920b837..d4f4412ec0 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -376,13 +376,18 @@ fn queue_files(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result, done: Receiver>, + /// The automation roots in force when the read started, kept in force when it is placed: a + /// DXF placed against an artboard that changed meanwhile is read again then. + scope: ScopeHandle, } /// A read waiting for the thread that reads the files. @@ -318,6 +321,7 @@ fn spawn_labeled( let (tx, done) = channel(); // The automation roots in force here are in force there. let scope = ScopeHandle::capture(); + let completion = scope.clone(); #[cfg(test)] let reading = app.placing.reading.clone(); let job: Job = Box::new(move || { @@ -352,7 +356,7 @@ fn spawn_labeled( let _ = reader.send(job); app.placing.reader = Some(reader); } - app.placing.pending.push(Pending { name, label: label.clone(), doc, dropped, paste: chain.is_some(), chain, done }); + app.placing.pending.push(Pending { name, label: label.clone(), doc, dropped, paste: chain.is_some(), chain, done, scope: completion }); let status = format!("{label}…"); app.status(status.clone()); Ok(Some(json!({ "background": true, "status": status }))) @@ -384,7 +388,7 @@ pub fn poll(app: &mut VectorcraftApp) { if app.ui.status == format!("{}…", p.label) { app.ui.status.clear(); } - finish(app, &p, r); + p.scope.clone().run(|| finish(app, &p, r)); if let Some(chain) = p.chain && !app.placing.swatch_paste.as_ref().is_some_and(|waiting| waiting.chain == chain) { diff --git a/crates/ui-egui/src/placing/tests.rs b/crates/ui-egui/src/placing/tests.rs index 90d1a551a2..fcd2090161 100644 --- a/crates/ui-egui/src/placing/tests.rs +++ b/crates/ui-egui/src/placing/tests.rs @@ -1284,3 +1284,42 @@ fn a_file_read_between_a_tools_clicks_is_placed() { assert_eq!(app.session.tool_busy(), !other_document, "other document: {other_document}"); } } + +/// A DXF placed within automation roots is read again within them when it is placed against an +/// artboard that changed meanwhile: a path redirected outside the roots after the read is refused. +#[cfg(unix)] +#[test] +fn a_file_read_again_when_placed_stays_within_the_roots_it_was_read_in() { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + src.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 20, "height": 10})).unwrap(); + let v = src.execute("document.serialize", &json!({"format": "dxf"})).unwrap(); + let dxf = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); + let base = std::env::temp_dir().join(format!("vc-placing-reread-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for d in ["in", "out"] { + std::fs::create_dir_all(base.join(d)).unwrap(); + std::fs::write(base.join(d).join("real.dxf"), &dxf).unwrap(); + } + let link = base.join("in").join("plan.dxf"); + std::os::unix::fs::symlink(base.join("in").join("real.dxf"), &link).unwrap(); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[&base.join("in")], &[]).unwrap().unwrap(); + let mut app = app(true); + let p = json!({"path": link.to_string_lossy(), "dxf": {"fit": true}, "at": [100, 150]}); + vectorcraft_engine::file_access::confine(Some(&roots), || start(&mut app, &p, false)).unwrap(); + let t0 = std::time::Instant::now(); + while !(app.placing.reading[1].load(std::sync::atomic::Ordering::SeqCst) == 1 + && app.placing.reading[0].load(std::sync::atomic::Ordering::SeqCst) == 0) + { + assert!(t0.elapsed().as_secs() < 60, "read within 60 s"); + std::thread::yield_now(); + } + // Read; now the path leads outside the roots and the artboard under `at` changes. + std::fs::remove_file(&link).unwrap(); + std::os::unix::fs::symlink(base.join("out").join("real.dxf"), &link).unwrap(); + app.run("artboard.setProps", json!({"index": 0, "width": 200})).unwrap(); + placed(&mut app); + assert_eq!(app.session.doc().unwrap().doc.layers.iter().flat_map(|l| l.children().into_iter().flatten()).count(), 0, "nothing placed"); + assert!(app.ui.status.contains("outside the read root"), "{}", app.ui.status); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 80fb23a176..2e47115056 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -391,3 +391,18 @@ fn hyphenation_exceptions_dialog_ok_reaches_the_hyphenator() { assert!(vectorcraft_text::hyphen::hyphen_points("typography").is_empty()); assert_eq!(vectorcraft_text::hyphen::hyphen_points("happen"), vec![3]); } + +/// #5236: File Handling › Use System Defaults for Edit Original is a checkbox, on by default, and +/// OK saves it off. +#[test] +fn use_system_defaults_for_edit_original_is_a_checkbox() { + let mut a = VectorcraftApp::new(Session::new(), Default::default()); + assert!(a.session.prefs.edit_original_system_defaults, "on by default"); + open(&mut a, Some("File Handling")); + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(text.contains("Use System Defaults for Edit Original"), "{text}"); + assert!(a.ui.dialog.as_ref().unwrap().bool("editOriginalSystemDefaults")); + a.ui.dialog.as_mut().unwrap().fields.insert("editOriginalSystemDefaults".into(), json!(false)); + confirm(&mut a).unwrap(); + assert!(!a.session.prefs.edit_original_system_defaults); +} diff --git a/crates/ui-egui/src/render_worker.rs b/crates/ui-egui/src/render_worker.rs index 5651f3ce29..1b28f7d1fb 100644 --- a/crates/ui-egui/src/render_worker.rs +++ b/crates/ui-egui/src/render_worker.rs @@ -7,6 +7,7 @@ use std::sync::Arc; use std::sync::mpsc::{Receiver, Sender, channel}; use vectorcraft_doc::Document; +use vectorcraft_engine::file_access::ScopeHandle; use vectorcraft_geom::Affine; use vectorcraft_render::{RenderOptions, Rendered, Renderer}; @@ -19,6 +20,9 @@ pub struct Job { pub h: u32, pub view: Affine, pub opts: RenderOptions, + /// The automation roots in force where the job was made: the render reads linked files under + /// them, as it would on that thread. + pub scope: ScopeHandle, } pub struct Done { @@ -56,7 +60,7 @@ impl Worker { job = newer; } let t0 = crate::now_ms(); - let img = r.render(&job.doc, job.w, job.h, job.view, &job.opts); + let img = job.scope.clone().run(|| r.render(&job.doc, job.w, job.h, job.view, &job.opts)); if done_tx.send(Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: crate::now_ms() - t0, moved: r.stats.moved }).is_err() { break; diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 45f363eda1..3d35247880 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -65,6 +65,9 @@ pub(crate) fn browsable_url(url: &str) -> Result<(), String> { /// Shows a file in the system file manager, or opens it in its app. pub type RevealFn = Box Result<(), String>>; +/// Opens a file in a fixed app; `Ok(false)` when that app isn't installed. +pub type OpenInFn = Box Result>; + /// Platform services injected by the host app (desktop or web). #[derive(Default)] pub struct Services { @@ -116,6 +119,10 @@ pub struct Services { /// Open a file (or a folder) in the system's default app for it (desktop: Edit Original, Show /// Package). Without it (the web) those answer with an error. pub open_file: Option, + /// Open a file in PhotoCraft where it is installed (desktop: Edit Original of a raster image + /// with Preferences › File Handling › Use System Defaults for Edit Original off); `Ok(false)` + /// when it isn't. Without it Edit Original uses `open_file`. + pub open_in_photocraft: Option, /// Show a folder picker; returns its path (desktop: Relink to Folder, Package). pub pick_folder: Option Option>>, /// Show the system's color sampler, which picks a color anywhere on the screen (macOS, and diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 0d531a2ae2..3b46710240 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -1445,6 +1445,35 @@ mod tests { assert!(import_json(&json!({})).is_err()); } + /// The dialog's Import… leaves an action its function key when the imported set gives the key + /// to a command, through both Cancel and OK. + #[test] + fn importing_into_the_dialog_preserves_action_keys_on_ok() { + use crate::panels::actions::{Action, ActionSet, FunctionKey}; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let f15 = FunctionKey { key: 15, cmd: false, shift: false }; + let mut nudge = Action::new("Nudge", vec![]); + nudge.key = Some(f15); + app.ui.action_sets.push(ActionSet::new("Mine", vec![nudge])); + let mut ov = Overrides::new(); + crate::keymap::set_override(&mut ov, "edit.duplicate", "F15"); + let bytes = serde_json::to_vec(&export_json("Imported", &ov)).unwrap(); + app.services.pick_open = Some(Box::new(|_: &crate::FilePick| Some("/sets/Imported.json".to_string()))); + app.services.read = Some(Box::new(move |_: &str| Ok(bytes.clone()))); + let key = |app: &VectorcraftApp| app.ui.action_sets.last().and_then(|s| s.actions.first()).and_then(|a| a.key); + open(&mut app); + import_into_dialog(&mut app); + assert_eq!(key(&app), Some(f15), "the import alone keeps the action's key"); + assert!(app.ui.shortcut_overrides.is_empty(), "the import is only in the dialog"); + app.ui.dialog = None; + assert_eq!(key(&app), Some(f15), "Cancel keeps the action's key"); + open(&mut app); + import_into_dialog(&mut app); + assert_eq!(key(&app), Some(f15)); + confirm(&mut app).unwrap(); + assert_eq!(key(&app), Some(f15), "OK keeps the action's function key"); + } + #[test] fn presets_are_the_defaults() { for p in PRESETS { diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index f93bde770b..9c62eb1885 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -154,14 +154,18 @@ fn runs_a_command(i: &egui::InputState, key: Key, cmd_only: bool) -> bool { /// `key` and `code` are the browser's names for the character typed and the key's position, which /// egui reads with [`Key::from_name`]; `modifiers` as egui reports them. The press is matched as /// the dispatcher matches it ([`dispatch`]) on a layout about which nothing is known: what typing -/// has shown of the layout is left out, and so are double presses. +/// has shown of the layout is left out, and so are double presses. An action's function key runs +/// a shortcut too. pub fn runs_a_shortcut(key: &str, code: &str, modifiers: Modifiers) -> bool { let physical_key = Key::from_name(code); let Some(key) = Key::from_name(key).or(physical_key) else { return false }; let press = egui::Event::Key { key, physical_key, pressed: true, repeat: false, modifiers }; let Some(input) = craft_keymap::KeyInput::from_egui(&press, crate::keymap::platform()) else { return false }; let mirror = crate::shortcut_editor::current(); - craft_keymap::Layout::default().candidates(&input).iter().any(|c| mirror.keymap.lookup(c, false, &Active::NONE) != craft_keymap::Lookup::None) + craft_keymap::Layout::default() + .candidates(&input) + .iter() + .any(|c| mirror.keymap.lookup(c, false, &Active::NONE) != craft_keymap::Lookup::None || crate::panels::actions::plays_an_action(c)) } /// Process one frame's events against the keymap at most once per context, viewport and frame, so @@ -338,6 +342,8 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { if claimed_tool_keys(app, ctx, view, rows_keys) { return; } + // An action's function key plays the action, also when a command has the same shortcut. + crate::panels::actions::play_function_key(app, ctx); // Command, panel and tool shortcuts. A bound shifted punctuation chord uses its key press; // other text keys use the typed character below. let row_key = |chord: &craft_keymap::Chord| { @@ -487,6 +493,7 @@ fn type_tool_input(app: &mut VectorcraftApp, ctx: &egui::Context, composing: boo }) }); } + crate::panels::actions::play_function_key(app, ctx); // Editing keys with modifiers and the clipboard (Cmd+A is Select All's, below: the text). crate::panels::character::route_type_input(app, ctx); // Enter was already delivered above as ToolKey::Enter (newline). Only chords with the diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 2693965e5b..efe9917492 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -902,6 +902,30 @@ fn press(key: Key, m: Modifiers) -> Vec { vec![egui::Event::ModifiersChanged(m), egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: m }] } +#[test] +fn enclosing_lasso_escape_cancels_and_q_returns_to_anchor_lasso() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + crate::shortcut_editor::sync(&app.ui); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.select_tool(vectorcraft_tools::addons::enclosing_lasso::ID); + let view = app.view_info(); + app.session.pointer(&PointerEvent::new(PointerKind::Down, 90.0, 90.0), view).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Drag, 210.0, 90.0), view).unwrap(); + assert!(app.session.tool_busy()); + frame(&mut app, press(Key::Escape, Modifiers::NONE)); + assert!(!app.session.tool_busy()); + app.session.pointer(&PointerEvent::new(PointerKind::Up, 90.0, 210.0), view).unwrap(); + assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(id)]); + let mut keys = press(Key::Q, Modifiers::NONE); + keys.push(egui::Event::Text("q".into())); + frame(&mut app, keys); + assert_eq!(app.session.tool_id(), "lasso"); +} + /// Binds Show Grid to `chord`, or with `None` leaves every command its default shortcut. fn bind_grid(app: &mut VectorcraftApp, chord: Option<&str>) { app.ui.shortcut_overrides.clear(); @@ -1823,6 +1847,37 @@ fn a_shortcut_on_the_backtick_key_runs_on_every_layout() { assert_eq!(count(&app), 1); } +/// The ISO key next to left Shift (`<` on Turkish Q and many European layouts, egui's +/// `IntlBackslash`) records, saves and runs its shortcut, apart from the `\` key (#4559). +#[test] +fn a_shortcut_on_the_iso_key_next_to_left_shift_records_and_runs() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let recorded = crate::shortcut_editor::chord_from_event(Key::IntlBackslash, Modifiers::NONE).unwrap(); + assert_eq!(recorded, "IntlBackslash"); + crate::shortcut_editor::assign(&mut app.ui.shortcut_overrides, "edit.clear", Some(&recorded), false).unwrap(); + assert_eq!(crate::shortcut_editor::effective_in(&app.ui.shortcut_overrides, "edit.clear").as_deref(), Some("IntlBackslash")); + for text in ["Cmd+IntlBackslash", "Shift+IntlBackslash", "Cmd+Alt+Shift+IntlBackslash"] { + assert_eq!(crate::shortcut_editor::normalize(text).as_deref(), Some(text)); + } + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + let id = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let backslash = + egui::Event::Key { key: Key::Backslash, physical_key: Some(Key::Backslash), pressed: true, repeat: false, modifiers: Modifiers::NONE }; + frame(&mut app, vec![backslash, egui::Event::Text("\\".into())]); + assert_eq!(count(&app), 1, "the `\\` key is another key"); + let press = egui::Event::Key { + key: Key::IntlBackslash, + physical_key: Some(Key::IntlBackslash), + pressed: true, + repeat: false, + modifiers: Modifiers::NONE, + }; + frame(&mut app, vec![press, egui::Event::Text("<".into())]); + assert_eq!(count(&app), 0, "the key next to left Shift runs Edit › Clear"); +} + /// eframe's web build with no text field focused sends the text before its key: the key after /// the `"` it typed is read when no press comes right before it. #[test] diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index ccced48139..4fc10697f6 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -463,6 +463,15 @@ pub struct UiState { /// Consolidate All Windows. Not saved: the reference app does not save windows with a document. #[serde(skip)] pub tiled: bool, + /// Window › Arrange › Float in Window, Float All in Windows and Cascade: the documents in + /// floating windows of their own, out of the tab strip, until Consolidate All Windows. Not + /// saved, as `tiled` is not. + #[serde(skip)] + pub floating: Vec, + /// The document (its uid) the tab strip shows while the current document is in a floating + /// window: the tabbed document that was current last. + #[serde(skip)] + pub tab_document: Option, /// Draw Normal / Behind / Inside. pub draw_mode: u8, pub about: bool, @@ -482,6 +491,11 @@ pub struct UiState { /// Recording in progress: (set index, action name, journal length when recording started). #[serde(skip)] pub recording: Option<(usize, String, usize)>, + /// The id of the action New Action made for the recording in progress + /// ([`crate::panels::actions::Action::id`]): Stop gives it the recorded steps. None when Stop + /// adds a new action, as after Begin Recording. + #[serde(skip)] + pub recording_into: Option, /// Keyboard shortcut overrides: command id, `tool:` or `panel:` → chord ("" = none), /// stored in the form every earlier version reads. #[serde(default, with = "crate::keymap::stored")] @@ -944,12 +958,15 @@ impl Default for UiState { palette_query: String::new(), screen_mode: 0, tiled: false, + floating: Vec::new(), + tab_document: None, draw_mode: 0, about: false, action_sets: crate::panels::actions::default_sets(), action_set: None, action_sets_selected: vec![], recording: None, + recording_into: None, shortcut_overrides: Default::default(), shortcut_set: default_shortcut_set(), workspace: default_workspace(), diff --git a/crates/ui-egui/src/tests/font_menu.rs b/crates/ui-egui/src/tests/font_menu.rs index 680afa6d1a..fa80c359d9 100644 --- a/crates/ui-egui/src/tests/font_menu.rs +++ b/crates/ui-egui/src/tests/font_menu.rs @@ -203,6 +203,336 @@ fn a_press_outside_the_menu_ends_the_preview_at_once() { assert!(!frame(vec![button(outside, false)]).1); } +/// A document with point type in Inter, selected; its id. +fn selected_inter(app: &mut VectorcraftApp) -> u64 { + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + // These tests exercise font picking, including system fonts without Latin glyphs. Missing + // glyph protection would intentionally keep the sample text in its previous font. + app.run("prefs.set", json!({"key": "missingGlyphProtection", "value": false})).unwrap(); + let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "Gagaku", "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + if !crate::panel_docking::showing(&app.ui, "character") { + app.run("window.panel", json!({"panel": "character"})).unwrap(); + } + id +} + +fn first_style(app: &VectorcraftApp, id: u64) -> vectorcraft_doc::CharStyle { + match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.first_style(), + _ => panic!("not type"), + } +} + +fn wheel(unit: egui::MouseWheelUnit, dy: f32, modifiers: egui::Modifiers) -> egui::Event { + egui::Event::MouseWheel { unit, delta: egui::vec2(0.0, dy), modifiers, phase: egui::TouchPhase::Move, source: egui::MouseWheelSource::Unknown } +} + +/// One frame of `draw` over `app`, as the shell runs it; the middle of the text naming `family` +/// lowest on the screen (the closed family field), if drawn, and whether the menu's search field +/// is drawn (the menu is open). +fn panel_frame( + ctx: &egui::Context, + app: &mut VectorcraftApp, + events: Vec, + family: &str, + draw: &dyn Fn(&mut VectorcraftApp, &mut egui::Ui), +) -> (Option, bool) { + let mut input = + egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 800.0))), ..Default::default() }; + app.raw_input_hook(ctx, &mut input); + let mut out = ctx.run_ui(input, |ui| { + crate::font_menu::end_stale_preview(app, ui.ctx()); + draw(app, ui); + }); + out.textures_delta.clear(); + let text = |label: &str| { + out.shapes.iter().find_map(|s| match &s.shape { + egui::Shape::Text(t) if t.galley.text() == label => Some(t.pos + egui::vec2(4.0, t.galley.size().y * 0.5)), + _ => None, + }) + }; + (text(family), text("Search").is_some()) +} + +/// #5253: in the Character panel, each notch of the mouse wheel over the closed font family field +/// applies the next family down the menu (up it when turned up) to the selected type, each its own +/// undo step, with the menu closed. Leaving the field or Escape keeps it; Undo puts it back. +#[test] +fn the_wheel_over_the_family_field_steps_the_selected_type_through_the_families() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let id = selected_inter(&mut app); + let font = |app: &VectorcraftApp| first_style(app, id).font_family; + let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let draw = |app: &mut VectorcraftApp, ui: &mut egui::Ui| crate::panels::character::show(app, ui); + let mut field = None; + for _ in 0..3 { + field = panel_frame(&ctx, &mut app, vec![], "Inter", &draw).0; + } + let field = field.expect("the Character panel shows the family field"); + // Other tests add fonts to the process-wide database meanwhile: compare places, not neighbours. + let place = |f: &str| FontDb::global().menu_family_list().iter().position(|x| x == f); + let before = steps(&app); + let line = egui::MouseWheelUnit::Line; + let (_, open) = panel_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(field), wheel(line, -1.0, Default::default())], "Inter", &draw); + let next = font(&app); + assert!(place(&next) > place("Inter") && steps(&app) == before + 1, "a notch down applies a family below, one step: {next}"); + assert!(!open && !app.session.in_interaction(), "the menu stays closed and nothing is left previewed"); + // The family is now a recent one: the order stays as it was while the pointer stays on the field. + panel_frame(&ctx, &mut app, vec![wheel(line, -1.0, Default::default())], &next, &draw); + let after = font(&app); + assert!(place(&after) > place(&next) && steps(&app) == before + 2, "{after}"); + panel_frame(&ctx, &mut app, vec![wheel(line, 1.0, Default::default())], &after, &draw); + assert_eq!((font(&app), steps(&app)), (next.clone(), before + 3), "a notch up, back"); + // A turn of a fine wheel in points: a notch is `line_scroll_speed` points, the rest carries over. + let speed = ctx.options(|o| o.input_options.line_scroll_speed); + panel_frame(&ctx, &mut app, vec![wheel(egui::MouseWheelUnit::Point, speed * 0.5, Default::default())], &next, &draw); + assert_eq!(font(&app), next, "less than a notch"); + panel_frame(&ctx, &mut app, vec![wheel(egui::MouseWheelUnit::Point, speed * 0.5, Default::default())], &next, &draw); + assert_eq!((font(&app), steps(&app)), ("Inter".to_string(), before + 4), "the rest of the notch"); + // A turn with a modifier key is not the field's. + panel_frame(&ctx, &mut app, vec![wheel(line, -1.0, egui::Modifiers::COMMAND)], "Inter", &draw); + assert_eq!((font(&app), steps(&app)), ("Inter".to_string(), before + 4), "Ctrl/Cmd-wheel"); + // Two notches at once: two families, two steps. + panel_frame(&ctx, &mut app, vec![wheel(line, -2.0, Default::default())], "Inter", &draw); + assert_eq!((font(&app), steps(&app)), (after.clone(), before + 6)); + // Escape and leaving the field keep the family. + panel_frame(&ctx, &mut app, key(egui::Key::Escape), &after, &draw); + panel_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(egui::pos2(580.0, 780.0))], &after, &draw); + panel_frame(&ctx, &mut app, vec![], &after, &draw); + assert_eq!((font(&app), steps(&app)), (after, before + 6), "the family stays applied"); + // The wheel away from the field does not change the font. + let shown = font(&app); + panel_frame(&ctx, &mut app, vec![wheel(line, -1.0, Default::default())], &shown, &draw); + assert_eq!(steps(&app), before + 6, "the wheel off the field"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(font(&app), next, "Undo takes back one notch"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(font(&app), "Inter"); +} + +/// Opposite wheel notches in one frame apply in order, each with its own undo step. +#[test] +fn opposite_wheel_notches_in_one_frame_keep_their_undo_steps() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let id = selected_inter(&mut app); + let draw = |app: &mut VectorcraftApp, ui: &mut egui::Ui| crate::panels::character::show(app, ui); + let mut field = None; + for _ in 0..3 { + field = panel_frame(&ctx, &mut app, vec![], "Inter", &draw).0; + } + let field = field.expect("the Character panel shows the family field"); + let before = app.session.active().unwrap().history.undo.len(); + let line = egui::MouseWheelUnit::Line; + panel_frame( + &ctx, + &mut app, + vec![egui::Event::PointerMoved(field), wheel(line, -1.0, Default::default()), wheel(line, 1.0, Default::default())], + "Inter", + &draw, + ); + assert_eq!(first_style(&app, id).font_family, "Inter"); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 2); + app.run("edit.undo", json!({})).unwrap(); + assert_ne!(first_style(&app, id).font_family, "Inter"); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(first_style(&app, id).font_family, "Inter"); +} + +/// A turn before opening applies once; the popup keeps the later wheel and cancels to that font. +#[test] +fn a_wheel_before_opening_the_family_popup_keeps_its_committed_change() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let id = selected_inter(&mut app); + let draw = |app: &mut VectorcraftApp, ui: &mut egui::Ui| crate::panels::character::show(app, ui); + let mut field = None; + for _ in 0..3 { + field = panel_frame(&ctx, &mut app, vec![], "Inter", &draw).0; + } + let field = field.unwrap(); + let before = app.session.active().unwrap().history.undo.len(); + let button = |pressed| egui::Event::PointerButton { pos: field, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let turn = || wheel(egui::MouseWheelUnit::Line, -1.0, Default::default()); + panel_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(field), turn(), button(true), button(false), turn()], "Inter", &draw); + let applied = first_style(&app, id).font_family; + assert_ne!(applied, "Inter"); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); + for _ in 0..3 { + panel_frame(&ctx, &mut app, vec![], &applied, &draw); + } + panel_frame(&ctx, &mut app, key(egui::Key::Escape), &applied, &draw); + assert_eq!(first_style(&app, id).font_family, applied); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(first_style(&app, id).font_family, "Inter"); +} + +/// A later pointer move must not change which field owns an earlier wheel event. +#[test] +fn wheel_events_use_the_pointer_position_when_they_occurred() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let id = selected_inter(&mut app); + let draw = |app: &mut VectorcraftApp, ui: &mut egui::Ui| crate::panels::character::show(app, ui); + let mut field = None; + for _ in 0..3 { + field = panel_frame(&ctx, &mut app, vec![], "Inter", &draw).0; + } + let field = field.expect("the Character panel shows the family field"); + let outside = egui::pos2(580.0, 780.0); + panel_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(outside)], "Inter", &draw); + let before = app.session.active().unwrap().history.undo.len(); + let line = egui::MouseWheelUnit::Line; + panel_frame(&ctx, &mut app, vec![wheel(line, -1.0, Default::default()), egui::Event::PointerMoved(field)], "Inter", &draw); + assert_eq!(first_style(&app, id).font_family, "Inter", "the wheel was outside the field"); + assert_eq!(app.session.active().unwrap().history.undo.len(), before); + assert!(ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::MouseWheel { .. }))), "outside wheel input is left for its owner"); + panel_frame(&ctx, &mut app, vec![wheel(line, -1.0, Default::default()), egui::Event::PointerMoved(outside)], "Inter", &draw); + assert_ne!(first_style(&app, id).font_family, "Inter", "the wheel was over the field before the pointer left"); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(first_style(&app, id).font_family, "Inter"); + let button = |pos| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + panel_frame(&ctx, &mut app, vec![button(field), wheel(line, -1.0, Default::default()), button(outside)], "Inter", &draw); + assert_ne!(first_style(&app, id).font_family, "Inter", "button events also carry the pointer's position"); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); + app.run("edit.undo", json!({})).unwrap(); + let end = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::Vec2::ZERO, + modifiers: Default::default(), + phase: egui::TouchPhase::End, + source: egui::MouseWheelSource::Unknown, + }; + panel_frame(&ctx, &mut app, vec![end], "Inter", &draw); + panel_frame( + &ctx, + &mut app, + vec![ + wheel(egui::MouseWheelUnit::Point, -2.0, Default::default()), + egui::Event::PointerMoved(field), + wheel(line, -1.0, Default::default()), + egui::Event::PointerMoved(outside), + ], + "Inter", + &draw, + ); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); + assert_eq!(ctx.input(|i| i.smooth_scroll_delta.y), -2.0, "only the outside wheel contributes to panel scrolling"); +} + +/// A turn queued for one document cannot restyle another document opened before its UI pass. +#[test] +fn a_wheel_queued_for_another_document_is_discarded() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + selected_inter(&mut app); + let draw = |app: &mut VectorcraftApp, ui: &mut egui::Ui| crate::panels::character::show(app, ui); + let mut field = None; + for _ in 0..3 { + field = panel_frame(&ctx, &mut app, vec![], "Inter", &draw).0; + } + let field = field.expect("the Character panel shows the family field"); + let mut raw = egui::RawInput { + events: vec![egui::Event::PointerMoved(field), wheel(egui::MouseWheelUnit::Line, -1.0, Default::default())], + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 800.0))), + ..Default::default() + }; + app.raw_input_hook(&ctx, &mut raw); + assert!(!raw.events.iter().any(|e| matches!(e, egui::Event::MouseWheel { .. }))); + let id = selected_inter(&mut app); + let before = app.session.active().unwrap().history.undo.len(); + let mut out = ctx.run_ui(raw, |ui| draw(&mut app, ui)); + out.textures_delta.clear(); + assert_eq!(first_style(&app, id).font_family, "Inter"); + assert_eq!(app.session.active().unwrap().history.undo.len(), before); +} + +/// Presentation mode hides an Appearance row's Character popup even if its state is still open. +#[test] +fn presentation_mode_leaves_a_transient_font_fields_wheel_available() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + selected_inter(&mut app); + app.run("window.panel.close", json!({"panel": "character"})).unwrap(); + app.run("window.panel.close", json!({"panel": "properties"})).unwrap(); + app.run("window.panel", json!({"panel": "appearance"})).unwrap(); + assert!(!crate::panel_docking::showing(&app.ui, "character")); + assert!(!crate::panel_docking::showing(&app.ui, "properties")); + assert!(crate::panel_docking::showing(&app.ui, "appearance")); + app.ui.transient_panel = Some("character".into()); + let draw = |app: &mut VectorcraftApp, ui: &mut egui::Ui| crate::panels::character::show(app, ui); + let mut field = None; + for _ in 0..3 { + field = panel_frame(&ctx, &mut app, vec![], "Inter", &draw).0; + } + app.ui.screen_mode = 3; + let mut raw = egui::RawInput { + events: vec![egui::Event::PointerMoved(field.unwrap()), wheel(egui::MouseWheelUnit::Line, -1.0, Default::default())], + ..Default::default() + }; + app.raw_input_hook(&ctx, &mut raw); + assert!(raw.events.iter().any(|e| matches!(e, egui::Event::MouseWheel { .. }))); +} + +/// #5253: the Properties panel and the Control bar have the same family field, and the wheel steps +/// the families over it too. +#[test] +fn the_wheel_steps_the_families_in_properties_and_the_control_bar() { + type Draw = fn(&mut VectorcraftApp, &mut egui::Ui); + let places: [(&str, Draw); 2] = [ + ("Properties", |app, ui| crate::panels::properties::type_sections(app, ui)), + ("Control bar", |app, ui| crate::panels::character::control_bar(app, ui)), + ]; + let at = |f: &str| FontDb::global().menu_family_list().iter().position(|x| x == f); + for (place, draw) in places { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let id = selected_inter(&mut app); + app.ui.control_bar = true; + let mut field = None; + for _ in 0..3 { + field = panel_frame(&ctx, &mut app, vec![], "Inter", &draw).0; + } + let field = field.unwrap_or_else(|| panic!("{place} shows the family field")); + let steps = app.session.active().unwrap().history.undo.len(); + let notch = wheel(egui::MouseWheelUnit::Line, -1.0, Default::default()); + panel_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(field), notch], "Inter", &draw); + let next = first_style(&app, id).font_family; + assert!(at(&next) > at("Inter"), "{place}: {next}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "{place}"); + } +} + +/// #5253: a family the wheel steps to keeps the type's style when it has that style, else takes the +/// closest it has, as a family picked from the menu does. The menus that only pick a font ignore +/// the wheel. +#[test] +fn a_family_stepped_to_keeps_the_style_it_has() { + let ctx = egui::Context::default(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let id = selected_inter(&mut app); + let db = FontDb::global(); + let bold: Vec = db.menu_family_list().iter().filter(|f| db.styles(f).iter().any(|s| s == "Bold")).take(2).cloned().collect(); + let [from, to] = bold.as_slice() else { panic!("two families with a Bold style: {bold:?}") }; + app.run("text.setStyle", json!({"font": from, "style": "Bold"})).unwrap(); + crate::font_menu::apply(&mut app, &ctx, FontPick::Wheel(vec![to.clone()])); + let s = first_style(&app, id); + assert_eq!((&s.font_family, s.font_style.as_str()), (to, "Bold")); + assert_eq!(crate::font_menu::picked(&mut app, Some(FontPick::Wheel(vec![from.clone()]))), None); + assert_eq!(&first_style(&app, id).font_family, to, "picking menus leave the document alone"); +} + #[test] fn bundled_families_are_classified() { use vectorcraft_text::FontClass; diff --git a/crates/ui-egui/src/tests/home.rs b/crates/ui-egui/src/tests/home.rs index 1b62ac94c2..4f5fc2b3c8 100644 --- a/crates/ui-egui/src/tests/home.rs +++ b/crates/ui-egui/src/tests/home.rs @@ -299,10 +299,11 @@ fn home_scrolls_in_a_short_window() { assert_eq!(app.session.documents().len(), 1, "the card opened its preset"); } -/// Home › Recent Files and File › Open Recent focus an open tab instead of opening a second copy -/// (#3455); `document.open` is unchanged. +/// A file that is already open is not opened again, however it is asked for: Home › Recent Files, +/// File › Open Recent, File › Open, the Finder and a drop all focus its tab, unsaved edits and all +/// (#3455). #[test] -fn home_recent_reopen_focuses_an_already_open_document() { +fn reopening_an_open_file_focuses_its_tab() { let services = crate::Services { read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))), @@ -316,13 +317,35 @@ fn home_recent_reopen_focuses_an_already_open_document() { app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); app.run("shape.rectangle", json!({"x": 1, "y": 2, "width": 10, "height": 10})).unwrap(); app.run("file.saveAs", json!({"path": path})).unwrap(); - app.run("file.new", json!({})).unwrap(); - assert_eq!(app.session.documents().len(), 2); - assert_eq!(app.session.active_index(), Some(1)); - let r = crate::io::open_recent_reporting(&mut app, &path).unwrap(); + // An edit not saved yet. + app.run("shape.rectangle", json!({"x": 20, "y": 2, "width": 10, "height": 10})).unwrap(); + let back = |app: &mut VectorcraftApp| { + app.run("file.new", json!({})).unwrap(); + assert_eq!(app.session.documents().len(), 2); + }; + let focused = |app: &VectorcraftApp, how: &str| { + assert_eq!(app.session.documents().len(), 2, "{how}: no second copy"); + assert_eq!(app.session.active_index(), Some(0), "{how}"); + assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "{how}: the unsaved edit is kept"); + app.session.doc().unwrap().uid + }; + back(&mut app); + // Home › Recent Files, File › Open Recent, File › Open… and the Finder. + let r = crate::io::open_reporting(&mut app, &path).unwrap(); assert_eq!(r["activated"], true); - assert_eq!(app.session.documents().len(), 2); - assert_eq!(app.session.active_index(), Some(0)); - assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 1); + let uid = focused(&app, "open_reporting"); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("file.close", json!({})).unwrap(); + back(&mut app); + // File › Open with a path (an open dialog's answer, `app.open`), and a path spelled differently. + let other = d.join(".").join("doc.vectorcraft").to_string_lossy().to_string(); + assert_eq!(app.run("file.open", json!({"path": other})).unwrap()["activated"], true); + assert_eq!(focused(&app, "file.open"), uid); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("file.close", json!({})).unwrap(); + back(&mut app); + // A drop. + crate::place::drop_files(&mut app, vec![(crate::place::DropTarget::Open, ("doc.vectorcraft".into(), Some(path.clone()), vec![]))]); + assert_eq!(focused(&app, "drop"), uid); let _ = std::fs::remove_dir_all(d); } diff --git a/crates/ui-egui/src/tests/pathtype.rs b/crates/ui-egui/src/tests/pathtype.rs index aa8397a045..46f5eff677 100644 --- a/crates/ui-egui/src/tests/pathtype.rs +++ b/crates/ui-egui/src/tests/pathtype.rs @@ -1,6 +1,7 @@ //! Type → Type on a Path → Type on a Path Options… (#429): the dialog shows the selected type's -//! options (Effect, Flip, Align to Path, Spacing) and OK leaves its brackets where they are. The -//! Selection tool draws no brackets on a huge selection. +//! options (Effect, Flip, Align to Path, Spacing) and OK leaves its brackets where they are; its +//! Preview shows them on the canvas while it is open (#5360). The Selection tool draws no brackets +//! on a huge selection. use serde_json::{Value, json}; use vectorcraft_doc::{NodeId, NodeKind, TextKind}; @@ -80,6 +81,98 @@ fn type_on_a_path_options_keep_the_type_where_it_is() { assert_eq!((d.fields.get("alignToPath"), d.fields.get("flip")), (Some(&json!("center")), Some(&json!(false)))); } +/// The effect, alignment and spacing of type on a path `id`. +fn options(app: &VectorcraftApp, id: NodeId) -> (&'static str, &'static str, f64) { + match app.session.doc().unwrap().doc.node(id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => (t.path_effect.id(), t.path_align.id(), t.path_spacing), + k => panic!("not text: {k:?}"), + } +} + +/// One headless frame of the open dialog. +fn frame(app: &mut VectorcraftApp) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); +} + +/// #5360: Type on a Path Options has a Preview checkbox, off when it opens. With it on, the type +/// on the canvas follows Effect, Flip, Align to Path and Spacing while the dialog is open (a +/// checked Flip turns it over once, however many frames show it); Cancel puts it back without a +/// step of history; OK keeps what was previewed as one step, and none when nothing changed. +#[test] +fn type_on_a_path_options_preview_on_the_canvas() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let path = app.run("path.create", json!({"d": "M100 200 L500 200"})).unwrap()["id"].as_u64().unwrap(); + let r = app.run("text.createInPath", json!({"path": path, "mode": "onPath", "text": "Along", "at": [300, 210]})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [id.0]})).unwrap(); + let original = (brackets(&app, id), options(&app, id)); + let state = |app: &VectorcraftApp| (brackets(app, id), options(app, id)); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let before = steps(&app); + + open_options(&mut app); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(dialogs::accepts_field(d, "preview")); + assert!(!d.bool("preview"), "Preview starts off"); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| dialogs::show(app, ui.ctx())); + assert!(text.contains("Preview"), "{text}"); + + // Off: the fields change nothing until OK. + app.ui.dialog.as_mut().unwrap().fields.insert("effect".into(), json!("skew")); + frame(&mut app); + assert_eq!(state(&app), original, "no preview without the checkbox"); + // On: the type follows the fields. + dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + frame(&mut app); + assert_eq!(options(&app, id).0, "skew"); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("alignToPath".into(), json!("center")); + d.fields.insert("spacing".into(), json!(6.0)); + frame(&mut app); + assert_eq!(options(&app, id), ("skew", "center", 6.0)); + // Flip turns the type over once, frame after frame, and back when unchecked. + app.ui.dialog.as_mut().unwrap().fields.insert("flip".into(), json!(true)); + frame(&mut app); + let flipped = brackets(&app, id); + assert_ne!(flipped, original.0, "the preview flips the type"); + frame(&mut app); + assert_eq!(brackets(&app, id), flipped, "and keeps it flipped once"); + app.ui.dialog.as_mut().unwrap().fields.insert("flip".into(), json!(false)); + frame(&mut app); + assert_eq!(brackets(&app, id), original.0, "unchecked, it turns back"); + // Cancel puts the original back and leaves no history. + dialogs::cancel(&mut app); + assert_eq!(state(&app), original, "Cancel restores the type"); + assert_eq!(steps(&app), before, "and adds no undo step"); + assert!(!app.session.in_interaction()); + + // OK with Preview on and nothing changed: no undo step. + open_options(&mut app); + dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + frame(&mut app); + dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!((state(&app), steps(&app)), (original, before)); + + // OK keeps the previewed values as one undo step. + open_options(&mut app); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("effect".into(), json!("stairStep")); + d.fields.insert("flip".into(), json!(true)); + dialogs::set_field(d, "preview".into(), json!(true)); + frame(&mut app); + dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!((options(&app, id).0, brackets(&app, id)), ("stairStep", flipped)); + assert_eq!(steps(&app), before + 1, "one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(state(&app), original, "one Undo takes the whole change back"); +} + /// The Selection tool's brackets on one selected type on a path add their lines to the frame's /// mesh. On 32,768 (an opened PDF can hold as many curved text lines) they add none. #[test] diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index 8608b7813f..574bb07b51 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -238,8 +238,8 @@ fn load_profile_asks_off_the_ui_thread() { } /// The Variables panel menu's Import Data Sets… and Export Data Sets… ask off the UI thread: the -/// data sets in the file picked are loaded, and the header and data set `B` are written to the -/// path the dialog answers. +/// data sets in the file picked are loaded, and the header and the data set's row are written to +/// the path the dialog answers. #[test] fn variables_panel_data_sets_ask_off_the_ui_thread() { let (mut app, shown, _) = app(); @@ -250,20 +250,20 @@ fn variables_panel_data_sets_ask_off_the_ui_thread() { } std::fs::create_dir_all(&dir).unwrap(); let (csv, out) = (dir.join("sets.csv"), dir.join("out.csv")); - std::fs::write(&csv, "name,Name\nB,y\n").unwrap(); + std::fs::write(&csv, "Name\ny\n").unwrap(); let sets = |app: &VectorcraftApp| app.session.doc().unwrap().doc.variables.datasets.iter().map(|d| d.name.clone()).collect::>(); click(&mut app, "Import Data Sets…", crate::panels::variables::menu); assert!(matches!(shown.requests().as_slice(), [PickRequest::Open(_)])); shown.answer(&[&csv.to_string_lossy()]); poll(&mut app); - assert_eq!(sets(&app), ["B"], "{}", app.ui.status); + assert_eq!(sets(&app), ["Data Set 1"], "{}", app.ui.status); click(&mut app, "Export Data Sets…", crate::panels::variables::menu); assert!(matches!(shown.requests().as_slice(), [PickRequest::Save(_)])); shown.answer(&[&out.to_string_lossy()]); poll(&mut app); - assert_eq!(std::fs::read_to_string(&out).ok().as_deref(), Some("name,Name\nB,y\n"), "{}", app.ui.status); + assert_eq!(std::fs::read_to_string(&out).ok().as_deref(), Some("Name\ny\n"), "{}", app.ui.status); let _ = std::fs::remove_dir_all(dir); } diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 0e7fe849b2..cb44318cff 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -576,7 +576,10 @@ fn switching_tabs_or_slider_modes_keeps_the_dialog_height() { ("sliderMode", json!("hsb")), ("sliderMode", json!("lab")), ("tab", json!("edit")), + ("display", json!("segmented")), + ("display", json!("bars")), ("sliderMode", json!("global")), + ("display", json!("smooth")), ("sliderMode", json!("rgb")), ("tab", json!("assign")), ] { @@ -939,3 +942,233 @@ fn the_last_edit_color_can_be_selected_edited_and_undone() { assert_eq!(h.state().session.doc().unwrap().doc, before); } } + +/// The height of the open Recolor Artwork dialog. +fn dialog_height(h: &egui_kittest::Harness<'_, VectorcraftApp>) -> f32 { + h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", "recolor")))).unwrap().height() +} + +/// Clicks the Edit tab's display button named `name` and lets the dialog settle. +fn show_display(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, name: &str) { + h.get_by_role_and_label(egui::accesskit::Role::Button, name).click(); + h.run_steps(6); +} + +/// The Edit tab opens on the smooth color wheel and its buttons switch to the segmented wheel and to +/// the color bars and back: the dialog keeps its size, and the rows and the selected row stay. The +/// choice stays while the dialog is open; the next opening starts on the smooth wheel again. +#[test] +fn the_edit_tab_shows_a_smooth_or_segmented_wheel_or_color_bars() { + let mut h = edit_harness(&["#ff0000", "#0000ff", "#00ff00"]); + set(h.state_mut(), "__sel", json!([1])); + h.run_steps(4); + let (rows, height) = (field(h.state(), "rows"), dialog_height(&h)); + let slider = |h: &egui_kittest::Harness<'_, VectorcraftApp>, name: &str| h.query_by_role_and_label(egui::accesskit::Role::Slider, name).is_some(); + let bar = |h: &egui_kittest::Harness<'_, VectorcraftApp>, name: &str| h.query_by_role_and_label(egui::accesskit::Role::Button, name).is_some(); + assert!(slider(&h, "Color wheel") && !slider(&h, "Segmented color wheel"), "the smooth wheel first"); + assert!(!bar(&h, "Color 1")); + show_display(&mut h, "Show segmented color wheel"); + assert_eq!(field(h.state(), "display"), json!("segmented")); + assert!(slider(&h, "Segmented color wheel") && !slider(&h, "Color wheel")); + assert_eq!(widget_of_size(&h, vec2(220.0, 220.0)).size(), vec2(220.0, 220.0), "the same size of wheel"); + assert!(slider(&h, "Brightness")); + show_display(&mut h, "Show color bars"); + assert_eq!(field(h.state(), "display"), json!("bars")); + assert!(!slider(&h, "Color wheel") && !slider(&h, "Segmented color wheel")); + assert!(["Color 1", "Color 2", "Color 3"].iter().all(|n| bar(&h, n)), "a bar per color"); + assert_eq!(dialog_height(&h), height, "the bars keep the dialog's height"); + show_display(&mut h, "Show smooth color wheel"); + assert!(slider(&h, "Color wheel")); + assert_eq!(dialog_height(&h), height); + assert_eq!(field(h.state(), "rows"), rows, "switching changes no color"); + assert_eq!(field(h.state(), "__sel"), json!([1]), "and keeps the selected row"); + show_display(&mut h, "Show color bars"); + set(h.state_mut(), "tab", json!("assign")); + h.run_steps(3); + set(h.state_mut(), "tab", json!("edit")); + h.run_steps(3); + assert!(bar(&h, "Color 1"), "the choice stays while the dialog is open"); + let app = h.state_mut(); + dialogs::cancel(app); + app.run("select.all", json!({})).unwrap(); + app.run("ui.recolorDialog", json!({})).unwrap(); + assert_eq!(field(app, "display"), Value::Null, "a new opening starts on the smooth wheel"); +} + +/// The segmented wheel's patches: 24 hues, centered on red, by 5 saturations, at the brightness asked. +#[test] +fn the_segmented_wheel_has_24_hues_by_5_saturations() { + let seg = |h, s, v| crate::widgets::segment_color(h, s, v).to_hsb(); + let near = |a: [f32; 3], b: [f32; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3); + assert!(near(seg(7.0, 0.95, 1.0), [0.0, 0.9, 1.0]), "{:?}", seg(7.0, 0.95, 1.0)); + assert!(near(seg(8.0, 0.0, 0.5), [15.0, 0.1, 0.5]), "{:?}", seg(8.0, 0.0, 0.5)); + assert!(near(seg(355.0, 1.0, 1.0), [0.0, 0.9, 1.0]), "{:?}", seg(355.0, 1.0, 1.0)); + assert!(near(seg(120.0, 0.5, 1.0), [120.0, 0.5, 1.0]), "{:?}", seg(120.0, 0.5, 1.0)); + let mut patches = std::collections::BTreeSet::new(); + for h in 0..360 { + for s in 0..=100 { + patches.insert(ColorKey::of(&crate::widgets::segment_color(h as f32, s as f32 / 100.0, 1.0)).to_string()); + } + } + assert_eq!(patches.len(), 24 * 5); +} + +/// On the segmented wheel a marker moves as freely as on the smooth one, past patch edges and +/// without snapping to a patch; linked colors turn with it from where the drag started, an excluded +/// row keeps its color, and the smooth wheel shows the result. Its Brightness slider works too. +#[test] +fn a_segmented_wheel_marker_moves_freely() { + let mut h = edit_harness(&["rgb 200 100 100", "rgb 100 200 200", "rgb 20 160 20"]); + let mut rows = field(h.state(), "rows"); + let green = (0..3).find(|i| rows[*i]["from"] == json!(["rgb 20 160 20"])).unwrap(); + let red = (0..3).find(|i| rows[*i]["from"] == json!(["rgb 200 100 100"])).unwrap(); + rows[green]["exclude"] = json!(true); + set(h.state_mut(), "rows", rows); + set(h.state_mut(), "__sel", json!([red])); + h.run_steps(4); + show_display(&mut h, "Show segmented color wheel"); + let start = new_hsb(h.state()); + let wheel = widget_of_size(&h, vec2(220.0, 220.0)); + let (c, r) = (wheel.center(), 100.0); + let at = |hue: f32, s: f32| c + vec2(hue.to_radians().cos(), -hue.to_radians().sin()) * r * s; + let [hue, s, _] = start[red]; + h.hover_at(at(hue, s)); + h.run_steps(1); + h.drag_at(at(hue, s)); + h.run_steps(1); + // 37° on in small steps, across two patch edges, ending inside a patch away from its center. + for k in 1..=10 { + h.hover_at(at(hue + 3.7 * k as f32, s)); + h.run_steps(1); + } + h.drop_at(at(hue + 37.0, s)); + h.run_steps(2); + let moved = new_hsb(h.state()); + let gap = |a: f32, b: f32| (a - b).rem_euclid(360.0).min((b - a).rem_euclid(360.0)); + let want = (hue + 37.0).rem_euclid(360.0); + assert!(gap(moved[red][0], want) < 1.0, "the marker follows the pointer: {} -> {}", hue, moved[red][0]); + assert!(gap(moved[red][0], (want / 15.0).round() * 15.0) > 2.0, "not snapped to a patch center: {}", moved[red][0]); + let other = 3 - red - green; + assert!((gap(moved[other][0], start[other][0]) - 37.0).abs() < 1.5, "linked: {:?} -> {:?}", start[other], moved[other]); + assert_eq!(field(h.state(), "rows")[green]["to"], json!("rgb 20 160 20"), "the excluded row stays"); + let rows = field(h.state(), "rows"); + show_display(&mut h, "Show smooth color wheel"); + assert_eq!(field(h.state(), "rows"), rows, "the smooth wheel shows the same colors"); + show_display(&mut h, "Show segmented color wheel"); + click_slider(&mut h, "Brightness", 0.25); + assert!((new_hsb(h.state())[red][2] - 0.25).abs() < 0.02, "the Brightness slider: {:?}", new_hsb(h.state())); +} + +/// The rows as `(current colors, new color)` pairs, sorted. +fn row_pairs(app: &VectorcraftApp) -> Vec { + let mut v: Vec = field(app, "rows").as_array().unwrap().iter().map(|r| format!("{} {}", r["from"], r["to"])).collect(); + v.sort(); + v +} + +/// The color bars: one per recolored row (none for an excluded row), the last one selected with a +/// click and edited with the H slider, then dragged to the top, which moves its row and changes no +/// color. Preview shows the edit, Cancel restores the art and OK keeps it as one undo step. +#[test] +fn color_bars_select_edit_and_reorder_the_rows() { + for confirm in [false, true] { + let mut h = edit_harness(&["#ff0000", "#0000ff", "#00ff00", "#ffff00"]); + let before = h.state().session.doc().unwrap().doc.clone(); + let undo = h.state().session.doc().unwrap().history.undo.len(); + let mut rows = field(h.state(), "rows"); + rows[1]["exclude"] = json!(true); + set(h.state_mut(), "rows", rows); + set(h.state_mut(), "linked", json!(false)); + set(h.state_mut(), "sliderMode", json!("hsb")); + show_display(&mut h, "Show color bars"); + let bar = |h: &egui_kittest::Harness<'_, VectorcraftApp>, name: &str| { + h.query_by_role_and_label(egui::accesskit::Role::Button, name).map(|n| n.rect()) + }; + assert!(bar(&h, "Color 2").is_none(), "no bar for the excluded row"); + let first = bar(&h, "Color 1").expect("a bar per recolored row"); + let last = bar(&h, "Color 4").expect("a bar per recolored row"); + assert!(bar(&h, "Color 3").is_some_and(|r| r.top() > first.bottom() && r.bottom() < last.top()), "in row order"); + h.input_mut().events.extend(press(last.center(), 1)); + h.run_steps(3); + assert_eq!(field(h.state(), "__sel"), json!([3]), "a click selects the bar's row"); + let unedited = field(h.state(), "rows"); + click_slider(&mut h, "H", 0.5); + let edited = field(h.state(), "rows"); + assert_ne!(edited[3]["to"], unedited[3]["to"], "the H slider edits the selected bar's color"); + assert_eq!(&edited.as_array().unwrap()[..3], &unedited.as_array().unwrap()[..3], "and only that one"); + let previewed = h.state().session.doc().unwrap().doc.clone(); + assert_ne!(previewed, before, "the art previews the edit"); + let pairs = row_pairs(h.state()); + let last = bar(&h, "Color 4").unwrap(); + h.hover_at(last.center()); + h.run_steps(1); + h.drag_at(last.center()); + h.run_steps(1); + let top = egui::pos2(last.center().x, first.top() + 2.0); + for k in 1..=8 { + h.hover_at(last.center().lerp(top, k as f32 / 8.0)); + h.run_steps(1); + } + h.drop_at(top); + h.run_steps(3); + let rows = field(h.state(), "rows"); + assert_eq!(rows[0], edited[3], "the dragged row moved to the top: {rows}"); + assert_eq!(rows.as_array().unwrap()[1..], [edited[0].clone(), edited[1].clone(), edited[2].clone()], "the others shift down"); + assert_eq!(row_pairs(h.state()), pairs, "moving a bar changes no color"); + assert_eq!(field(h.state(), "__sel"), json!([0]), "the moved row stays selected"); + assert_eq!(h.state().session.doc().unwrap().doc, previewed, "and the art keeps the same colors"); + h.get_by_label(if confirm { "OK" } else { "Cancel" }).click(); + h.run_steps(2); + assert!(h.state().ui.dialog.is_none()); + let app = h.state(); + if confirm { + assert_eq!(app.session.doc().unwrap().doc, previewed, "OK keeps the edit"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "as one undo step"); + } else { + assert_eq!(app.session.doc().unwrap().doc, before, "Cancel restores the art"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + } + } +} + +/// Many color bars scroll within the wheel's height, the dialog keeps its height, and the last bar +/// can be reached and selected; with every row excluded the bars area says there is nothing to +/// recolor. +#[test] +fn color_bars_scroll_and_show_when_nothing_is_recolored() { + let colors: Vec = (1..=40).map(|i| format!("#{:06x}", i * 9973)).collect(); + let refs: Vec<&str> = colors.iter().map(String::as_str).collect(); + let mut h = edit_harness(&refs); + let height = dialog_height(&h); + show_display(&mut h, "Show color bars"); + assert_eq!(dialog_height(&h), height, "40 bars keep the dialog's height"); + let first = h.get_by_role_and_label(egui::accesskit::Role::Button, "Color 1").rect(); + let wheel_bottom = first.top() + 251.0; + let last = |h: &egui_kittest::Harness<'_, VectorcraftApp>| h.get_by_role_and_label(egui::accesskit::Role::Button, "Color 40").rect(); + assert!(last(&h).top() > wheel_bottom, "the last bar starts out of view: {:?}", last(&h)); + h.input_mut().events.extend([ + Event::PointerMoved(first.center()), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -10000.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.run_steps(12); + let shown = last(&h); + assert!(shown.bottom() <= wheel_bottom + 1.0, "the last bar scrolls into view: {shown:?}"); + assert_eq!(dialog_height(&h), height); + h.input_mut().events.extend(press(shown.center(), 1)); + h.run_steps(3); + assert_eq!(field(h.state(), "__sel"), json!([39])); + let mut rows = field(h.state(), "rows"); + for r in rows.as_array_mut().unwrap() { + r["exclude"] = json!(true); + } + set(h.state_mut(), "rows", rows); + h.run_steps(4); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Button, "Color 1").is_none()); + let _ = h.get_by_label("No colors to recolor (preserved colors are left out)."); +} diff --git a/crates/ui-egui/src/tests/save.rs b/crates/ui-egui/src/tests/save.rs index 472f564ebe..ec8790f9f2 100644 --- a/crates/ui-egui/src/tests/save.rs +++ b/crates/ui-egui/src/tests/save.rs @@ -232,6 +232,8 @@ fn a_document_reopens_at_its_saved_view() { // Moving around afterwards isn't an edit. app.view_mut().unwrap().zoom = 0.5; assert!(!app.session.active().unwrap().is_dirty()); + // Reopened: an open file would only come to the front (#3455). + app.run("file.close", json!({})).unwrap(); io::open_path(&mut app, &path).unwrap(); let v = *app.view().unwrap(); assert_eq!((v.zoom, v.center, v.rotation, v.fitted), (3.0, Point::new(70.0, 40.0), 30.0, true)); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 1061d6c7fd..94054a0d46 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -235,7 +235,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, cols: usize, floating: Option egui::Shape { egui::Shape::mesh(mesh) } +/// Hue sectors and saturation rings of the [`segmented_wheel`]: patches 15° of hue by 20% +/// saturation wide, the sectors centered on red at 0°. +const WHEEL_SECTORS: u32 = 24; +const WHEEL_RINGS: u32 = 5; + +/// The color of the [`segmented_wheel`] patch that holds hue `h` (degrees) and saturation `s` (0 to +/// 1), at brightness `v`: the hue and saturation at the patch's center. +pub fn segment_color(h: f32, s: f32, v: f32) -> Color { + let step = 360.0 / WHEEL_SECTORS as f32; + let sector = (h.rem_euclid(360.0) / step).round() % WHEEL_SECTORS as f32; + let ring = (s.clamp(0.0, 1.0) * WHEEL_RINGS as f32).floor().min((WHEEL_RINGS - 1) as f32); + Color::from_hsb(sector * step, (ring + 0.5) / WHEEL_RINGS as f32, v) +} + +/// The segmented hue and saturation wheel at brightness `v`: a solid patch per hue sector and +/// saturation ring, in its [`segment_color`]. +fn segmented_wheel_shape(c: Pos2, r: f32, v: f32) -> egui::Shape { + // Points along each patch's arcs. + const ARC: u32 = 4; + let step = 360.0 / WHEEL_SECTORS as f32; + let mut mesh = egui::Mesh::default(); + for ring in 0..WHEEL_RINGS { + let (s0, s1) = (ring as f32 / WHEEL_RINGS as f32, (ring + 1) as f32 / WHEEL_RINGS as f32); + for k in 0..WHEEL_SECTORS { + let h = k as f32 * step; + let col = crate::panels::c32(&segment_color(h, (s0 + s1) / 2.0, v)); + let first = mesh.vertices.len() as u32; + for j in 0..=ARC { + let a = h - step / 2.0 + step * j as f32 / ARC as f32; + mesh.colored_vertex(wheel_pos(c, r, a, s0), col); + mesh.colored_vertex(wheel_pos(c, r, a, s1), col); + } + for j in 0..ARC { + let at = first + 2 * j; + mesh.add_triangle(at, at + 1, at + 3); + mesh.add_triangle(at, at + 3, at + 2); + } + } + } + egui::Shape::mesh(mesh) +} + /// What a [`harmony_wheel`] did this frame. #[derive(Default)] pub struct WheelResponse { @@ -501,6 +543,18 @@ pub struct WheelResponse { /// marker per colour joined to the centre (the selected colour, `base`, larger) and a Brightness /// slider for the selected colour below it. pub fn harmony_wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option) -> WheelResponse { + wheel(ui, id, size, colors, base, false) +} + +/// [`harmony_wheel`] drawn as solid patches (24 hues by 5 saturations, each in its +/// [`segment_color`]). The markers sit at their colors' own hue and +/// saturation, and a drag moves them as freely as on the smooth wheel. +pub fn segmented_wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option) -> WheelResponse { + wheel(ui, id, size, colors, base, true) +} + +/// [`harmony_wheel`], or with `segmented` [`segmented_wheel`]. +fn wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option, segmented: bool) -> WheelResponse { let t = Tokens::get(ui.ctx()); let mut out = WheelResponse::default(); let base_hsb = base.and_then(|b| colors.get(b)).map(Color::to_hsb); @@ -510,7 +564,7 @@ pub fn harmony_wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: O let (rect, resp) = ui.allocate_exact_size(vec2(size, size), Sense::click_and_drag()); let (c, r) = (rect.center(), size / 2.0 - 10.0); let painter = ui.painter_at(rect); - painter.add(wheel_shape(c, r, v.max(0.15))); + painter.add(if segmented { segmented_wheel_shape(c, r, v.max(0.15)) } else { wheel_shape(c, r, v.max(0.15)) }); painter.circle_stroke(c, r, Stroke::new(1.0, t.border)); let at = |col: &Color| { let [h, s, _] = col.to_hsb(); @@ -539,7 +593,8 @@ pub fn harmony_wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: O let h = (-dv.y).atan2(dv.x).to_degrees().rem_euclid(360.0); out.moved = Some((i, [Some(h), Some((dv.length() / r).clamp(0.0, 1.0)), None])); } - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Slider, ui.is_enabled(), tl!("Color wheel"))); + let name = if segmented { tl!("Segmented color wheel") } else { tl!("Color wheel") }; + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Slider, ui.is_enabled(), name)); }); ui.add_space(6.0); ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index 22ae68345f..a9b56e0914 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -135,6 +135,18 @@ pub(crate) fn combo_menu( width: f32, menu: impl FnOnce(craft_ui::combo::Menu<'_>) -> Option, ) -> Option { + combo_menu_field(ui, id, current, width, menu).1 +} + +/// [`combo_menu`], also returning the closed field's response (the font family field reads the +/// mouse wheel turned over it). +pub(crate) fn combo_menu_field( + ui: &mut Ui, + id: impl std::hash::Hash, + current: &str, + width: f32, + menu: impl FnOnce(craft_ui::combo::Menu<'_>) -> Option, +) -> (Response, Option) { let t = Tokens::get(ui.ctx()); let label = take_previous_label(ui); egui::Frame::NONE @@ -148,7 +160,8 @@ pub(crate) fn combo_menu( egui::Popup::open_id(ui.ctx(), egui::Popup::default_response_id(&resp)); ui.memory_mut(|m| m.stop_text_input()); } - menu(craft_ui::combo::Menu::new(ui, &resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)) + let shown = menu(craft_ui::combo::Menu::new(ui, &resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)); + (resp, shown) }) .inner } @@ -204,7 +217,7 @@ pub fn popover(resp: &Response, toggle: bool, content: impl FnOnce(&mut Ui) - let ctx = &resp.ctx; let id = resp.id.with("popover"); let frame = ctx.cumulative_frame_nr(); - let was_open = ctx.data(|d| d.get_temp::(id)).is_some_and(|f| f + 1 >= frame); + let was_open = popover_is_open(ctx, resp.id); let mut open = if toggle { !was_open } else { @@ -233,6 +246,12 @@ pub fn popover(resp: &Response, toggle: bool, content: impl FnOnce(&mut Ui) - inner } +/// Whether the popover for this anchor was open in the latest completed frame. +pub(crate) fn popover_is_open(ctx: &egui::Context, anchor: egui::Id) -> bool { + let frame = ctx.cumulative_frame_nr(); + ctx.data(|d| d.get_temp::(anchor.with("popover"))).is_some_and(|f| f + 1 >= frame) +} + /// Records where the bottom bars (status and hint bars) start this frame, so menus can stop above /// them (#2086). Without bars it is the bottom of the window. pub fn set_menu_floor(ctx: &egui::Context, y: f32) { diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index 9244c32bf6..91cd18eebc 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -59,14 +59,20 @@ pub fn num_field_within( bounds: RangeInclusive, ) -> Option { let label = take_previous_label(ui); - unit_field(ui, id, label, None, value, unit, width, false, bounds, &[]) + unit_field(ui, id, label, None, value, unit, width, false, bounds, &[], false) } /// [`num_field`] for a row whose visible label is not an adjacent label widget (a grid cell with /// its label painted separately): screen readers name the field `name` (already translated). pub fn num_field_named(ui: &mut Ui, id: impl std::hash::Hash, name: Option<&str>, value: Option, unit: Unit, width: f32) -> Option { let label = take_previous_label(ui); - unit_field(ui, id, label, name, value, unit, width, false, ANY, &[]) + unit_field(ui, id, label, name, value, unit, width, false, ANY, &[], false) +} + +/// The field returns valid typed distances immediately and preserves the text being edited. +pub fn num_field_live(ui: &mut Ui, id: impl std::hash::Hash, value: Option, unit: Unit, width: f32) -> Option { + let label = take_previous_label(ui); + unit_field(ui, id, label, None, value, unit, width, false, ANY, &[], true) } /// Any number: the bounds of a field that has none. @@ -93,6 +99,7 @@ fn unit_field( share_of_value: bool, bounds: RangeInclusive, stops: &[f64], + live: bool, ) -> Option { let id = id_with(ui.scope_id(), id); let shown = value.map(|v| unit.format(v)).unwrap_or_default(); @@ -129,7 +136,18 @@ fn unit_field( } } else { ui.data_mut(|d| d.insert_temp(id, buf.clone())); - stepped.or(scrubbed).map(|v| unit.to_pt(v)) + if let Some(v) = stepped.or(scrubbed) { + return Some(unit.to_pt(v)); + } + if live + && resp.changed() + && let Some(v) = read(&buf).filter(|v| v.is_finite()).map(|v| within(v, &bounds)).filter(|v| Some(*v) != value) + { + ui.data_mut(|d| d.insert_temp(id.with("shown"), unit.format(v))); + ui.ctx().request_repaint(); + return Some(v); + } + None } } @@ -312,7 +330,7 @@ pub fn size_field_named(ui: &mut Ui, id: impl std::hash::Hash, name: Option<&str } }); } - unit_field(ui, id, label, name, value, unit, width, true, ANY, &[]) + unit_field(ui, id, label, name, value, unit, width, true, ANY, &[], false) } /// [`plain_field`] for a number kept within `range` (the values of dialogs, preferences and panels @@ -346,7 +364,34 @@ pub fn range_field_named( let places = decimals.min(6) as i32; let value = value.into().map(|v| within(v, &range)); let label = take_previous_label(ui); - bounded_field(ui, id, label, name, value, suffix, decimals, width, &range, None, false).map(|v| within(round_to(v, places), &range)) + bounded_field(ui, id, label, name, value, suffix, decimals, width, &range, None, false, false).map(|v| within(round_to(v, places), &range)) +} + +/// The field returns valid typed values immediately within `range` and preserves incomplete input. +pub fn range_field_live( + ui: &mut Ui, + id: impl std::hash::Hash, + value: impl Into>, + range: RangeInclusive, + suffix: &str, + decimals: usize, + width: f32, +) -> Option { + let value = value.into().map(|v| within(v, &range)); + let label = take_previous_label(ui); + let field = id_with(ui.scope_id(), &id); + let result = bounded_field(ui, id, label, None, value, suffix, decimals, width, &range, None, false, true) + .map(|v| within(round_to(v, decimals.min(6) as i32), &range)); + if let Some(value) = result { + ui.data_mut(|d| d.insert_temp(field.with("shown"), field_text(value, suffix, decimals))); + } + result +} + +/// The field returns valid typed numbers immediately and preserves the text being edited. +pub fn plain_field_live(ui: &mut Ui, id: impl std::hash::Hash, value: f64, suffix: &str, decimals: usize, width: f32) -> Option { + let label = take_previous_label(ui); + bounded_field(ui, id, label, None, Some(value), suffix, decimals, width, &ANY, None, false, true) } /// [`range_field`] whose ↑/↓ and wheel take `step`'s steps instead of whole numbers (see @@ -366,7 +411,7 @@ pub fn range_field_stepped( let places = decimals.min(6) as i32; let value = value.into().map(|v| within(v, &range)); let label = take_previous_label(ui); - bounded_field(ui, id, label, None, value, suffix, decimals, width, &range, Some(step), false).map(|v| within(round_to(v, places), &range)) + bounded_field(ui, id, label, None, value, suffix, decimals, width, &range, Some(step), false, false).map(|v| within(round_to(v, places), &range)) } /// [`plain_field`] for a value the selected objects may not share: `None` shows a blank field. @@ -385,7 +430,7 @@ pub fn mixed_field_named( width: f32, ) -> Option { let label = take_previous_label(ui); - bounded_field(ui, id, label, name, value, suffix, decimals, width, &ANY, None, false) + bounded_field(ui, id, label, name, value, suffix, decimals, width, &ANY, None, false, false) } /// [`mixed_field`] whose ↑/↓, wheel and scrub stop at `bounds`; ↑/↓ and the wheel take `step`'s steps @@ -404,6 +449,7 @@ fn bounded_field( bounds: &RangeInclusive, step: Option f64>, parentheses: bool, + live: bool, ) -> Option { let armed = take_armed_focus(ui, &id); let id = id_with(ui.scope_id(), id); @@ -431,7 +477,18 @@ fn bounded_field( let decimals = decimals.min(6) as i32; let stepped = step_value(ui, &resp, &mut buf, bounds, (read, show), step, &[]).map(|v| round_to(v, decimals)); let scrubbed = scrub::field(ui, id, rect, &buf, value, decimals, bounds); - if commit && buf != shown { read(&buf) } else { stepped.or(scrubbed).filter(|&v| Some(v) != value) } + if commit && buf != shown { + read(&buf) + } else if let Some(v) = stepped.or(scrubbed).filter(|&v| Some(v) != value) { + Some(v) + } else if live && resp.changed() { + read(&buf).filter(|v| v.is_finite()).map(|v| within(v, bounds)).filter(|v| Some(*v) != value).inspect(|&v| { + ui.data_mut(|d| d.insert_temp(id.with("shown"), show(v))); + ui.ctx().request_repaint(); + }) + } else { + None + } } /// The text [`plain_field`] shows for `value`: at most `decimals` places, without trailing zeros, @@ -510,7 +567,7 @@ pub fn spin_field_stops_named( ) -> Option { let label = take_previous_label(ui); spin_generic(ui, label, value, None, None, None, width, step, min, presets, presets, &|v| unit.format(v), &mut |ui, fw, label| { - unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, presets) + unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, presets, false) }) .and_then(SpinPick::value) } @@ -567,7 +624,7 @@ pub fn spin_field_auto_named( ) -> Option { let label = take_previous_label(ui); spin_generic(ui, label, value, auto, None, None, width, step, min, presets, &[], &|v| unit.format(v), &mut |ui, fw, label| { - unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, &[]) + unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, &[], false) }) } @@ -606,7 +663,7 @@ pub fn spin_plain_named( let value = value.into(); let fmt = |v: f64| format!("{v}{suffix}"); spin_generic(ui, label, value, None, None, None, width, step, min, presets, &[], &fmt, &mut |ui, fw, label| { - bounded_field(ui, id, label, name, value, suffix, decimals, fw, &(min..=f64::INFINITY), None, false) + bounded_field(ui, id, label, name, value, suffix, decimals, fw, &(min..=f64::INFINITY), None, false, false) }) .and_then(SpinPick::value) } @@ -638,7 +695,7 @@ pub fn spin_kerning( presets, &[], &|v| format!("{v}"), - &mut |ui, fw, label| bounded_field(ui, id, label, None, value, "", 0, fw, &(-1000.0..=f64::INFINITY), None, parentheses), + &mut |ui, fw, label| bounded_field(ui, id, label, None, value, "", 0, fw, &(-1000.0..=f64::INFINITY), None, parentheses, false), ) } diff --git a/crates/ui-egui/tests/font_wheel.rs b/crates/ui-egui/tests/font_wheel.rs new file mode 100644 index 0000000000..9e658a97b9 --- /dev/null +++ b/crates/ui-egui/tests/font_wheel.rs @@ -0,0 +1,162 @@ +//! Wheel routing when a font field disappears before the next layout pass. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use egui::{Event, MouseWheelSource, MouseWheelUnit, Pos2, RawInput, Rect, Shape, TouchPhase, vec2}; +use serde_json::{Value, json}; +use vectorcraft_engine::Session; +use vectorcraft_ui_egui::VectorcraftApp; + +#[test] +fn hiding_control_between_passes_leaves_its_old_fields_wheel_available() { + assert!(control_wheel_available_after("window.control", json!({}))); +} + +#[test] +fn hiding_properties_preserves_the_visible_control_fields_wheel() { + assert!(!control_wheel_available_after("window.panel.close", json!({"panel": "properties"}))); +} + +#[test] +fn deselecting_type_leaves_the_missing_control_fields_wheel_available() { + assert!(control_wheel_available_after("select.set", json!({"ids": []}))); +} + +#[test] +fn a_queued_font_wheel_does_not_restyle_a_new_object_selection() { + assert_queued_wheel_discarded_after_target_change(false); +} + +#[test] +fn a_queued_font_wheel_does_not_restyle_a_new_character_range() { + assert_queued_wheel_discarded_after_target_change(true); +} + +fn assert_queued_wheel_discarded_after_target_change(range: bool) { + let (ctx, mut app) = selected_type_with_control(); + let first = app.session.active().unwrap().selection.objects.first().unwrap().0; + let second = app.run("text.create", json!({"x": 30, "y": 120, "text": "Other text", "font": "Inter"})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [first]})).unwrap(); + if range { + app.select_tool("type"); + app.session.set_tool_option("textSelection", &json!({"editing": first, "anchor": 0, "caret": 2})); + } + let mut texts = Vec::new(); + for _ in 0..8 { + texts = frame(&mut app, &ctx, vec![]); + } + let point = texts.iter().find(|(t, p)| t == "Inter" && p.y < 150.0).unwrap().1; + let mut raw = wheel_input(point); + app.raw_input_hook(&ctx, &mut raw); + assert!(!raw.events.iter().any(|e| matches!(e, Event::MouseWheel { .. })), "the original field captured its turn"); + if range { + app.session.set_tool_option("textSelection", &json!({"editing": first, "anchor": 2, "caret": 4})); + } else { + app.run("select.set", json!({"ids": [second]})).unwrap(); + } + let before = app.session.active().unwrap().history.undo.len(); + let mut out = ctx.run_ui(raw, |ui| app.ui(ui)); + out.textures_delta.clear(); + assert_eq!(app.session.active().unwrap().history.undo.len(), before, "the captured turn cannot restyle the new target"); +} + +#[test] +fn artboard_controls_leave_replaced_font_fields_wheel_available() { + let (ctx, mut app) = selected_type_with_control(); + let mut texts = Vec::new(); + for _ in 0..8 { + texts = frame(&mut app, &ctx, vec![]); + } + let fields: Vec<_> = texts.iter().filter(|(t, _)| t == "Inter").map(|(_, point)| *point).collect(); + assert_eq!(fields.len(), 2, "Control and Properties each show a font field"); + app.select_tool("artboard"); + for point in fields { + let mut raw = wheel_input(point); + app.raw_input_hook(&ctx, &mut raw); + assert!(raw.events.iter().any(|e| matches!(e, Event::MouseWheel { .. })), "the Artboard tool replaces this font field"); + } +} + +#[test] +fn the_control_character_popover_keeps_its_visible_font_wheel() { + let (ctx, mut app) = selected_type_with_control(); + app.run("window.panel.close", json!({"panel": "character"})).unwrap(); + let mut texts = Vec::new(); + for _ in 0..8 { + texts = frame(&mut app, &ctx, vec![]); + } + let link = texts.iter().find(|(t, p)| t == "Character:" && p.y < 100.0).unwrap().1; + let button = |pressed| Event::PointerButton { pos: link, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![Event::PointerMoved(link), button(true)]); + frame(&mut app, &ctx, vec![button(false)]); + for _ in 0..3 { + texts = frame(&mut app, &ctx, vec![]); + } + let point = texts + .iter() + .find(|(t, p)| t == "Inter" && p.y > link.y + 10.0 && p.y < link.y + 100.0 && (p.x - link.x).abs() < 100.0) + .expect("the Character popover shows its family field") + .1; + let mut raw = wheel_input(point); + app.raw_input_hook(&ctx, &mut raw); + assert!(!raw.events.iter().any(|e| matches!(e, Event::MouseWheel { .. })), "the visible popover keeps font wheel input"); + app.run("window.control", json!({})).unwrap(); + let mut raw = wheel_input(point); + app.raw_input_hook(&ctx, &mut raw); + assert!(raw.events.iter().any(|e| matches!(e, Event::MouseWheel { .. })), "hiding Control also hides its popover"); +} + +fn selected_type_with_control() -> (egui::Context, VectorcraftApp) { + let ctx = egui::Context::default(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 250})).unwrap(); + let text = app.run("text.create", json!({"x": 30, "y": 70, "text": "Control wheel", "font": "Inter"})).unwrap(); + app.run("select.set", json!({"ids": [text["id"]]})).unwrap(); + app.run("window.control", json!({})).unwrap(); + (ctx, app) +} + +fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec<(String, Pos2)> { + let mut raw = RawInput { events, screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), ..Default::default() }; + app.raw_input_hook(ctx, &mut raw); + let mut out = ctx.run_ui(raw, |ui| app.ui(ui)); + let texts = out + .shapes + .iter() + .filter_map(|s| match &s.shape { + Shape::Text(t) => Some((t.galley.text().to_string(), t.pos + vec2(4.0, 6.0))), + _ => None, + }) + .collect(); + out.textures_delta.clear(); + texts +} + +fn control_wheel_available_after(command: &str, params: Value) -> bool { + let (ctx, mut app) = selected_type_with_control(); + let mut texts = Vec::new(); + for _ in 0..8 { + texts = frame(&mut app, &ctx, vec![]); + } + let point = texts.iter().find(|(t, p)| t == "Inter" && p.y < 150.0).expect("the Control bar's family field is rendered").1; + app.run(command, params).unwrap(); + let mut raw = wheel_input(point); + app.raw_input_hook(&ctx, &mut raw); + raw.events.iter().any(|e| matches!(e, Event::MouseWheel { .. })) +} + +fn wheel_input(point: Pos2) -> RawInput { + RawInput { + events: vec![ + Event::PointerMoved(point), + Event::MouseWheel { + unit: MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: TouchPhase::Move, + modifiers: Default::default(), + source: MouseWheelSource::Unknown, + }, + ], + ..Default::default() + } +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 720bfeed37..cdb7471df1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -264,7 +264,10 @@ same sliders under the wheel, and its mode menu also has Global Adjust (`sliderM Brightness, Temperature and Luminosity sliders that set `globalAdjust` (`{saturation, brightness, temperature, luminosity}`, percent from -100 to 100, 0 by default). The dialog sends a non-zero `globalAdjust` as `recolor.apply`'s `globalAdjust` in every slider mode, so one slider changes every recolored color at once and the rows keep their new -colors; colors opened alone are saved as a group with the change. Setting +colors; colors opened alone are saved as a group with the change. `display` sets how the Edit tab shows the new +colors: `smooth` (the smooth wheel, also when unset; each opening starts there), `segmented` (a wheel of solid patches, +24 hues by 5 saturations, whose markers move as freely) or `bars` (a solid bar per recolored color in row order; a click +selects its row for the sliders and a drag moves the row without changing a color). Setting `colors`, a preserve flag or `limitTo` reduces the rows again (also on `ui.dialog.confirm`). The dialog previews `recolor.apply` on the canvas; confirm keeps it as one undo step (with a group, the group is rewritten in the same step; with no art selected only the group changes). In the Swatches panel, double-clicking a colour group's folder, @@ -665,6 +668,11 @@ one undo step. The Links panel (`window.panel {panel: "links"}`) shows `links.li `links.info`; `links.editOriginal` and `links.reveal` (Edit › Edit Original, Show in Folder) hand the linked file to the system and return `{path}`. Edit Original opens only a regular file whose extension is a format `document.open` reads, and answers a control request with an error unless the file is a placed document (which opens in a tab). +The preference `editOriginalSystemDefaults` (Preferences › File Handling › Use System Defaults for Edit Original, on +by default, #5236) opens the file in the system's default app for it; off, in the app that made it: a raster image in +PhotoCraft, looked for only where it installs (the Applications folders on macOS; on Windows the path its installer +registers under App Paths, then `ArtCraft\PhotoCraft` in the per-user and per-machine program folders, then the `PATH`; +the `PATH` elsewhere), and any other file, or a raster image without PhotoCraft installed, in the system's default app. Package: File → Package… (`ui.packageDialog`) opens the `package` dialog for a saved document (a document never saved gets a `confirm` dialog whose OK runs `file.saveAs`). Fields: `folder` (the location), `name` (the package folder), diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 450872215b..6f02703ca5 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -104,25 +104,16 @@ private editing data. VectorCraft: without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868. Graphs (`%_Gs` … `%_GS`) come in as their drawn art, as plain groups, paths and type, without their data or settings, with a note. without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868, with its paragraphs' letter - and word spacing (`TC`, `TW`), hanging punctuation (`Tq`) and hyphenation (`Th`). + and word spacing (`TC`, `TW`), hanging punctuation (`Tq`) and hyphenation (`Th`). Its patterns in + the version 7 form (a list of `@` and `&` layers, `_ &` for the tile's background) open as pattern swatches, + with a fill's offset, scale, rotation, reflection and shear applied before its matrix. - Estimate: **~65%** for real exchange with Illustrator users (open: ~75%; save: PDF-compatible, or legacy version 7 with layers and groups; not yet tested by users who hand files back). Closing the open-side issues: 10–20 h with users' files. ### Illustrator's private editing data -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow, Drop Shadow, Offset Path, Outline Object or Outline Stroke comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or a graphic after the text object of a legacy wraparound group (`*w` … `*W`), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow, Drop Shadow or Convert to Shape comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur, Bas Relief (its settings at their defaults) and Convert to Shape, and a style with others keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners or Scribble comes in as itself with them and their saved settings; one with more, other effects, an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke or Convert to Shape comes in as itself with them and their saved settings; one with more, other effects, an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its settings at their defaults) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. ## Format by format diff --git a/docs/gaps.md b/docs/gaps.md index 8a305fb7ee..8b707fd9f6 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,10 +1,19 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (G5: dynamic symbols, #4938; estimate 15–26 → 14–24 h) · **Target:** Adobe Illustrator 2026 (30.x; G12: Units › East Asian Type acts, with Q and Ha units; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence -**Feature evidence last updated:** 2026-10-22. +Creating a gradient from solid or empty paint uses the document's color model for its default stops, including drawing its vector with the Gradient tool. Explicit `keepModel: true` retains RGB defaults, and existing gradients keep their own colors. Scores and estimates are unchanged. + +The closed font-family fields in Character, Properties and Control now accept the +mouse wheel for selected text (#5253). Each effective notch applies one family and +adds one undo step; the list follows saved font filters, ignores search text, and +stops at its ends. These interaction details +are VectorCraft's choices. Scores and estimates are unchanged. + +**Feature evidence last updated:** 2026-11-02. +**Feature evidence last updated:** 2026-11-03. The shared assessment status line and revision history are current upstream; this dated section records the submission's feature evidence and revisions without rescoring upstream or claiming a new combined build or runtime measurement. @@ -19,6 +28,8 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | +| 2026-11-02 | minor | Font-family fields step selected text with the mouse wheel (#5253); no scored gap or estimate reassessed. | | 2026-10-24 | minor | G12: General › Corner Radius is the Rounded Rectangle tool's radius, a change while the tool is active reaches it, and the radius ↑/↓ set while drawing (or a Tool Options value) becomes the preference, within 0–1296 pt (#394, `crates/engine/src/tests/constrain_tools.rs`); no entry closed, estimate unchanged. | | 2026-10-22 | minor | Reconcile upstream documentation after review F-3; preserve every dated revision and the original scaleArt runtime evidence without repeating completed jobs. | | 2026-10-22 | minor | Reconcile upstream documentation after review F-2; preserve every dated revision and the original scaleArt runtime evidence without repeating completed jobs. | @@ -376,7 +387,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall own pixels until a document takes them in; estimate unchanged. - **Missing:** CJK vertical composition (mojikumi sets and dialog, kinsoku settings #633, manual tate-chu-yoko), Middle Eastern - features beyond bidi and digit types (Character Direction, kashidas, composers), spell check with an open dictionary, + features beyond bidi, digit types, Character Direction and Kashidas (Middle Eastern composers, a split caret), spell check with an open dictionary, Touch Type, Retype, Snap to Glyph; optional preservation of font sizes during group scaling (#1034 enhancement). Itemized in [type-parity.md](type-parity.md). - **Impact:** professional typography and Japanese/Chinese publishing. @@ -416,13 +427,16 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall the other Units preferences. The model stays in points; any length field reads `13q` or `13h` (`Ha`, `H`) with or without a space. Not done: no field shows in it (it waits for a source). Tests `east_asian_*` and `q_and_ha_*` in `crates/doc` and `crates/engine`. Estimate unchanged. -- **Audited (2026-10-30, #394):** every Preferences dialog option but the four below is read by shipped code, +- **Audited (2026-10-30, #394):** every Preferences dialog option but four is read by shipped code, by its field or its key; Highlight Alternate Glyphs (the canvas's render options), Real-time Drawing and Editing (tool previews wait for the commit), Show Tool Tips, Anti-aliased Artwork, Use Precise Cursors and Devices › - Enable Touch Workspace and Touch Gestures included. -- **Missing:** 4 Preferences options stored but not acted on (#394), each waiting on a subsystem of its own: - User Interface › Open Documents As Tabs (off would open documents in floating windows; one window per - document is G7), Hyphenation › Default Language (hyphenation is English-only, with no per-language + Enable Touch Workspace and Touch Gestures included. One of the four, Open Documents As Tabs, acts now (below); + the other three are listed under Missing. +- **Done:** User Interface › Open Documents As Tabs: with the box cleared, each document opened or created + afterwards opens in a floating window of its own (G7's Float in Window); documents already open stay where they + are. Estimate unchanged. +- **Missing:** 3 Preferences options stored but not acted on (#394), each waiting on a subsystem of its own: + Hyphenation › Default Language (hyphenation is English-only, with no per-language dictionaries), Plug-ins & Scratch Disks › Primary and Secondary (documents are kept in memory; nothing pages to disk), and Clipboard Handling › Legacy vector clipboard with its Preserve Paths / Preserve Appearance and Overprints choice (Illustrator's own clipboard flavour, which has no public specification). Also Properties @@ -529,7 +543,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall Export Type (Graphic or Movie Clip; default Movie Clip; `symbol.new` / `symbol.options` / Symbols panel; canvas placement unchanged; Animate / Flash handoff metadata); Symbol Options › Enable Guides for 9-Slice Scaling (four guides as fractions of the symbol size, `nineSlice` / `nineSliceGuides` on `symbol.new` / - `symbol.options`, stored per symbol; handoff metadata, not drawn on the canvas, #2342); Brush Options › Key + `symbol.options`, stored per symbol; handoff metadata, #2342; drawn dotted over the art in symbol editing + mode, where the Selection tool drags them); Brush Options › Key Color eyedropper for scatter, art and pattern brushes (Hue Shift colorization; samples canvas art); Select › Start Global Edit (#3521) on paths, compound paths and symbol instances: the objects of the same shape at any place and size, narrowed by Appearance, Size and the artboards to search, take an edit of any one of @@ -565,7 +580,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall dynamic instance, with the Fill/Stroke controls and Appearance panel then setting its change) and their `.ai` read and write; Global Edit of groups holding type or images, rotated copies as matches, Shift-click to leave a match out and highlighting matches before the start; - drawing the 9-slice guides on the canvas in symbol edit mode. + 9-slice guides outside the symbol's art (a dragged guide stops at the art's edge). - **Estimate:** 14–24 h. ## G3 3D and Materials @@ -591,7 +606,9 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done (#4135):** floating panels open in OS windows of their own on the desktop, so they can sit on another monitor; on the web and on Wayland they float inside the window. - **Done:** View › New View… and Edit Views… ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)): a document keeps up to 25 named views (zoom, centre and rotation), saved with the file; every one is listed by name at the bottom of the View menu (`view.goto1`–`view.goto25`), and choosing one changes the current window to it. Edit Views… lists them to rename or delete, applied together on OK as one undo step (`view.saved.edit {edits}`); a file's views are checked when it opens. Estimate unchanged. - **Done:** Window › Arrange › Tile (`window.arrange.tile`) shows every open document in its own pane, edge to edge in the document area, and Consolidate All Windows (`window.arrange.consolidateAllWindows`) goes back to one document under its tab, on the desktop and the web. Estimate unchanged. -- **Missing:** multiple windows and the rest of Window › Arrange (Cascade, Float in Window, Float All in Windows). +- **Done:** Window › Arrange › Float in Window (`window.arrange.floatInWindow`), Float All in Windows (`window.arrange.floatAllInWindows`) and Cascade (`window.arrange.cascade`) move documents out of the tab strip into floating windows of their own, OS windows on the desktop and windows inside the app's window on the web and on Wayland; Cascade stacks them from the upper left to the lower right. Consolidate All Windows brings them back under the tabs. Estimate unchanged. +- **Done:** a document tab dragged off the tab strip floats its document in a window under the pointer, and a document window dragged by its title bar (an OS window by the tab at its top) onto the tab strip goes back under the tabs. Estimate unchanged. +- **Missing:** several windows of one document (Window › New Window). - **Estimate:** 15–25 h. ## G6 Automation and scripting @@ -605,6 +622,18 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall ## G15 Performance budgets and a GPU renderer +- **Improved (2026-11-02):** the renderer keeps a compound path's assembled path with the node, as it keeps a plain + path's, instead of assembling its members again in every frame; the path is assembled into a buffer sized up front. + Unused geometry entries are dropped after a few frames however few there are (before, only past 1,024 entries), so + the copies a drag makes in every frame no longer stay alive with all their members + (`crates/render/src/tests/memory.rs`, `crates/doc/src/node/tests.rs`). Not timed; `vectorcraft-cli perf` not rerun. +- **Improved (2026-11-02):** a click or hover culls paths and compound paths by the box of their control points + (grown by their strokes' reach) instead of measuring along their curves, and tests a compound path's outline and + fill against only the members whose control box, grown by the tolerance, holds the point; painted strokes are + still measured along the whole compound path. The same objects are hit (`crates/doc/src/hit/tests.rs`: a + 2,000-member compound path against the whole-path test for both fill rules, Outline view and Object Selection by + Path Only; wide strokes past the control points). A 20,000-member compound path went from about 18 ms to about + 1 ms a click in a debug test build (one run, not idle); `vectorcraft-cli perf` not rerun. - **Improved (#1257):** Craquelure, Mosaic Tiles and Stained Glass reuse squared distances during nearest-cell searches, with the original distance ordering retained near rounding/tie boundaries. A brute-force boundary regression and full-viewport pixel comparisons agree with the old result. `texture_drag_perf` reproduces a moved CMYK rounded rectangle at 190.07% and DPI 1.5; timings from a busy development machine are supporting evidence, with idle Windows drag QA still pending. - **Missing:** an idle-machine run of `vectorcraft-cli perf` at 50k paths (2026-10-11 at 25k paths, every budget met, 400% zoom 12.3 ms against 16 ms, measured; runs of 0.10.0 on Linux with 4 logical CPUs, reported in #1172 @@ -703,6 +732,9 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | G15: the renderer keeps a compound path's assembled path between frames and drops unused geometry entries after a few frames however few there are. Estimate unchanged. | +| 2026-11-02 | minor | G15: hit testing culls paths and compound paths by their control points' box and tests a compound path's outline and fill against only its members near the click; the same objects are hit. Estimate unchanged. | +| 2026-11-03 | minor | Symbol editing shows draggable 9-slice guides within the artwork (#5280). Guides outside the artwork remain unsupported. The G5 estimate remains 14–24 h. | | 2026-10-31 | minor | G12: Units › East Asian Type acts (#394): Q and Ha (a quarter of a millimetre each) are units that preference offers; 4 Preferences options remain stored but not acted on. Estimate unchanged. | | 2026-11-01 | minor | G5: dynamic symbols (#4938): Symbol Options › Symbol Type, per-instance fill, stroke, opacity and blend for objects of a dynamic symbol's art that stay linked (redefining keeps them, Break Link bakes them, Reset and Static drop them; `symbol.instance.setAppearance`, `symbol.instance.reset`; `crates/engine/src/tests/dynamic_symbols.rs`); on-canvas Direct Selection of the parts and `.ai` round trip remain. Estimate 15–26 → 14–24 h. | | 2026-11-01 | minor | G13: Artboard background colors in output (#4937): raster exports (a transparent background too), PDF, SVG and EPS pages, `.ai` files' PDF pages, Export for Screens and print (and its preview) draw each artboard's color behind its art, inside the artboard and in the color's own model; Export for Screens has Include Artboard Fill beside Include Bleed (on by default, remembered; `includeArtboardFill`, also on `document.export` and `file.print`); editing data keeps the color as the artboard's, and Export for Screens' document rows keep it too; estimate unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index 07fbd7b556..0ca4e32353 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -428,7 +428,7 @@ objects' fills or strokes differ (`fillMixed` / `strokeMixed`, drawn as a "?" pr | `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. | | `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. | | `open_file` | `{path}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a Photoshop file as its merged image). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). `run_command document.formats` lists the formats. | -| `save_file` | `{path?, compress?, version?, preview?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), and `preview: true` embeds a PNG of the first artboard. `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version` or `preview` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a `.ai` file reads `compress` but not `version` or `preview`). `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warning for a top-level `compress`, `version` or `preview`. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. | +| `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a `.ai` file reads `compress` but not `version`, `preview` or `precision`). `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warning for a top-level `compress`, `version`, `preview` or `precision`. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. | | `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF and WMF write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | | `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`); `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | | `apply_effect` | `{effect?, params?, ids?}` | Appends a live effect. Without `effect`, returns the effect catalogue with parameters and defaults. | @@ -548,7 +548,7 @@ Brushes of different types, or a `type` other than theirs, are refused with "bru Document colour mode: `file.new {colorMode: "cmyk"}` starts a CMYK document with CMYK default swatches, and RGB colors applied to it (`paint.setFill`/`setStroke` colors, gradient stops and freeform points, `paint.editGradient` stops, `paint.freeform.addPoint`/`setPoint`, `paint.sampleColor`, `object.mesh.setPointColor`/`addLine`, the -`text.create` and `text.createInPath` color, the `text.setStyle` fill, `text.setRangeStyle` fills and strokes, a +`text.create` and `text.createInPath` color, `text.setStyle` and `text.setRangeStyle` fills and strokes, a `shapeBuilder.merge` hex fill (its `fill: {color, keepModel: true}` form keeps RGB), the `symbol.adjust` stain color, `swatch.new {color}` and `{colors}`, `swatch.newGroup`, `swatch.editGroup` and `swatch.edit`) are stored as CMYK, converted through the color settings (`edit.colorSettings`: the CMYK @@ -643,7 +643,14 @@ can't be read becomes a placeholder in its box, named in `warnings` and `missing Native files: `run_command document.save {compress: true}` writes a gzip-compressed `.vectorcraft` (the `useCompression` preference makes that the default for saves; compressed files open like any other, told apart by their content). `version: 2` or `1` writes a file older VectorCraft versions open (format name `drawcraft`, never -compressed), and `preview: true` embeds a PNG of the first artboard, at most 256 px on its longer side. A save writes +compressed), and `preview: true` embeds a PNG of the first artboard, at most 256 px on its longer side. +`precision: 4` (0 to 9) rounds the anchors and handles of paths to that many decimal places (in the layers, symbols, +graph designs, patterns, opacity masks and brushes); colors, transforms, opacity and type are written exactly. +Each coordinate goes to the nearest step of its stored binary value, and a value exactly halfway rounds away from +zero (`0.125` at 2 places is `0.13`); `1.005` is stored as slightly less than that and is written as `1.0`. Each anchor is rounded on +its own, so a closed path stays closed and a shape smaller than one step keeps its anchors on one point. Opening the +file and saving it again does not bring back the dropped digits. The embedded preview and the PDF that `pdfCompatible: true` adds show the rounded paths. Without `precision` a save writes the coordinates exactly, and Save does not remember it. A `.ai` file ignores +`precision`. A save writes a temporary file and renames it over the old one, so a failed save never damages the file; only the images the document uses are written, and document keys written by a newer version are kept. An uncompressed file is indented JSON when the document has at most 2,000 layers and objects and the indented @@ -1431,6 +1438,13 @@ everything in it, and `select.all`, `select.allOnArtboard` and `select.inverse` among the objects beside it in its group or layer, passing over hidden and locked objects and sublayers. When there is no such object, the selection stays as it is. +`select.same.textFillAndStrokeColor` (Select › Same › Text Fill & Stroke Color) selects the type objects that have +characters whose fill and stroke both match the first character of the first selected type, and returns `{count}`. +`select.same.textFillColor` and `select.same.textStrokeColor` compare the fill or the stroke alone. In type with +several runs, one run has to match both: type with the fill in one run and the stroke in another is left out. The fill +and stroke of other objects are not compared. Without type among the selected objects it returns the error "select a +text object", and it records no undo step. + ## Shaper Groups `shaper.releaseSource {source, group?}` takes the original shape `source` out of its Shaper Group: the shape becomes a @@ -1484,6 +1498,14 @@ Redo, a cancelled drag or scrub), the matches it no longer has leave the Global are left. An edit that would take any match past the canvas fails with the coordinates-out-of-range error and changes nothing. Nothing of it is saved. +`select.globalEditExclude {id}` leaves the match `id` out of the Global Edit, as a Shift-click on a highlighted match +(or on an object inside it) with the Selection tool does: it is no longer highlighted, and later edits leave it as it +is. It returns `{active, count, ids}`, the objects left in the Global Edit; with fewer than two left, the Global Edit +ends (`{active: false, count: 0, ids: []}`). The object the Global Edit started from can't be left out, and neither +can an object that is not a match. It is not an undo step. A Shift-drag that starts on a match selects it and moves +it with the selection, and leaves it in the Global Edit. Source: [Update assets quickly with Global +Edit](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html). + ## Saved selections Select → Save Selection… keeps the selected objects under a name, in the document: `select.save {name?}` (default @@ -1570,7 +1592,8 @@ already walks Image Trace. Short agent entry points: `symbol.options {name?, newName?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?}` (`nineSlice` bool turns 9-slice guides on or off; `nineSliceGuides` is `[left, top, right, bottom]`, fractions 0..1 of the symbol size, a quarter each when none are given; rows of `symbol.list` carry `nineSlice`: the guides or `null`; a scaled instance of - a symbol with guides keeps its corners at their size, and `symbol.breakLink` gives its art as it draws; `type` is + a symbol with guides keeps its corners at their size, and `symbol.breakLink` gives its art as it draws; dragging a + guide on the canvas in symbol editing mode sends `nineSliceGuides` in one undo step; `type` is Symbol Type, `static` by default for the command and `dynamic` by default in the Symbol Options dialog), `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}`, `symbol.replace`, `symbol.edit {id?, ids?, name?, x?, y?, artboard?, viewCenter?}` (symbol editing mode: the symbol's art on a temporary @@ -1661,10 +1684,13 @@ already walks Image Trace. Short agent entry points: renames the row, in the same undo step; Edit Data Set's Name field sends it), `dataset.rename`, `dataset.delete`, `dataset.capture`, `dataset.update`, `dataset.select {name}`, `dataset.next` / `dataset.prev` (each `dataset.select` / next / prev is one undo step over every bound object), `dataset.import {path|data|dataBase64|csv}` / - `dataset.export {path?}` (CSV: `name`, then one column per variable). `dataset.import` also reads tab-separated - files, and files whose first header cell isn't `name`: every header cell is then a variable, and the rows take the - first free names `Data Set 1`, `Data Set 2` and so on. An import error about a row's values or name gives the file - line the row starts on. A header cell that names no variable defines one, unbound, in the same undo step as the + `dataset.export {path?}` (CSV: one column per variable, and no column of data set names). `dataset.import` also + reads tab-separated files. Every header cell is a variable, whatever its case (`name` and `Name` included), as the + [set-up page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/set-up-data-source-files.html) + describes the first row: "Specify your data field name in the first row of your spreadsheet." The rows replace every + data set 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, and the reply's `deletedDataSets` lists the data sets that were replaced. An import error + about a row's values gives the file line the row starts on. A header cell that names no variable defines one, unbound, in the same undo step as the rows. `#Shown` defines a visibility variable `Shown`, `@Photo` defines an image variable `Photo`, and a cell without a prefix defines a text variable. `dataset.export` writes a visibility variable's header as `#Shown` and an image variable's as `@Photo`, and a text or graph variable's as its name alone. Its reply's `warning` names the variables @@ -1731,9 +1757,32 @@ already walks Image Trace. Short agent entry points: refused, and no set is added. The Actions panel menu's Save Actions… and Load Actions… run these; Load Actions… is disabled where there is no open dialog (the web). - Actions: `ui.action.rename {set, action, name}` renames the Actions panel's action at `action` in set `set` (0 is - the top set) to `name` with spaces trimmed from both ends, keeps its steps, and returns `{name}`. An index past the - last set or action, or an empty name, is an error, and then nothing is renamed. The panel menu's Action Options… - runs this for the selected action. + the top set) to `name` with spaces trimmed from both ends, keeps its steps, function key and color, and returns + `{name}`. An index past the last set or action, or an empty name, is an error, and then nothing is renamed. +- Actions: `ui.action.new {set, name, key?, cmd?, shift?, color?}` adds an action named `name` (spaces + trimmed) after the last action of set `set` (0 is the top set), starts recording into it and returns + `{set, action}`; Stop Playing/Recording (`ui.action.stop`) ends the recording. `key` 1 to 15 is the function key F1 to F15 that plays the + action (0 or null for none), with `cmd` (Ctrl, Command on macOS) and `shift`. `color` is its Button Mode color + (`red`, `yellow`, `green`, `blue` or `violet`; null or `""` for none), which the panel does not show. Action function + keys take priority over command shortcuts and preserve the command's binding. On Windows F1, Ctrl+F4 and Ctrl+F6 + cannot be used. While an action is recording, and for an index past the last set, + an empty name, or a key or color that is not one of these, it is an error and nothing is added. The panel's Create + New Action button and menu's New Action… open the `actionNew` dialog, whose Record runs this. +- Actions: `ui.action.options {set, action, name?, key?, cmd?, shift?, color?}` changes the action at + `action` in set `set` and keeps its steps: `name` renames it, `key` with `cmd` and `shift` sets its function key, + and `color` its Button Mode color, as `ui.action.new` takes them; a param left out keeps what the action has, and + `cmd` or `shift` alone changes that modifier of its key. It + returns `{name, key, color}`. The panel menu's Action Options… runs this for the selected action. A function key + plays its action from the keyboard; like command shortcuts, it does nothing while a dialog, the command palette or + a text field has the keyboard, or while a tool is busy. Editing command shortcuts (`shortcuts.set`, Keyboard Shortcuts), loading preferences and + `ui.actionSet.load` preserve action function keys. When several actions have the same key, the first in panel order + plays. A stored key reserved on the current platform does not play an action. +- Actions: `ui.action.play {action, set?}` plays the action named `action` as one undoable batch; `set` names the set + to look in (default: every set), and a `set` that is not a string is an error. A name that no action has, or that + more than one action in the sets looked in has, is an error, and then nothing plays. +- Actions: `ui.action.stop {}` ends the recording in progress and keeps its steps, in the action `ui.action.new` made + for it, else in a new action after the last action of its set, and returns `{stopped}`. With nothing recording it + changes nothing. The panel's Stop Playing/Recording button runs this. - Action sets: `ui.actionSet.delete {sets?: [index], ids?: [id]}` deletes the Actions panel's sets at these indexes (0 is the top set) with their actions, by default the current set, and returns `{deleted}`. An index past the last set is an error, and then no set is deleted. `ids` holds the panel's own set ids, which its question passes: the @@ -1890,6 +1939,10 @@ act on several fills/strokes at once, and `appearance.showAllHidden` makes every visible again. In remote mode, `effect.dialog {effect, index, item}` opens an applied effect's dialog prefilled (`ui.dialog.confirm` runs `effect.setParams`); see the control protocol for the "already applied" question. +Effect dialogs use the targeted object, group, or layer shown in Appearance. The Transform dialog previews valid +numbers as they are typed, including Copies, distances with units, and rotation. With Preview off, changes apply +on OK. Cancel restores the original artwork. + ## Overprint Each fill and stroke (and each character's fill and stroke) can overprint: its inks print over the inks below instead @@ -2335,7 +2388,11 @@ dash options go to every run (the object keeps no stroke of its own); an `item` with `appearance.addStroke`, which takes every stroke option (dashes, profile, opacity, blend) like a path's and paints under or over the characters as its place relative to the Characters row says. To stroke some characters, use `text.setRangeStyle {id, start, end, strokeOptions: {weight?, cap?, join?, miterLimit?, align?, -dash?, dashOffset?, alignDashes?}}`. `align: "inside"|"outside"` keeps the characters' stroke on that side of the +dash?, dashOffset?, alignDashes?}}`. `text.setStyle {ids?, stroke?, strokeWidth?, start?, end?}` sets the stroke color +and weight of the characters of each object given (without `start` and `end`: all of its text), with its other keys in +one undo step; `strokeWidth` is in document points, as `stroke.set` gives the weight of scaled type. A `stroke` color +without `strokeWidth` gives characters that have no stroke weight 1 pt, as `paint.setStroke` does. +`align: "inside"|"outside"` keeps the characters' stroke on that side of the glyph outlines, drawn at twice the weight and clipped, while the type stays editable (beyond Illustrator); SVG export writes the text live and that stroke as glyph outlines over it. `inspect_document` reports each object's stroke as `strokeOptions` (type: its first run's) in `stroke.set` terms. `stroke.set` on a group leaves the images and symbol instances in it alone. @@ -3611,11 +3668,30 @@ document. With no document open they fail with "no document open". `document.act the current one. `window.arrange.tile` (Window › Arrange › Tile) shows every open document in its own pane, edge to edge in the document area, in a grid of as many columns as the square root of the number of documents, rounded up, and fits each document to +its pane; with fewer than two documents open it leaves the view and `tiled` as they are. It returns `{tiled, panes}`. +The current document's pane is the canvas, and a press in another pane makes its document the current one. +`window.arrange.consolidateAllWindows` (Window › Arrange › Consolidate All Windows) shows one document under its tab +again and returns `{tiled: false}`. The arrangement is not saved. `ui.inspect` reports `tiled` and `panes` (each pane's +`document` index, `rect` and whether it is `active`); canvas coordinates map to the current document's pane +(`canvasRect`). its pane; it returns `{tiled, panes}`. The current document's pane is the canvas, and a press in another pane makes its -document the current one. `window.arrange.consolidateAllWindows` (Window › Arrange › Consolidate All Windows) shows one -document under its tab again and returns `{tiled: false}`. The arrangement is not saved. `ui.inspect` reports `tiled` -and `panes` (each pane's `document` index, `rect` and whether it is `active`); canvas coordinates map to the current -document's pane (`canvasRect`). +document the current one. `window.arrange.floatInWindow` (Window › Arrange › Float in Window) moves the current document +out of the tab strip into a floating window of its own, `window.arrange.floatAllInWindows` (Float All in Windows) does +so for every tabbed document, and `window.arrange.cascade` (Cascade) floats every document and stacks the windows 30 pt +apart from the upper left of the document area; each returns `{floating}`, the floating documents' indices. On the +desktop each window is an OS window; on the web, on Wayland and while the control channel is attached (`--control`), +it is a window inside the app's window, so `ui.click`, `ui.drag` and `ui.screenshot` reach it. The current +document's window holds the canvas, and a press in another document's window makes its document the current one. +`window.arrange.consolidateAllWindows` (Window › Arrange › Consolidate All Windows) shows one document under its tab +again, floating ones included, and returns `{tiled: false, floating: []}`; Tile brings floating documents back into its +grid. `window.arrange.floatInWindow {index, at: [x, y]}` floats document `index`, makes it the current one and puts its +window's top-left corner at `at` in the main window's points, as dragging its tab more than 24 pt above or below the tab +strip does. `window.arrange.consolidateAllWindows {index}` brings only document `index` back under its tab and makes it +the current one, as dragging its window by the title bar (an OS window by the tab at its top) onto the tab strip does; +it returns `{tiled, floating}`. An `index` that names no open document fails with "no such document". The arrangement +is not saved. `ui.inspect` reports `tiled`, `panes` (each pane's `document` index, `rect` and +whether it is `active`) and `floating`; canvas coordinates map to the current document's pane or window +(`canvasRect`), in that window's coordinates while it floats. ```json {"name":"run_command","arguments":{"command":"file.new","params":{"preset":"A4","orientation":"landscape","artboards":4,"artboardLayout":{"columns":2},"bleed":9}}} @@ -4167,7 +4243,9 @@ file is missing stays linked: relink it first); `links.unembed {id, path}` write clip?}` decides how a relinked or updated file takes an image's place (default `bounds`: stretched into the old bounds; `clip` puts it in a clip group of the old bounds when it is larger). The UI commands `links.editOriginal` and `links.reveal` open the linked file in its app or show it in its folder (desktop). Edit Original runs only from the app's window, -except for a placed document, which opens in a tab. +except for a placed document, which opens in a tab. With the preference `editOriginalSystemDefaults` (Preferences › +File Handling › Use System Defaults for Edit Original, on by default) off, Edit Original opens a raster image in the app +that made it, PhotoCraft, where it is installed, and anything else in the system's default app (#5236). ```json {"name":"run_command","arguments":{"command":"links.list","params":{"show":"missing"}}} @@ -5446,19 +5524,39 @@ attribute map in one undo step. `to` is trimmed and must be unique. The command while preserving local overrides; Undo/Redo restores the definition and its users. The `charStyleOptions` dialog exposes `name`, `font_family`, `font_style`, `size`, `leading`, `kerning`, `tracking`, `case`, `position`, `underline`, `strikethrough`, `charAlign`, `h_scale`, `v_scale`, `baseline_shift`, `rotation`, -`language`, `section` (`general`, `basic` or `advanced`), and `preview`. An empty field leaves its +`language`, `fill`, `fill_tint`, `stroke`, `stroke_tint`, `stroke_width`, `overprint_fill`, `overprint_stroke`, +`ot_figure`, `ot_position`, `ot_liga`, `ot_calt`, `ot_dlig`, `ot_swsh`, `ot_salt`, `ot_titl`, `ot_ordn`, `ot_frac`, +`ot_sets`, `section` (`general`, `basic`, `advanced`, `color` or `opentype`), and `preview`. An empty field leaves its attribute unset. `leading` and `kerning` also accept `Auto` to store an explicit automatic value. Advanced Character Formats holds `h_scale` and `v_scale` (percent, above 0 and at most 4000000), `baseline_shift` (points, -4000000 to 4000000), `rotation` (degrees, stored from -180 to 180) and `language` (a name or tag from Document Setup's languages; English: USA stores the explicit default `null`, and a tag not in the list that the style already has is kept). Language sets the language the characters are shaped in; it does not change hyphenation or spelling. +Character Color holds `fill` and `stroke` (a paint: `{"type": "none"}` or a solid color; the menu lists None and +the document's solid swatches, a global swatch or a tint of one as a paint linked to it), `fill_tint` and +`stroke_tint` (percent, 0 to 100, for a paint linked to a global swatch), `stroke_width` (points, 0 to 4000000) +and the `overprint_fill` and `overprint_stroke` checkboxes. A gradient or pattern paint the style already has is +kept until another paint is chosen. A paint linked to a global swatch takes the swatch's color at its tint, and +editing the swatch later updates the style and its text. `swatch.unused` counts a swatch a character style's fill or +stroke links to as used, whether or not text uses the style. +OpenType Features holds `ot_figure` (`default`, `tabularLining`, `proportionalLining`, `proportionalOldstyle` or +`tabularOldstyle`), `ot_position` (`default`, `superscript`, `subscript`, `numerator` or `denominator`), the on, +off or unset checkboxes `ot_liga`, `ot_calt`, `ot_dlig`, `ot_swsh`, `ot_salt`, `ot_titl`, `ot_ordn` and `ot_frac`, +and `ot_sets` (a list of stylistic sets `ss01` to `ss20`, each on, or off with a leading `-`, as in +`["ss02", "-ss05"]`; a set not listed is unset). They write the style's `features` list: a changed control +replaces only its own tags, so tags the dialog does not show stay, and Default Figure or Default Position stores +its features turned off, distinct from unset. +`charStyle.new`, `charStyle.setAttrs` and `charStyle.edit` reject a tint outside 0 to 1, a link to a swatch that is +not a global swatch of the document, a stroke weight outside 0 to 4000000, more than 256 feature tags and an +OpenType feature tag the shaper does not know, unless the style or the text it is made from already has that value. The New Character Style dialog accepts the same character fields and starts with the selected text's captured attributes. Without selected text, it starts with the character defaults for the interface language (including `charAlign: "emBoxCenter"` in Japanese); changing a Basic field keeps other seeded attributes. Without selected text, the New Paragraph Style dialog sends no `attrs`, and the engine gives the new style the paragraph defaults for the interface language. Reset Panel in Basic Character -Formats removes those fields from the definition, and Reset Panel in Advanced Character Formats removes its five. +Formats removes those fields from the definition, Reset Panel in Advanced Character Formats removes its five, Reset +Panel in Character Color removes its five attributes and Reset Panel in OpenType Features removes `features`. `ui.charStyleOptions.resetPanel {}` performs that reset for the section selected in either character-style dialog; it is disabled on General. @@ -5989,12 +6087,22 @@ attaches nothing. The group stays live: after every edit its objects go back on its path. Editing the path moves them, an object moved on its own goes back to its place, an object moved into the group (`layer.move` with `place: "inside"`) joins the end of the path, an object moved out of it leaves, and art that replaces an object (`symbol.breakLink`) keeps its place. -`object.objectsOnPath.options {ids?, pivot?, rotate?}` changes Pivot and Rotate, and +`object.objectsOnPath.options {ids?, pivot?, rotate?, spacing?, start?}` changes Pivot, Rotate and Space, and `object.objectsOnPath.expand {ids?}` makes the groups plain groups. Both act on the groups that `ids` names (Objects on Path groups or objects in them), or on the groups of the selection when `ids` is not given. The native file keeps the group with an `objects_on_path` record; SVG, PDF and the other exports write the path and the objects as plain art. +Space sets the distance along the path between neighboring objects' attachment points. `spacing` takes points, 0 or +more, or `"auto"`, the default, which spreads the objects evenly with the last one at the end of an open path. `start` +is the distance in points along the path from its first anchor to the first object's attachment point (default 0). A +`spacing` larger than the path has room for is drawn smaller: on an open path the last object stops at the end, and on +a closed path the objects go no more than once around. The value is kept, so lengthening the path again brings the +objects back to it. On a closed path, `start` counts around from the first anchor. Pivot, Rotate, moving the group and +saving the file keep the Space. Scaling, rotating or shearing the group keeps the first and last objects where the +transform takes them on the new path, and sets `spacing` and `start` to match; a value that cannot be kept that way +scales as much as the path's length. + In the desktop app, double-clicking the Objects on Path tool (`tool.options {tool: "objectsOnPath"}`) opens Objects on Path Tool Options (dialog `objectsOnPathOptions`): the nine-point Pivot grid and the Rotate field (°). Save sets the tool's options (`tool.setOption {tool: "objectsOnPath", values: {pivot, rotate}}`), which the objects attached next @@ -6009,10 +6117,20 @@ counter-clockwise on the page: the drag previews `object.objectsOnPath.options { group's Rotate plus that angle and keeps it as one undo step on release. Shift turns in steps of 15°, and Escape cancels the drag. +With two or more objects in the group, the same tools show the Space widget, a square handle beyond the group's last +object, ahead along the path and joined by a line to its attachment point. Dragging it moves the last object along the +path as far as the pointer moves along the path, and previews +`object.objectsOnPath.options {ids: [group], spacing, start}` and keeps it as one undo step on release. The first +object stays where it is and the others move toward or away from it; on an open path the last object goes no further +than the end. With Alt (Option on macOS) held, the objects spread from both ends toward or away from the center of an +open path, or of the first anchor of a closed path, up to the whole path. With measurement labels on, the distance +between the objects shows next to the pointer in the document's units. Escape cancels the drag. + ```json {"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"objectsOnPath","values":{"pivot":7,"rotate":30}}}} {"name":"run_command","arguments":{"command":"object.objectsOnPath.attach","params":{"path":30,"ids":[12,15,18]}}} {"name":"run_command","arguments":{"command":"object.objectsOnPath.options","params":{"pivot":7,"rotate":15}}} +{"name":"run_command","arguments":{"command":"object.objectsOnPath.options","params":{"spacing":24,"start":0}}} {"name":"run_command","arguments":{"command":"object.objectsOnPath.expand","params":{}}} ``` @@ -6059,7 +6177,8 @@ Envelope Options. The Mesh tool and Direct Selection pick mesh points on gradient meshes and mesh envelopes. A click picks one point (its handles show); Shift-click adds a point or takes a picked one away. Direct Selection's marquee picks the points -inside it (Shift toggles them) and selects their meshes; its click on a gradient mesh's line picks the line's two +inside it (Shift toggles them) and selects their meshes, as does a Lasso loop round them (Shift adds, Alt takes +away); its click on a gradient mesh's line picks the line's two ends, and a click inside a patch picks the four points around it. The picked points show filled. Dragging one of them moves them all as one undo step (`object.mesh.movePoints`), a click on one of several picked points picks it alone, and the arrow keys nudge them by the keyboard increment. The active tool lists them in its options @@ -6686,3 +6805,30 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la ```json {"name":"run_command","arguments":{"command":"addon.document.symbolsFromLayers","params":{"replace":true}}} ``` + +## Type Tools add-on + +Type Tools is a built-in add-on for type: its command is `addon.type.textTweaker`, and in the desktop app it lives in +Object › Plug-ins › Type Tools (#4924). Text Tweaker gives one character attribute to the characters letter by letter, +from a start value to an end value along a shape, as one undo step; the text stays live and editable. Each value is set +as `text.setRangeStyle` sets it (the Character panel), in its units and ranges, so on scaled type it is the size shown. +It changes the range of `id` (`start`/`end` bytes), else all the text of the type objects in `ids`, else the text the +Type tool has selected (at a caret: all of that object's text), else all the text of every selected type object; each +object gets its own ramp, and at most 100000 characters change in one run. A run that changes nothing makes no step. + +| Parameter | Values (default) | +|---|---| +| `attribute` | `size` (pt 0.1…1296), `baselineShift` (pt −1296…1296), `rotation` (° −360…360), `hScale`, `vScale` (% 1…10000), `tracking` (1/1000 em −1000…10000), `leading` (pt 0.1…5000), `strokeWidth` (pt 0…1000; shows only on characters with a stroke) (`size`) | +| `from`, `to` | the first and last character's values, in the attribute's units and range (size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2) | +| `shape` | `straight` (an even ramp), `ease` (slow at both ends), `bow` (`from` at both ends, rising smoothly to `to` in the middle), `spike` (the same, in straight lines), `random` (each character anywhere from `from` to `to`) (`straight`) | +| `seed` | whole number (0): `random` with the same seed and text gives the same values | +| `skipSpaces` | true: spaces and line breaks keep their values and don't count | + +→ `{count (characters changed), ids}`. Text Tweaker… opens a dialog (`ui.menuDialog {command}`, dialog kind +`textTweaker`) whose fields are the command's parameters, with Preview; another attribute starts from its own +default values, and the seed starts new whenever the document has changed. + +```json +{"name":"run_command","arguments":{"command":"addon.type.textTweaker","params":{"attribute":"baselineShift","from":0,"to":18,"shape":"bow"}}} +{"name":"run_command","arguments":{"command":"addon.type.textTweaker","params":{"attribute":"rotation","from":-15,"to":15,"shape":"random","seed":4}}} +``` diff --git a/docs/pdf-backend.md b/docs/pdf-backend.md index fb97151ca2..d21ae4145e 100644 --- a/docs/pdf-backend.md +++ b/docs/pdf-backend.md @@ -1,7 +1,7 @@ # PDF backend PDF writing uses `craft-pdf` from `storytold/craft-libs`, pinned to -`92d392cff132eaf53e13afff77f38b5c11b73aa0`. Its `write` feature supplies Krilla configuration, +`f8f8829cc7be65d466d687dae381d1ca60e31242`. Its `write` feature supplies Krilla configuration, metadata construction, fallible font preparation and serialization, and native unwind guards. The dependency disables default features and enables `write` and `interpret`. The production writer retains Krilla’s raster-image support without its optional text shaper. @@ -16,7 +16,7 @@ Desktop printer submission remains in `craft-print`. The shared writer vendors Krilla 0.8.2 with an unwind-safe cleanup and poisoning patch. The root `[patch.crates-io]` selects that copy from craft-libs revision -`fb08be5fa19eee8d37e624397fcdc96df6035e92`, which adds craft-libs#417 (CMYK, gray and spot +`f8f8829cc7be65d466d687dae381d1ca60e31242`, which includes craft-libs#417 (CMYK, gray and spot colors keep their exact inks): Cargo does not inherit a dependency workspace's patches. A failed page or surface cleanup poisons the backend document, so serialization cannot return an incomplete PDF after unwinding. The shared crate's compile-time backend marker and `cargo xtask pdf-deps` (included in CI) diff --git a/docs/roadmap.md b/docs/roadmap.md index abfaea70ba..cd27fae7f4 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,10 +1,17 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (M5: supersampled exports avoid redundant opaque knockout layers; File formats: `.ai`/EPS import fidelity from a user's file audit; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence -**Feature evidence last updated:** 2026-10-30. +Creating a gradient from solid or empty paint uses the document's color model for its default stops, including drawing its vector with the Gradient tool. Explicit `keepModel: true` retains RGB defaults, and existing gradients keep their own colors. Scores and estimates are unchanged. + +**Feature evidence last updated:** 2026-11-03. + +M1 selection: Enclosing Lasso selects whole objects enclosed by a freehand loop. It is an add-on +under Object › Plug-ins and has its own heading in All Tools. It has no default shortcut or Basic +toolbar slot. Shift adds and Alt subtracts enclosed objects; Escape cancels the loop. +This is a VectorCraft addition; milestone estimates and parity scores are unchanged. The shared assessment status line and revision history are current upstream; this dated section records the submission's feature evidence and revisions without rescoring upstream or claiming a new combined build or runtime measurement. @@ -17,11 +24,17 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard ### Feature revisions +M7 type: Touch Type moves a right-to-left character along its line and up from it while keeping the text editable. A preceding logical character on the same line is required for along-line movement. Direction rules are VectorCraft's choices; estimates are unchanged. + | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | M1: Enclosing Lasso provides whole-object enclosure selection as an add-on with no default shortcut or Basic toolbar slot; estimates unchanged. | +| 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | | 2026-10-30 | minor | M4: G9: `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout) in its state block after its record, so its steps knock each other out as the page draws them; a user's file comes in 0.6% from its page instead of 1.3%. Scores and estimates unchanged. | | 2026-10-30 | minor | M4: File formats: `.ai`/EPS editing-data fidelity from an audit of a user's files: All Caps and Small Caps (#4708); placed files at their box's corner, kept where they draw closer to the page (#4664, #4723, #4742); pages cropped to the art, with `UserUnit` (#4658, #4727); gradient mesh corners with handle weights of 0 and the state written after a mesh (#4738, #4744, #4748); type on a path spaced as the file lays it out (#4743); synthetic regressions in `crates/eps`; scores and estimates unchanged. | +| 2026-11-03 | minor | M7: Find Font replacement sources Document, Recent and System are shipped (#5217); estimates unchanged. | | 2026-10-30 | minor | Raster effects: bounded length fields in effect dialogs clamp on commit and reject invalid inputs visibly (#4638); estimates unchanged. | +| 2026-11-03 | minor | M7: composition spacing remains along the line when characters rotate; estimates unchanged. | | 2026-10-22 | minor | Reconcile upstream documentation after review F-3; preserve every dated revision and the original scaleArt runtime evidence without repeating completed jobs. | | 2026-10-22 | minor | Reconcile upstream documentation after review F-2; preserve every dated revision and the original scaleArt runtime evidence without repeating completed jobs. | | 2026-10-22 | minor | Reconcile subsequent upstream progress updates without changing the runtime or repeating completed evidence; retain every dated upstream and feature revision. | @@ -92,15 +105,19 @@ Checked 2026-10-10 from the code, tests and open issues; no workflow fails, so V | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; confirm the Scale Strokes & Effects default | 4–8 | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, a generated Basic Shapes library, User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); brushes/symbols in progress | 23–37 | +| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, a generated Basic Shapes library, User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged) | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol and brush libraries done; brushes/symbols in progress | 23–37 | +| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol and brush libraries done; symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | +| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, a generated Basic Shapes library, User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); brushes/symbols in progress | 23–37 | +| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged) | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | +| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol and brush libraries done; brushes/symbols in progress | 23–37 | +| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; broader scripting and batch work remains | 18–27 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 | 18–27 | @@ -141,7 +158,13 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | M1: Enclosing Lasso adds freehand whole-object selection under Object › Plug-ins; estimates unchanged. | +| 2026-11-02 | minor | Font-family fields in Character, Properties and Control step selected text with the wheel (#5253), with one undo step per notch; scores and estimates unchanged. | +| 2026-11-03 | minor | M7 records Find Font's shipped replacement-source chooser (#5217); estimates unchanged. | +| 2026-11-03 | minor | Symbol editing shows draggable 9-slice guides (#5280). Guides outside the artwork remain unsupported. Scores and hours remain unchanged. | +| 2026-11-03 | minor | M7: Touch Type moves right-to-left characters along their line while keeping text editable; first-logical-character restriction retained. Estimates unchanged. | | 2026-10-30 | patch | M5: opaque solid-fill knockout paths avoid redundant erase/add layers in hard-edge frames and supersampled raster export; exact-pixel regression coverage retains analytical-AA rounding and translucent knockout behavior; scores and estimates unchanged | +| 2026-11-03 | minor | M7: retain composition trimming in rotated character placement and rotation metadata; estimates unchanged. | | 2026-10-30 | minor | M4: G9: `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout) in its state block after its record, so its steps knock each other out as the page draws them; a user's file comes in 0.6% from its page instead of 1.3%. Scores and estimates unchanged. | | 2026-10-30 | minor | M4: File formats: `.ai`/EPS editing-data fidelity from an audit of a user's files: All Caps and Small Caps (#4708); placed files at their box's corner, kept where they draw closer to the page (#4664, #4723, #4742); pages cropped to the art, with `UserUnit` (#4658, #4727); gradient mesh corners with handle weights of 0 and the state written after a mesh (#4738, #4744, #4748); type on a path spaced as the file lays it out (#4743); synthetic regressions in `crates/eps`; scores and estimates unchanged. | | 2026-10-29 | minor | M6: Pathfinder: live compound shapes (#4522): the panel menu's Make, Release and Expand Compound Shape, Alt-clicking a Shape Mode, a selected member's Shape Mode and the Expand button act; scores unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7e32418659..b4370a3a0c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,10 +1,12 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Color Effects add-on: Find Nearest Swatch, #4923; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence -**Feature evidence last updated:** 2026-10-22. +Creating a gradient from solid or empty paint uses the document's color model for its default stops, including drawing its vector with the Gradient tool. Explicit `keepModel: true` retains RGB defaults, and existing gradients keep their own colors. Scores and estimates are unchanged. + +**Feature evidence last updated:** 2026-11-03. The shared assessment status line and revision history are current upstream; this dated section records the submission's feature evidence and revisions without rescoring upstream or claiming a new combined build or runtime measurement. @@ -19,10 +21,17 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | +| 2026-11-03 | minor | Type Tools add-on: Text Tweaker (a VectorCraft addition, #4924): evidence added; scores unchanged. | +| 2026-11-03 | minor | Transform previews valid typed values while numeric fields remain focused. Effect dialogs use the object, group, or layer targeted in Appearance. | | 2026-11-02 | minor | Legacy `.ai` saves (version 7) write type with rotated characters as outlines that keep each character's rotation, with a warning unless `outlineText` is on (#5186); scores unchanged. | +| 2026-11-03 | minor | Record shipped Find Font replacement sources: Document, Recent and System (#5217); scores and estimates unchanged. | | 2026-10-31 | minor | Object › Path › Smooth smooths a path along its length before refitting it, so Auto-Smooth takes a shaky line to one smooth curve instead of leaving its jags, and with anchor points direct-selected it smooths only that section; scores unchanged. | +| 2026-11-03 | minor | Enclosing Lasso adds freehand whole-object enclosure selection under Object › Plug-ins; scores and estimates unchanged. | | 2026-10-31 | minor | New Document: More Settings has the Save Preset button beside the name too, saving its settings (artboard layout included) as a preset (#4893); scores unchanged. | +| 2026-11-03 | minor | Touch Type moves right-to-left characters along their line when a preceding logical character is on the same line; direction rules are VectorCraft's choices. Scores and estimates unchanged. | | 2026-10-31 | minor | Object › Rasterize in a CMYK document with its CMYK colour model makes a CMYK image of the art's ink amounts (as CMYK exports draw them), so the Properties panel says CMYK and CMYK exports keep its inks; a transparent background becomes the image's opacity mask (#4882); scores unchanged. | +| 2026-11-03 | minor | Composition spacing stays along the line under Character Rotation, including the turning point and unrotated placement; scores and estimates unchanged. | | 2026-10-31 | minor | Export for Screens is laid out as Illustrator's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged. | | 2026-10-31 | minor | Export for Screens is laid out as the reference app's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged. | | 2026-10-31 | minor | Artwork Cleanup add-on: Join Point Text (`addon.cleanup.joinText`) joins stacked one-line point type into one object, a paragraph per line keeping its baseline (#4826); scores unchanged. | @@ -121,18 +130,18 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Area | Weight | Done | Main gaps | One agent (h) | Kind | |---|---:|---:|---|---:|---| -| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939); the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies and excluding a match with Shift-click, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | +| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, and PDF gradients mixing a spot color with RGB or Lab stops | 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (four generated libraries, User Defined, Other Library…, Save Brushes); remaining: Art brush Overlap, Pattern brush auto corners, pen pressure on macOS, tilt/bearing/rotation | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | -| Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated | +| Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, more built-in symbol libraries, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guide settings (stored, not drawn) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, more built-in symbol libraries, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, symbol libraries, Start Global Edit, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guide settings (stored, not drawn) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, symbol libraries, Start Global Edit, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged) | | Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility); materials, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | @@ -144,10 +153,10 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, more built-in symbol libraries, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration and Export Type (Graphic / Movie Clip) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | estimated | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers panel row context menus and Collect for Export (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | -| View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated; document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | +| View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | | File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. | -| View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated; document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | -| View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated | +| View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | +| View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged) | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; video rulers (View › Rulers › Show Video Rulers, #2849) done, score unchanged | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), global/artboard ruler mode switch, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; video rulers (View › Rulers › Show Video Rulers, #2849) done, score unchanged | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), video rulers, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; status-bar X/Y uses the active ruler origin and General units | @@ -399,13 +408,13 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Appearance, transparency, graphic styles, masks | 5 | 98% | raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, 3D Classic and more complete visibility remain | 25–45 | -| Type core | 9 | 80% | Middle Eastern features beyond bidi layout and Paragraph Direction (Character Direction, kashidas, the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); the Every-line Composer (justified and ragged text, per object) is tuned by eye and mixed type sizes in a paragraph still break single-line (Hyphenation… and Justification… options are done, #2310, #2755), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034) | 14–19 | +| Type core | 9 | 80% | Middle Eastern features beyond bidi layout and Paragraph Direction (the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); the Every-line Composer (justified and ragged text, per object) is tuned by eye and mixed type sizes in a paragraph still break single-line (Hyphenation… and Justification… options are done, #2310, #2755), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034) | 14–19 | | Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko), tab leaders, spell check (open dictionary), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | | Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 35% | ~36 Photoshop-style filters (Artistic, Brush Strokes, Sketch, Stylize) and Texturizer's Load Texture (since done, see the area table above, as is the Effect Gallery, #2883); Document Raster Effects Settings, raster effects in PDF, the pixel-filter pipeline, Radial Blur, Smart Blur (Normal, Edge Only and Overlay Edge), Unsharp Mask, Glowing Edges, Distort (Diffuse Glow, Glass, Ocean Ripple), Pixelate (Color Halftone, Crystallize, Mezzotint, Pointillize), Texture (Craquelure, Grain, Mosaic Tiles, Patchwork, Stained Glass, Texturizer) and Video (De-Interlace, NTSC Colors) are done | 8–14 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting and four original lighting presets; materials, shadows, ray tracing, 3D Classic and more complete visibility remain | 25–45 | | Type advanced | 4 | 50% | CJK composition for vertical type (mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko is done, its up/down settings remain; No Break is done), tab leaders, spell check (open dictionary), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | -| Type core | 9 | 80% | Middle Eastern features beyond bidi layout and Paragraph Direction (Character Direction, kashidas, the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); Hyphenation… and Justification… options (Every-line Composer for justified and ragged text, per object, is done; it is tuned by eye, not yet compared side by side with Illustrator; mixed type sizes in a paragraph still break single-line in non-rectangular area type and with text wrap), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034). Fractional Widths and System Layout are done | 14–19 | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | more built-in symbol libraries (original), dynamic symbols, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type done (9-slice guides remain) | 4–7 | +| Type core | 9 | 80% | Middle Eastern features beyond bidi layout and Paragraph Direction (the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); Hyphenation… and Justification… options (Every-line Composer for justified and ragged text, per object, is done; it is tuned by eye, not yet compared side by side with Illustrator; mixed type sizes in a paragraph still break single-line in non-rectangular area type and with text wrap), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034). Fractional Widths and System Layout are done | 14–19 | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | more built-in symbol libraries (original), dynamic symbols, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | | Image Trace, graphs, image tools | 3 | 72% | graph Column designs (Graph Design, Marker designs and series colours set with Group Selection are done), Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 | | Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | | View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 | @@ -483,6 +492,7 @@ since 2026-10-01. - **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. +- **Global Edit: Shift-click leaves a match out:** while Global Edit is on, a Shift-click with the Selection tool on a highlighted match, or on an object inside a matched group, leaves that match out (`select.globalEditExclude`): it is no longer highlighted and later edits leave it as it is; the object the edit started from stays, and Global Edit ends when fewer than two matches are left ([Update assets quickly with Global Edit](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)). Regression tests: `a_shift_click_*`, `an_object_left_out_*`, `a_group_left_out_*` and `leaving_out_all_but_one_*` in `crates/engine/src/tests/globaledit.rs`. - **Pattern-only backquote drags:** With Selection move, bounding-box scale or rotate, or the Rotate, Reflect, Scale or Shear tool, backquote held at mouse release applies the drag matrix to selected pattern paint while object geometry stays in place. The key may be pressed after mouse press; if released before the mouse button, the drag commits as an ordinary transform. Objects without pattern paint stay still; stroke-only patterns and patterned objects in mixed selections take the same matrix. Regression tests: `backquote_move_uses_release_state_and_one_commit` and `backquote_box_scale_and_rotate_use_pattern_matrix_at_release` in `select/tests.rs`, `backquote_drag_previews_and_commits_pattern_only_for_each_transform_tool` in `xform/transform.rs`, `selection_backquote_drag_changes_pattern_fill_and_stroke_without_moving_mixed_art` and `selection_backquote_drag_changes_stroke_only_pattern` in `tests/pattern.rs`, `egui_backtick_drag_uses_key_state_at_release` in `canvas/tests.rs`, and `synthetic_pointer_backquote_keeps_solid_object_in_place` in `control/tests.rs`. Scores and hours unchanged. - **Existing-guide Escape cancellation (G1):** Escape clears a pending guide press or drag through Selection and Direct/Group Selection, cancelling a begun preview. Eight app-input regressions cover both axes, move/copy, temporary selection-tool borrowing from idle Pen, preselected-guide document/interaction-start selection and Undo/Redo/saved-state preservation, later on-canvas motion/release, Shift-press cancellation, and ordinary-release/Enter/idle controls. Historical focused checks on `8ab574b7` recorded five expected RED failures with three passing controls, then all eight GREEN tests and the Direct Selection Escape control passed. All nine also passed in current full CI. A full CI retry on the five-unit combined source at `a0671777` passed all seven stages with 6,613 test outcomes on 2026-10-14. An earlier full-CI run on the identical source panicked in the randomized `ai_mutated_save_never_panics` test; the cause remains unresolved. This five-fix batch does not claim to repair that failure. The original 1280×960 headless app capture from `b076025a` was reviewed for one vertical Selection guide after Escape; source review found its scene unchanged on `a0671777`. Scores and hours unchanged. - **Escape in more tool drags:** Escape during an Anchor Point drag, a Mesh tool drag, a Direct Selection drag of a mesh point, a corner widget or the brackets of type on a path, or a Shape Builder drag cancels it: the art goes back to how the press found it, no undo step is added, the release does nothing, and the tool stays chosen. Escape during a Measure tool drag brings back the measurement before it. Regression tests: `escape_cancels_*` in `draw2/anchor/tests.rs`, `meshedit.rs`, `direct/tests.rs`, `builder/tests.rs` and `xform/measure.rs`, and `escape_cancels_an_anchor_point_mesh_shape_builder_or_measure_drag` in `tests/toolescape.rs`. @@ -503,7 +513,8 @@ since 2026-10-01. - **OpenType SVG colour fonts:** each glyph's SVG document is read by the SVG importer (registered by the engine) into vector art in the run's colours, then drawn, exported and outlined as COLR glyphs are; PDF real text writes them as text that draws nothing and draws their art where they sit. Measured by `tests_svg_glyphs`, `svg/tests/it/svg_glyphs.rs`, `tests_colourfonts::create_outlines_turns_svg_glyphs_into_groups`, `tests_colourfonts::pdf_real_text_draws_svg_glyphs_as_art_and_keeps_their_characters`. Scores unchanged (estimated). - **Character-style Auto leading:** capture and explicit style attributes retain Auto as a reset, distinct from omitted leading. Redefine and later numeric updates preserve local leading overrides; the Character Styles marker recognizes Auto correctly. Regression assertions cover partial definitions, Undo/Redo and native save/load serialization. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Leading](https://helpx.adobe.com/illustrator/using/line-character-spacing.html). - **Character Style Options, General and Basic Character Formats:** the dialog edits a style's name and stored character formats together. Empty fields remain unset, checkboxes show an indeterminate unset state, Basic's Reset Panel clears its explicit settings, and Preview can be canceled without changing history. OK saves one undo step; New Character Style offers the same fields from captured text or the interface language's defaults without a selection. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). -- **Character Style Options, Advanced Character Formats:** Character Style Options and New Character Style set a style's Horizontal Scale and Vertical Scale (above 0% and at most 4,000,000%), Baseline Shift (-4,000,000 pt to 4,000,000 pt), Character Rotation (stored from -180° to 180°) and Language; text that uses the style takes them and keeps its local overrides. Empty fields remain unset, an explicit 100%, 0° or English: USA stays distinct from unset, and the section's Reset Panel clears only these five. Language sets the language the characters are shaped in, not hyphenation or spelling. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) ("Adjust the Horizontal and Vertical Scale, Baseline Shift, Character Rotation, and Language options"). +- **Character Style Options, Advanced Character Formats:** Character Style Options and New Character Style set a style's Horizontal Scale and Vertical Scale (above 0% and at most 4,000,000%), Baseline Shift (-4,000,000 pt to 4,000,000 pt), Character Rotation (stored from -180° to 180°) and Language; text that uses the style takes them and keeps its local overrides. Empty fields remain unset, an explicit 100%, 0° or English: USA stays distinct from unset, and the section's Reset Panel clears only these five. Language sets the language the characters are shaped in, not hyphenation or spelling. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). +- **Character Style Options, Character Color and OpenType Features:** Character Style Options and New Character Style set a style's fill and stroke (None or a document swatch; a global swatch stays linked, with a Tint from 0% to 100%), stroke Weight, Overprint Fill and Overprint Stroke, and its Figure, Position, Standard and Discretionary Ligatures, Contextual, Stylistic and Titling Alternates, Swash, Ordinals, Fractions and Stylistic Sets 1 to 20; text that uses the style takes them and keeps its local overrides, and editing a global swatch later updates the style and its text. Empty controls remain unset, an explicit None, off, Default Figure or Default Position stays distinct from unset, each stylistic set is on, off or unset, a gradient or pattern paint stays until another paint is chosen, a changed OpenType control keeps the style's other feature tags, and each section's Reset Panel clears only its own attributes. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html). - **Text styles redefined to the defaults:** New and Redefine Character Style and Paragraph Style capture every attribute of the selected text, including those at their defaults (Auto kerning, Roman baseline alignment, the default Hyphenation options, the Every-line Composer, no tab stops), and `charStyle.setAttrs` and `paraStyle.setAttrs` keep an attribute set to its default value. After a redefinition, text whose value still equals the old definition's takes the new value, a default included; local overrides stay, and text that still has the old value of an attribute the new definition leaves out goes back to the Normal style's value. The style panels show "+" only where the text differs from its style, including type with Auto alignment. Public reference: [Character and paragraph styles](https://web.archive.org/web/20260825113735/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Text styles dragged onto the panel's buttons:** a style dragged from the Character Styles or Paragraph Styles panel onto Create New Style is copied (`charStyle.duplicate`, `paraStyle.duplicate`, which name the copy ` copy`) and the copy is highlighted; dragged onto Delete it is deleted (`charStyle.delete`, `paraStyle.delete`); the Normal style is not deleted. Each drop is one undo step. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Auto Leading outside the layout:** a paragraph's Justification… › Auto Leading () also sets the Leading the Character panel shows for Auto type (blank where the selected paragraphs differ), the leading the Alt+↑/↓ nudge (`type.step`) steps from, each paragraph's own, and the lines Fill with Placeholder Text counts in area type. Evidence: `ParaStyle::effective_leading` (`crates/doc/src/text.rs` test `paragraph_effective_leading_follows_auto_leading`), `tests_prefs::auto_leading_steps_and_fills_from_the_paragraph_auto_leading`, `panels::character` test `leading_field_shows_the_paragraph_auto_leading`. @@ -524,7 +535,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Global and artboard rulers:** View › Rulers › Change to Global / Artboard Rulers (Cmd+Alt+R, `view.globalRulers`). A new document has artboard rulers: the rulers and the Transform, Properties, Control and Info X/Y count from the active artboard's top-left corner, or the zero point dragged out for that artboard, which moves with it; with global rulers one document zero point serves every artboard. Guide readouts and Shift ruler-tick snapping follow the same zero point. The mode is saved with the document; files from before it open with global rulers, as they measured. Regression tests: `engine/tests/it/ruler_origin.rs`, `ui-egui/src/tests/ruler_origin.rs`, `tools/src/rulerguide.rs`. Public reference: [About rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/about-rulers.html). - **Video display options (#2849):** Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio, and View › Rulers › Show Video Rulers ([Set video display options for artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)). Each artboard has its own (`artboard.setProps`/`artboard.new` `showVideoSafeAreas`, `videoRulerPixelAspectRatio` 0.1–10, default 1), set in one undo step and written to the native format only when on or not 1, so other documents save byte for byte as before. The help page names the safe areas without numbers; our choice is [EBU R 95](https://tech.ebu.ch/docs/r/r095.pdf)'s (note 5): the canvas outlines the action-safe area 3.5% and the title-safe (graphics-safe) area 5% in from each edge, 1 point wide and turned with the view; exports and print leave them out. Show Video Rulers (`view.videoRulers`) shows the rulers counting the active artboard in pixels from its top-left corner, whatever the ruler origin: a pixel is as many points wide as the ratio and one point tall, so a 720 × 480 pt artboard at 0.9 reads 800 × 480. Hide Video Rulers returns them to the General unit; Shift ruler-tick snapping of new guides keeps the General unit. Regression tests: `tests/panelcmds.rs` (`artboard_video_display_options_*`, `artboard_display_marks_stay_out_of_exports`), `tests/docsetup.rs` (`an_artboard_shows_its_video_safe_areas`), `canvas.rs` (`video_rulers_count_the_artboard_in_pixels_of_its_aspect_ratio`), `tests/ruler_origin.rs` (`show_video_rulers_counts_the_active_artboard_in_pixels`), `dialogs/tests.rs` (`artboard_options_show_video_display_options`). - **Saved views (G7):** View › New View… and Edit Views… ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): up to 25 views per document, saved with it, renamed or deleted in Edit Views, chosen from the bottom of the View menu). Each view keeps the zoom, centre and rotation; the View menu lists all 25 (`view.goto1`–`view.goto25`), and Edit Views… lists them to rename or delete, applied together as one undo step. A file's views are checked when it opens (at most 25, unique names up to 255 characters, a finite centre and a positive zoom). Tests: `saved_views_round_trip_and_from_a_file_are_tidied` (`crates/format/tests/prop_format.rs`), `crates/engine/src/cmd/views.rs`, `crates/ui-egui/src/dialogs/edit_views.rs` and `every_saved_view_is_listed_at_the_bottom_of_the_view_menu` (`crates/ui-egui/src/menus.rs`). +- **Window › Arrange › Tile (G7):** Tile (`window.arrange.tile`) shows every open document at once, edge to edge in the document area ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)), one pane each in a grid of as many columns as the square root of the number of documents, rounded up, each fitted to its pane. The current document's pane is the canvas; the other panes draw their documents with their artboards, guides and selected objects, and a press in one makes its document the current one. Consolidate All Windows (`window.arrange.consolidateAllWindows`) shows one document under its tab again. The grid and when the two items are enabled (Tile with two documents or more, Consolidate All Windows while they are tiled) are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. - **Window › Arrange › Tile (G7):** Tile (`window.arrange.tile`) shows every open document at once, edge to edge in the document area ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): "Tile displays windows edge to edge"), one pane each in a grid of as many columns as the square root of the number of documents, rounded up, each fitted to its pane. The current document's pane is the canvas; the other panes draw their documents with their artboards, guides and selected objects, and a press in one makes its document the current one. Consolidate All Windows (`window.arrange.consolidateAllWindows`) shows one document under its tab again. The grid and when the two items are enabled (Tile with two documents or more, Consolidate All Windows while they are tiled) are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. +- **Window › Arrange › Float in Window, Float All in Windows and Cascade (G7):** documents float in windows of their own, out of the tab strip ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html): "drag the window's tab out of the group"). Float in Window (`window.arrange.floatInWindow`) floats the current document, Float All in Windows (`window.arrange.floatAllInWindows`) every tabbed one, and Cascade (`window.arrange.cascade`) floats every document and stacks the windows from the upper left to the lower right ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): "Cascade displays windows stacked and descending from the upper-left to the lower-right of the screen"). On the desktop each window is an OS window; on the web and on Wayland it is a window inside the app's window. The window of the current document holds the canvas; the others draw their documents as Tile's panes do, and a press in one makes its document the current one. Closing a window closes its document, asking to save unsaved changes. Consolidate All Windows brings every document back under the tabs, and Tile brings them back into its grid. The cascade's 30 pt step, the windows' size and when the items are enabled (Cascade with two documents or more, Float in Window for a tabbed current document, Float All in Windows while a document is tabbed, Consolidate All Windows while documents are tiled or floating) are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. +- **Dragging a document tab out and a document window back (G7):** a document tab dragged more than 24 pt above or below the tab strip floats its document in a window under the pointer, and a document window dragged onto the tab strip goes back under the tabs ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html): "To undock (float or untab) a Document window from a group of windows, drag the window’s tab out of the group. To dock a Document window to a separate group of Document windows, drag the window into the group."). A window inside the app's window is dragged by its title bar; an OS window by the document's tab at its top, and the window follows the pointer. The 24 pt distance and the tab at the top of an OS window are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. +- **Preferences › User Interface › Open Documents As Tabs (G7, #394):** checked by default, documents open under tabs in one document window ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/workspace-overview.html): "When you create or open documents, they are arranged in tabs in a single document window"). With the box cleared, each document opened or created afterwards opens in a floating window of its own, at the next cascade place, as Float in Window floats it; documents already open stay where they are, and checking the box again leaves floating documents in their windows. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Document Setup modal handoff:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). @@ -552,7 +567,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Variables: Lock Variables (`variable.lock`, in the Variables panel's bottom bar and menu) stops variables from being defined, deleted or renamed until they are unlocked, while objects can still be bound and unbound and data sets still change and apply; the lock is saved with the document. - Batch…: Override Save and Override Export name each file with the extension of the format the step writes, however the step spells the format (`.svg` and `SVG` give `.svg`, `png8` gives `.png`), in `action.batch`. - Actions panel menu: Save Actions… writes the current action set with all its actions to a file, and Load Actions… adds the set from such a file to the panel ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html): "Select Save Actions from the Actions panel menu", "You can save only the entire contents of a set", "Select Load Actions from the Actions panel menu"; `ui.actionSet.save`, `ui.actionSet.load`). The file is VectorCraft's own action set file (`.vcactions`); a loaded set named like one in the panel gets the next free number. - - Actions panel: the panel menu's Action Options… renames the selected action and keeps its steps ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html): "Opens a dialog to rename or assign function keys/colors to the action"; `ui.action.rename`). The dialog has the name only; the function key and color are not there yet. + - Actions panel: the panel menu's Action Options… renames the selected action and keeps its steps ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html): the menu item opens a dialog that renames the action or gives it a function key and color; `ui.action.options`). It also sets the action's function key and color. + - Actions panel: Create New Action (bottom bar) and the panel menu's New Action… ask for the new action's name, set, function key and color, and Record adds the action and starts recording into it ([Create new actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/record-actions.html): the New Action dialog takes the action's name and the set it goes in; `ui.action.new`, `ui.action.play`). The function key (F1 to F15, with Ctrl or Command and Shift) plays the action. An action's function key plays the action even when a command has the same shortcut, and the command keeps it. VectorCraft's own rules, which the page does not cover: when several actions have the same key the first in panel order plays; a copied action has no key; New Action does not open while an action is recording. The color is kept with the action for Button Mode, which VectorCraft does not have yet. - Actions panel (record/playback, persisted), generic parameter dialogs for every "…" command. - Actions panel: the current set is kept with the UI preferences, so after a restart a recording goes into the set that was current, not into the first set. With no set current, Begin Recording records into the first set and makes it current. - Actions panel: Delete Selection deletes the selected action set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html): "Removes the selected action, command, or action set from the panel"; `ui.actionSet.delete`). VectorCraft's own rules, which the overview does not cover: deleting a set asks first, Shift-click on a set's name selects a range of sets to delete together, the panel menu's Delete does the same, and Default Actions and the last set can be deleted. Undo does not bring a deleted set back. @@ -566,7 +582,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). - Export for Screens numbers distinct row files whose names collide, compared without case, as `-2`, `-3`… instead of leaving them out; identical rows still write one file. It puts row folders that differ only in case into one folder (`document.exportForScreens`). - Variables (data merge): text, visibility and image variables bound to objects (an object may carry several), dataset rows applied in one undo step (`variable.*`, `dataset.*`) from a Variables panel and Window › Variables, with dialogs to define, bind and edit, Make Text/Visibility/Image Dynamic, Capture/Update Data Set, CSV import/export (`dataset.import` / `dataset.export`), and a row in italics when an edit leaves the art not matching it; an image dataset value is a file path and apply keeps the object's bounds; bindings let go of deleted art and locked art is left alone; every command, like the rest, is drivable over MCP and the CLI. - - Variables: Import Data Sets… (`dataset.import`) reads tab-separated files as well as comma-separated ones, and files without a `name` column, whose rows take the first free names Data Set 1, Data Set 2 and so on. An import error about a row's values or name gives the file line the row starts on. + - Variables: Import Data Sets… (`dataset.import`) reads tab-separated files as well as comma-separated ones. Every header cell is a variable, and the rows replace the document's data sets as Data Set 1, Data Set 2 and so on. An import error about a row's values gives the file line the row starts on. - Variables: Import Data Sets… (`dataset.import`) defines the variables a file's header names that the document lacks, unbound. `#Shown` defines a visibility variable, `@Photo` defines an image variable, and a header without a prefix defines a text variable. A header that is a variable's exact name keeps naming it, and any other `%` header (graph data files) is refused. - Variables: Load Variable Library… in the Variables panel menu (`variable.loadLibrary`) replaces the document's variables and data sets with a variable library's, read from its XML file, in one undo step: every variable is deleted with its bindings and values, and every data set is deleted; then the library's text variables are defined, unbound, and its data sets take the text of each value's `p` elements, one paragraph each. Variables of other kinds are left out with a warning that names their kinds. - Variables: Save Variable Library… in the Variables panel menu (`variable.saveLibrary`) writes the document's text variables and data sets as a variable library's XML file, which Load Variable Library reads back with the same text variables, data set names and text values. Variables of other kinds are left out with a warning that names their kinds. @@ -619,9 +635,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - macOS: Finder opens every format File › Open reads with VectorCraft (double-click, Open With, a drop on the Dock icon, `open -a`), at launch or while it runs; the release and `cargo xtask bundle` apps share one `Info.plist` that declares those document types, owning only VectorCraft's own formats. The DMG opens on a designed Finder window, VectorCraft.app beside the `Applications` link over a background with the app icon (#493). - Swatch and graphic style libraries, Libraries panel files, presets and plug-ins open wherever they are dropped on the window, as File › Open opens them. - **Symbol libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own, as swatch and graphic style libraries do. The built-in library, Basic Shapes, is original art generated in code (`crates/engine/src/cmd/symbollib.rs`). A click on a symbol adds it to the document's Symbols as one undo step, with its Symbol Options (size, registration, export type, 9-slice guides) and every resource it uses (the symbols it nests, patterns, swatches, brushes, graphic styles, images), and makes it the current symbol; a symbol the document already has is not added again and another symbol of the same name keeps its name, the library's comes in numbered. Thumbnails, in the library panels and the Symbols panel, draw a symbol with the symbols it nests and the patterns and images it uses. Dragging a library symbol onto the canvas also places an instance there, in the same step ([placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)). Save Symbols (the library menu) and Save Symbol Library… (the Symbols panel menu) write the document's symbols as a `.vectorcraft` document holding only them, into the user library folder (listed under User Defined) or a file; Other Library… reads the symbols of any document VectorCraft opens; a file it can't read is an error and opens no panel. Tests: `crates/engine/src/tests/symbollib.rs`, `crates/ui-egui/src/panels/tests_symbol_libraries.rs`, `panels::symbols::tests::thumbnails_show_the_symbols_a_symbol_nests`, `canvas::tests::a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step`. - - **9-slice scaling** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html): "When you scale the symbol, the parts of the symbol that don't lie within the guides are not scaled."): a scaled instance of a symbol with Enable Guides for 9-Slice Scaling on stays an instance and keeps the parts of its art outside the guides at their size. New guides sit a quarter of the symbol's width and height in from each edge ([reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), "Use 9-slice scaling": "guides are placed at 25% (or 1/4)"); saved guides keep their values. The rest is VectorCraft's own rule: the corners keep both sizes, the top and bottom edges stretch in width, the left and right edges in height and the center in both; an instance smaller than its two outer cells on an axis shrinks them in proportion and leaves the center empty; the cells are sized along the symbol's axes before the instance's rotation, shear or reflection. A path with solid paint that crosses a guide is cut there and stays one path, its stroke at its weight with Scale Strokes & Effects on or off; type, images, live objects and gradient or pattern paint that cross a guide are drawn in each cell they reach, clipped to it, except those that draw symbol art (a nested instance, type with an inline graphic, a placed document, a brushed stroke, or a pattern whose tile draws one of these), which are placed by the cell their center is in; an object in one cell is placed by that cell and stays as it is. The canvas, bounds, the Eyedropper, Break Link to Symbol and the PDF, EPS, DXF, EMF/WMF and SVG exports place the art the same way; SVG writes such an instance as its placed art instead of a ``, and DXF and WMF, which do not clip, cut every path that crosses a guide and place other such objects by the cell their center is in. Guides are not drawn in symbol edit mode yet. Tests: `symbol_nine_slice::tests` in `crates/doc`, `crates/engine/src/tests/symbol_nine_slice.rs`, `a_scaled_nine_slice_instance_keeps_its_corners` (PDF), `a_scaled_nine_slice_instance_is_written_as_the_canvas_draws_it` (SVG), `a_scaled_nine_slice_instance_is_sampled_as_it_is_drawn` (Eyedropper). + - **9-slice scaling** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html): "When you scale the symbol, the parts of the symbol that don't lie within the guides are not scaled."): a scaled instance of a symbol with Enable Guides for 9-Slice Scaling on stays an instance and keeps the parts of its art outside the guides at their size. New guides sit a quarter of the symbol's width and height in from each edge ([reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), "Use 9-slice scaling": "guides are placed at 25% (or 1/4)"); saved guides keep their values. The rest is VectorCraft's own rule: the corners keep both sizes, the top and bottom edges stretch in width, the left and right edges in height and the center in both; an instance smaller than its two outer cells on an axis shrinks them in proportion and leaves the center empty; the cells are sized along the symbol's axes before the instance's rotation, shear or reflection. A path with solid paint that crosses a guide is cut there and stays one path, its stroke at its weight with Scale Strokes & Effects on or off; type, images, live objects and gradient or pattern paint that cross a guide are drawn in each cell they reach, clipped to it, except those that draw symbol art (a nested instance, type with an inline graphic, a placed document, a brushed stroke, or a pattern whose tile draws one of these), which are placed by the cell their center is in; an object in one cell is placed by that cell and stays as it is. The canvas, bounds, the Eyedropper, Break Link to Symbol and the PDF, EPS, DXF, EMF/WMF and SVG exports place the art the same way; SVG writes such an instance as its placed art instead of a ``, and DXF and WMF, which do not clip, cut every path that crosses a guide and place other such objects by the cell their center is in. Tests: `symbol_nine_slice::tests` in `crates/doc`, `crates/engine/src/tests/symbol_nine_slice.rs`, `a_scaled_nine_slice_instance_keeps_its_corners` (PDF), `a_scaled_nine_slice_instance_is_written_as_the_canvas_draws_it` (SVG), `a_scaled_nine_slice_instance_is_sampled_as_it_is_drawn` (Eyedropper). - **Symbol editing mode** ([Edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): a double-click on a symbol instance, the Control bar's Edit Symbol button, a double-click on a symbol in the Symbols panel and the panel menu's Edit Symbol (`symbol.edit`) open the symbol's art on a temporary isolated layer, where the instance shows it (from the panel: centered on the active artboard, or in the view in a document without artboards), with the rest of the document dimmed. Each edit there changes every instance at once; the instances keep their own transforms and stay linked (Break Link to Symbol still expands one), and a dynamic symbol's instances keep their appearance changes to the objects the art still has. Escape, the isolation bar's back button, the Control bar's Exit Symbol Editing Mode and a double-click outside the art leave the mode (`symbol.exitEditing`); leaving without an edit adds no undo step. Saving leaves the editing layer out. Tests: `crates/engine/src/tests/symboledit.rs`, `select::tests::a_double_click_on_a_symbol_instance_edits_its_symbol`, `panels::symbols::tests::edit_symbol_from_the_panel_centers_the_art_on_the_active_artboard_or_the_view`. - Symbol editing mode keeps every instance in step: instances of a dynamic symbol inside other symbols' art, pattern tiles, graph designs, stored brushes and opacity masks keep their appearance changes on the objects an edit reorders and drop the changes to objects it deletes. The view does not draw the instance the edit was entered from. Area type in the symbol's art takes the text wrap that moving a wrap object gives it. Editing another symbol at a place that fails keeps the current edit open, and only the editing layer or art on it can be isolated. Tests: `crates/engine/src/tests/symboledit.rs`, `isolation::symbol_editing_does_not_draw_the_instance_it_was_entered_from`, `panels::symbols::tests::double_clicking_a_symbol_in_the_panel_edits_it_in_either_view`, `the_panel_menus_edit_symbol_edits_the_instances_symbol_or_the_panels`, `the_control_bars_edit_symbol_edits_the_selected_instances_symbol`, `chrome::tests::the_control_bar_exits_symbol_editing_mode`. + - **9-slice guides on the canvas** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html)): while a symbol with Enable Guides for 9-Slice Scaling on is edited in symbol editing mode, the canvas draws its two horizontal and two vertical guides as dotted lines across its art, with any tool and with ruler guides hidden. With the Selection tool the pointer near a guide shows the Move cursor, and dragging the guide moves it (`symbol.options`'s `nineSliceGuides`) as one undo step; Escape during the drag puts it back. VectorCraft's own rules: a guide within 4 screen pixels takes the press before the art and the bounding box; it stays within the art's box (guides outside the art are not supported yet) and stops short of the opposite guide; the drag does not snap. Tests: `nineslice::tests`, `symbol_nine_slice::tests::the_edited_symbols_guides_cross_its_art_where_the_editing_layer_shows_it`, `a_moved_guide_stays_in_the_art_and_short_of_the_opposite_guide`, `canvas::tests::the_edited_symbols_nine_slice_guides_are_drawn_and_dragged_on_the_canvas`. - **Delete Symbol asks first** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Alt-click Delete](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): the Symbols panel's Delete Symbol button and menu item ask "Delete the selected symbol?" with Yes and No for a symbol no instance uses. For a symbol with placed instances they ask with Expand Instances (the instances become ordinary art), Delete Instances and Cancel; either Instances button deletes the symbol in one undo step. Alt-click on the button deletes an unused symbol without asking and still asks about one with instances. A question left open while another document became active deletes nothing. `symbol.delete` itself does not ask. Tests: `panels::symbols::tests::delete_symbol_asks_first_and_alt_click_deletes_an_unused_symbol_at_once`, `the_in_use_question_expands_or_deletes_the_instances`, `a_stale_delete_symbol_question_deletes_nothing`, `the_delete_symbol_questions_show_their_buttons`. - **Symbols › Select All Unused** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), #4918): the Symbols panel menu's Select All Unused shows the symbols nothing places selected (`symbol.unused`): instances in the art (opacity masks included), graph designs, pattern tiles and brush art count, and so do instances in a used symbol's art. Delete Symbol, the button or the menu item, then asks "Delete the selected symbols?" once and deletes those still unused in one undo step (`symbol.delete {names}`); Alt-click on the button deletes them without asking, and a click on a symbol picks just it again. Tests: `tests::brushsym::symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several`, `panels::symbols::tests::select_all_unused_picks_the_unused_symbols_and_delete_deletes_them`, `dialogs::symbol_delete::tests::several_symbols_get_the_plural_question`. - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol. A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. @@ -633,9 +650,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (off by default: on, pink behind OpenType substitutions on screen — ligatures, contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set`, #394). About 14 stored options still do nothing yet (the rest of #394: Open Documents As Tabs, Real-time Drawing and Editing, GPU Performance beyond Animated Zoom, hyphenation language, scratch disks, the legacy clipboard, Touch Workspace). - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (on by default: pink behind OpenType substitutions on screen — ligatures, contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set`, #394). About 14 stored options still do nothing yet (the rest of #394: Open Documents As Tabs, Real-time Drawing and Editing, GPU Performance beyond Animated Zoom, hyphenation language, scratch disks, the legacy clipboard, Touch Workspace). - The desktop app keeps the Color panel's Show Options or Hide Options between sessions, and `ui.colorPanel` sets its mode and options as its panel menu does. - - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Units › East Asian Type (the bullet below). Four stored options still do nothing yet (the audit below). + - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Three stored options still do nothing yet (the audit below). - Preferences › Type › Highlight Substituted Fonts (on by default) paints pink behind text drawn in a substitute for a missing font in every document, and turning it off removes that highlight everywhere (`prefs.set highlightSubstitutedFonts`); Document Setup keeps Highlight Substituted Glyphs ([help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/edit-text-without-replacing-missing-fonts.html)). - - Preferences audit (2026-10-30, #394): every Preferences dialog option is read by shipped code, by its field or its key, except User Interface › Open Documents As Tabs, Hyphenation › Default Language, Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard and its mode, which are stored only (Units › East Asian Type, stored only on the day of the audit, acts since 2026-10-31); [gaps.md G12](gaps.md#g12-preferences-and-panels-that-dont-act-yet) says what each waits on. + - Preferences audit (2026-10-30, #394): every Preferences dialog option is read by shipped code, by its field or its key, except Hyphenation › Default Language, Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard and its mode, which are stored only (Units › East Asian Type and User Interface › Open Documents As Tabs, stored only on the day of the audit, act now: East Asian Type since 2026-10-31, Open Documents As Tabs as the Window › Arrange bullet says); [gaps.md G12](gaps.md#g12-preferences-and-panels-that-dont-act-yet) says what each waits on. - Units › East Asian Type (#394, `unitsAsianType`): Points by default; it offers every unit and Q and Ha, a quarter of a millimetre each (0.709 pt: the [Illustrator Scripting Guide](https://ai-scripting.docsforadobe.dev/scripting/measurementUnits/); `q` and `h` are the field suffixes [InDesign's notation table](https://helpx.adobe.com/in/indesign/desktop/layout-and-grid-tools/rulers-and-measure-tools/change-ruler-measurement-units.html) lists), and only it lists them: rulers, Document Setup and the other Units preferences keep their ten. The public pages do not say which fields follow it, so no field uses it yet and that waits for a source. The model stays in points; any length field reads `13q`/`13h`. Evidence: `q_and_ha_are_a_quarter_millimetre`, `east_asian_type_unit_*` (`crates/engine/src/tests/units.rs`). - Preferences audit (2026-10-30, #394): every Preferences dialog option is read by shipped code, by its field or its key, except User Interface › Open Documents As Tabs, Units › East Asian Type, Hyphenation › Default Language, Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard and its mode, which are stored only; [gaps.md G12](gaps.md#g12-preferences-and-panels-that-dont-act-yet) says what each waits on. - With Performance › Real-time Drawing and Editing off, the bounding box moves with a Selection-tool move drag and the object moves when the button is released ([help](https://web.archive.org/web/20220324053041id_/https://helpx.adobe.com/illustrator/using/real-time-editing.html); `real_time_drawing_off_moves_the_bounding_box_with_a_move_drag`). @@ -684,6 +701,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A Direct Selection marquee over part of a segment, with neither of its anchors inside, selects that segment as a click on it does (Shift toggles it), as [Selecting objects](http://web.archive.org/web/20211230015528/https://helpx.adobe.com/illustrator/using/selecting-objects.html) describes (#4654). With the Selection or Group Selection tool, pressing E while dragging a marquee makes the marquee select only the objects that lie entirely inside it. Pressing E again switches the marquee back to its default selection. The Lasso picks anchor points only on art a click can pick, and the Add Anchor Point, Delete Anchor Point, Anchor Point and Scissors tools pick anchor points and segments only on the selected paths and on art a click can pick: not on a Shaper Group's original shapes outside Construction mode, and in isolation mode only inside the isolated group or object. Smart Guides and Snap to Point do not snap to a Shaper Group's original shapes, and the reference point of the transform tools snaps to one only when it is selected, or under the pointer in Construction mode. + Enclosing Lasso provides whole-object enclosure selection under Object › Plug-ins and its own heading in All Tools. It has no default shortcut or Basic toolbar slot. It follows path curves and keeps partially enclosed objects out, including objects crossing a concave part of the loop. Ordinary group members can be selected individually; compound paths remain whole. This is a VectorCraft addition; scores and estimates are unchanged. A marquee selects a clip group, or an object on a layer with a clipping mask, only when it reaches the area inside the clipping path, and it measures the art only within that path's bounds. Within the bounds of a mask that is not a rectangle, it can still select art that the mask hides. Direct Selection's marquee still selects the hidden anchor points inside it (#2345). A marquee selects a Shaper Group only when it reaches the art the group shows, not the original shapes kept under it, and Direct Selection's clicks and marquee do not select those shapes' anchor points. In Construction mode a marquee selects the original shapes, and Direct Selection selects their anchor points. While an opacity mask or a pattern is edited, a Shaper double-click on a Shaper Group in the mask or pattern art selects the original shape under the pointer without entering Construction mode, the Shaper Group's mode widget does not show, and a Shaper scribble, Release and Expand keep the editing layer isolated. @@ -757,9 +775,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur While a drag rotates the view, a dial at the center of the canvas shows the angle. - **Editing type:** double-clicking type with a selection tool (Selection or Direct Selection) switches to the Type tool with the caret where it was clicked; pressing Escape finishes editing and switches back to the selection tool used before double-clicking it (when in isolation mode, the first Escape exits text editing while preserving isolation mode, and a second Escape exits isolation). While a Type tool edits type, a click that lands on no type ends the editing without making new type, and that tool stays active; the next click makes new type (#2871, #2854). + Inside a ligature (one glyph for several characters, such as fi), the Type tool's caret, clicks, arrow keys and selection stop between its characters, at the font's ligature carets ([OpenType GDEF ligature caret list](https://learn.microsoft.com/en-us/typography/opentype/spec/gdef)) or, when the font does not list one valid caret for each stop, at the glyph's width divided equally. Duplicate Artboards, the Artboard tool's Alt-drag and Paste give the new artboard an id that no other artboard has, also when an artboard's id is the largest possible value (#1718). Deleting the copy or the original then leaves the other's guides. - **Touch Type:** a click with the Touch Type tool (Shift+T) selects one character and shows a box around it. Dragging the box or its lower-left handle moves the character. The upper-left handle scales it vertically, the lower-right handle scales it horizontally, the upper-right handle scales it proportionally, and the upper-middle handle rotates it. Each drag is one undo step that sets the character's kerning, baseline shift, scales or rotation, and the type stays editable (`text.touchType`; behavior reference: [Touch Type tool](https://web.archive.org/web/20261007185617/https://helpx.adobe.com/illustrator/using/tool-techniques/touch-type-tool.html), [Add text with the Type, Area Type, and Touch Type tools](https://web.archive.org/web/20260926095922/https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/add-text-illustrator-text-tools.html)). + Composition's leading-space reduction stays along the line when a character rotates. An opening bracket trimmed by Line-end Punctuation Half Width Mojikumi keeps that placement under Character Rotation; its turning point follows the composition adjustment, and removing the rotation keeps the trim. Scores and estimates are unchanged. A character rotated near or at a quarter turn follows a Touch Type drag across its line as well as along it: baseline shift moves a character up from its line at any rotation, and the character turns about its shifted pen position. + Right-to-left characters can also move along their line when a preceding logical character is on that line. Positive `text.touchType` `dx` follows reading order, toward the left in horizontal right-to-left text; the first logical character still moves only up and down. These direction rules are VectorCraft's choices; the public Touch Type page describes moving a character without specifying this case. Scores and estimates are unchanged. - **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool. Space held while the Zoom tool drags a marquee moves the marquee and keeps its size ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). When Space is let go, the drag sizes the marquee again from where it moved to. A Space+Shift drag rotates the view whatever the tool, as a Rotate View tool drag does, and Shift does not round the angle to 15°. @@ -838,6 +859,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With the view rotated, a second Escape less than a second after the first resets the rotation, as Reset Rotate View does. The first Escape may end something else, such as isolation mode or a path being drawn. The second resets the view only when it has nothing else to end, and an Escape that closes a menu does not count. After a click, or a press of another key that is not a modifier (Shift, Control, Alt/Option or Command), the next Escape counts as the first. With the Rotate View tool chosen, one Escape resets the view. A two-finger rotation on a Mac trackpad turns the view about the pointer once it reaches 5° (Preferences › General › Trackpad Gesture to Rotate View, on by default). On a touch screen a second finger cancels the tool press the first finger began, in the frame it lands or later: the Pencil's stroke or a Selection move is rolled back with no undo entry, and a finger that lands while another is down presses nothing, so a pinch or two-finger pan only zooms and pans (#4198; canvas test `a_second_finger_cancels_the_tool_gesture_the_first_began`). + A tool press dropped by a second finger, a long touch or a canceled touch cancels the tool's drag as Escape does: the tool gets back the options it had when the press began (the Polygon tool's sides, set with ↑ and ↓) and they are not stored, a press held still opens no size dialog, a Selection or Artboard tool marquee selects nothing, and the Pen goes on drawing its path without the dropped anchor (canvas tests `a_canceled_touch_drops_the_drag_without_keeping_its_options` and `long_touch_drops_a_tool_press_without_committing_art`; engine tests in `tests::toolsettings`). The status bar navigator's field shows the active artboard's number and name, and its drop-down lists every artboard by number and name, as the Artboards panel does. Choosing an artboard in the list makes it the active artboard and fits it in the window (`view.goToArtboard`). The list opens on the active artboard's row and lays out only the rows in view and at most one more. - **Geometry and effects:** - **Open-path anchor Delete:** Delete/Backspace removes selected anchors and their adjoining segments, leaving drawable runs as separate open subpaths of the original object. Surviving curves and appearance stay intact; one Undo restores the document and selection, and a second Delete removes the selected remainder. Explicit Remove Anchor Points still reconnects/refits. Four core regressions, one full-frame Delete/Backspace regression and three existing removal/segment controls pass, covering these distinctions, multiple deletions, transformed geometry and mixed whole-object selection. Behaviour references: the legacy public [Illustrator reference guide, Add or delete an anchor point](https://helpx.adobe.com/content/dam/help/en/pdf/illustrator_reference.pdf) distinguishes keyboard deletion from dedicated removal; the current [Add or remove anchor points](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/add-or-remove-anchor-points.html) describes the dedicated tools. Other G11 gaps and scores/hours remain unchanged. @@ -875,13 +897,17 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Optical kerning:** Character and Properties offer Optical beside Auto for automatic pair spacing. The side-profile spacing method is VectorCraft's own. Optical keeps its mode across cosmetic style runs. Choosing Optical clears manual pair values, as Auto does, and leaves additive tracking intact; a manual value typed afterwards replaces that pair's correction ([Adjust kerning and tracking](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/adjust-kerning-and-tracking.html)). Native documents retain the mode and pair overrides; old documents use Auto. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/engine/src/tests/textedit.rs`. - **Kerning across style runs:** characters that differ only in fill, stroke, underline, strikethrough, overprint, character style name, leading, baseline shift, rotation, Character Alignment, kerning, or tracking that keeps or drops ligatures alike are shaped together, so restyling one character keeps the font's kerning pairs with its neighbors. A character with manual kerning that follows one with automatic kerning keeps the font's kerning with it (unless All Caps or Small Caps sets it as two letters, as ß becomes SS), and its value replaces the font's kerning after it. A ligature does not form across a change of style, and a change of font, size or OpenType features still shapes the characters apart. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/text/src/tests/bidi.rs`. - **Manual kerning in right-to-left text:** a manual kerning value on a Hebrew or Arabic character changes the space between it and the next character in reading order, the one drawn to its left, under Auto and Optical kerning. The character before it keeps its place, and the caret between the pair stays beside the next character. The side the space goes on is VectorCraft's own rule. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) ("Kerning is the process of adding or subtracting space between specific pairs of characters."). Test: `rtl_manual_kerning_spaces_the_character_from_the_next_in_reading_order`. +- **Manual kerning on inline graphics:** a manual kerning value on an inline graphic's character spaces it from the next character in reading order by the same distance as on a letter of its run's size, in left-to-right, right-to-left and vertical type; Auto and Optical kerning still apply no font pairs to it. This is VectorCraft's own rule. Test: `manual_kerning_on_an_inline_graphic_spaces_it_like_a_letter`. - **Recent font pickers (#3515):** The shared Character, Properties, Glyphs and Find Font family picker lists recently applied families first, once each, in most-recent order and limited by Preferences › Type › Number of Recent Fonts. Search and filters apply to both sections; unavailable families are omitted. Section headings cannot be selected or previewed. Confirmed character-range font edits update the same saved history; previews and failed edits do not. Requirement: [issue #3515](https://github.com/storytold/vectorcraft/issues/3515). +- **Find Font: Replace With Font From:** a dropdown under Replace With Font chooses the list the replacement font comes from: Document lists the families the document uses, once each; Recent lists the recently applied families that are installed (fonts applied with Find Font's Change and Change All included), newest first, as many as Preferences › Type › Number of Recent Fonts allows; System, the default, lists the installed families available in the font menu. The dialog opens on System with Source Sans 3 chosen, or the font menu's first family when Source Sans 3 is not installed. Choosing a list keeps the chosen font when the list has it and it is installed; otherwise Document and Recent choose the list's first installed font, and System chooses Source Sans 3 or the font menu's first family. Change and Change All are unavailable when the list has no installed font (Recent before any font was applied) and when the chosen family is not installed or is not in the shown list. Behavior reference: [Find and replace fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-replace-fonts.html) (public documentation). Tests: `crates/ui-egui/src/find_font.rs`. +- **Mouse wheel over the font family field (#5253):** In the Character and Properties panels and the Control bar, turning the mouse wheel over the closed font family field applies the next family to the selected type (the previous one when turned up), keeping the style when the family has it, else its closest. Each notch is one undo step; leaving the field or Escape keeps the family, and Undo takes it back. The steps use the font menu's order at the first turn and keep it until the pointer leaves the field or the text selection changes, so recent-font updates do not reshuffle later turns. That order follows the menu's saved font filters but ignores its search text, puts recent families first, and stops at the first and last family. A turn with a modifier key is left to the panel and the canvas. Behavior reference: the [Illustrator CS6 reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf#page=10) describes editing hovered dropdown controls with the mouse wheel; [Find and apply fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-apply-fonts.html) names the family field's places. Applying it to the font field, the order, the ends and the undo steps are VectorCraft's own rules. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/tests/font_wheel.rs`. - **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in rectangular area type, rows and columns included. In area type of another shape, or with text wrap, such a paragraph is broken with the Single-line Composer. The Character panel's Small Caps, Superscript and Subscript buttons and the panel menu's items of the same names turn small caps and the superscript or subscript position on and off for the selected type, or for the text the Type tool has selected (`text.setFormat` or `text.setRangeStyle` `{smallCaps, position}`), in Document Setup's proportions. Turning Superscript on turns Subscript off, and turning Subscript on turns Superscript off. A button or item shows as on when the first selected character (at a caret, the character before it) has its attribute. The OpenType panel's Stylistic Alternates and Titling Alternates checkboxes turn `salt` and `titl` on and off for the selected type, and its Figure menu lists Default Figure, Tabular Lining, Proportional Lining, Proportional Oldstyle and Tabular Oldstyle; Proportional Lining sets `pnum` and `lnum` and turns `tnum` and `onum` off, Tabular Lining turns `pnum` off and keeps `lnum`, Proportional Oldstyle turns `lnum` off and keeps `pnum`, and Default Figure and Tabular Oldstyle turn `pnum` and `lnum` off. Behavior reference: [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) and [Use swashes, titling alternates, or stylistic alternates](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/use-swashes-titling-alternates-or-stylistic-alternates.html) (public documentation). Tests: `panels::opentype::tests`. The OpenType panel's Position menu lists Default Position, Superscript, Subscript, Numerator and Denominator, as [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) describes; Superscript, Subscript, Numerator and Denominator set `sups`, `subs`, `numr` and `dnom` for the selected type and turn the other three off, and Default Position turns all four off. The menu shows Mixed when the characters it acts on differ, and an entry chosen then applies to all of them. These two rules are VectorCraft's own, as is setting the feature on type whose font lacks the glyphs, which then draws unchanged. The panel's menus and checkboxes change only their own features on each selected character, so characters keep their other OpenType features (`text.setStyle` and `text.setRangeStyle` `{featureChanges}`). Tests: `panels::opentype::tests`, `features::tests::numerators_and_denominators_are_kept_and_shaped`. + `text.setStyle {stroke, strokeWidth}` sets the character stroke's color and weight of the selected type or of a range of its characters (the weight in document points, as `stroke.set` sets it), in the same undo step as the command's other changes. Tests: `tests::textedit::set_style_sets_the_character_stroke`. - **Paragraph alignment:** the shared Paragraph/Properties alignment row leaves every button unselected when the paragraphs it acts on differ. Auto resolves per paragraph; choosing an alignment uses the existing command. Headless paragraph_mixed_alignment_* regressions exercise mixed → Center → Undo, caret/uniform states, Unicode range boundaries, Auto/direction, split runs and grouped text. These regressions and full integration CI pass. Original captures confirm mixed → Center → Undo in the existing alignment-button layout. The [public Paragraph panel guide](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/paragraph-panel-overview.html) lists the seven controls, but does not specify mixed-state rendering. Other paragraph fields remain outside this change; scores and hours unchanged. For Auto Size area type in columns, the bisection for the frame's height runs on the lines of the one-column layout, and its result is checked with at most two layouts of the columns. When the text wraps around objects or does not fit the one-column layout, or when the check fails, the columns are laid out at every step of the bisection, as before. Typing at the start of a story of 50,000 characters in 2 columns took 1,670 ms a keystroke and now takes 292 ms (release build, `auto_height_in_columns_typing_timing`). Exports to PDF, EPS, SVG, EMF, WMF and the raster formats warn about the area type and type on a path that they draw without the text that doesn't fit, and give their ids, as Print and Print Preview do. @@ -891,6 +917,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Object › Rasterize on a frame of threaded text takes it out of the thread with the text it shows, which the image draws, and the other frames keep the text they hold. When the last frame is rasterized, the text it has no room for goes after the text of the last frame that stays. Type › Create Outlines, Object › Expand and Object › Expand Appearance on a frame of threaded text take it out of the thread with the text it shows, which the outlines draw, and the other frames keep the text they hold. When the last frame is outlined, the text it has no room for goes after the text of the last frame that stays. When Expand Appearance keeps the frame as type in a group with its shadow, outer glow or Crop Marks, the type stays in the thread. The public help on threads ([Create text threads between objects](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html), [Remove or break text threads between objects](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/remove-or-break-text-threads-between-objects.html)) does not describe outlining a threaded frame; this handling is VectorCraft's own behavior. Select › Same › Link Block Series selects every frame of the threads of the selected type; type in no thread selects itself (`select.same.linkBlockSeries`). The menu entry is listed in [Select objects by characteristics](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects-by-characteristics.html); selecting several threads at once and type in no thread selecting itself are VectorCraft's own behavior. + Select › Same › Text Fill & Stroke Color selects the type whose characters match both the fill and the stroke of the selected type (`select.same.textFillAndStrokeColor`). The menu entry is listed in [Select objects by characteristics](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects-by-characteristics.html); requiring one run of characters to match both is VectorCraft's own behavior. Object › Flatten Transparency takes a frame of threaded text out of the thread in the same way when Convert All Text to Outlines outlines it or when the frame becomes flat regions or an image, and the other frames keep the text they hold. New Symbol and Redefine Symbol on a frame of threaded text take it out of the thread with the text it shows, which the symbol's art holds, and the other frames keep the text they hold. When the last frame goes into the symbol, the text it has no room for goes after the text of the last frame that stays. When every frame of a thread goes into the symbol, the copy of the last frame keeps all its text. With Optical Margin Alignment on, or Roman Hanging Punctuation on in the first paragraph, the glyphs at the ends of left-to-right type on a path hang outside its brackets, measured along the path. The type hangs at the start bracket when its line is placed there, hangs at the end bracket when the line is placed there, and hangs at both when it is centered. Glyphs that hang past the end bracket do not make the type overflow, and a hang stops at an open path's end. SVG export writes such type as outlines. @@ -900,6 +927,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Paragraph panel menu's Hyphenation… (`ui.hyphenation`, `text.setFormat {wordsLongerThan, afterFirst, beforeLast, hyphenLimit, hyphenationZone, hyphenateCapitalized}`) sets each paragraph's hyphenation limits: the shortest word that breaks, the fewest letters on each side of the hyphen, the most hyphenated lines in a row, a zone at the right edge where the Single-line Composer breaks before a word instead of hyphenating it, and whether capitalized words break. The defaults are words longer than 5 letters, 3 letters on each side, no limit or zone, and capitalized words hyphenated; paragraph styles and the native file keep the options. PDF export with type as text writes the hyphen that ends a line broken inside a word as a hyphen character where the line draws it, and the file opens with the hyphen in the line's text; kashidas are drawn as paths. The Paragraph panel's Insert Kashidas (with the Indic options; `text.setFormat {kashida}`) lengthens each Arabic word of a justified horizontal area type line with a kashida, a tatweel between its last pair of joined letters, before the word spaces widen: Short, Medium and Long kashidas are at most a quarter, half and a whole em long, Stylistic ones are whole tatweels up to an em, and None (the default) leaves the line as before; paragraph styles and the native file keep the setting. + The Character panel menu's Kashidas switch (with the Indic options; `text.setFormat` / `text.setRangeStyle {kashidas}`) allows Kashidas on selected characters, on by default for new and old text. A pair of joined letters receives one only when both characters allow it; turning one off leaves other eligible pairs in the word available. Character styles and the native file keep the switch. [Public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/justify-text-using-kashida-and-hyphenation.html) documents the menu control and the separate paragraph length choices; the default and pair rule are VectorCraft choices. The Paragraph panel's Bullets button, Type › Bullets and Numbering › Apply Bullets and the context menu's Apply Bullets (`text.setFormat {list, bullet}`, `type.applyBullets`) make paragraphs a bulleted list with the documented presets (none, filled dot, dash, hollow circle, filled square; [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): the bullet starts each paragraph's first line in its first character's font, size and color, the first line's text starts at the next tab stop after the bullet (the left indent counts as a stop), the lines it wraps to start at the left indent, a paragraph with no indents gets 18 pt and -18 pt, and Return continues the list; Reset Panel turns it off, and paragraph styles and the native file keep it. The Bullets and Numbering dialog, levels and list detection while typing are not built yet. The Paragraph panel's Bullets button, Type › Bullets and Numbering › Apply Bullets and the context menu's Apply Bullets (`text.setFormat {list, bullet}`, `type.applyBullets`) make paragraphs a bulleted list with the documented presets (none, filled dot, dash, hollow circle, filled square; [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): the bullet starts each paragraph's first line in its first character's font, size and color, the first line's text starts at the next tab stop after the bullet (the left indent counts as a stop), the lines it wraps to start at the left indent, a paragraph with no indents gets 18 pt and -18 pt, and Return continues the list; Reset Panel turns it off, and paragraph styles and the native file keep it. The Bullets and Numbering dialog, levels and Convert to Text are not built yet. The Paragraph panel's Numbered List button, Type › Bullets and Numbering › Apply Numbers and the context menu's Apply Numbers (`text.setFormat {list, number}`, `type.applyNumbers`) make paragraphs a numbered list with the documented presets (1, A, a, I, i, 01, 001, and None, which turns the list off; [Bullets and numbering](https://web.archive.org/web/20250807202418/https://helpx.adobe.com/illustrator/using/bullets-numbering.html), [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): each paragraph starts with its number and a period, counted through the list paragraphs of the story and its threaded frames, with the text and indents as in a bulleted list; letters go on from Z to AA, and roman numerals go on from III to IV, an empty paragraph is not numbered, and a paragraph in no list starts the count again at 1. @@ -917,6 +945,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian and Finnish also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). Character panel menu › Standard Vertical Roman Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {standardVerticalRoman}`, off by default) stands the selected Latin letters, digits and other half-width characters upright one below the other in vertical type instead of rotating them ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); spaces keep their width, tate-chu-yoko blocks stay across the column, and Character Style Options gives it its own checkbox beside Character Alignment. Character panel menu › Tate-chu-yoko Settings… (with the East Asian options; `ui.tateChuYokoSettings`, `text.setFormat` or `text.setRangeStyle {tcyUpDown, tcyLeftRight}`, in points, 0 by default) moves a marked tate-chu-yoko block in vertical type up by a positive Up/Down and right by a positive Left/Right ([format East Asian characters in vertical text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html), [formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); the block moves as one piece with its first character's values and keeps its one em down the column, automatic digit blocks do not move, Reset Panel sets both back to 0, and character styles and the native file keep them. + A file whose character styles hold a Tate-chu-yoko Up/Down or Left/Right offset past the coordinate limit (`MAX_COORD`) either way opens with the nearer end, as the type's own offsets do; an offset within it stays as saved. The Character panel's All Caps, Underline and Strikethrough buttons and its menu's All Caps, Underline, Strikethrough, Proportional Metrics, Tate-chu-yoko and No Break show off while only some of the selected characters have the attribute, and choosing one then turns it on for all of them, as `type.underline` (Cmd+Shift+U) does for underlining; the Character Alignment and Digits submenus check no item while the selected characters differ. `text.setFormat` refuses a value that is not true or false for its on/off attributes, as `text.setRangeStyle` does. - **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `` and PDF soft masks. The constant alpha soft mask that PDF and `.ai` export draw a CMYK page with transparency through is white, so applications that read every soft mask by its luminosity show the page too (#1359, part of #1286). Isolation mode and opacity mask editing exclude each other ([transparency and blending modes](https://web.archive.org/web/20230102045151/https://helpx.adobe.com/illustrator/using/transparency-blending-modes.html)): in isolation mode a click or Alt-click on the mask thumbnail does not edit the mask, and Make Mask is off for one object; while a mask is edited, Enter Isolation Mode and Object › Perspective › Edit Text are off, the Contextual Task Bar leaves out Isolate, and Quick Actions leave out Isolate Group. @@ -966,7 +995,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When the object the Blend tool picked first is deleted or undone away before the second click, the next click on an object picks that object first instead of doing nothing. Regression tests: `blend_tool_picks_again_when_its_first_pick_is_gone` in `meshblend.rs` and `the_blend_tool_picks_again_when_its_first_pick_is_deleted` in `tests/blendopts.rs`. Window › Blend opens the Blend panel: Make, the selected blend's Spacing and Orientation (with no blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release, each running its Object › Blend command. Make is dimmed until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two or more objects are selected, and the other buttons are dimmed until a blend is selected. With the Blend tool, Escape drops the object clicked first and stops the next click adding to the blend just made, so the next click picks a new first object; the document and the selection stay as they are. Regression tests: `escape_drops_the_blend_tools_first_pick` in `meshblend.rs` and `tests/blendopts.rs`. - Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`), and with Objects on Path groups selected the Properties panel's Objects on Path Options section shows them as a nine-point Pivot grid and a Rotate field with common angles, each change one undo step for every selected group. Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. With one Objects on Path group selected, the Selection and Objects on Path tools show the Rotate All widget beside its first object: dragging it turns every object about its attachment point by the angle the pointer turns, adding it to the group's Rotate in one undo step, in 15° steps with Shift ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). The Space, Move All and Select/Move widgets and Detach are missing. + Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`), and with Objects on Path groups selected the Properties panel's Objects on Path Options section shows them as a nine-point Pivot grid and a Rotate field with common angles, each change one undo step for every selected group. Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. With one Objects on Path group selected, the Selection and Objects on Path tools show the Rotate All widget beside its first object: dragging it turns every object about its attachment point by the angle the pointer turns, adding it to the group's Rotate in one undo step, in 15° steps with Shift ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). The Move All and Select/Move widgets and Detach are missing. + Objects on Path Space widget: with one Objects on Path group of two or more objects selected, the Selection and Objects on Path tools show a square handle beyond its last object; dragging it along the path, round its bends, sets the distance between the objects' attachment points in one undo step, the first object staying where it is, and with Alt (Option on macOS) the objects spread from both ends toward the center; the distance shows next to the pointer during the drag, in the document's units ([Rearrange and edit objects on a path](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rearrange-and-edit-objects-on-a-path.html), [Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). The group keeps the distance (`object.objectsOnPath.options {spacing, start}`) through Pivot and Rotate changes, path edits, copies, saving and reopening, and scales it with the group; by default (`"auto"`) the objects are spread evenly as before. Evidence: `objects_on_path::tests::{space_sets_the_distance_between_the_stops, space_on_a_closed_path_wraps_at_the_first_anchor_and_stops_short_of_the_first_object}` in `crates/doc`, `tests::objects_on_path::space_sets_the_distance_between_the_objects_in_one_undo_step` in `crates/engine`, `objects_on_path::tests::dragging_the_space_widget_spaces_the_objects_from_the_first_one` in `crates/tools`. Double-clicking the Objects on Path tool opens Objects on Path Tool Options ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)): the nine-point Pivot grid and the Rotate field set the attachment point and angle of the objects attached next, and groups already attached keep theirs; Reset puts the center and 0° back. Save keeps the options across tool switches and saves them with the preferences (`tool.setOption {tool: "objectsOnPath"}`). - **Paint and appearance (M3):** - **CSS swatch libraries:** fractional linear and radial gradient stop positions are preserved, so nearby stops such as 12.5% and 12.890625% remain distinct instead of collapsing to 13%. Reference: [CSS Images 3 color stops](https://www.w3.org/TR/css-images-3/#color-stop-syntax). The original synthetic regression is `palette_io::tests::css_preserves_fractional_gradient_stop_positions` in `crates/color/src/palette_io.rs`. Scores and hours are unchanged. @@ -984,6 +1014,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Separations Preview panel's Gamut Check button reports one color outside the CMYK gamut in the singular and more in the plural, in English and in each language's plural forms (`gamut_check_status_takes_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). - **Document Color Mode outside the layers:** File › Document Color Mode (in one undo step) and `document.open {colorMode}` also convert the colors of graph designs, graphic styles, opacity-mask art, the tile that pattern editing's Cancel puts back and the art of brushes (with a Hue Shift brush's key color); a tint of a global swatch there becomes the converted swatch's color at its tint, as in the art. - **Recolor Artwork layout (#3416):** the Edit chip list uses the modal scroll helper and its actual remaining height; the tab's minimum-height space scrolls with the chips. `tests_recolor` covers 5/20/200/400 colors, window resizing, 100/125/150/200% UI scaling, scrolling to and editing the final chip, Preview, Cancel, Confirm and Undo, alongside the existing #1733 drag regressions. Scores and estimates unchanged. + - **Recolor Artwork Edit displays:** buttons beside the Edit tab's wheel show the colors on a smooth color wheel, a segmented color wheel or as color bars ([Edit colors using Recolor Artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-colors-using-edit-colors-dialog.html)). The segmented wheel draws 24 hues by 5 saturations as solid patches, and its markers move freely as on the smooth wheel. The bars show one solid bar per recolored color in row order: a click selects a bar for the color sliders, and a drag moves its row without changing a color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The dialog opens on the smooth wheel; `display` (`smooth`, `segmented`, `bars`) is the dialog field. `tests_recolor` covers switching, the dialog height, segmented dragging and Brightness, and bar selection, editing, reordering, scrolling, Preview, Cancel and OK. Scores and estimates unchanged. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. - **Color Picker layout (#2008):** a centered draggable header, equal-width actions above aligned HSB/RGB/Hex and Lab/CMYK fields, compact field and slider, and warnings below the preview. No horizontal scrolling; narrow windows stack the sections with vertical scrolling. Tests in `dialogs/color_picker.rs` cover actual pointer/key input, typed values before OK/Enter, Cancel/Escape rollback, one Undo step, mode-size stability, warnings and layout at two UI scales. The screen sampler sits above the field and the upstream two-grid Tab order is retained. AccessKit regressions check the action names and each channel slider's displayed value, units and range. German and enlarged English UI renders were reviewed locally; no reference images are shipped. This is a layout improvement, with no change to scores or remaining-hour estimates. - **Eyedropper sources (#1251):** ordinary and Shift clicks, Shift+Alt appearance append, raster pixels and gradient-stop sampling can read visible locked/template art and sources outside isolation. Sampling leaves the source and selection intact; Alt reverse still uses editable hits, and hidden art stays excluded. Engine/tool/hit regressions cover the editing boundary, color models and one-step Undo/Redo. The general object/image workflow is described in [public HelpX](https://helpx.adobe.com/illustrator/using/tool-techniques/eyedropper-tool.html); the lock/isolation expectations come from the user report and these regressions, without a new full-parity measurement. @@ -1044,7 +1075,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur All Artwork Above and Other Layers (Object › Lock and Object › Hide), Transform Each, Rearrange All Artboards, the width point and width profile commands, Liquify, Puppet Warp, Define Perspective Grid, Attach to Active Plane, Release with Perspective, moves and transforms in perspective, Move Plane and Move Plane to Match Object record no undo step when they change nothing. Move in Perspective (its copy, perpendicular and Snap to Grid choices), Transform in Perspective (its copy), Nudge in Perspective (its ×10 and copy), Draw in Perspective (Snap to Grid), Define Perspective Grid (its reproject choice), Show Perspective Grid, Width Point (Adjust Adjoining Width Points), Liquify (its pen pressure, Simplify and Affect choices) and Puppet Warp (its pins' rest shape) refuse a value other than true, false or null, such as "true", and leave the document and its undo history as they were. Moves and transforms in perspective and Define Perspective Grid with reproject return an error, and leave the document and its undo history as they were, when the projection they would give type or a symbol instance in perspective has a number too large to store. Object › Perspective › Edit Text returns an error, and does not enter isolation mode, when the type cannot be shown flat where it is drawn: when part of it crosses the horizon, or when that view's projection has a number too large to store. Regressions: `a_product_that_overflows_is_none` in `crates/geom/src/projective.rs`, and `moving_type_whose_projection_would_overflow_is_refused` and `edit_text_whose_flat_view_would_overflow_is_refused` in `crates/engine/src/tests/persp_text.rs`. - A stored projection with numbers so large that its determinant overflows is judged on a copy divided by a power of two: an invertible one is read back when the document opens as the same map at a smaller scale (divided by the largest number in its bottom row), so points that overflowed at the stored scale draw, and one that cannot be inverted, such as one whose bottom row is 0 at that scale, is not. Regression: `a_determinant_that_overflows_is_taken_at_a_smaller_scale` in `crates/geom/src/projective.rs`. + A stored projection with numbers so large that its determinant overflows is judged on a copy divided by a power of two: an invertible one is read back when the document opens as the same map at a smaller scale (divided by the largest absolute value in its bottom row), so points that overflowed at the stored scale draw, and one that cannot be inverted, such as one whose bottom row is 0 at that scale, is not. Regression: `a_determinant_that_overflows_is_taken_at_a_smaller_scale` in `crates/geom/src/projective.rs`. + A projection gives the same answers when every one of its numbers is multiplied by the same factor. A point is on or past its horizon when its w is at most 1e-9 times the largest absolute value in the bottom row, so a point with a negative w is past it. The projection is invertible when the absolute value of its determinant is more than 1e-15 times the largest absolute value among the six products the determinant sums, so a negative determinant counts the same as a positive one. A stored projection with very small numbers draws and inverts, and one that cannot be inverted is refused at every scale. Regression: `the_checks_do_not_depend_on_the_scale_of_the_map` in `crates/geom/src/projective.rs`. Create Object Mosaic (its columns and rows), Transform Each (its reference point and Random seed) and Rearrange All Artboards (its columns) refuse a fraction, a negative number or a string, such as 2.5, -1 or "4"; 4.0 counts as 4. Move, Rotate, Scale, Reflect, Shear, Transform Again, Nudge and the Transform panel's values (their copy, Scale Strokes & Effects, Scale Corners, Transform Patterns, Transform Objects and area type options), Align, Distribute and Distribute Spacing (Transform Patterns), Object Properties (visible, locked, Isolate Blending and Opacity & Mask Define Knockout Shape) and Live Shape Properties (Invert Pie, Make Sides Equal and relative rounding) refuse a value other than true, false or null, such as "false", and leave the document as it was. Object Properties (its opacity), Live Shape Properties (corner radius and polygon sides), the Transform panel's reference point and Align, Distribute and Distribute Spacing to an artboard (the artboard's number) refuse a value other than a number or null, such as "50", and leave the document as it was. @@ -1066,6 +1098,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Invisible text in a PDF (rendering mode 3, which carries a scanned page's recognized text over the scan) opens as type with no fill or stroke, a run of its own beside visible text on the same line; text that can't come in as type (opened as outlines, Type 3 fonts) is left out with a warning. PDF export, and printing, write characters with no fill or stroke as real text in rendering mode 3, so they draw nothing but stay selectable and searchable, also in PDF/X-1a and PDF/A-2b (#2675, `pdf/src/tests/import_fidelity.rs`, `pdf/src/tests/realtext.rs`). A PDF, or a `.ai` read through its PDF part, whose spot inks have the same values but different names opens with a spot swatch for each ink. The solid fills and strokes of paths and type, and the stops of gradients on paths, link to the swatch of the ink they are painted in, the points of a gradient mesh in one of these inks keep the ink's color, and PDF export writes each of these inks as its own separation (`pdf/src/tests/import_color.rs`). Paint in these inks inside pattern cells, soft masks and type 3 glyphs, and gradients on type in these inks, still import as RGB. Type in one of these inks can also import as RGB when type in another Separation or DeviceN ink is shown with no path drawn between them. PDF export writes a linear or radial gradient that mixes a spot color with process colors, or two spot colors, as a DeviceN shading of the spot inks and the process inks its stops use, so each spot ink prints on its own plate; an off-center midpoint is written as a stop with the inks halfway between its two stops. A gradient that mixes a spot color with RGB or Lab colors is still written without the spot ink, with a warning, and a gradient with the Perceptual method is written as an image, without the spot ink. A Lab spot color in such a shading is named by the same Separation space, with the Lab alternate, as its flat fills (`engine/src/tests/linked_stops.rs`, `engine/src/tests/labspots.rs`). + PDF export writes a spot color named All or None (in a Separation space, the names of every plate and of no plate: [ISO 32000-1:2008](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf), 8.6.6.4) as the ink All Spot or None Spot (All Spot 2 and on when a spot swatch already has that name) in its fills, strokes, gradients, colorized images and Lab alternates; Registration still prints on every plate (`pdf/src/tests/output.rs`). - `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465). Native documents with a lot of path data (traced or generated art, in layers, symbols or patterns) are saved as compact JSON, about a fifth of the size; small documents stay pretty-printed (#1492). Saving to a network drive on macOS falls back to a plain fsync when the share refuses a full flush (#1625, part of #1620; not confirmed on a real share), and a save still succeeds when a folder refuses the temporary file, the rename over the document or copying permissions: the content is written elsewhere first and copied in, and a failed copy keeps the temporary file and names it (#1649, part of #1620). A document opened by a relative path finds its relatively linked images, and `vectorcraft-cli convert` lists what reading the input left out as `importWarnings` (#1606, fixes #1604). A name typed in the desktop save panel without the file type's extension gets it, and when a file of that name exists, which the panel did not ask about, Save, Save As, Save a Copy, Save as Template, the exports and every other write through a save panel ask before replacing it (dialog `replaceFile`; Cancel writes nothing). A name returned by the desktop save panel with the extension of a format the save does not write has it replaced with the saved format's: Save As of a new document saves `card.ait` and `card.png` as `card.vectorcraft`, and Save as Template saves `card.pdf` as `card.vctemplate`. An extension that names no format stays part of the name (`notes.v2` is saved as `notes.v2.vectorcraft`). @@ -1084,6 +1117,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur SVG import's style cascade, used for hidden objects, non-scaling strokes and type, tests each element only against the `